function _crm_update_contact($contact, $values, $overwrite = true) { // first check to make sure the location arrays sync up $param = array("contact_id" => $contact->id); $contact = crm_get_contact($param); $locMatch = _crm_location_match($contact, $values); if (!$locMatch) { return _crm_error('Cannot update contact location'); } // it is possible that an contact type object record does not exist // if the contact_type_object is null etc, if so we create one if ($contact->contact_type_object == null) { require_once str_replace('_', DIRECTORY_SEPARATOR, "CRM_Contact_BAO_" . $contact->contact_type) . ".php"; eval('$contact->contact_type_object =& new CRM_Contact_BAO_' . $contact->contact_type . '( );'); $contact->contact_type_object->contact_id = $contact->id; } $sortNameArray = array(); // fix sort_name and display_name if ($contact->contact_type == 'Individual') { if ($overwrite || !isset($contact->contact_type_object->first_name)) { $firstName = CRM_Utils_Array::value('first_name', $values); } else { $firstName = null; } if (!$firstName) { $firstName = isset($contact->contact_type_object->first_name) ? $contact->contact_type_object->first_name : ''; } if ($overwrite || !isset($contact->contact_type_object->middle_name)) { $middleName = CRM_Utils_Array::value('middle_name', $values); } else { $middleName = null; } if (!$middleName) { $middleName = isset($contact->contact_type_object->middle_name) ? $contact->contact_type_object->middle_name : ''; } if ($overwrite || !isset($contact->contact_type_object->last_name)) { $lastName = CRM_Utils_Array::value('last_name', $values); } else { $lastName = null; } if (!$lastName) { $lastName = isset($contact->contact_type_object->last_name) ? $contact->contact_type_object->last_name : ''; } if ($overwrite || !isset($contact->contact_type_object->prefix_id)) { $prefix = CRM_Utils_Array::value('prefix', $values); } else { $prefix = null; } if (!$prefix) { if (isset($contact->contact_type_object->prefix_id)) { $prefix =& new CRM_Core_DAO_IndividualPrefix(); $prefix->id = $contact->contact_type_object->prefix_id; $prefix->find(); $prefix->fetch(); $prefix = $prefix->name; } else { $prefix = ""; } } if ($overwrite || !isset($contact->contact_type_object->suffix_id)) { $suffix = CRM_Utils_Array::value('suffix', $values); } else { $suffix = null; } if (!$suffix) { if (isset($contact->contact_type_object->suffix_id)) { $suffix =& new CRM_Core_DAO_IndividualSuffix(); $suffix->id = $contact->contact_type_object->suffix_id; $suffix->find(); $suffix->fetch(); $suffix = $suffix->name; } else { $suffix = ""; } } if ($overwrite) { $gender = CRM_Utils_Array::value('gender', $values); } else { $gender = null; } if ($gender) { $genderDao =& new CRM_Core_DAO_Gender(); $genderDao->name = $gender; $genderDao->find(true); $values['gender_id'] = $genderDao->id; } if ($lastName != "" && $firstName != "") { $values['sort_name'] = "{$lastName}, {$firstName}"; } else { if ($lastName != "") { $values['sort_name'] = "{$lastName}"; } else { if ($firstName != "") { $values['sort_name'] = "{$firstName}"; } } } $values['display_name'] = "{$prefix} {$firstName} {$middleName} {$lastName} {$suffix} "; } else { if ($contact->contact_type == 'Household') { if ($overwrite || !isset($contact->contact_type_object->household_name)) { $householdName = CRM_Utils_Array::value('household_name', $values); } else { $householdName = null; } if (!$householdName) { $householdName = isset($contact->contact_type_object->household_name) ? $contact->contact_type_object->household_name : ''; } $values['sort_name'] = $householdName; } else { if ($overwrite || !isset($contact->contact_type_object->organization_name)) { $organizationName = CRM_Utils_Array::value('organization_name', $values); } else { $organizationName = null; } if (!$organizationName) { $organizationName = isset($contact->contact_type_object->organization_name) ? $contact->contact_type_object->organization_name : ''; } $values['sort_name'] = $organizationName; } } _crm_update_object($contact, $values); _crm_update_object($contact->contact_type_object, $values); if (!isset($contact->location)) { $contact->location = array(); } if (!array_key_exists(1, $contact->location) || empty($contact->location[1])) { $contact->location[1] =& new CRM_Core_BAO_Location(); } $primary_location = null; foreach ($contact->location as $key => $loc) { if ($loc->is_primary) { $primary_location = $key; break; } } if (is_array($values['location'])) { foreach ($values['location'] as $updateLocation) { $emptyBlock = $contactLocationBlock = null; /* Scan the location array for the correct block to update */ foreach ($contact->location as $key => $loc) { if ($loc->location_type_id == $updateLocation['location_type_id']) { $contactLocationBlock = $key; break; } else { if (!isset($loc->location_type_id)) { $emptyBlock = $key; } } } if ($contactLocationBlock == null) { if ($emptyBlock != null) { $contactLocationBlock = $emptyBlock; } else { /* no matching blocks and no empty blocks, make a new one */ $contact->location[] =& new CRM_Core_BAO_Location(); $contactLocationBlock = count($contact->location); } } $updateLocation['entity_id'] = $contact->id; $updateLocation['entity_table'] = CRM_Contact_BAO_Contact::getTableName(); /* If we're not overwriting, copy old data back before updating */ if (!$overwrite) { _crm_update_from_object($contact->location[$contactLocationBlock], $updateLocation, true); } /* Make sure we only have one primary location */ if ($primary_location == null && $updateLocation['is_primary']) { $primary_location = $contactLocationBlock; } else { if ($primary_location != $contactLocationBlock) { $updateLocation['is_primary'] = false; } } _crm_update_object($contact->location[$contactLocationBlock], $updateLocation); if (!isset($contact->location[$contactLocationBlock]->address)) { $contact->location[$contactLocationBlock]->address =& new CRM_Core_BAO_Address(); } $updateLocation['address']['location_id'] = $contact->location[$contactLocationBlock]->id; if ($updateLocation['address']['state_province']) { $state_province =& new CRM_Core_DAO_StateProvince(); $state_province->name = $updateLocation['address']['state_province']; if (!$state_province->find(true)) { $state_province->name = null; $state_province->abbreviation = $updateLocation['address']['state_province']; $state_province->find(true); } $updateLocation['address']['state_province_id'] = $state_province->id; } if ($updateLocation['address']['country']) { $country =& new CRM_Core_DAO_Country(); $country->name = $updateLocation['address']['country']; if (!$country->find(true)) { $country->name = null; $country->iso_code = $updateLocation['address']['country']; $country->find(true); } $updateLocation['address']['country_id'] = $country->id; } if (!$overwrite) { _crm_update_from_object($contact->location[$contactLocationBlock]->address, $updateLocation['address'], true); } _crm_update_object($contact->location[$contactLocationBlock]->address, $updateLocation['address']); $blocks = array('Email', 'IM'); foreach ($blocks as $block) { $name = strtolower($block); if (!is_array($updateLocation[$name])) { continue; } if (!isset($contact->location[$contactLocationBlock]->{$name})) { $contact->location[$contactLocationBlock]->{$name} = array(); } $primary = null; foreach ($contact->location[$contactLocationBlock]->{$name} as $key => $value) { if ($value->is_primary) { $primary = $key; break; } } $propertyBlock = 1; foreach ($updateLocation[$name] as $property) { if (!isset($contact->location[$contactLocationBlock]->{$name}[$propertyBlock])) { require_once str_replace('_', DIRECTORY_SEPARATOR, "CRM_Core_BAO_" . $block) . ".php"; eval('$contact->location[$contactLocationBlock]->{$name}[$propertyBlock] =& new CRM_Core_BAO_' . $block . '( );'); } $property['location_id'] = $contact->location[$contactLocationBlock]->id; if (!$overwrite) { _crm_update_from_object($contact->location[$contactLocationBlock]->{$name}[$propertyBlock], $property, true); } if ($primary == null && $property['is_primary']) { $primary = $propertyBlock; } else { if ($primary != $propertyBlock) { $property['is_primary'] = false; } } _crm_update_object($contact->location[$contactLocationBlock]->{$name}[$propertyBlock], $property); $propertyBlock++; } } /* handle multiple phones */ if (is_array($updateLocation['phone'])) { if (!isset($contact->location[$contactLocationBlock]->phone)) { $contact->location[$contactLocationBlock]->phone = array(); } $primary_phone = null; foreach ($contact->location[$contactLocationBlock]->phone as $key => $value) { if ($value->is_primary) { $primary_phone = $key; break; } } foreach ($updateLocation['phone'] as $phone) { /* scan through the contact record for matching phone type at this location */ $contactPhoneBlock = null; foreach ($contact->location[$contactLocationBlock]->phone as $key => $contactPhoneBlock) { if ($contactPhoneBlock->phone_type_id == $phone['phone_type_id']) { $contactPhoneBlock = $key; break; } } if ($contactPhoneBlock == null) { if (empty($contact->location[$contactLocationBlock]->phone)) { $contactPhoneBlock = 1; } else { $contactPhoneBlock = count($contact->location[$contactLocationBlock]->phone) + 1; } $contact->location[$contactLocationBlock]->phone[$contactPhoneBlock] =& new CRM_Core_BAO_Phone(); } $phone['location_id'] = $contact->location[$contactLocationBlock]->id; if (!$overwrite) { _crm_update_from_object($contact->location[$contactLocationBlock]->phone[$contactPhoneBlock], $phone, true); } if ($primary_phone == null && $phone['is_primary']) { $primary_phone = $contactPhoneBlock; } else { if ($primary_phone != $contactPhoneBlock) { $phone['is_primary'] = false; } } _crm_update_object($contact->location[$contactLocationBlock]->phone[$contactPhoneBlock], $phone); } } } } /* Custom data */ if (is_array($values['custom'])) { foreach ($values['custom'] as $customValue) { /* get the field for the data type */ $field = CRM_Core_BAO_CustomValue::typeToField($customValue['type']); if (!$field) { /* FIXME failure! */ continue; } /* adjust the value if it's boolean */ if ($customValue['type'] == 'Boolean') { $value = CRM_Utils_String::strtobool($customValue['value']); } else { $value = $customValue['value']; } /* look for a matching existing custom value */ $match = false; foreach ($contact->custom_values as $cv) { if ($cv->custom_field_id == $customValue['custom_field_id']) { /* match */ $match = true; if ($overwrite) { $cv->{$field} = $value; $cv->save(); break; } } } if (!$match) { /* no match, so create a new CustomValue */ $cvParams = array('entity_table' => 'civicrm_contact', 'entity_id' => $contact->id, 'value' => $value, 'type' => $customValue['type'], 'custom_field_id' => $customValue['custom_field_id']); CRM_Core_BAO_CustomValue::create($cvParams); } } } return $contact; }
/** * Returns all entities assigned to a specific Tag. Optionally filtered by entity_type. * * @param $tag object Valid Tag object. * @param $entity_type enum Optional filter for type of entity being queried. Valid values: 'Individual', 'Organization', 'Household', 'Group', 'Contact_action'. * * @return $entities Array An array of entity objects (Individuals and/or Organizations and/or etc.). * @access public */ function crm_get_entities_by_tag(&$tag, $entity_type = null) { require_once 'CRM/Core/BAO/EntityTag.php'; if (!isset($tag->id)) { return _crm_error('Invalid tag object passed in'); } $contactIDs =& CRM_Core_BAO_EntityTag::getEntitiesByTag($tag); $entities = array(); foreach ($contactIDs as $Id) { $params = array('contact_id' => $Id); if ($entity_type != null) { $temp = clone crm_get_contact($params); if ($entity_type == $temp->contact_type) { $entities[] = $temp; } } else { $entities[] = clone crm_get_contact($params); } } return $entities; }
function &crm_update_contact_formatted($contactId, &$params, $overwrite = true) { $contact = crm_get_contact(array('contact_id' => $contactId)); if (!$contact || is_a($contact, 'CRM_Core_Error')) { return _crm_error("Could not find valid contact for: {$contactId}"); } return _crm_update_contact($contact, $params, $overwrite); }
/** * handle the values in import mode * * @param int $onDuplicate the code for what action to take on duplicates * @param array $values the array of values belonging to this line * * @return boolean the result of this processing * @access public */ function import($onDuplicate, &$values) { // first make sure this is a valid line //$this->_updateWithId = false; $response = $this->summary($values); if ($response != CRM_IMPORT_PARSER_VALID) { return $response; } $params =& $this->getActiveFieldParams(); $formatted = array('contact_type' => $this->_contactType); //for date-Formats $session =& CRM_Core_Session::singleton(); $dateType = $session->get("dateType"); $customFields = CRM_Core_BAO_CustomField::getFields($params['contact_type']); foreach ($params as $key => $val) { if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) { if ($customFields[$customFieldID][2] == 'Date') { CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key); } } if ($key == 'birth_date') { if ($val) { CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key); } } } //date-Format part ends if ($GLOBALS['_CRM_IMPORT_PARSER_CONTACT']['indieFields'] == null) { require_once str_replace('_', DIRECTORY_SEPARATOR, "CRM_Contact_DAO_" . $this->_contactType) . ".php"; eval('$tempIndieFields =& CRM_Contact_DAO_' . $this->_contactType . '::import();'); //modified for PHP4 issue $GLOBALS['_CRM_IMPORT_PARSER_CONTACT']['indieFields'] = $tempIndieFields; } foreach ($params as $key => $field) { if ($field == null || $field === '') { continue; } if (is_array($field)) { foreach ($field as $value) { $break = false; if (is_array($value)) { foreach ($value as $name => $testForEmpty) { if ($name !== 'phone_type' && ($testForEmpty === '' || $testForEmpty == null)) { $break = true; break; } } } else { $break = true; } if (!$break) { _crm_add_formatted_param($value, $formatted); } } continue; } $value = array($key => $field); if (array_key_exists($key, $GLOBALS['_CRM_IMPORT_PARSER_CONTACT']['indieFields'])) { $value['contact_type'] = $this->_contactType; } _crm_add_formatted_param($value, $formatted); } /*if (in_array('id',$this->_mapperKeys)) { $this->_updateWithId = true; }*/ $relationship = false; // Support Match and Update Via Contact ID if ($this->_updateWithId) { $error = _crm_duplicate_formatted_contact($formatted); if (CRM_Import_Parser_Contact::isDuplicate($error)) { $matchedIDs = explode(',', $error->_errors[0]['params'][0]); if (count($matchedIDs) >= 1) { $updateflag = true; foreach ($matchedIDs as $contactId) { if ($params['id'] == $contactId) { $paramsValues = array('contact_id' => $contactId); $contactExits = crm_get_contact($paramsValues); if ($formatted['contact_type'] == $contactExits->contact_type) { $newContact = crm_update_contact_formatted($contactId, $formatted, true); $updateflag = false; $this->_retCode = CRM_IMPORT_PARSER_VALID; } else { $message = "Mismatched contact Types :"; array_unshift($values, $message); $updateflag = false; $this->_retCode = CRM_IMPORT_PARSER_NO_MATCH; } } } if ($updateflag) { $message = "Mismatched contact IDs OR Mismatched contact Types :"; array_unshift($values, $message); $this->_retCode = CRM_IMPORT_PARSER_NO_MATCH; } } } else { $paramsValues = array('contact_id' => $params['id']); $contact = crm_get_contact($paramsValues); if (is_a($contact, CRM_Contact_BAO_Contact)) { if ($formatted['contact_type'] == $contact->contact_type) { $newContact = crm_update_contact_formatted($contact->id, $formatted, true); $this->_retCode = CRM_IMPORT_PARSER_VALID; } else { $message = "Mismatched contact Types :"; array_unshift($values, $message); $this->_retCode = CRM_IMPORT_PARSER_NO_MATCH; } } else { $message = "No contact found for this contact ID:" . $params['id']; array_unshift($values, $message); $this->_retCode = CRM_IMPORT_PARSER_NO_MATCH; } } if (is_a($newContact, CRM_Contact_BAO_Contact)) { $relationship = true; } else { if (is_a($error, CRM_Core_Error)) { $newContact = $error; $relationship = true; } } if ($newContact && !is_a($newContact, CRM_Core_Error)) { $this->_newContacts[] = $newContact->id; } } else { $newContact = crm_create_contact_formatted($formatted, $onDuplicate); $relationship = true; } if ($relationship) { if (CRM_Import_Parser_Contact::isDuplicate($newContact)) { foreach ($newContact->_errors[0]['params'] as $cid) { $primaryContactId = $cid; } } else { $primaryContactId = $newContact->id; } if (CRM_Import_Parser_Contact::isDuplicate($newContact) || is_a($newContact, CRM_Contact_BAO_Contact)) { //relationship contact insert foreach ($params as $key => $field) { list($id, $first, $second) = explode('_', $key); if (!($first == 'a' && $second == 'b') && !($first == 'b' && $second == 'a')) { continue; } $relationType = new CRM_Contact_DAO_RelationshipType(); $relationType->id = $id; $relationType->find(true); $name_a_b = $relationType->name_a_b; if ($params[$key]['contact_type']) { $formatting = array('contact_type' => $params[$key]['contact_type']); } else { $fld = array_keys($params[$key]); foreach (CRM_Core_SelectValues::contactType() as $cType => $val) { if ($cType) { $contactFields =& CRM_Contact_BAO_Contact::importableFields($cType); if (array_key_exists($fld[0], $contactFields)) { $formatting['contact_type'] = $cType; $params[$key]['contact_type'] = $cType; $field['contact_type'] = $cType; break; } } } } $contactFields = null; if ($contactFields == null) { require_once str_replace('_', DIRECTORY_SEPARATOR, "CRM_Contact_DAO_" . $params[$key]['contact_type']) . ".php"; eval('$contactFields =& CRM_Contact_DAO_' . $params[$key]['contact_type'] . '::import();'); } foreach ($field as $k => $v) { if ($v == null || $v === '') { continue; } if (is_array($v)) { foreach ($v as $value) { $break = false; foreach ($value as $testForEmpty) { if ($testForEmpty === '' || $testForEmpty == null) { $break = true; break; } } if (!$break) { _crm_add_formatted_param($value, $formatting); } } continue; } $value = array($k => $v); if (array_key_exists($k, $contactFields)) { $value['contact_type'] = $params[$key]['contact_type']; } _crm_add_formatted_param($value, $formatting); } $relatedNewContact = crm_create_contact_formatted($formatting, $onDuplicate); if (CRM_Import_Parser_Contact::isDuplicate($relatedNewContact)) { foreach ($relatedNewContact->_errors[0]['params'] as $cid) { $relContactId = $cid; } } else { $relContactId = $relatedNewContact->id; $this->_newRelatedContacts[] = $relContactId; } if (CRM_Import_Parser_Contact::isDuplicate($relatedNewContact) || is_a($relatedNewContact, CRM_Contact_BAO_Contact)) { //store the related contact id for groups //$this->_newRelatedContacts[] = $relContactId; // now create the relationship record $relationParams = array(); $relationParams = array('relationship_type_id' => $key, 'contact_check' => array($relContactId => 1)); $relationIds = array('contact' => $primaryContactId); CRM_Contact_BAO_Relationship::create($relationParams, $relationIds); //check if the two contacts are related and of type individual if ($params[$key]['contact_type'] == 'Individual' && $this->_contactType == 'Individual') { if ($name_a_b == 'Spouse of' || $name_a_b == 'Child of' || $name_a_b == 'Sibling of') { $householdName = "The " . $formatting['last_name'] . " household"; $householdFormatting = array('contact_type' => 'Household', 'household_name' => $householdName); $householdContact = crm_create_contact_formatted($householdFormatting, $onDuplicate); if (CRM_Import_Parser_Contact::isDuplicate($householdContact)) { foreach ($householdContact->_errors[0]['params'] as $cid) { $householdId = $cid; } } else { $householdId = $householdContact->id; $this->_newRelatedContacts[] = $householdId; } //Household contact is created //for two related individual contacts waiting confirmation whether //to add it in a group //$this->_newRelatedContacts[] = $householdId; $relationParams = array(); // adding household relationship $relType = '7_' . $second . '_' . $first; $relationParams = array('relationship_type_id' => $relType, 'contact_check' => array($relContactId => 1, $primaryContactId => 1)); $relationIds = array('contact' => $householdId); CRM_Contact_BAO_Relationship::create($relationParams, $relationIds); } } } } } } if ($this->_updateWithId) { return $this->_retCode; } //dupe checking if (is_a($newContact, CRM_Core_Error)) { $code = $newContact->_errors[0]['code']; if ($code == CRM_CORE_ERROR_DUPLICATE_CONTACT) { $urls = array(); foreach ($newContact->_errors[0]['params'] as $cid) { $urls[] = CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $cid, true); } $url_string = implode("\n", $urls); array_unshift($values, $url_string); /* If we duplicate more than one record, skip no matter what */ if (count($newContact->_errors[0]['params']) > 1) { array_unshift($values, ts('Record duplicates multiple contacts')); return CRM_IMPORT_PARSER_ERROR; } /* Params only had one id, so shift it out */ $contactId = array_shift($newContact->_errors[0]['params']); if ($onDuplicate == CRM_IMPORT_PARSER_DUPLICATE_REPLACE) { $newContact = crm_replace_contact_formatted($contactId, $formatted); } else { if ($onDuplicate == CRM_IMPORT_PARSER_DUPLICATE_UPDATE) { $newContact = crm_update_contact_formatted($contactId, $formatted, true); } else { if ($onDuplicate == CRM_IMPORT_PARSER_DUPLICATE_FILL) { $newContact = crm_update_contact_formatted($contactId, $formatted, false); } } } // else skip does nothing and just returns an error code. if ($newContact && !is_a($newContact, CRM_Core_Error)) { $this->_newContacts[] = $newContact->id; } //CRM-262 No Duplicate Checking if ($onDuplicate == CRM_IMPORT_PARSER_DUPLICATE_SKIP) { return CRM_IMPORT_PARSER_DUPLICATE; } return CRM_IMPORT_PARSER_VALID; } else { /* Not a dupe, so we had an error */ array_unshift($values, $newContact->_errors[0]['message']); return CRM_IMPORT_PARSER_ERROR; } } if ($newContact && !is_a($newContact, CRM_Core_Error)) { $this->_newContacts[] = $newContact->id; } return CRM_IMPORT_PARSER_VALID; }
function delete_contact($user_name, $id) { /* global $current_user; require_once('modules/Users/User.php'); $seed_user = new User(); $user_id = $seed_user->retrieve_user_id($user_name); $current_user = $seed_user; $current_user->retrieve($user_id); require_once('modules/Contacts/Contact.php'); $contact = new Contact(); $contact->id = $id; //$contact->delete($contact->id); $contact->mark_deleted($contact->id); // $contact->delete(); */ $contactId = $id; $param = array('contact_id' => $contactId); $contact = crm_get_contact($param); crm_delete_contact(&$contact); return "Suceeded in deleting contact"; }
function get_contact($key, $params, $returnProperties) { $this->verify($key); return crm_get_contact($params, $returnProperties); }
/** * Process the form * * @return void * @access public */ function postProcess() { $contactID = $this->get('contactID'); if (!$contactID) { // make a copy of params so we dont destroy our params // (since we pass this by reference) $premiumParams = $params = $this->_params; // so now we have a confirmed financial transaction // lets create or update a contact first require_once 'api/crm.php'; $ids = CRM_Core_BAO_UFGroup::findContact($params); $contactsIDs = explode(',', $ids); // if we find more than one contact, use the first one $contact_id = $contactsIDs[0]; $contact = null; if ($contact_id) { $contact =& crm_get_contact(array('contact_id' => $contact_id)); } $ids = array(); if (!$contact || !is_a($contact, 'CRM_Contact_BAO_Contact')) { $contact =& CRM_Contact_BAO_Contact::createFlat($params, $ids); } else { // need to fix and unify all contact creation $idParams = array('id' => $contact_id, 'contact_id' => $contact_id); $defaults = array(); CRM_Contact_BAO_Contact::retrieve($idParams, $defaults, $ids); $contact =& CRM_Contact_BAO_Contact::createFlat($params, $ids); } if (is_a($contact, 'CRM_Core_Error')) { CRM_Core_Error::fatal("Failed creating contact for contributor"); } $contactID = $contact->id; $this->set('contactID', $contactID); } $contributionType =& new CRM_Contribute_DAO_ContributionType(); $contributionType->id = $this->_values['contribution_type_id']; if (!$contributionType->find(true)) { CRM_Core_Error::fatal("Could not find a system table"); } // add some contribution type details to the params list // if folks need to use it $this->_params['contributionType_name'] = $contributionType->name; $this->_params['contributionType_accounting_code'] = $contributionType->accounting_code; $this->_params['contributionForm_id'] = $this->_values['id']; require_once 'CRM/Contribute/Payment.php'; $payment =& CRM_Contribute_Payment::singleton($this->_mode); if ($this->_contributeMode == 'express') { $result =& $payment->doExpressCheckout($this->_params); } else { $result =& $payment->doDirectPayment($this->_params); } if (is_a($result, 'CRM_Core_Error')) { CRM_Core_Error::displaySessionError($result); CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', '_qf_Main_display=true')); } $now = date('YmdHis'); $this->_params = array_merge($this->_params, $result); $this->_params['receive_date'] = $now; $this->set('params', $this->_params); $this->assign('trxn_id', $result['trxn_id']); $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($this->_params['receive_date'])); // result has all the stuff we need // lets archive it to a financial transaction $config =& CRM_Core_Config::singleton(); $receiptDate = null; if ($this->_values['is_email_receipt']) { $receiptDate = $now; } if ($contributionType->is_deductible) { $this->assign('is_deductible', true); $this->set('is_deductible', true); } // assigning Premium information to receipt tpl if ($premiumParams['selectProduct'] && $premiumParams['selectProduct'] != 'no_thanks') { $startDate = $endDate = ""; $this->assign('selectPremium', true); require_once 'CRM/Contribute/DAO/Product.php'; $productDAO =& new CRM_Contribute_DAO_Product(); $productDAO->id = $premiumParams['selectProduct']; $productDAO->find(true); $this->assign('product_name', $productDAO->name); $this->assign('price', $productDAO->price); $this->assign('sku', $productDAO->sku); $this->assign('option', $premiumParams['options_' . $premiumParams['selectProduct']]); $periodType = $productDAO->period_type; if ($periodType) { $fixed_period_start_day = $productDAO->fixed_period_start_day; $duration_unit = $productDAO->duration_unit; $duration_interval = $productDAO->duration_interval; if ($periodType == 'rolling') { $startDate = date('Y-m-d'); } else { if ($periodType == 'fixed') { if ($fixed_period_start_day) { $date = explode('-', date('Y-m-d')); $month = substr($fixed_period_start_day, 0, strlen($fixed_period_start_day) - 2); $day = substr($fixed_period_start_day, -2) . "<br>"; $year = $date[0]; $startDate = $year . '-' . $month . '-' . $day; } else { $startDate = date('Y-m-d'); } } } $date = explode('-', $startDate); $year = $date[0]; $month = $date[1]; $day = $date[2]; switch ($duration_unit) { case 'year': $year = $year + $duration_interval; break; case 'month': $month = $month + $duration_interval; break; case 'day': $day = $day + $duration_interval; break; case 'week': $day = $day + $duration_interval * 7; } $endDate = date('Y-m-d H:i:s', mktime($hour, $minute, $second, $month, $day, $year)); $this->assign('start_date', $startDate); $this->assign('end_date', $endDate); } require_once 'CRM/Contribute/DAO/Premium.php'; $dao =& new CRM_Contribute_DAO_Premium(); $dao->entity_table = 'civicrm_contribution_page'; $dao->entity_id = $this->_id; $dao->find(true); $this->assign('contact_phone', $dao->premiums_contact_phone); $this->assign('contact_email', $dao->premiums_contact_email); } CRM_Core_DAO::transaction('BEGIN'); $nonDeductibleAmount = $result['gross_amount']; if ($contributionType->is_deductible) { if ($premiumParams['selectProduct'] != 'no_thanks') { require_once 'CRM/Contribute/DAO/Product.php'; $productDAO =& new CRM_Contribute_DAO_Product(); $productDAO->id = $premiumParams['selectProduct']; $productDAO->find(true); if ($result['gross_amount'] < $productDAO->price) { $nonDeductibleAmount = $result['gross_amount']; } else { $nonDeductibleAmount = $productDAO->price; } } else { $nonDeductibleAmount = '0.00'; } } // check contribution Type // first create the contribution record $params = array('contact_id' => $contactID, 'contribution_type_id' => $contributionType->id, 'payment_instrument_id' => 1, 'receive_date' => $now, 'non_deductible_amount' => $nonDeductibleAmount, 'total_amount' => $result['gross_amount'], 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $result['gross_amount']), 'trxn_id' => $result['trxn_id'], 'invoice_id' => $this->_params['invoiceID'], 'currency' => $this->_params['currencyID'], 'receipt_date' => $receiptDate, 'source' => ts('Online Contribution:') . ' ' . $this->_values['title']); $ids = array(); $contribution =& CRM_Contribute_BAO_Contribution::add($params, $ids); //create Premium record if ($premiumParams['selectProduct'] && $premiumParams['selectProduct'] != 'no_thanks') { require_once 'CRM/Contribute/DAO/Product.php'; $productDAO =& new CRM_Contribute_DAO_Product(); $productDAO->id = $premiumParams['selectProduct']; $productDAO->find(true); $periodType = $productDAO->period_type; require_once 'CRM/Utils/Date.php'; $params = array('product_id' => $premiumParams['selectProduct'], 'contribution_id' => $contribution->id, 'product_option' => $premiumParams['options_' . $premiumParams['selectProduct']], 'quantity' => 1, 'start_date' => CRM_Utils_Date::customFormat($startDate, '%Y%m%d'), 'end_date' => CRM_Utils_Date::customFormat($endDate, '%Y%m%d')); CRM_Contribute_BAO_Contribution::addPremium($params); } // process the custom data that is submitted or that came via the url $groupTree = $this->get('groupTree'); $customValues = $this->get('customGetValues'); $customValues = array_merge($this->_params, $customValues); require_once 'CRM/Core/BAO/CustomGroup.php'; CRM_Core_BAO_CustomGroup::postProcess($groupTree, $customValues); CRM_Core_BAO_CustomGroup::updateCustomData($groupTree, 'Contribution', $contribution->id); // next create the transaction record $params = array('entity_table' => 'civicrm_contribution', 'entity_id' => $contribution->id, 'trxn_date' => $now, 'trxn_type' => 'Debit', 'total_amount' => $result['gross_amount'], 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $result['gross_amount']), 'currency' => $this->_params['currencyID'], 'payment_processor' => $config->paymentProcessor, 'trxn_id' => $result['trxn_id']); require_once 'CRM/Contribute/BAO/FinancialTrxn.php'; $trxn =& CRM_Contribute_BAO_FinancialTrxn::create($params); // also create an activity history record require_once 'CRM/Utils/Money.php'; $params = array('entity_table' => 'civicrm_contact', 'entity_id' => $contactID, 'activity_type' => $contributionType->name, 'module' => 'CiviContribute', 'callback' => 'CRM_Contribute_Page_Contribution::details', 'activity_id' => $contribution->id, 'activity_summary' => 'Online - ' . CRM_Utils_Money::format($this->_params['amount']), 'activity_date' => $now); if (is_a(crm_create_activity_history($params), 'CRM_Core_Error')) { CRM_Core_Error::fatal("Could not create a system record"); } CRM_Core_DAO::transaction('COMMIT'); // finally send an email receipt if ($this->_values['is_email_receipt']) { list($displayName, $email) = CRM_Contact_BAO_Contact::getEmailDetails($contactID); $template =& CRM_Core_Smarty::singleton(); $subject = trim($template->fetch('CRM/Contribute/Form/Contribution/ReceiptSubject.tpl')); $message = $template->fetch('CRM/Contribute/Form/Contribution/ReceiptMessage.tpl'); $receiptFrom = '"' . $this->_values['receipt_from_name'] . '" <' . $this->_values['receipt_from_email'] . '>'; require_once 'CRM/Utils/Mail.php'; CRM_Utils_Mail::send($receiptFrom, $displayName, $email, $subject, $message, $this->_values['cc_receipt'], $this->_values['bcc_receipt']); } }