/** * Add or update a relationship * * @param array $params input parameters * * @throws API_Exception * @example RelationshipCreate.php Std Create example * * @return array API Result Array * {@getfields relationship_create} * @static void * @access public */ function civicrm_api3_relationship_create($params) { $values = array(); _civicrm_api3_relationship_format_params($params, $values); $ids = array(); $action = CRM_Core_Action::ADD; if (!empty($params['id'])) { $ids['contactTarget'] = $values['contact_id_b']; $action = CRM_Core_Action::UPDATE; } $values['relationship_type_id'] = $values['relationship_type_id'] . '_a_b'; if (!empty($params['contact_id_b'])) { $values['contact_check'] = array($params['contact_id_b'] => $params['contact_id_b']); } if (!empty($values['contact_id_a'])) { $ids['contact'] = $values['contact_id_a']; } $relationshipBAO = CRM_Contact_BAO_Relationship::create($values, $ids); if ($relationshipBAO[1]) { throw new API_Exception('Relationship is not valid'); } elseif ($relationshipBAO[2]) { throw new API_Exception('Relationship already exists'); } // Handle related memberships CRM-13652 if (!empty($params['contact_id_a'])) { CRM_Contact_BAO_Relationship::relatedMemberships($params['contact_id_a'], $values, $ids, $action); } $id = $relationshipBAO[4][0]; $values = array(); _civicrm_api3_object_to_array($relationshipBAO[5][$id], $values[$id]); return civicrm_api3_create_success($values, $params, 'relationship', 'create'); }
/** * Add or update a relationship * * @param array $params input parameters * * @example RelationshipCreate.php Std Create example * * @return array API Result Array * {@getfields relationship_create} * @static void * @access public * */ function civicrm_api3_relationship_create($params) { // check entities exist $orig_values = _civicrm_api3_relationship_check_params($params); $values = array(); _civicrm_api3_relationship_format_params($params, $values); $ids = array(); require_once 'CRM/Core/Action.php'; $action = CRM_Core_Action::ADD; require_once 'CRM/Utils/Array.php'; if (CRM_Utils_Array::value('id', $params)) { $params = array_merge($params, $orig_values); $ids['relationship'] = $params['id']; $ids['contactTarget'] = $params['contact_id_b']; $action = CRM_Core_Action::UPDATE; } $values['relationship_type_id'] = $params['relationship_type_id'] . '_a_b'; $values['contact_check'] = array($params['contact_id_b'] => $params['contact_id_b']); $ids['contact'] = $params['contact_id_a']; $relationshipBAO = CRM_Contact_BAO_Relationship::create($values, $ids); if ($relationshipBAO[1]) { return civicrm_api3_create_error('Relationship is not valid'); } elseif ($relationshipBAO[2]) { return civicrm_api3_create_error('Relationship already exists'); } CRM_Contact_BAO_Relationship::relatedMemberships($params['contact_id_a'], $values, $ids, $action); $relationID = $relationshipBAO[4][0]; return civicrm_api3_create_success(array($relationID => array('id' => $relationID, 'moreIDs' => implode(',', $relationshipBAO[4])))); }
/** * Add or update a relationship * * @param array $params (reference ) input parameters * * @return array (reference) id of created or updated record * @static void * @access public */ function civicrm_relationship_create(&$params) { _civicrm_initialize(); if (empty($params)) { return civicrm_create_error('No input parameter present'); } if (!is_array($params)) { return civicrm_create_error(ts('Input parameter is not an array')); } if (!isset($params['contact_id_a']) && !isset($params['contact_id_b']) && !isset($params['relationship_type_id'])) { return civicrm_create_error(ts('Missing required parameters')); } $values = array(); require_once 'CRM/Contact/BAO/Relationship.php'; $error = _civicrm_relationship_format_params($params, $values); if (civicrm_error($error)) { return $error; } $ids = array(); require_once 'CRM/Utils/Array.php'; if (CRM_Utils_Array::value('id', $params)) { $ids['relationship'] = $params['id']; $ids['contactTarget'] = $params['contact_id_b']; } $values['relationship_type_id'] = $params['relationship_type_id'] . '_a_b'; $values['contact_check'] = array($params['contact_id_b'] => $params['contact_id_b']); $ids['contact'] = $params['contact_id_a']; $relationshipBAO = CRM_Contact_BAO_Relationship::create($values, $ids); if (is_a($relationshipBAO, 'CRM_Core_Error')) { return civicrm_create_error("Relationship can not be created"); } else { if ($relationshipBAO[1]) { return civicrm_create_error("Relationship is not valid"); } else { if ($relationshipBAO[2]) { return civicrm_create_error("Relationship already exist"); } } } return civicrm_create_success(array('id' => implode(",", $relationshipBAO[4]))); }
/** * Add or update a relationship * * @param array $params (reference ) input parameters * * @return array (reference) id of created or updated record * @static void * @access public */ function civicrm_relationship_create(&$params) { _civicrm_initialize(); // check params for required fields (add/update) $error = _civicrm_relationship_check_params($params); if (civicrm_error($error)) { return $error; } $values = array(); require_once 'CRM/Contact/BAO/Relationship.php'; $error = _civicrm_relationship_format_params($params, $values); if (civicrm_error($error)) { return $error; } $ids = array(); require_once 'CRM/Utils/Array.php'; if (CRM_Utils_Array::value('id', $params)) { $ids['relationship'] = $params['id']; $ids['contactTarget'] = $params['contact_id_b']; } $values['relationship_type_id'] = $params['relationship_type_id'] . '_a_b'; $values['contact_check'] = array($params['contact_id_b'] => $params['contact_id_b']); $ids['contact'] = $params['contact_id_a']; $relationshipBAO = CRM_Contact_BAO_Relationship::create($values, $ids); if (is_a($relationshipBAO, 'CRM_Core_Error')) { return civicrm_create_error('Relationship can not be created'); } else { if ($relationshipBAO[1]) { return civicrm_create_error('Relationship is not valid'); } else { if ($relationshipBAO[2]) { return civicrm_create_error('Relationship already exists'); } } } return civicrm_create_success(array('id' => implode(',', $relationshipBAO[4]))); }
static function relationship(&$config) { // CRM_Core_Error::debug_var( 'GET' , $_GET , true, true ); // CRM_Core_Error::debug_var( 'POST', $_POST, true, true ); $relType = CRM_Utils_Array::value('rel_type', $_POST); $relContactID = CRM_Utils_Array::value('rel_contact', $_POST); $sourceContactID = CRM_Utils_Array::value('contact_id', $_POST); $relationshipID = CRM_Utils_Array::value('rel_id', $_POST); $caseID = CRM_Utils_Array::value('case_id', $_POST); $relationParams = array('relationship_type_id' => $relType . '_a_b', 'contact_check' => array($relContactID => 1), 'is_active' => 1, 'case_id' => $caseID, 'start_date' => date("Ymd")); if ($relationshipID == 'null') { $relationIds = array('contact' => $sourceContactID); } else { $relationIds = array('contact' => $sourceContactID, 'relationship' => $relationshipID, 'contactTarget' => $relContactID); } require_once "CRM/Contact/BAO/Relationship.php"; $return = CRM_Contact_BAO_Relationship::create($relationParams, $relationIds); $relationshipID = $return[4][0]; // we should return phone and email require_once "CRM/Case/BAO/Case.php"; $caseRelationship = CRM_Case_BAO_Case::getCaseRoles($sourceContactID, $caseID, $relationshipID); //create an activity for case role assignment.CRM-4480 CRM_Case_BAO_Case::createCaseRoleActivity($caseID, $relationshipID, $relContactID); $relation = $caseRelationship[$relationshipID]; $relation['rel_id'] = $relationshipID; echo json_encode($relation); exit; }
/** * Create Current employer relationship for a individual * * @param int $contactID contact id of the individual * @param $organizationId * @param null $previousEmployerID * * @internal param string $organization it can be name or id of organization * * @access public * @static */ static function createCurrentEmployerRelationship($contactID, $organizationId, $previousEmployerID = NULL, $newContact = FALSE) { if ($organizationId && is_numeric($organizationId)) { $cid = array('contact' => $contactID); // get the relationship type id of "Employee of" $relTypeId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b'); if (!$relTypeId) { CRM_Core_Error::fatal(ts("You seem to have deleted the relationship type 'Employee of'")); } // create employee of relationship $relationshipParams = array('is_active' => TRUE, 'relationship_type_id' => $relTypeId . '_a_b', 'contact_check' => array($organizationId => TRUE)); list($valid, $invalid, $duplicate, $saved, $relationshipIds) = CRM_Contact_BAO_Relationship::create($relationshipParams, $cid); // In case we change employer, clean previous employer related records. if (!$previousEmployerID && !$newContact) { $previousEmployerID = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id'); } if ($previousEmployerID && $previousEmployerID != $organizationId) { self::clearCurrentEmployer($contactID, $previousEmployerID); } // set current employer self::setCurrentEmployer(array($contactID => $organizationId)); $relationshipParams['relationship_ids'] = $relationshipIds; // handle related meberships. CRM-3792 self::currentEmployerRelatedMembership($contactID, $organizationId, $relationshipParams, $duplicate, $previousEmployerID); } }
static function relationship() { $relType = CRM_Utils_Array::value('rel_type', $_POST); $relContactID = CRM_Utils_Array::value('rel_contact', $_POST); $sourceContactID = CRM_Utils_Array::value('contact_id', $_POST); $relationshipID = CRM_Utils_Array::value('rel_id', $_POST); $caseID = CRM_Utils_Array::value('case_id', $_POST); $relationParams = array('relationship_type_id' => $relType . '_a_b', 'contact_check' => array($relContactID => 1), 'is_active' => 1, 'case_id' => $caseID, 'start_date' => date("Ymd")); $relationIds = array('contact' => $sourceContactID); if ($relationshipID && $relationshipID != 'null') { $relationIds['relationship'] = $relationshipID; $relationIds['contactTarget'] = $relContactID; } $return = CRM_Contact_BAO_Relationship::create($relationParams, $relationIds); $status = 'process-relationship-fail'; if (CRM_Utils_Array::value(0, $return[4])) { $relationshipID = $return[4][0]; $status = 'process-relationship-success'; } $caseRelationship = array(); if ($relationshipID && $relationshipID != 'null') { // we should return phone and email $caseRelationship = CRM_Case_BAO_Case::getCaseRoles($sourceContactID, $caseID, $relationshipID); //create an activity for case role assignment.CRM-4480 CRM_Case_BAO_Case::createCaseRoleActivity($caseID, $relationshipID, $relContactID); } $relation = CRM_Utils_Array::value($relationshipID, $caseRelationship, array()); $relation['rel_id'] = $relationshipID; $relation['status'] = $status; echo json_encode($relation); CRM_Utils_System::civiExit(); }
/** * Create Current employer relationship for a individual * * @param int $contactID contact id of the individual * @param string $organization it can be name or id of organization * * @access public * @static */ static function createCurrentEmployerRelationship($contactID, $organization) { require_once 'CRM/Contact/BAO/Relationship.php'; $organizationId = null; // if organization id is passed. if (is_numeric($organization)) { $organizationId = $organization; } else { $orgName = explode('::', $organization); trim($orgName[0]); $organizationParams = array(); $organizationParams['organization_name'] = $orgName[0]; require_once 'CRM/Dedupe/Finder.php'; $dedupeParams = CRM_Dedupe_Finder::formatParams($organizationParams, 'Organization'); $dedupeParams['check_permission'] = false; $dupeIDs = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Organization', 'Fuzzy'); if (is_array($dupeIDs) && !empty($dupeIDs)) { // we should create relationship only w/ first org CRM-4193 foreach ($dupeIDs as $orgId) { $organizationId = $orgId; break; } } else { //create new organization $newOrg = array('contact_type' => 'Organization', 'organization_name' => trim($orgName[0])); $org = CRM_Contact_BAO_Contact::add($newOrg); $organizationId = $org->id; } } if ($organizationId) { $cid = array('contact' => $contactID); // get the relationship type id of "Employee of" $relTypeId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b'); if (!$relTypeId) { CRM_Core_Error::fatal(ts("You seem to have deleted the relationship type 'Employee of'")); } // create employee of relationship $relationshipParams = array('is_active' => true, 'relationship_type_id' => $relTypeId . '_a_b', 'contact_check' => array($organizationId => true)); list($valid, $invalid, $duplicate, $saved, $relationshipIds) = CRM_Contact_BAO_Relationship::create($relationshipParams, $cid); // In case we change employer, clean prveovious employer related records. $previousEmployerID = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id'); if ($previousEmployerID && $previousEmployerID != $organizationId) { self::clearCurrentEmployer($contactID, $previousEmployerID); } // set current employer self::setCurrentEmployer(array($contactID => $organizationId)); // handle related meberships. CRM-3792 self::currentEmployerRelatedMembership($contactID, $organizationId, $relationshipParams, $duplicate); } }
/** * This function is called when the form is submitted * * @access public * @return None */ function postProcess() { // store the submitted values in an array $params = $this->controller->exportValues($this->_name); $this->set('searchDone', 0); if (CRM_Utils_Array::value('_qf_Relationship_refresh', $_POST)) { $this->search($params); $this->set('searchDone', 1); return; } // action is taken depending upon the mode $ids = array(); $ids['contact'] = $this->_contactId; if ($this->_action & CRM_CORE_ACTION_DELETE) { CRM_Contact_BAO_Relationship::del($this->_relationshipId); return; } 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; } list($valid, $invalid, $duplicate, $saved) = CRM_Contact_BAO_Relationship::create($params, $ids); $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.'); } CRM_Core_Session::setStatus($status); }
/** * 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()); } }
/** * Function to create relationship between contacts who share an address * * Note that currently we create relationship only for Individual contacts * Individual + Household and Individual + Orgnization * * @param int $masterAddressId master address id * @param array $params associated array of submitted values * * @return void * @access public * @static */ static function processSharedAddressRelationship($masterAddressId, $params) { if (!$masterAddressId) { return; } // get the contact type of contact being edited / created $currentContactType = CRM_Contact_BAO_Contact::getContactType($params['contact_id']); $currentContactId = $params['contact_id']; // if current contact is not of type individual return if ($currentContactType != 'Individual') { return; } // get the contact id and contact type of shared contact // check the contact type of shared contact, return if it is of type Individual $query = 'SELECT cc.id, cc.contact_type FROM civicrm_contact cc INNER JOIN civicrm_address ca ON cc.id = ca.contact_id WHERE ca.id = %1'; $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($masterAddressId, 'Integer'))); $dao->fetch(); // if current contact is not of type individual return, since we don't create relationship between // 2 individuals if ($dao->contact_type == 'Individual') { return; } $sharedContactType = $dao->contact_type; $sharedContactId = $dao->id; // create relationship between ontacts who share an address if ($sharedContactType == 'Organization') { return CRM_Contact_BAO_Contact_Utils::createCurrentEmployerRelationship($currentContactId, $sharedContactId); } else { // get the relationship type id of "Household Member of" $relationshipType = 'Household Member of'; } $cid = array('contact' => $currentContactId); $relTypeId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', $relationshipType, 'id', 'name_a_b'); if (!$relTypeId) { CRM_Core_Error::fatal(ts("You seem to have deleted the relationship type '%1'", array(1 => $relationshipType))); } // create relationship $relationshipParams = array('is_active' => TRUE, 'relationship_type_id' => $relTypeId . '_a_b', 'contact_check' => array($sharedContactId => TRUE)); list($valid, $invalid, $duplicate, $saved, $relationshipIds) = CRM_Contact_BAO_Relationship::create($relationshipParams, $cid); }
/** * 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; }
static function relationship() { $relType = CRM_Utils_Request::retrieve('rel_type', 'Positive', CRM_Core_DAO::$_nullObject, TRUE); $relContactID = CRM_Utils_Request::retrieve('rel_contact', 'Positive', CRM_Core_DAO::$_nullObject, TRUE); $relationshipID = CRM_Utils_Array::value('rel_id', $_REQUEST); // this used only to determine add or update mode $caseID = CRM_Utils_Request::retrieve('case_id', 'Positive', CRM_Core_DAO::$_nullObject, TRUE); // check if there are multiple clients for this case, if so then we need create // relationship and also activities for each contacts // get case client list $clientList = CRM_Case_BAO_Case::getCaseClients($caseID); $ret = array('is_error' => 0); foreach ($clientList as $sourceContactID) { $relationParams = array('relationship_type_id' => $relType . '_a_b', 'contact_check' => array($relContactID => 1), 'is_active' => 1, 'case_id' => $caseID, 'start_date' => date("Ymd")); $relationIds = array('contact' => $sourceContactID); // check if we are editing/updating existing relationship if ($relationshipID && $relationshipID != 'null') { // here we need to retrieve appropriate relationshipID based on client id and relationship type id $caseRelationships = new CRM_Contact_DAO_Relationship(); $caseRelationships->case_id = $caseID; $caseRelationships->relationship_type_id = $relType; $caseRelationships->contact_id_a = $sourceContactID; $caseRelationships->find(); while ($caseRelationships->fetch()) { $relationIds['relationship'] = $caseRelationships->id; $relationIds['contactTarget'] = $relContactID; } $caseRelationships->free(); } // create new or update existing relationship $return = CRM_Contact_BAO_Relationship::create($relationParams, $relationIds); if (!empty($return[4][0])) { $relationshipID = $return[4][0]; //create an activity for case role assignment.CRM-4480 CRM_Case_BAO_Case::createCaseRoleActivity($caseID, $relationshipID, $relContactID); } else { $ret = array('is_error' => 1, 'error_message' => ts('The relationship type definition for the case role is not valid for the client and / or staff contact types. You can review and edit relationship types at <a href="%1">Administer >> Option Lists >> Relationship Types</a>.', array(1 => CRM_Utils_System::url('civicrm/admin/reltype', 'reset=1')))); } } CRM_Utils_JSON::output($ret); }
function testRelCreateWithinDiffTypeStudentSponsor() { //check for Student to Sponcer $relTypeParams = array('name_a_b' => 'StudentToSponsor', 'name_b_a' => 'SponsorToStudent', 'contact_type_a' => 'Individual', 'contact_sub_type_a' => $this->student, 'contact_type_b' => 'Organization', 'contact_sub_type_b' => $this->sponsor); $relTypeIds = array(); $relType = CRM_Contact_BAO_RelationshipType::add($relTypeParams, $relTypeIds); $params = array('relationship_type_id' => $relType->id . '_a_b', 'is_active' => 1, 'contact_check' => array($this->organization_sponsor => 1)); $ids = array('contact' => $this->indivi_student); list($valid, $invalid, $duplicate, $saved, $relationshipIds) = CRM_Contact_BAO_Relationship::create($params, $ids); $this->assertEquals($valid, 1, 'In line ' . __LINE__); $this->assertEquals(empty($relationshipIds), FALSE, 'In line ' . __LINE__); $this->relationshipTypeDelete($relType->id); }
/** * Function to add on behalf of organization and it's location * * @param $behalfOrganization array array of organization info * @param $contactID int individual contact id. One * who is doing the process of signup / contribution. * * @param $values array form values array * @param $params * @param null $fields * * @return void * @access public */ static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params, $fields = NULL) { $isCurrentEmployer = FALSE; $orgID = NULL; if (!empty($behalfOrganization['organization_id']) && !empty($behalfOrganization['org_option'])) { $orgID = $behalfOrganization['organization_id']; unset($behalfOrganization['organization_id']); $isCurrentEmployer = TRUE; } // formalities for creating / editing organization. $behalfOrganization['contact_type'] = 'Organization'; // get the relationship type id $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 $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'] = $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 $relParams['contact_check'][$orgID] = 1; $cid = array('contact' => $contactID); CRM_Contact_BAO_Relationship::create($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; // 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; 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; } }
/** * 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()); } }
static function relationship() { $relType = CRM_Utils_Array::value('rel_type', $_REQUEST); $relContactID = CRM_Utils_Array::value('rel_contact', $_REQUEST); $sourceContactID = CRM_Utils_Array::value('contact_id', $_REQUEST); // we no longer need this. $relationshipID = CRM_Utils_Array::value('rel_id', $_REQUEST); // this used only to determine add or update mode $caseID = CRM_Utils_Array::value('case_id', $_REQUEST); // check if there are multiple clients for this case, if so then we need create // relationship and also activities for each contacts // get case client list $clientList = CRM_Case_BAO_Case::getCaseClients($caseID); foreach ($clientList as $sourceContactID) { $relationParams = array('relationship_type_id' => $relType . '_a_b', 'contact_check' => array($relContactID => 1), 'is_active' => 1, 'case_id' => $caseID, 'start_date' => date("Ymd")); $relationIds = array('contact' => $sourceContactID); // check if we are editing/updating existing relationship if ($relationshipID && $relationshipID != 'null') { // here we need to retrieve appropriate relationshipID based on client id and relationship type id $caseRelationships = new CRM_Contact_DAO_Relationship(); $caseRelationships->case_id = $caseID; $caseRelationships->relationship_type_id = $relType; $caseRelationships->contact_id_a = $sourceContactID; $caseRelationships->find(); while ($caseRelationships->fetch()) { $relationIds['relationship'] = $caseRelationships->id; $relationIds['contactTarget'] = $relContactID; } $caseRelationships->free(); } // create new or update existing relationship $return = CRM_Contact_BAO_Relationship::create($relationParams, $relationIds); $status = 'process-relationship-fail'; if (CRM_Utils_Array::value(0, $return[4])) { $relationshipID = $return[4][0]; $status = 'process-relationship-success'; //create an activity for case role assignment.CRM-4480 CRM_Case_BAO_Case::createCaseRoleActivity($caseID, $relationshipID, $relContactID); } } $relation['status'] = $status; echo json_encode($relation); CRM_Utils_System::civiExit(); }
/** * 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 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'); } }