/** * 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, $doGeocodeAddress = false) { $config =& CRM_Core_Config::singleton(); $this->_unparsedStreetAddressContacts = array(); if (!$doGeocodeAddress) { // CRM-5854, reset the geocode method to null to prevent geocoding $config->geocodeMethod = null; } // first make sure this is a valid line //$this->_updateWithId = false; $response = $this->summary($values); $statusFieldName = $this->_statusFieldName; if ($response != CRM_Import_Parser::VALID) { $importRecordParams = array($statusFieldName => 'INVALID', "{$statusFieldName}Msg" => "Invalid (Error Code: {$response})"); $this->updateImportRecord($values[count($values) - 1], $importRecordParams); return $response; } $params =& $this->getActiveFieldParams(); $formatted = array('contact_type' => $this->_contactType); static $contactFields = null; if ($contactFields == null) { require_once "CRM/Contact/DAO/Contact.php"; $contactFields =& CRM_Contact_DAO_Contact::import(); } //check if external identifier exists in database if (CRM_Utils_Array::value('external_identifier', $params) && (CRM_Utils_Array::value('id', $params) || in_array($onDuplicate, array(CRM_Import_Parser::DUPLICATE_SKIP, CRM_Import_Parser::DUPLICATE_NOCHECK)))) { require_once "CRM/Contact/BAO/Contact.php"; if ($internalCid = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['external_identifier'], 'id', 'external_identifier')) { if ($internalCid != CRM_Utils_Array::value('id', $params)) { $errorMessage = ts('External Identifier already exists in database.'); array_unshift($values, $errorMessage); $importRecordParams = array($statusFieldName => 'ERROR', "{$statusFieldName}Msg" => $errorMessage); $this->updateImportRecord($values[count($values) - 1], $importRecordParams); return CRM_Import_Parser::ERROR; } } } if (!empty($this->_contactSubType)) { $params['contact_sub_type'] = $this->_contactSubType; } if ($subType = CRM_Utils_Array::value('contact_sub_type', $params)) { if (CRM_Contact_BAO_ContactType::isExtendsContactType($subType, $this->_contactType, false, 'label')) { $subTypes = CRM_Contact_BAO_ContactType::subTypePairs($this->_contactType, false, null); $params['contact_sub_type'] = array_search($subType, $subTypes); } elseif (!CRM_Contact_BAO_ContactType::isExtendsContactType($subType, $this->_contactType)) { $message = "Mismatched or Invalid Contact SubType."; array_unshift($values, $message); return CRM_Import_Parser::NO_MATCH; } } //get contact id to format common data in update/fill mode, //if external identifier is present, CRM-4423 if ($this->_updateWithId && !CRM_Utils_Array::value('id', $params) && CRM_Utils_Array::value('external_identifier', $params)) { if ($cid = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['external_identifier'], 'id', 'external_identifier')) { $formatted['id'] = $cid; } } //format common data, CRM-4062 $this->formatCommonData($params, $formatted, $contactFields); $relationship = false; $createNewContact = true; // Support Match and Update Via Contact ID if ($this->_updateWithId) { $createNewContact = false; if (!CRM_Utils_Array::value('id', $params) && CRM_Utils_Array::value('external_identifier', $params)) { if ($cid) { $params['id'] = $cid; } else { //update contact if dedupe found contact id, CRM-4148 $dedupeParams = $formatted; //special case to check dedupe if external id present. //if we send external id dedupe will stop. unset($dedupeParams['external_identifier']); $checkDedupe = _civicrm_duplicate_formatted_contact($dedupeParams); if (civicrm_duplicate($checkDedupe)) { $matchingContactIds = explode(',', $checkDedupe['error_message']['params'][0]); if (count($matchingContactIds) == 1) { $params['id'] = array_pop($matchingContactIds); } else { $message = "More than one matching contact found for given criteria."; array_unshift($values, $message); $this->_retCode = CRM_Import_Parser::NO_MATCH; } } else { $createNewContact = true; } } } $error = _civicrm_duplicate_formatted_contact($formatted); if (civicrm_duplicate($error)) { $matchedIDs = explode(',', $error['error_message']['params'][0]); if (count($matchedIDs) >= 1) { $updateflag = true; foreach ($matchedIDs as $contactId) { if ($params['id'] == $contactId) { $contactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['id'], 'contact_type'); if ($formatted['contact_type'] == $contactType) { //validation of subtype for update mode //CRM-5125 $contactSubType = null; if (CRM_Utils_Array::value('contact_sub_type', $params)) { $contactSubType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['id'], 'contact_sub_type'); } if (!empty($contactSubType) && (!CRM_Contact_BAO_ContactType::isAllowEdit($params['id'], $contactSubType) || $contactSubType != CRM_Utils_Array::value('contact_sub_type', $formatted))) { $message = "Mismatched contact SubTypes :"; array_unshift($values, $message); $updateflag = false; $this->_retCode = CRM_Import_Parser::NO_MATCH; } else { $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $contactId, false); $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 { $contactType = null; if (CRM_Utils_Array::value('id', $params)) { $contactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['id'], 'contact_type'); if ($contactType) { if ($formatted['contact_type'] == $contactType) { //validation of subtype for update mode //CRM-5125 $contactSubType = null; if (CRM_Utils_Array::value('contact_sub_type', $params)) { $contactSubType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['id'], 'contact_sub_type'); } if (!empty($contactSubType) && (!CRM_Contact_BAO_ContactType::isAllowEdit($params['id'], $contactSubType) || $contactSubType != CRM_Utils_Array::value('contact_sub_type', $formatted))) { $message = "Mismatched contact SubTypes :"; array_unshift($values, $message); $this->_retCode = CRM_Import_Parser::NO_MATCH; } else { $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $params['id'], false); $this->_retCode = CRM_Import_Parser::VALID; } } else { $message = "Mismatched contact Types :"; array_unshift($values, $message); $this->_retCode = CRM_Import_Parser::NO_MATCH; } } else { // we should avoid multiple errors for single record // since we have already retCode and we trying to force again. if ($this->_retCode != CRM_Import_Parser::NO_MATCH) { $message = "No contact found for this contact ID:" . $params['id']; array_unshift($values, $message); $this->_retCode = CRM_Import_Parser::NO_MATCH; } } } else { //CRM-4148 //now we want to create new contact on update/fill also. $createNewContact = true; } } if (is_a($newContact, 'CRM_Contact_BAO_Contact')) { $relationship = true; } else { if (is_a($error, 'CRM_Core_Error')) { $newContact = $error; $relationship = true; } } } //fixed CRM-4148 //now we create new contact in update/fill mode also. if ($createNewContact) { //CRM-4430, don't carry if not submitted. foreach (array('prefix', 'suffix', 'gender') as $name) { if (array_key_exists($name, $formatted)) { if (in_array($name, array('prefix', 'suffix'))) { $formattedName = "individual_{$name}"; $formatted[$formattedName] = CRM_Core_OptionGroup::getValue($formattedName, (string) $formatted[$name]); } else { $formatted[$name] = CRM_Core_OptionGroup::getValue($name, (string) $formatted[$name]); } } } $newContact = $this->createContact($formatted, $contactFields, $onDuplicate); } if (is_object($newContact) || $newContact instanceof CRM_Contact_BAO_Contact) { $relationship = true; $newContact = clone $newContact; $this->_newContacts[] = $newContact->id; //get return code if we create new contact in update mode, CRM-4148 if ($this->_updateWithId) { $this->_retCode = CRM_Import_Parser::VALID; } } else { if (civicrm_duplicate($newContact)) { $relationship = true; $contactID = $newContact['error_message']['params'][0]; if (!in_array($contactID, $this->_newContacts)) { $this->_newContacts[] = $contactID; } } } if ($relationship) { $primaryContactId = null; if (civicrm_duplicate($newContact)) { if (CRM_Utils_Rule::integer($newContact['error_message']['params'][0])) { $primaryContactId = $newContact['error_message']['params'][0]; } } else { $primaryContactId = $newContact->id; } if ((civicrm_duplicate($newContact) || is_a($newContact, 'CRM_Contact_BAO_Contact')) && $primaryContactId) { //relationship contact insert foreach ($params as $key => $field) { list($id, $first, $second) = CRM_Utils_System::explode('_', $key, 3); if (!($first == 'a' && $second == 'b') && !($first == 'b' && $second == 'a')) { continue; } $relationType = new CRM_Contact_DAO_RelationshipType(); $relationType->id = $id; $relationType->find(true); $direction = "contact_sub_type_{$second}"; $formatting = array('contact_type' => $params[$key]['contact_type']); //set subtype for related contact CRM-5125 if (isset($relationType->{$direction})) { //validation of related contact subtype for update mode if ($relCsType = CRM_Utils_Array::value('contact_sub_type', $params[$key]) && $relCsType != $relationType->{$direction}) { $errorMessage = ts("Mismatched or Invalid contact subtype found for this related contact"); array_unshift($values, $errorMessage); return CRM_Import_Parser::NO_MATCH; } else { $formatting['contact_sub_type'] = $relationType->{$direction}; } } $relationType->free(); $contactFields = null; $contactFields = CRM_Contact_DAO_Contact::import(); //Relation on the basis of External Identifier. if (!CRM_Utils_Array::value('id', $params[$key]) && isset($params[$key]['external_identifier'])) { $params[$key]['id'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params[$key]['external_identifier'], 'id', 'external_identifier'); } // check for valid related contact id in update/fill mode, CRM-4424 if (in_array($onDuplicate, array(CRM_Import_Parser::DUPLICATE_UPDATE, CRM_Import_Parser::DUPLICATE_FILL)) && CRM_Utils_Array::value('id', $params[$key])) { $relatedContactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params[$key]['id'], 'contact_type'); if (!$relatedContactType) { $errorMessage = ts("No contact found for this related contact ID: %1", array(1 => $params[$key]['id'])); array_unshift($values, $errorMessage); return CRM_Import_Parser::NO_MATCH; } else { //validation of related contact subtype for update mode //CRM-5125 $relatedCsType = null; if (CRM_Utils_Array::value('contact_sub_type', $formatting)) { $relatedCsType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params[$key]['id'], 'contact_sub_type'); } if (!empty($relatedCsType) && (!CRM_Contact_BAO_ContactType::isAllowEdit($params[$key]['id'], $relatedCsType) || $relatedCsType != CRM_Utils_Array::value('contact_sub_type', $formatting))) { $errorMessage = ts("Mismatched or Invalid contact subtype found for this related contact ID: %1", array(1 => $params[$key]['id'])); array_unshift($values, $errorMessage); return CRM_Import_Parser::NO_MATCH; } else { // get related contact id to format data in update/fill mode, //if external identifier is present, CRM-4423 $formatting['id'] = $params[$key]['id']; } } } //format common data, CRM-4062 $this->formatCommonData($field, $formatting, $contactFields); //fixed for CRM-4148 if ($params[$key]['id']) { $contact = array('contact_id' => $params[$key]['id']); $defaults = array(); $relatedNewContact = CRM_Contact_BAO_Contact::retrieve($contact, $defaults); } else { $relatedNewContact = $this->createContact($formatting, $contactFields, $onDuplicate, null, false); } if (is_object($relatedNewContact) || $relatedNewContact instanceof CRM_Contact_BAO_Contact) { $relatedNewContact = clone $relatedNewContact; } $matchedIDs = array(); // To update/fill contact, get the matching contact Ids if duplicate contact found // otherwise get contact Id from object of related contact if (is_array($relatedNewContact) && civicrm_error($relatedNewContact)) { if (civicrm_duplicate($relatedNewContact)) { $matchedIDs = explode(',', $relatedNewContact['error_message']['params'][0]); } else { $errorMessage = $relatedNewContact['error_message']; array_unshift($values, $errorMessage); $importRecordParams = array($statusFieldName => 'ERROR', "{$statusFieldName}Msg" => $errorMessage); $this->updateImportRecord($values[count($values) - 1], $importRecordParams); return CRM_Import_Parser::ERROR; } } else { $matchedIDs[] = $relatedNewContact->id; } // update/fill related contact after getting matching Contact Ids, CRM-4424 if (in_array($onDuplicate, array(CRM_Import_Parser::DUPLICATE_UPDATE, CRM_Import_Parser::DUPLICATE_FILL))) { //validation of related contact subtype for update mode //CRM-5125 $relatedCsType = null; if (CRM_Utils_Array::value('contact_sub_type', $formatting)) { $relatedCsType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $matchedIDs[0], 'contact_sub_type'); } if (!empty($relatedCsType) && (!CRM_Contact_BAO_ContactType::isAllowEdit($matchedIDs[0], $relatedCsType) || $relatedCsType != CRM_Utils_Array::value('contact_sub_type', $formatting))) { $errorMessage = ts("Mismatched or Invalid contact subtype found for this related contact."); array_unshift($values, $errorMessage); return CRM_Import_Parser::NO_MATCH; } else { $updatedContact = $this->createContact($formatting, $contactFields, $onDuplicate, $matchedIDs[0]); } } static $relativeContact = array(); if (civicrm_duplicate($relatedNewContact)) { if (count($matchedIDs) >= 1) { $relContactId = $matchedIDs[0]; //add relative contact to count during update & fill mode. //logic to make count distinct by contact id. if ($this->_newRelatedContacts || !empty($relativeContact)) { $reContact = array_keys($relativeContact, $relContactId); if (empty($reContact)) { $this->_newRelatedContacts[] = $relativeContact[] = $relContactId; } } else { $this->_newRelatedContacts[] = $relativeContact[] = $relContactId; } } } else { $relContactId = $relatedNewContact->id; $this->_newRelatedContacts[] = $relativeContact[] = $relContactId; } if (civicrm_duplicate($relatedNewContact) || $relatedNewContact instanceof CRM_Contact_BAO_Contact) { //fix for CRM-1993.Checks for duplicate related contacts if (count($matchedIDs) >= 1) { //if more than one duplicate contact //found, create relationship with first contact // now create the relationship record $relationParams = array(); $relationParams = array('relationship_type_id' => $key, 'contact_check' => array($relContactId => 1), 'is_active' => 1, 'skipRecentView' => true); // we only handle related contact success, we ignore failures for now // at some point wold be nice to have related counts as separate $relationIds = array('contact' => $primaryContactId); list($valid, $invalid, $duplicate, $saved, $relationshipIds) = CRM_Contact_BAO_Relationship::create($relationParams, $relationIds); CRM_Contact_BAO_Relationship::relatedMemberships($primaryContactId, $relationParams, $relationIds); //handle current employer, CRM-3532 if ($valid) { require_once 'CRM/Core/PseudoConstant.php'; $allRelationships = CRM_Core_PseudoConstant::relationshipType('name'); $relationshipTypeId = str_replace(array('_a_b', '_b_a'), array('', ''), $key); $relationshipType = str_replace($relationshipTypeId . '_', '', $key); $orgId = $individualId = null; if ($allRelationships[$relationshipTypeId]["name_{$relationshipType}"] == 'Employee of') { $orgId = $relContactId; $individualId = $primaryContactId; } else { if ($allRelationships[$relationshipTypeId]["name_{$relationshipType}"] == 'Employer of') { $orgId = $primaryContactId; $individualId = $relContactId; } } if ($orgId && $individualId) { $currentEmpParams[$individualId] = $orgId; require_once 'CRM/Contact/BAO/Contact/Utils.php'; CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($currentEmpParams); } } } } } } } if ($this->_updateWithId) { //return warning if street address is unparsed, CRM-5886 return $this->processMessage($values, $statusFieldName, $this->_retCode); } //dupe checking if (is_array($newContact) && civicrm_error($newContact)) { $code = null; if (($code = CRM_Utils_Array::value('code', $newContact['error_message'])) && $code == CRM_Core_Error::DUPLICATE_CONTACT) { $urls = array(); // need to fix at some stage and decide if the error will return an // array or string, crude hack for now if (is_array($newContact['error_message']['params'][0])) { $cids = $newContact['error_message']['params'][0]; } else { $cids = explode(',', $newContact['error_message']['params'][0]); } foreach ($cids as $cid) { $urls[] = CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $cid, true); } $url_string = implode("\n", $urls); // If we duplicate more than one record, skip no matter what if (count($cids) > 1) { $errorMessage = ts('Record duplicates multiple contacts'); $importRecordParams = array($statusFieldName => 'ERROR', "{$statusFieldName}Msg" => $errorMessage); //combine error msg to avoid mismatch between error file columns. $errorMessage .= "\n" . $url_string; array_unshift($values, $errorMessage); $this->updateImportRecord($values[count($values) - 1], $importRecordParams); return CRM_Import_Parser::ERROR; } // Params only had one id, so shift it out $contactId = array_shift($cids); $cid = null; $vals = array('contact_id' => $contactId); if ($onDuplicate == CRM_Import_Parser::DUPLICATE_REPLACE) { $result = civicrm_replace_contact_formatted($contactId, $formatted, $contactFields); $cid = $result['result']; } else { if ($onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE) { $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $contactId); } else { if ($onDuplicate == CRM_Import_Parser::DUPLICATE_FILL) { $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $contactId); } } } // else skip does nothing and just returns an error code. if ($cid) { $contact = array('contact_id' => $cid); $defaults = array(); $newContact = CRM_Contact_BAO_Contact::retrieve($contact, $defaults); } if (civicrm_error($newContact)) { $contactID = $newContact['error_message']['params'][0]; if (!in_array($contactID, $this->_newContacts)) { $this->_newContacts[] = $contactID; } } //CRM-262 No Duplicate Checking if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) { array_unshift($values, $url_string); $importRecordParams = array($statusFieldName => 'DUPLICATE', "{$statusFieldName}Msg" => "Skipping duplicate record"); $this->updateImportRecord($values[count($values) - 1], $importRecordParams); return CRM_Import_Parser::DUPLICATE; } $importRecordParams = array($statusFieldName => 'IMPORTED'); $this->updateImportRecord($values[count($values) - 1], $importRecordParams); //return warning if street address is not parsed, CRM-5886 return $this->processMessage($values, $statusFieldName, CRM_Import_Parser::VALID); } else { // Not a dupe, so we had an error $errorMessage = $newContact['error_message']; array_unshift($values, $errorMessage); $importRecordParams = array($statusFieldName => 'ERROR', "{$statusFieldName}Msg" => $errorMessage); $this->updateImportRecord($values[count($values) - 1], $importRecordParams); return CRM_Import_Parser::ERROR; } } // sleep(3); return $this->processMessage($values, $statusFieldName, CRM_Import_Parser::VALID); }
/** * This function is called when the form is submitted * * @access public * @return None */ public function postProcess() { // store the submitted values in an array $params = $this->controller->exportValues($this->_name); $quickSave = false; if (CRM_Utils_Array::value('_qf_Relationship_refresh_save', $_POST) || CRM_Utils_Array::value('_qf_Relationship_refresh_savedetails', $_POST)) { $quickSave = true; } $this->set('searchDone', 0); $this->set('callAjax', false); if (CRM_Utils_Array::value('_qf_Relationship_refresh', $_POST) || $quickSave) { if (is_numeric($params['rel_contact_id'])) { if ($quickSave) { $params['contact_check'] = array($params['rel_contact_id'] => 1); } else { $this->search($params); $quickSave = false; } } else { $this->set('callAjax', true); $this->set('relType', $params['relationship_type_id']); $this->set('relContact', $params['rel_contact']); $quickSave = false; } $this->set('searchDone', 1); if (!$quickSave) { return; } } // action is taken depending upon the mode $ids = array(); $ids['contact'] = $this->_contactId; // modify params for ajax call $this->modifyParams($params); if ($this->_action & CRM_Core_Action::DELETE) { CRM_Contact_BAO_Relationship::del($this->_relationshipId); return; } $relationshipTypeId = str_replace(array('_a_b', '_b_a'), array('', ''), $params['relationship_type_id']); if ($this->_action & CRM_Core_Action::UPDATE) { $ids['relationship'] = $this->_relationshipId; $relation = CRM_Contact_BAO_Relationship::getContactIds($this->_relationshipId); $ids['contactTarget'] = $relation->contact_id_a == $this->_contactId ? $relation->contact_id_b : $relation->contact_id_a; //if relationship type change and previously it was //employer / emplyee relationship with current employer //than clear the current employer. CRM-3235. //make sure we has to have employer id before firing queries, CRM-7306 $employerId = CRM_Utils_Array::value('current_employee_id', $this->_values); $isDisabled = true; if (CRM_Utils_Array::value('is_active', $params)) { $isDisabled = false; } $relChanged = true; if ($relationshipTypeId == $this->_values['relationship_type_id']) { $relChanged = false; } if ($employerId && ($isDisabled || $relChanged)) { require_once 'CRM/Contact/BAO/Contact/Utils.php'; CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($this->_values['current_employee_id']); } } elseif ($quickSave) { if ($params['add_current_employee'] && $this->_allRelationshipNames[$relationshipTypeId]["name_a_b"] == 'Employee of') { $params['employee_of'] = $params['rel_contact_id']; } elseif ($params['add_current_employer'] && $this->_allRelationshipNames[$relationshipTypeId]["name_b_a"] == 'Employer of') { $params['employer_of'] = array($params['rel_contact_id'] => 1); } if (!$this->_rtype) { $this->_rtype = str_replace($relationshipTypeId . '_', '', $params['relationship_type_id']); } } $params['start_date'] = CRM_Utils_Date::processDate($params['start_date'], null, true); $params['end_date'] = CRM_Utils_Date::processDate($params['end_date'], null, true); //special case to handle if all checkboxes are unchecked $customFields = CRM_Core_BAO_CustomField::getFields('Relationship', false, false, $relationshipTypeId); $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_relationshipId, 'Relationship'); list($valid, $invalid, $duplicate, $saved, $relationshipIds) = CRM_Contact_BAO_Relationship::create($params, $ids); // if this is called from case view, //create an activity for case role removal.CRM-4480 if ($this->_caseId) { require_once "CRM/Case/BAO/Case.php"; CRM_Case_BAO_Case::createCaseRoleActivity($this->_caseId, $relationshipIds, $params['contact_check'], $this->_contactId); } $status = ''; if ($valid) { $status .= ' ' . ts('%count new relationship record created.', array('count' => $valid, 'plural' => '%count new relationship records created.')); } if ($invalid) { $status .= ' ' . ts('%count relationship record not created due to invalid target contact type.', array('count' => $invalid, 'plural' => '%count relationship records not created due to invalid target contact type.')); } if ($duplicate) { $status .= ' ' . ts('%count relationship record not created - duplicate of existing relationship.', array('count' => $duplicate, 'plural' => '%count relationship records not created - duplicate of existing relationship.')); } if ($saved) { $status .= ts('Relationship record has been updated.'); } $note = new CRM_Core_DAO_Note(); $note->entity_id = $relationshipIds[0]; $note->entity_table = 'civicrm_relationship'; $noteIds = array(); if ($note->find(true)) { $id = $note->id; $noteIds["id"] = $id; } $noteParams = array('entity_id' => $relationshipIds[0], 'entity_table' => 'civicrm_relationship', 'note' => $params['note'], 'contact_id' => $this->_contactId); CRM_Core_BAO_Note::add($noteParams, $noteIds); // Membership for related contacts CRM-1657 if (CRM_Core_Permission::access('CiviMember') && !$duplicate) { CRM_Contact_BAO_Relationship::relatedMemberships($this->_contactId, $params, $ids, $this->_action); } //handle current employee/employer relationship, CRM-3532 if ($this->_allRelationshipNames[$relationshipTypeId]["name_{$this->_rtype}"] == 'Employee of') { $orgId = null; if (CRM_Utils_Array::value('employee_of', $params)) { $orgId = $params['employee_of']; } else { if ($this->_action & CRM_Core_Action::UPDATE) { if (CRM_Utils_Array::value('is_current_employer', $params) && CRM_Utils_Array::value('is_active', $params)) { if (CRM_Utils_Array::value('contactTarget', $ids) != CRM_Utils_Array::value('current_employer_id', $this->_values)) { $orgId = CRM_Utils_Array::value('contactTarget', $ids); } } else { if (CRM_Utils_Array::value('contactTarget', $ids) == CRM_Utils_Array::value('current_employer_id', $this->_values)) { //clear current employer. require_once 'CRM/Contact/BAO/Contact/Utils.php'; CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($this->_contactId); } } } } //set current employer if ($orgId) { $currentEmpParams[$this->_contactId] = $orgId; require_once 'CRM/Contact/BAO/Contact/Utils.php'; CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($currentEmpParams); } } else { if ($this->_allRelationshipNames[$relationshipTypeId]["name_{$this->_rtype}"] == 'Employer of') { $individualIds = array(); if (CRM_Utils_Array::value('employer_of', $params)) { $individualIds = array_keys($params['employer_of']); } else { if ($this->_action & CRM_Core_Action::UPDATE) { if (CRM_Utils_Array::value('is_current_employer', $params)) { if (CRM_Utils_Array::value('contactTarget', $ids) != CRM_Utils_Array::value('current_employee_id', $this->_values)) { $individualIds[] = CRM_Utils_Array::value('contactTarget', $ids); } } else { if (CRM_Utils_Array::value('contactTarget', $ids) == CRM_Utils_Array::value('current_employee_id', $this->_values)) { // clear current employee require_once 'CRM/Contact/BAO/Contact/Utils.php'; CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($ids['contactTarget']); } } } } //set current employee if (!empty($individualIds)) { //build the employee params. foreach ($individualIds as $key => $Id) { $currentEmpParams[$Id] = $this->_contactId; } require_once 'CRM/Contact/BAO/Contact/Utils.php'; CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($currentEmpParams); } } } CRM_Core_Session::setStatus($status); if ($quickSave) { $session =& CRM_Core_Session::singleton(); CRM_Utils_System::redirect($session->popUserContext()); } }
/** * Add on behalf of organization and it's location. * * This situation occurs when on behalf of is enabled for the contribution page and the person * signing up does so on behalf of an organization. * * @param array $behalfOrganization * array of organization info. * @param int $contactID * individual contact id. One. * who is doing the process of signup / contribution. * * @param array $values * form values array. * @param array $params * @param array $fields * Array of fields from the onbehalf profile relevant to the organization. */ public static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params, $fields = NULL) { $isNotCurrentEmployer = FALSE; $dupeIDs = array(); $orgID = NULL; if (!empty($behalfOrganization['organization_id'])) { $orgID = $behalfOrganization['organization_id']; unset($behalfOrganization['organization_id']); } else { // get the Employee relationship type id $relTypeId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b'); // keep relationship params ready $relParams['relationship_type_id'] = $relTypeId . '_a_b'; $relParams['is_permission_a_b'] = 1; $relParams['is_active'] = 1; $isNotCurrentEmployer = TRUE; } // formalities for creating / editing organization. $behalfOrganization['contact_type'] = 'Organization'; if (!$orgID) { // check if matching organization contact exists $dedupeParams = CRM_Dedupe_Finder::formatParams($behalfOrganization, 'Organization'); $dedupeParams['check_permission'] = FALSE; $dupeIDs = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Organization', 'Unsupervised'); // CRM-6243 says to pick the first org even if more than one match if (count($dupeIDs) >= 1) { $behalfOrganization['contact_id'] = $orgID = $dupeIDs[0]; // don't allow name edit unset($behalfOrganization['organization_name']); } } else { // if found permissioned related organization, allow location edit $behalfOrganization['contact_id'] = $orgID; // don't allow name edit unset($behalfOrganization['organization_name']); } // handling for image url if (!empty($behalfOrganization['image_URL'])) { CRM_Contact_BAO_Contact::processImageParams($behalfOrganization); } // create organization, add location $orgID = CRM_Contact_BAO_Contact::createProfileContact($behalfOrganization, $fields, $orgID, NULL, NULL, 'Organization'); // create relationship if ($isNotCurrentEmployer) { $relParams['contact_check'][$orgID] = 1; $cid = array('contact' => $contactID); CRM_Contact_BAO_Relationship::legacyCreateMultiple($relParams, $cid); } // if multiple match - send a duplicate alert if ($dupeIDs && count($dupeIDs) > 1) { $values['onbehalf_dupe_alert'] = 1; // required for IPN $params['onbehalf_dupe_alert'] = 1; } // make sure organization-contact-id is considered for recording // contribution/membership etc.. if ($contactID != $orgID) { // take a note of contact-id, so we can send the // receipt to individual contact as well. // required for mailing/template display ..etc $values['related_contact'] = $contactID; //make this employee of relationship as current //employer / employee relationship, CRM-3532 if ($isNotCurrentEmployer && $orgID != CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id')) { $isNotCurrentEmployer = FALSE; } if (!$isNotCurrentEmployer && $orgID) { //build current employer params $currentEmpParams[$contactID] = $orgID; CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($currentEmpParams); } // contribution / signup will be done using this // organization id. $contactID = $orgID; } }
/** * Function to add on behalf of organization and it's location * * @param $behalfOrganization array array of organization info * @param $values array form values array * @param $contactID int individual contact id. One * who is doing the process of signup / contribution. * * @return void * @access public */ static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params) { $isCurrentEmployer = false; if ($behalfOrganization['organization_id'] && $behalfOrganization['org_option']) { $orgID = $behalfOrganization['organization_id']; unset($behalfOrganization['organization_id']); $isCurrentEmployer = true; } // formalities for creating / editing organization. require_once "CRM/Core/BAO/LocationType.php"; $locType = CRM_Core_BAO_LocationType::getDefault(); $behalfOrganization['contact_type'] = 'Organization'; foreach (array('phone', 'email', 'address') as $locFld) { $behalfOrganization[$locFld][1]['is_primary'] = 1; $behalfOrganization[$locFld][1]['location_type_id'] = $locType->id; } // get the relationship type id require_once "CRM/Contact/DAO/RelationshipType.php"; $relType =& new CRM_Contact_DAO_RelationshipType(); $relType->name_a_b = "Employee of"; $relType->find(true); $relTypeId = $relType->id; // keep relationship params ready $relParams['relationship_type_id'] = $relTypeId . '_a_b'; $relParams['is_permission_a_b'] = 1; $relParams['is_active'] = 1; if (!$orgID) { // check if matching organization contact exists require_once 'CRM/Dedupe/Finder.php'; $dedupeParams = CRM_Dedupe_Finder::formatParams($behalfOrganization, 'Organization'); $dupeIDs = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Organization', 'Strict'); if (count($dupeIDs) == 1) { $behalfOrganization['contact_id'] = $dupeIDs[0]; // don't allow name edit unset($behalfOrganization['organization_name']); } } else { // if found permissioned related organization, allow location edit $behalfOrganization['contact_id'] = $orgID; // don't allow name edit unset($behalfOrganization['organization_name']); } // create organization, add location $org = CRM_Contact_BAO_Contact::create($behalfOrganization); // create relationship $relParams['contact_check'][$org->id] = 1; $cid = array('contact' => $contactID); $relationship = CRM_Contact_BAO_Relationship::create($relParams, $cid); // take a note of new/updated organiation contact-id. $orgID = $org->id; // if multiple match - send a duplicate alert if ($dupeIDs && count($dupeIDs) > 1) { $values['onbehalf_dupe_alert'] = 1; // required for IPN $params['onbehalf_dupe_alert'] = 1; } // make sure organization-contact-id is considered for recording // contribution/membership etc.. if ($contactID != $orgID) { // take a note of contact-id, so we can send the // receipt to individual contact as well. // required for mailing/template display ..etc $values['related_contact'] = $contactID; // required for IPN $params['related_contact'] = $contactID; //make this employee of relationship as current //employer / employee relationship, CRM-3532 if ($isCurrentEmployer && $orgID != CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id')) { $isCurrentEmployer = false; } if (!$isCurrentEmployer && $orgID) { //build current employer params $currentEmpParams[$contactID] = $orgID; require_once 'CRM/Contact/BAO/Contact/Utils.php'; CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($currentEmpParams); } // contribution / signup will be done using this // organization id. $contactID = $orgID; } }
/** * 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. * * @param bool $doGeocodeAddress * * @return bool * the result of this processing */ public function import($onDuplicate, &$values, $doGeocodeAddress = FALSE) { $config = CRM_Core_Config::singleton(); $this->_unparsedStreetAddressContacts = array(); if (!$doGeocodeAddress) { // CRM-5854, reset the geocode method to null to prevent geocoding $config->geocodeMethod = NULL; } // first make sure this is a valid line //$this->_updateWithId = false; $response = $this->summary($values); $statusFieldName = $this->_statusFieldName; if ($response != CRM_Import_Parser::VALID) { $importRecordParams = array($statusFieldName => 'INVALID', "{$statusFieldName}Msg" => "Invalid (Error Code: {$response})"); $this->updateImportRecord($values[count($values) - 1], $importRecordParams); return $response; } $params =& $this->getActiveFieldParams(); $formatted = array('contact_type' => $this->_contactType); static $contactFields = NULL; if ($contactFields == NULL) { $contactFields = CRM_Contact_DAO_Contact::import(); } //check if external identifier exists in database if (!empty($params['external_identifier']) && (!empty($params['id']) || in_array($onDuplicate, array(CRM_Import_Parser::DUPLICATE_SKIP, CRM_Import_Parser::DUPLICATE_NOCHECK)))) { if ($internalCid = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['external_identifier'], 'id', 'external_identifier')) { if ($internalCid != CRM_Utils_Array::value('id', $params)) { $errorMessage = ts('External ID already exists in Database.'); array_unshift($values, $errorMessage); $importRecordParams = array($statusFieldName => 'ERROR', "{$statusFieldName}Msg" => $errorMessage); $this->updateImportRecord($values[count($values) - 1], $importRecordParams); return CRM_Import_Parser::DUPLICATE; } } } if (!empty($this->_contactSubType)) { $params['contact_sub_type'] = $this->_contactSubType; } if ($subType = CRM_Utils_Array::value('contact_sub_type', $params)) { if (CRM_Contact_BAO_ContactType::isExtendsContactType($subType, $this->_contactType, FALSE, 'label')) { $subTypes = CRM_Contact_BAO_ContactType::subTypePairs($this->_contactType, FALSE, NULL); $params['contact_sub_type'] = array_search($subType, $subTypes); } elseif (!CRM_Contact_BAO_ContactType::isExtendsContactType($subType, $this->_contactType)) { $message = "Mismatched or Invalid Contact Subtype."; array_unshift($values, $message); return CRM_Import_Parser::NO_MATCH; } } // Get contact id to format common data in update/fill mode, // prioritising a dedupe rule check over an external_identifier check, but falling back on ext id. if ($this->_updateWithId && empty($params['id'])) { $possibleMatches = $this->getPossibleContactMatches($params); foreach ($possibleMatches as $possibleID) { $params['id'] = $formatted['id'] = $possibleID; } } //format common data, CRM-4062 $this->formatCommonData($params, $formatted, $contactFields); $relationship = FALSE; $createNewContact = TRUE; // Support Match and Update Via Contact ID if ($this->_updateWithId && isset($params['id'])) { $createNewContact = FALSE; // @todo - it feels like all the rows from here to the end of the IF // could be removed in favour of a simple check for whether the contact_type & id match // the call to the deprecated function seems to add no value other that to do an additional // check for the contact_id & type. $error = _civicrm_api3_deprecated_duplicate_formatted_contact($formatted); if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) { $matchedIDs = explode(',', $error['error_message']['params'][0]); if (count($matchedIDs) >= 1) { $updateflag = TRUE; foreach ($matchedIDs as $contactId) { if ($params['id'] == $contactId) { $contactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['id'], 'contact_type'); if ($formatted['contact_type'] == $contactType) { //validation of subtype for update mode //CRM-5125 $contactSubType = NULL; if (!empty($params['contact_sub_type'])) { $contactSubType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['id'], 'contact_sub_type'); } if (!empty($contactSubType) && (!CRM_Contact_BAO_ContactType::isAllowEdit($params['id'], $contactSubType) && $contactSubType != CRM_Utils_Array::value('contact_sub_type', $formatted))) { $message = "Mismatched contact SubTypes :"; array_unshift($values, $message); $updateflag = FALSE; $this->_retCode = CRM_Import_Parser::NO_MATCH; } else { $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 { $contactType = NULL; if (!empty($params['id'])) { $contactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['id'], 'contact_type'); if ($contactType) { if ($formatted['contact_type'] == $contactType) { //validation of subtype for update mode //CRM-5125 $contactSubType = NULL; if (!empty($params['contact_sub_type'])) { $contactSubType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params['id'], 'contact_sub_type'); } if (!empty($contactSubType) && (!CRM_Contact_BAO_ContactType::isAllowEdit($params['id'], $contactSubType) && $contactSubType != CRM_Utils_Array::value('contact_sub_type', $formatted))) { $message = "Mismatched contact SubTypes :"; array_unshift($values, $message); $this->_retCode = CRM_Import_Parser::NO_MATCH; } else { $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $params['id'], FALSE, $this->_dedupeRuleGroupID); $this->_retCode = CRM_Import_Parser::VALID; } } else { $message = "Mismatched contact Types :"; array_unshift($values, $message); $this->_retCode = CRM_Import_Parser::NO_MATCH; } } else { // we should avoid multiple errors for single record // since we have already retCode and we trying to force again. if ($this->_retCode != CRM_Import_Parser::NO_MATCH) { $message = "No contact found for this contact ID:" . $params['id']; array_unshift($values, $message); $this->_retCode = CRM_Import_Parser::NO_MATCH; } } } else { //CRM-4148 //now we want to create new contact on update/fill also. $createNewContact = TRUE; } } if (isset($newContact) && is_a($newContact, 'CRM_Contact_BAO_Contact')) { $relationship = TRUE; } elseif (is_a($error, 'CRM_Core_Error')) { $newContact = $error; $relationship = TRUE; } } //fixed CRM-4148 //now we create new contact in update/fill mode also. $contactID = NULL; if ($createNewContact || $this->_retCode != CRM_Import_Parser::NO_MATCH && $this->_updateWithId) { //CRM-4430, don't carry if not submitted. foreach (array('prefix_id', 'suffix_id', 'gender_id') as $name) { if (!empty($formatted[$name])) { $options = CRM_Contact_BAO_Contact::buildOptions($name, 'get'); if (!isset($options[$formatted[$name]])) { $formatted[$name] = CRM_Utils_Array::key((string) $formatted[$name], $options); } } } if ($this->_updateWithId && !empty($params['id'])) { $contactID = $params['id']; } $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $contactID, TRUE, $this->_dedupeRuleGroupID); } if (isset($newContact) && is_object($newContact) && $newContact instanceof CRM_Contact_BAO_Contact) { $relationship = TRUE; $newContact = clone $newContact; $contactID = $newContact->id; $this->_newContacts[] = $contactID; //get return code if we create new contact in update mode, CRM-4148 if ($this->_updateWithId) { $this->_retCode = CRM_Import_Parser::VALID; } } elseif (isset($newContact) && CRM_Core_Error::isAPIError($newContact, CRM_Core_ERROR::DUPLICATE_CONTACT)) { // if duplicate, no need of further processing if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) { $errorMessage = "Skipping duplicate record"; array_unshift($values, $errorMessage); $importRecordParams = array($statusFieldName => 'DUPLICATE', "{$statusFieldName}Msg" => $errorMessage); $this->updateImportRecord($values[count($values) - 1], $importRecordParams); return CRM_Import_Parser::DUPLICATE; } $relationship = TRUE; # see CRM-10433 - might return comma separate list of all dupes $dupeContactIDs = explode(',', $newContact['error_message']['params'][0]); $dupeCount = count($dupeContactIDs); $contactID = array_pop($dupeContactIDs); // check to see if we had more than one duplicate contact id. // if we have more than one, the record will be rejected below if ($dupeCount == 1) { // there was only one dupe, we will continue normally... if (!in_array($contactID, $this->_newContacts)) { $this->_newContacts[] = $contactID; } } } if ($contactID) { // call import hook $currentImportID = end($values); $hookParams = array('contactID' => $contactID, 'importID' => $currentImportID, 'importTempTable' => $this->_tableName, 'fieldHeaders' => $this->_mapperKeys, 'fields' => $this->_activeFields); CRM_Utils_Hook::import('Contact', 'process', $this, $hookParams); } if ($relationship) { $primaryContactId = NULL; if (CRM_Core_Error::isAPIError($newContact, CRM_Core_ERROR::DUPLICATE_CONTACT)) { if (CRM_Utils_Rule::integer($newContact['error_message']['params'][0])) { $primaryContactId = $newContact['error_message']['params'][0]; } } else { $primaryContactId = $newContact->id; } if ((CRM_Core_Error::isAPIError($newContact, CRM_Core_ERROR::DUPLICATE_CONTACT) || is_a($newContact, 'CRM_Contact_BAO_Contact')) && $primaryContactId) { //relationship contact insert foreach ($params as $key => $field) { list($id, $first, $second) = CRM_Utils_System::explode('_', $key, 3); if (!($first == 'a' && $second == 'b') && !($first == 'b' && $second == 'a')) { continue; } $relationType = new CRM_Contact_DAO_RelationshipType(); $relationType->id = $id; $relationType->find(TRUE); $direction = "contact_sub_type_{$second}"; $formatting = array('contact_type' => $params[$key]['contact_type']); //set subtype for related contact CRM-5125 if (isset($relationType->{$direction})) { //validation of related contact subtype for update mode if ($relCsType = CRM_Utils_Array::value('contact_sub_type', $params[$key]) && $relCsType != $relationType->{$direction}) { $errorMessage = ts("Mismatched or Invalid contact subtype found for this related contact."); array_unshift($values, $errorMessage); return CRM_Import_Parser::NO_MATCH; } else { $formatting['contact_sub_type'] = $relationType->{$direction}; } } $relationType->free(); $contactFields = NULL; $contactFields = CRM_Contact_DAO_Contact::import(); //Relation on the basis of External Identifier. if (empty($params[$key]['id']) && !empty($params[$key]['external_identifier'])) { $params[$key]['id'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params[$key]['external_identifier'], 'id', 'external_identifier'); } // check for valid related contact id in update/fill mode, CRM-4424 if (in_array($onDuplicate, array(CRM_Import_Parser::DUPLICATE_UPDATE, CRM_Import_Parser::DUPLICATE_FILL)) && !empty($params[$key]['id'])) { $relatedContactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params[$key]['id'], 'contact_type'); if (!$relatedContactType) { $errorMessage = ts("No contact found for this related contact ID: %1", array(1 => $params[$key]['id'])); array_unshift($values, $errorMessage); return CRM_Import_Parser::NO_MATCH; } else { //validation of related contact subtype for update mode //CRM-5125 $relatedCsType = NULL; if (!empty($formatting['contact_sub_type'])) { $relatedCsType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $params[$key]['id'], 'contact_sub_type'); } if (!empty($relatedCsType) && (!CRM_Contact_BAO_ContactType::isAllowEdit($params[$key]['id'], $relatedCsType) && $relatedCsType != CRM_Utils_Array::value('contact_sub_type', $formatting))) { $errorMessage = ts("Mismatched or Invalid contact subtype found for this related contact.") . ' ' . ts("ID: %1", array(1 => $params[$key]['id'])); array_unshift($values, $errorMessage); return CRM_Import_Parser::NO_MATCH; } else { // get related contact id to format data in update/fill mode, //if external identifier is present, CRM-4423 $formatting['id'] = $params[$key]['id']; } } } //format common data, CRM-4062 $this->formatCommonData($field, $formatting, $contactFields); //do we have enough fields to create related contact. $allowToCreate = $this->checkRelatedContactFields($key, $formatting); if (!$allowToCreate) { $errorMessage = ts('Related contact required fields are missing.'); array_unshift($values, $errorMessage); return CRM_Import_Parser::NO_MATCH; } //fixed for CRM-4148 if (!empty($params[$key]['id'])) { $contact = array('contact_id' => $params[$key]['id']); $defaults = array(); $relatedNewContact = CRM_Contact_BAO_Contact::retrieve($contact, $defaults); } else { $relatedNewContact = $this->createContact($formatting, $contactFields, $onDuplicate, NULL, FALSE); } if (is_object($relatedNewContact) || $relatedNewContact instanceof CRM_Contact_BAO_Contact) { $relatedNewContact = clone $relatedNewContact; } $matchedIDs = array(); // To update/fill contact, get the matching contact Ids if duplicate contact found // otherwise get contact Id from object of related contact if (is_array($relatedNewContact) && civicrm_error($relatedNewContact)) { if (CRM_Core_Error::isAPIError($relatedNewContact, CRM_Core_ERROR::DUPLICATE_CONTACT)) { $matchedIDs = explode(',', $relatedNewContact['error_message']['params'][0]); } else { $errorMessage = $relatedNewContact['error_message']; array_unshift($values, $errorMessage); $importRecordParams = array($statusFieldName => 'ERROR', "{$statusFieldName}Msg" => $errorMessage); $this->updateImportRecord($values[count($values) - 1], $importRecordParams); return CRM_Import_Parser::ERROR; } } else { $matchedIDs[] = $relatedNewContact->id; } // update/fill related contact after getting matching Contact Ids, CRM-4424 if (in_array($onDuplicate, array(CRM_Import_Parser::DUPLICATE_UPDATE, CRM_Import_Parser::DUPLICATE_FILL))) { //validation of related contact subtype for update mode //CRM-5125 $relatedCsType = NULL; if (!empty($formatting['contact_sub_type'])) { $relatedCsType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $matchedIDs[0], 'contact_sub_type'); } if (!empty($relatedCsType) && (!CRM_Contact_BAO_ContactType::isAllowEdit($matchedIDs[0], $relatedCsType) && $relatedCsType != CRM_Utils_Array::value('contact_sub_type', $formatting))) { $errorMessage = ts("Mismatched or Invalid contact subtype found for this related contact."); array_unshift($values, $errorMessage); return CRM_Import_Parser::NO_MATCH; } else { $updatedContact = $this->createContact($formatting, $contactFields, $onDuplicate, $matchedIDs[0]); } } static $relativeContact = array(); if (CRM_Core_Error::isAPIError($relatedNewContact, CRM_Core_ERROR::DUPLICATE_CONTACT)) { if (count($matchedIDs) >= 1) { $relContactId = $matchedIDs[0]; //add relative contact to count during update & fill mode. //logic to make count distinct by contact id. if ($this->_newRelatedContacts || !empty($relativeContact)) { $reContact = array_keys($relativeContact, $relContactId); if (empty($reContact)) { $this->_newRelatedContacts[] = $relativeContact[] = $relContactId; } } else { $this->_newRelatedContacts[] = $relativeContact[] = $relContactId; } } } else { $relContactId = $relatedNewContact->id; $this->_newRelatedContacts[] = $relativeContact[] = $relContactId; } if (CRM_Core_Error::isAPIError($relatedNewContact, CRM_Core_ERROR::DUPLICATE_CONTACT) || $relatedNewContact instanceof CRM_Contact_BAO_Contact) { //fix for CRM-1993.Checks for duplicate related contacts if (count($matchedIDs) >= 1) { //if more than one duplicate contact //found, create relationship with first contact // now create the relationship record $relationParams = array(); $relationParams = array('relationship_type_id' => $key, 'contact_check' => array($relContactId => 1), 'is_active' => 1, 'skipRecentView' => TRUE); // we only handle related contact success, we ignore failures for now // at some point wold be nice to have related counts as separate $relationIds = array('contact' => $primaryContactId); list($valid, $invalid, $duplicate, $saved, $relationshipIds) = CRM_Contact_BAO_Relationship::legacyCreateMultiple($relationParams, $relationIds); if ($valid || $duplicate) { $relationIds['contactTarget'] = $relContactId; $action = $duplicate ? CRM_Core_Action::UPDATE : CRM_Core_Action::ADD; CRM_Contact_BAO_Relationship::relatedMemberships($primaryContactId, $relationParams, $relationIds, $action); } //handle current employer, CRM-3532 if ($valid) { $allRelationships = CRM_Core_PseudoConstant::relationshipType('name'); $relationshipTypeId = str_replace(array('_a_b', '_b_a'), array('', ''), $key); $relationshipType = str_replace($relationshipTypeId . '_', '', $key); $orgId = $individualId = NULL; if ($allRelationships[$relationshipTypeId]["name_{$relationshipType}"] == 'Employee of') { $orgId = $relContactId; $individualId = $primaryContactId; } elseif ($allRelationships[$relationshipTypeId]["name_{$relationshipType}"] == 'Employer of') { $orgId = $primaryContactId; $individualId = $relContactId; } if ($orgId && $individualId) { $currentEmpParams[$individualId] = $orgId; CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($currentEmpParams); } } } } } } } if ($this->_updateWithId) { //return warning if street address is unparsed, CRM-5886 return $this->processMessage($values, $statusFieldName, $this->_retCode); } //dupe checking if (is_array($newContact) && civicrm_error($newContact)) { $code = NULL; if (($code = CRM_Utils_Array::value('code', $newContact['error_message'])) && $code == CRM_Core_Error::DUPLICATE_CONTACT) { $urls = array(); // need to fix at some stage and decide if the error will return an // array or string, crude hack for now if (is_array($newContact['error_message']['params'][0])) { $cids = $newContact['error_message']['params'][0]; } else { $cids = explode(',', $newContact['error_message']['params'][0]); } foreach ($cids as $cid) { $urls[] = CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $cid, TRUE); } $url_string = implode("\n", $urls); // If we duplicate more than one record, skip no matter what if (count($cids) > 1) { $errorMessage = ts('Record duplicates multiple contacts'); $importRecordParams = array($statusFieldName => 'ERROR', "{$statusFieldName}Msg" => $errorMessage); //combine error msg to avoid mismatch between error file columns. $errorMessage .= "\n" . $url_string; array_unshift($values, $errorMessage); $this->updateImportRecord($values[count($values) - 1], $importRecordParams); return CRM_Import_Parser::ERROR; } // Params only had one id, so shift it out $contactId = array_shift($cids); $cid = NULL; $vals = array('contact_id' => $contactId); if ($onDuplicate == CRM_Import_Parser::DUPLICATE_REPLACE) { civicrm_api('contact', 'delete', $vals); $cid = CRM_Contact_BAO_Contact::createProfileContact($formatted, $contactFields, $contactId, NULL, NULL, $formatted['contact_type']); } elseif ($onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE) { $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $contactId); } elseif ($onDuplicate == CRM_Import_Parser::DUPLICATE_FILL) { $newContact = $this->createContact($formatted, $contactFields, $onDuplicate, $contactId); } // else skip does nothing and just returns an error code. if ($cid) { $contact = array('contact_id' => $cid); $defaults = array(); $newContact = CRM_Contact_BAO_Contact::retrieve($contact, $defaults); } if (civicrm_error($newContact)) { if (empty($newContact['error_message']['params'])) { // different kind of error other than DUPLICATE $errorMessage = $newContact['error_message']; array_unshift($values, $errorMessage); $importRecordParams = array($statusFieldName => 'ERROR', "{$statusFieldName}Msg" => $errorMessage); $this->updateImportRecord($values[count($values) - 1], $importRecordParams); return CRM_Import_Parser::ERROR; } $contactID = $newContact['error_message']['params'][0]; if (!in_array($contactID, $this->_newContacts)) { $this->_newContacts[] = $contactID; } } //CRM-262 No Duplicate Checking if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) { array_unshift($values, $url_string); $importRecordParams = array($statusFieldName => 'DUPLICATE', "{$statusFieldName}Msg" => "Skipping duplicate record"); $this->updateImportRecord($values[count($values) - 1], $importRecordParams); return CRM_Import_Parser::DUPLICATE; } $importRecordParams = array($statusFieldName => 'IMPORTED'); $this->updateImportRecord($values[count($values) - 1], $importRecordParams); //return warning if street address is not parsed, CRM-5886 return $this->processMessage($values, $statusFieldName, CRM_Import_Parser::VALID); } else { // Not a dupe, so we had an error $errorMessage = $newContact['error_message']; array_unshift($values, $errorMessage); $importRecordParams = array($statusFieldName => 'ERROR', "{$statusFieldName}Msg" => $errorMessage); $this->updateImportRecord($values[count($values) - 1], $importRecordParams); return CRM_Import_Parser::ERROR; } } // sleep(3); return $this->processMessage($values, $statusFieldName, CRM_Import_Parser::VALID); }
/** * This function is called when the form is submitted. */ public function postProcess() { // Store the submitted values in an array. $params = $this->controller->exportValues($this->_name); // CRM-14612 - Don't use adv-checkbox as it interferes with the form js $params['is_permission_a_b'] = CRM_Utils_Array::value('is_permission_a_b', $params, 0); $params['is_permission_b_a'] = CRM_Utils_Array::value('is_permission_b_a', $params, 0); // action is taken depending upon the mode if ($this->_action & CRM_Core_Action::DELETE) { CRM_Contact_BAO_Relationship::del($this->_relationshipId); // CRM-15881 UPDATES // Since the line above nullifies the organization_name and employer_id fiels in the contact record, we need to reload all blocks to reflect this chage on the user interface. $this->ajaxResponse['reloadBlocks'] = array('#crm-contactinfo-content'); return; } $relationshipTypeParts = explode('_', $params['relationship_type_id']); $params['relationship_type_id'] = $relationshipTypeParts[0]; if (!$this->_rtype) { // Do we need to wrap this in an if - when is rtype used & is relationship_type_id always set then? $this->_rtype = $params['relationship_type_id']; } $params['contact_id_' . $relationshipTypeParts[1]] = $this->_contactId; // Update mode (always single) if ($this->_action & CRM_Core_Action::UPDATE) { $update = TRUE; $params['id'] = $this->_relationshipId; $ids['relationship'] = $this->_relationshipId; $relation = CRM_Contact_BAO_Relationship::getRelationshipByID($this->_relationshipId); if ($relation->contact_id_a == $this->_contactId) { // I couldn't replicate this path in testing. See below. $params['contact_id_a'] = $this->_contactId; $params['contact_id_b'] = array($params['related_contact_id']); $outcome = CRM_Contact_BAO_Relationship::createMultiple($params, $relationshipTypeParts[1]); $relationshipIds = $outcome['relationship_ids']; } else { // The only reason we have changed this to use the api & not the above is that this was broken. // Recommend extracting all of update into a function that uses the api // and ensuring api / bao take care of 'other stuff' in this form // the contact_id_a & b can't be changed on this form so don't really need setting. $params['contact_id_b'] = $this->_contactId; $params['contact_id_a'] = $params['related_contact_id']; $result = civicrm_api3('relationship', 'create', $params); $relationshipIds = array($result['id']); } $ids['contactTarget'] = $relation->contact_id_a == $this->_contactId ? $relation->contact_id_b : $relation->contact_id_a; // @todo this belongs in the BAO. if ($this->_isCurrentEmployer) { // if relationship type changes, relationship is disabled, or "current employer" is unchecked, // clear the current employer. CRM-3235. $relChanged = $params['relationship_type_id'] != $this->_values['relationship_type_id']; if (!$params['is_active'] || !$params['is_current_employer'] || $relChanged) { // CRM-15881 UPDATES // If not is_active then is_current_employer needs to be set false as well! Logically a contact cannot be a current employee of a disabled employer relationship. // If this is not done, then the below process will go ahead and disable the organization_name and employer_id fields in the contact record (which is what is wanted) but then further down will be re-enabled becuase is_current_employer is not false, therefore undoing what was done correctly. if (!$params['is_active']) { $params['is_current_employer'] = FALSE; } CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($this->_values['contact_id_a']); // Refresh contact summary if in ajax mode $this->ajaxResponse['reloadBlocks'] = array('#crm-contactinfo-content'); } } if (empty($outcome['saved']) && !empty($update)) { $outcome['saved'] = $update; } $this->setMessage($outcome); } else { $params['contact_id_' . $relationshipTypeParts[2]] = explode(',', $params['related_contact_id']); $outcome = CRM_Contact_BAO_Relationship::createMultiple($params, $relationshipTypeParts[1]); $relationshipIds = $outcome['relationship_ids']; if (empty($outcome['saved']) && !empty($update)) { $outcome['saved'] = $update; } $this->setMessage($outcome); } // if this is called from case view, //create an activity for case role removal.CRM-4480 // @todo this belongs in the BAO. if ($this->_caseId) { CRM_Case_BAO_Case::createCaseRoleActivity($this->_caseId, $relationshipIds, $params['contact_check'], $this->_contactId); } // Save notes // @todo this belongs in the BAO. if ($this->_action & CRM_Core_Action::UPDATE || $params['note']) { foreach ($relationshipIds as $id) { $noteParams = array('entity_id' => $id, 'entity_table' => 'civicrm_relationship'); $existing = civicrm_api3('note', 'get', $noteParams); if (!empty($existing['id'])) { $noteParams['id'] = $existing['id']; } $noteParams['note'] = $params['note']; $noteParams['contact_id'] = $this->_contactId; if (!empty($existing['id']) || $params['note']) { $action = $params['note'] ? 'create' : 'delete'; civicrm_api3('note', $action, $noteParams); } } } $params['relationship_ids'] = $relationshipIds; // Refresh contact tabs which might have been affected $this->ajaxResponse['updateTabs'] = array('#tab_member' => CRM_Contact_BAO_Contact::getCountComponent('membership', $this->_contactId), '#tab_contribute' => CRM_Contact_BAO_Contact::getCountComponent('contribution', $this->_contactId)); // Set current employee/employer relationship, CRM-3532 if ($params['is_current_employer'] && $this->_allRelationshipNames[$params['relationship_type_id']]["name_a_b"] == 'Employee of') { $employerParams = array(); foreach ($relationshipIds as $id) { // Fixme this is dumb why do we have to look this up again? $rel = CRM_Contact_BAO_Relationship::getRelationshipByID($id); $employerParams[$rel->contact_id_a] = $rel->contact_id_b; } // @todo this belongs in the BAO. CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($employerParams); // Refresh contact summary if in ajax mode $this->ajaxResponse['reloadBlocks'] = array('#crm-contactinfo-content'); } }
/** * This function is called when the form is submitted * * @access public * * @return None */ public function postProcess() { $quickSave = FALSE; if (CRM_Utils_Array::value('_qf_Relationship_refresh_save', $_POST) || CRM_Utils_Array::value('_qf_Relationship_refresh_savedetails', $_POST)) { //CRM-15873 //Parse custom file uploads $pageName = $this->getAttribute('name'); $data =& $this->controller->container(); foreach ($this->controller->get('uploadNames') as $name) { $this->controller->_actions['upload']->upload($this, $data, $pageName, $name); } $quickSave = TRUE; } // store the submitted values in an array $params = $this->controller->exportValues($this->_name); $this->set('searchDone', 0); $this->set('callAjax', FALSE); if (CRM_Utils_Array::value('_qf_Relationship_refresh', $_POST) || $quickSave) { if (is_numeric($params['contact_select_id'][1])) { if ($quickSave) { $params['contact_check'] = array($params['contact_select_id'][1] => 1); } } else { $this->set('callAjax', TRUE); $this->set('relType', $params['relationship_type_id']); $this->set('relContact', $params['contact'][1]); $quickSave = FALSE; } $this->set('searchDone', 1); if (!$quickSave) { return; } } // action is taken depending upon the mode $ids = array(); $ids['contact'] = $this->_contactId; // modify params for ajax call $this->modifyParams($params); if ($this->_action & CRM_Core_Action::DELETE) { CRM_Contact_BAO_Relationship::del($this->_relationshipId); return; } $relationshipTypeId = str_replace(array('_a_b', '_b_a'), array('', ''), $params['relationship_type_id']); if ($this->_action & CRM_Core_Action::UPDATE) { $ids['relationship'] = $this->_relationshipId; $relation = CRM_Contact_BAO_Relationship::getContactIds($this->_relationshipId); $ids['contactTarget'] = $relation->contact_id_a == $this->_contactId ? $relation->contact_id_b : $relation->contact_id_a; //if relationship type change and previously it was //employer / emplyee relationship with current employer //than clear the current employer. CRM-3235. //make sure we has to have employer id before firing queries, CRM-7306 $employerId = CRM_Utils_Array::value('current_employee_id', $this->_values); $isDisabled = TRUE; if (CRM_Utils_Array::value('is_active', $params)) { $isDisabled = FALSE; } $relChanged = TRUE; if ($relationshipTypeId == $this->_values['relationship_type_id']) { $relChanged = FALSE; } if ($employerId && ($isDisabled || $relChanged)) { CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($this->_values['current_employee_id']); } //if field key doesn't exists in params that means the user has unchecked checkbox, //hence fill FALSE to params $params['is_active'] = $isDisabled ? FALSE : TRUE; $params['is_permission_a_b'] = CRM_Utils_Array::value('is_permission_a_b', $params, FALSE); $params['is_permission_b_a'] = CRM_Utils_Array::value('is_permission_b_a', $params, FALSE); } elseif ($quickSave) { if (CRM_Utils_Array::value('add_current_employee', $params) && $this->_allRelationshipNames[$relationshipTypeId]['name_a_b'] == 'Employee of') { $params['employee_of'] = $params['contact_select_id'][1]; } elseif (CRM_Utils_Array::value('add_current_employer', $params) && $this->_allRelationshipNames[$relationshipTypeId]['name_b_a'] == 'Employer of') { $params['employer_of'] = array($params['contact_select_id'][1] => 1); } if (!$this->_rtype) { $this->_rtype = str_replace($relationshipTypeId . '_', '', $params['relationship_type_id']); } } if (!$params['note']) { $params['note'] = 'null'; } $params['start_date'] = CRM_Utils_Date::processDate($params['start_date'], NULL, TRUE); $params['end_date'] = CRM_Utils_Date::processDate($params['end_date'], NULL, TRUE); //special case to handle if all checkboxes are unchecked $customFields = CRM_Core_BAO_CustomField::getFields('Relationship', FALSE, FALSE, $relationshipTypeId); $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_relationshipId, 'Relationship'); list($valid, $invalid, $duplicate, $saved, $relationshipIds) = CRM_Contact_BAO_Relationship::create($params, $ids); // if this is called from case view, //create an activity for case role removal.CRM-4480 if ($this->_caseId) { CRM_Case_BAO_Case::createCaseRoleActivity($this->_caseId, $relationshipIds, $params['contact_check'], $this->_contactId); } $status = ''; if ($valid) { CRM_Core_Session::setStatus(ts('New relationship created.', array('count' => $valid, 'plural' => '%count new relationships created.')), ts('Saved'), 'success'); } if ($invalid) { CRM_Core_Session::setStatus(ts('%count relationship record was not created due to an invalid target contact type.', array('count' => $invalid, 'plural' => '%count relationship records were not created due to invalid target contact types.')), ts('%count invalid relationship record', array('count' => $invalid, 'plural' => '%count invalid relationship records'))); } if ($duplicate) { CRM_Core_Session::setStatus(ts('One relationship was not created because it already exists.', array('count' => $duplicate, 'plural' => '%count relationships were not created because they already exist.')), ts('%count duplicate relationship', array('count' => $duplicate, 'plural' => '%count duplicate relationships'))); } if ($saved) { CRM_Core_Session::setStatus(ts('Relationship record has been updated.'), ts('Saved'), 'success'); } if (!empty($relationshipIds)) { $note = new CRM_Core_DAO_Note(); $note->entity_id = $relationshipIds[0]; $note->entity_table = 'civicrm_relationship'; $noteIds = array(); if ($note->find(TRUE)) { $id = $note->id; $noteIds['id'] = $id; } $noteParams = array('entity_id' => $relationshipIds[0], 'entity_table' => 'civicrm_relationship', 'note' => $params['note'], 'contact_id' => $this->_contactId); CRM_Core_BAO_Note::add($noteParams, $noteIds); $params['relationship_ids'] = $relationshipIds; } // Membership for related contacts CRM-1657 if (CRM_Core_Permission::access('CiviMember') && !$duplicate) { if ($this->_action & CRM_Core_Action::ADD) { CRM_Contact_BAO_Relationship::relatedMemberships($this->_contactId, $params, $ids, $this->_action); } elseif ($this->_action & CRM_Core_Action::UPDATE) { //fixes for CRM-7985 //only if the relationship has been toggled to enable /disable if (CRM_Utils_Array::value('is_active', $params) != $this->_enabled) { $active = CRM_Utils_Array::value('is_active', $params) ? CRM_Core_Action::ENABLE : CRM_Core_Action::DISABLE; CRM_Contact_BAO_Relationship::disableEnableRelationship($this->_relationshipId, $active); } } } //handle current employee/employer relationship, CRM-3532 if ($this->_allRelationshipNames[$relationshipTypeId]["name_{$this->_rtype}"] == 'Employee of') { $orgId = NULL; if (CRM_Utils_Array::value('employee_of', $params)) { $orgId = $params['employee_of']; } elseif ($this->_action & CRM_Core_Action::UPDATE) { if (CRM_Utils_Array::value('is_current_employer', $params) && CRM_Utils_Array::value('is_active', $params)) { if (CRM_Utils_Array::value('contactTarget', $ids) != CRM_Utils_Array::value('current_employer_id', $this->_values)) { $orgId = CRM_Utils_Array::value('contactTarget', $ids); } } elseif (CRM_Utils_Array::value('contactTarget', $ids) == CRM_Utils_Array::value('current_employer_id', $this->_values)) { //clear current employer. CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($this->_contactId); } } //set current employer if ($orgId) { $currentEmpParams[$this->_contactId] = $orgId; CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($currentEmpParams); } } elseif ($this->_allRelationshipNames[$relationshipTypeId]["name_{$this->_rtype}"] == 'Employer of') { $individualIds = array(); if (CRM_Utils_Array::value('employer_of', $params)) { $individualIds = array_keys($params['employer_of']); } elseif ($this->_action & CRM_Core_Action::UPDATE) { if (CRM_Utils_Array::value('is_current_employer', $params)) { if (CRM_Utils_Array::value('contactTarget', $ids) != CRM_Utils_Array::value('current_employee_id', $this->_values)) { $individualIds[] = CRM_Utils_Array::value('contactTarget', $ids); } } elseif (CRM_Utils_Array::value('contactTarget', $ids) == CRM_Utils_Array::value('current_employee_id', $this->_values)) { // clear current employee CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($ids['contactTarget']); } } //set current employee if (!empty($individualIds)) { //build the employee params. foreach ($individualIds as $key => $Id) { $currentEmpParams[$Id] = $this->_contactId; } CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($currentEmpParams); } } if ($quickSave) { $session = CRM_Core_Session::singleton(); CRM_Utils_System::redirect($session->popUserContext()); } }
/** * This function is called when the form is submitted * * @access public * * @return void */ public function postProcess() { // store the submitted values in an array $params = $this->controller->exportValues($this->_name); // action is taken depending upon the mode if ($this->_action & CRM_Core_Action::DELETE) { CRM_Contact_BAO_Relationship::del($this->_relationshipId); return; } $ids = array('contact' => $this->_contactId); $relationshipTypeId = str_replace(array('_', 'a', 'b'), '', $params['relationship_type_id']); // CRM-14612 - Don't use adv-checkbox as it interferes with the form js $params['is_permission_a_b'] = CRM_Utils_Array::value('is_permission_a_b', $params, 0); $params['is_permission_b_a'] = CRM_Utils_Array::value('is_permission_b_a', $params, 0); // Update mode (always single) if ($this->_action & CRM_Core_Action::UPDATE) { $ids['relationship'] = $this->_relationshipId; $relation = CRM_Contact_BAO_Relationship::getContactIds($this->_relationshipId); $ids['contactTarget'] = $relation->contact_id_a == $this->_contactId ? $relation->contact_id_b : $relation->contact_id_a; if ($this->_isCurrentEmployer) { // if relationship type changes, relationship is disabled, or "current employer" is unchecked, // clear the current employer. CRM-3235. $relChanged = $relationshipTypeId != $this->_values['relationship_type_id']; if (!$params['is_active'] || !$params['is_current_employer'] || $relChanged) { CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($this->_values['contact_id_a']); // Refresh contact summary if in ajax mode $this->ajaxResponse['reloadBlocks'] = array('#crm-contactinfo-content'); } } } else { // Fill up this weird param with contact ids like the weird relationship bao expects $params['contact_check'] = array_fill_keys(explode(',', $params['related_contact_id']), 1); if (!$this->_rtype) { list(, $this->_rtype) = explode('_', $params['relationship_type_id'], 2); } } $params['start_date'] = CRM_Utils_Date::processDate($params['start_date'], NULL, TRUE); $params['end_date'] = CRM_Utils_Date::processDate($params['end_date'], NULL, TRUE); // Process custom data $customFields = CRM_Core_BAO_CustomField::getFields('Relationship', FALSE, FALSE, $relationshipTypeId); $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_relationshipId, 'Relationship'); // Save relationships list($valid, $invalid, $duplicate, $saved, $relationshipIds) = CRM_Contact_BAO_Relationship::create($params, $ids); // if this is called from case view, //create an activity for case role removal.CRM-4480 if ($this->_caseId) { CRM_Case_BAO_Case::createCaseRoleActivity($this->_caseId, $relationshipIds, $params['contact_check'], $this->_contactId); } if ($valid) { CRM_Core_Session::setStatus(ts('Relationship created.', array('count' => $valid, 'plural' => '%count relationships created.')), ts('Saved'), 'success'); } if ($invalid) { CRM_Core_Session::setStatus(ts('%count relationship record was not created due to an invalid contact type.', array('count' => $invalid, 'plural' => '%count relationship records were not created due to invalid contact types.')), ts('%count invalid relationship record', array('count' => $invalid, 'plural' => '%count invalid relationship records'))); } if ($duplicate) { CRM_Core_Session::setStatus(ts('One relationship was not created because it already exists.', array('count' => $duplicate, 'plural' => '%count relationships were not created because they already exist.')), ts('%count duplicate relationship', array('count' => $duplicate, 'plural' => '%count duplicate relationships'))); } if ($saved) { CRM_Core_Session::setStatus(ts('Relationship record has been updated.'), ts('Saved'), 'success'); } // Save notes if ($this->_action & CRM_Core_Action::UPDATE || $params['note']) { foreach ($relationshipIds as $id) { $noteParams = array('entity_id' => $id, 'entity_table' => 'civicrm_relationship'); $existing = civicrm_api3('note', 'get', $noteParams); if (!empty($existing['id'])) { $noteParams['id'] = $existing['id']; } $noteParams['note'] = $params['note']; $noteParams['contact_id'] = $this->_contactId; if (!empty($existing['id']) || $params['note']) { $action = $params['note'] ? 'create' : 'delete'; civicrm_api3('note', $action, $noteParams); } } } // Membership for related contacts CRM-1657 if (CRM_Core_Permission::access('CiviMember') && !$duplicate) { $params['relationship_ids'] = $relationshipIds; if ($this->_action & CRM_Core_Action::ADD) { CRM_Contact_BAO_Relationship::relatedMemberships($this->_contactId, $params, $ids, $this->_action); } elseif ($this->_action & CRM_Core_Action::UPDATE) { //fixes for CRM-7985 //only if the relationship has been toggled to enable /disable if (CRM_Utils_Array::value('is_active', $params) != $this->_enabled) { $active = !empty($params['is_active']) ? CRM_Core_Action::ENABLE : CRM_Core_Action::DISABLE; CRM_Contact_BAO_Relationship::disableEnableRelationship($this->_relationshipId, $active); } } // Refresh contact tabs with related data $this->ajaxResponse['updateTabs'] = array('#tab_member' => CRM_Contact_BAO_Contact::getCountComponent('membership', $this->_contactId)); } // Set current employee/employer relationship, CRM-3532 if ($params['is_current_employer'] && $this->_allRelationshipNames[$relationshipTypeId]["name_a_b"] == 'Employee of') { $employerParams = array(); foreach ($relationshipIds as $id) { // Fixme this is dumb why do we have to look this up again? $rel = CRM_Contact_BAO_Relationship::getContactIds($id); $employerParams[$rel->contact_id_a] = $rel->contact_id_b; } CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($employerParams); // Refresh contact summary if in ajax mode $this->ajaxResponse['reloadBlocks'] = array('#crm-contactinfo-content'); } }