/** * View details of a relationship * * @return void * * @access public */ function view() { require_once 'CRM/Core/DAO.php'; $viewRelationship = CRM_Contact_BAO_Relationship::getRelationship($this->_contactId, null, null, null, $this->_id); //To check whether selected contact is a contact_id_a in //relationship type 'a_b' in relationship table, if yes then //revert the permissionship text in template $relationship = new CRM_Contact_DAO_Relationship(); $relationship->id = $viewRelationship[$this->_id]['id']; if ($relationship->find(true)) { if ($viewRelationship[$this->_id]['rtype'] == 'a_b' && $this->_contactId == $relationship->contact_id_a) { $this->assign("is_contact_id_a", true); } } $relType = $viewRelationship[$this->_id]['civicrm_relationship_type_id']; $this->assign('viewRelationship', $viewRelationship); $employerId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'employer_id'); $this->assign('isCurrentEmployer', false); if ($viewRelationship[$this->_id]['employer_id'] == $this->_contactId) { $this->assign('isCurrentEmployer', true); } else { if ($relType == 4 && $viewRelationship[$this->_id]['cid'] == $employerId) { // make sure we are viewing employee of relationship $this->assign('isCurrentEmployer', true); } } $viewNote = CRM_Core_BAO_Note::getNote($this->_id); $this->assign('viewNote', $viewNote); $groupTree =& CRM_Core_BAO_CustomGroup::getTree('Relationship', $this, $this->_id, 0, $relType); CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree); $rType = CRM_Utils_Array::value('rtype', $viewRelationship[$this->_id]); // add viewed contribution to recent items list require_once 'CRM/Utils/Recent.php'; $url = CRM_Utils_System::url('civicrm/contact/view/rel', "action=view&reset=1&id={$viewRelationship[$this->_id]['id']}&cid={$this->_contactId}&context=home"); require_once 'CRM/Core/Session.php'; require_once 'CRM/Contact/BAO/Contact/Permission.php'; $session = CRM_Core_Session::singleton(); $recentOther = array(); if ($session->get('userID') == $this->_contactId || CRM_Contact_BAO_Contact_Permission::allow($this->_contactId, CRM_Core_Permission::EDIT)) { $recentOther = array('editUrl' => CRM_Utils_System::url('civicrm/contact/view/rel', "action=update&reset=1&id={$viewRelationship[$this->_id]['id']}&cid={$this->_contactId}&rtype={$rType}&context=home"), 'deleteUrl' => CRM_Utils_System::url('civicrm/contact/view/rel', "action=delete&reset=1&id={$viewRelationship[$this->_id]['id']}&cid={$this->_contactId}&rtype={$rType}&context=home")); } $displayName = CRM_Contact_BAO_Contact::displayName($this->_contactId); $this->assign('displayName', $displayName); $title = $displayName . ' (' . $viewRelationship[$this->_id]['relation'] . ' ' . CRM_Contact_BAO_Contact::displayName($viewRelationship[$this->_id]['cid']) . ')'; // add the recently viewed Relationship CRM_Utils_Recent::add($title, $url, $viewRelationship[$this->_id]['id'], 'Relationship', $this->_contactId, null, $recentOther); }
/** * Get a list of relationships. * * @param int $contactId * Contact id. * @param int $status * 1: Past 2: Disabled 3: Current. * @param int $numRelationship * No of relationships to display (limit). * @param int $count * Get the no of relationships. * @param int $relationshipId * @param array $links * the list of links to display * @param int $permissionMask * the permission mask to be applied for the actions * @param bool $permissionedContact * to return only permissioned Contact * @param array $params * * @return array|int * relationship records */ public static function getRelationship($contactId = NULL, $status = 0, $numRelationship = 0, $count = 0, $relationshipId = 0, $links = NULL, $permissionMask = NULL, $permissionedContact = FALSE, $params = array()) { $values = array(); if (!$contactId && !$relationshipId) { return $values; } list($select1, $from1, $where1) = self::makeURLClause($contactId, $status, $numRelationship, $count, $relationshipId, 'a_b', $params); list($select2, $from2, $where2) = self::makeURLClause($contactId, $status, $numRelationship, $count, $relationshipId, 'b_a', $params); $order = $limit = ''; if (!$count) { if (empty($params['sort'])) { $order = ' ORDER BY civicrm_relationship_type_id, sort_name '; } else { $order = " ORDER BY {$params['sort']} "; } $offset = 0; if (!empty($params['offset']) && $params['offset'] > 0) { $offset = $params['offset']; } if ($numRelationship) { $limit = " LIMIT {$offset}, {$numRelationship}"; } } // building the query string $queryString = $select1 . $from1 . $where1 . $select2 . $from2 . $where2 . $order . $limit; $relationship = new CRM_Contact_DAO_Relationship(); $relationship->query($queryString); $row = array(); if ($count) { $relationshipCount = 0; while ($relationship->fetch()) { $relationshipCount += $relationship->cnt1 + $relationship->cnt2; } return $relationshipCount; } else { $mask = NULL; if ($status != self::INACTIVE) { if ($links) { $mask = array_sum(array_keys($links)); if ($mask & CRM_Core_Action::DISABLE) { $mask -= CRM_Core_Action::DISABLE; } if ($mask & CRM_Core_Action::ENABLE) { $mask -= CRM_Core_Action::ENABLE; } if ($status == self::CURRENT) { $mask |= CRM_Core_Action::DISABLE; } elseif ($status == self::DISABLED) { $mask |= CRM_Core_Action::ENABLE; } $mask = $mask & $permissionMask; } } while ($relationship->fetch()) { $rid = $relationship->civicrm_relationship_id; $cid = $relationship->civicrm_contact_id; if ($permissionedContact && !CRM_Contact_BAO_Contact_Permission::allow($cid)) { continue; } $values[$rid]['id'] = $rid; $values[$rid]['cid'] = $cid; $values[$rid]['contact_id_a'] = $relationship->contact_id_a; $values[$rid]['contact_id_b'] = $relationship->contact_id_b; $values[$rid]['contact_type'] = $relationship->contact_type; $values[$rid]['relationship_type_id'] = $relationship->civicrm_relationship_type_id; $values[$rid]['relation'] = $relationship->relation; $values[$rid]['name'] = $relationship->sort_name; $values[$rid]['display_name'] = $relationship->display_name; $values[$rid]['job_title'] = $relationship->job_title; $values[$rid]['email'] = $relationship->email; $values[$rid]['phone'] = $relationship->phone; $values[$rid]['employer_id'] = $relationship->employer_id; $values[$rid]['organization_name'] = $relationship->organization_name; $values[$rid]['country'] = $relationship->country; $values[$rid]['city'] = $relationship->city; $values[$rid]['state'] = $relationship->state; $values[$rid]['start_date'] = $relationship->start_date; $values[$rid]['end_date'] = $relationship->end_date; $values[$rid]['description'] = $relationship->description; $values[$rid]['is_active'] = $relationship->is_active; $values[$rid]['is_permission_a_b'] = $relationship->is_permission_a_b; $values[$rid]['is_permission_b_a'] = $relationship->is_permission_b_a; $values[$rid]['case_id'] = $relationship->case_id; if ($status) { $values[$rid]['status'] = $status; } $values[$rid]['civicrm_relationship_type_id'] = $relationship->civicrm_relationship_type_id; if ($relationship->contact_id_a == $contactId) { $values[$rid]['rtype'] = 'a_b'; } else { $values[$rid]['rtype'] = 'b_a'; } if ($links) { $replace = array('id' => $rid, 'rtype' => $values[$rid]['rtype'], 'cid' => $contactId, 'cbid' => $values[$rid]['cid'], 'caseid' => $values[$rid]['case_id'], 'clientid' => $contactId); if ($status == self::INACTIVE) { // setting links for inactive relationships $mask = array_sum(array_keys($links)); if (!$values[$rid]['is_active']) { $mask -= CRM_Core_Action::DISABLE; } else { $mask -= CRM_Core_Action::ENABLE; $mask -= CRM_Core_Action::DISABLE; } $mask = $mask & $permissionMask; } // Give access to manage case link by copying to MAX_ACTION index temporarily, depending on case permission of user. if ($values[$rid]['case_id']) { // Borrowed logic from CRM_Case_Page_Tab $hasCaseAccess = FALSE; if (CRM_Core_Permission::check('access all cases and activities')) { $hasCaseAccess = TRUE; } else { $userCases = CRM_Case_BAO_Case::getCases(FALSE); if (array_key_exists($values[$rid]['case_id'], $userCases)) { $hasCaseAccess = TRUE; } } if ($hasCaseAccess) { // give access by copying to MAX_ACTION temporarily, otherwise leave at NONE which won't display $links[CRM_Core_Action::MAX_ACTION] = $links[CRM_Core_Action::NONE]; $links[CRM_Core_Action::MAX_ACTION]['name'] = ts('Manage Case #%1', array(1 => $values[$rid]['case_id'])); $links[CRM_Core_Action::MAX_ACTION]['class'] = 'no-popup'; // Also make sure we have the right client cid since can get here from multiple relationship tabs. if ($values[$rid]['rtype'] == 'b_a') { $replace['clientid'] = $values[$rid]['cid']; } } } $values[$rid]['action'] = CRM_Core_Action::formLink($links, $mask, $replace, ts('more'), FALSE, 'relationship.selector.row', 'Relationship', $rid); unset($links[CRM_Core_Action::MAX_ACTION]); } } $relationship->free(); return $values; } }
/** * Clear cached current employer name. * * @param int $contactId * Contact id ( mostly individual contact id). * @param int $employerId * Contact id ( mostly organization contact id). */ public static function clearCurrentEmployer($contactId, $employerId = NULL) { $query = "UPDATE civicrm_contact\nSET organization_name=NULL, employer_id = NULL\nWHERE id={$contactId}; "; $dao = CRM_Core_DAO::executeQuery($query); // need to handle related meberships. CRM-3792 if ($employerId) { //1. disable corresponding relationship. //2. delete related membership. //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'")); } $relMembershipParams['relationship_type_id'] = $relTypeId . '_a_b'; $relMembershipParams['contact_check'][$employerId] = 1; //get relationship id. if (CRM_Contact_BAO_Relationship::checkDuplicateRelationship($relMembershipParams, $contactId, $employerId)) { $relationship = new CRM_Contact_DAO_Relationship(); $relationship->contact_id_a = $contactId; $relationship->contact_id_b = $employerId; $relationship->relationship_type_id = $relTypeId; if ($relationship->find(TRUE)) { CRM_Contact_BAO_Relationship::setIsActive($relationship->id, FALSE); CRM_Contact_BAO_Relationship::relatedMemberships($contactId, $relMembershipParams, $ids = array(), CRM_Core_Action::DELETE); } $relationship->free(); } } }
/** * Delete Relationship Types. * * @param int $relationshipTypeId * * @throws CRM_Core_Exception * @return mixed */ public static function del($relationshipTypeId) { // make sure relationshipTypeId is an integer // @todo review this as most delete functions rely on the api & form layer for this // or do a find first & throw error if no find if (!CRM_Utils_Rule::positiveInteger($relationshipTypeId)) { throw new CRM_Core_Exception(ts('Invalid relationship type')); } //check dependencies // delete all relationships $relationship = new CRM_Contact_DAO_Relationship(); $relationship->relationship_type_id = $relationshipTypeId; $relationship->delete(); // remove this relationship type from membership types $mems = civicrm_api3('MembershipType', 'get', array('relationship_type_id' => array('LIKE' => "%{$relationshipTypeId}%"), 'return' => array('id', 'relationship_type_id', 'relationship_direction'))); foreach ($mems['values'] as $membershipTypeId => $membershipType) { $pos = array_search($relationshipTypeId, $membershipType['relationship_type_id']); // Api call may have returned false positives but currently the relationship_type_id uses // nonstandard serialization which makes anything more accurate impossible. if ($pos !== FALSE) { unset($membershipType['relationship_type_id'][$pos], $membershipType['relationship_direction'][$pos]); civicrm_api3('MembershipType', 'create', $membershipType); } } //fixed for CRM-3323 $mappingField = new CRM_Core_DAO_MappingField(); $mappingField->relationship_type_id = $relationshipTypeId; $mappingField->find(); while ($mappingField->fetch()) { $mappingField->delete(); } $relationshipType = new CRM_Contact_DAO_RelationshipType(); $relationshipType->id = $relationshipTypeId; return $relationshipType->delete(); }
/** * Function to delete Relationship Types * * @param int $relationshipTypeId * @static */ static function del($relationshipTypeId) { // make sure relationshipTypeId is an integer // @todo review this as most delete functions rely on the api & form layer for this // or do a find first & throw error if no find if (!CRM_Utils_Rule::positiveInteger($relationshipTypeId)) { throw new CRM_Core_Exception(ts('Invalid relationship type')); } //check dependencies // delete all relationships $relationship = new CRM_Contact_DAO_Relationship(); $relationship->relationship_type_id = $relationshipTypeId; $relationship->delete(); // set all membership_type to null $query = "\nUPDATE civicrm_membership_type\n SET relationship_type_id = NULL\n WHERE relationship_type_id = %1\n"; $params = array(1 => array(CRM_Core_DAO::VALUE_SEPARATOR . $relationshipTypeId . CRM_Core_DAO::VALUE_SEPARATOR, 'String')); CRM_Core_DAO::executeQuery($query, $params); //fixed for CRM-3323 $mappingField = new CRM_Core_DAO_MappingField(); $mappingField->relationship_type_id = $relationshipTypeId; $mappingField->find(); while ($mappingField->fetch()) { $mappingField->delete(); } $relationshipType = new CRM_Contact_DAO_RelationshipType(); $relationshipType->id = $relationshipTypeId; return $relationshipType->delete(); }
/** * @param array $params * * @return bool */ public function createRelationship(&$params) { $dao = new CRM_Contact_DAO_Relationship(); $dao->copyValues($params); // only create a relationship if it does not exist if (!$dao->find(TRUE)) { $dao->save(); } return TRUE; }
/** * Function to delete Relationship Types * * @param int $relationshipTypeId * @static */ static function del($relationshipTypeId) { // make sure relationshipTypeId is an integer if (!CRM_Utils_Rule::positiveInteger($relationshipTypeId)) { CRM_Core_Error::fatal(ts('Invalid relationship type')); } //check dependencies // delete all relationships $relationship = new CRM_Contact_DAO_Relationship(); $relationship->relationship_type_id = $relationshipTypeId; $relationship->delete(); // set all membership_type to null $query = "\nUPDATE civicrm_membership_type\n SET relationship_type_id = NULL\n WHERE relationship_type_id = %1\n"; $params = array(1 => array($relationshipTypeId, 'Integer')); CRM_Core_DAO::executeQuery($query, $params); //fixed for CRM-3323 $mappingField = new CRM_Core_DAO_MappingField(); $mappingField->relationship_type_id = $relationshipTypeId; $mappingField->find(); while ($mappingField->fetch()) { $mappingField->delete(); } $relationshipType = new CRM_Contact_DAO_RelationshipType(); $relationshipType->id = $relationshipTypeId; return $relationshipType->delete(); }
/** * Function to get individual id for onbehalf contribution * @param int $contributionId contribution id * @param int $contributorId contributer id * @return array $ids containing organization id and individual id * @access public */ function getOnbehalfIds($contributionId, $contributorId = null) { $ids = array(); if (!$contributionId) { return $ids; } // fetch contributor id if null if (!$contributorId) { require_once 'CRM/Core/DAO.php'; $contributorId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contact_id'); } require_once 'CRM/Core/PseudoConstant.php'; $activityTypeIds = CRM_Core_PseudoConstant::activityType(true, false, false, 'name'); $activityTypeId = array_search("Contribution", $activityTypeIds); if ($activityTypeId && $contributorId) { $activityQuery = "\nSELECT source_contact_id \n FROM civicrm_activity \n WHERE activity_type_id = %1 \n AND source_record_id = %2"; $params = array(1 => array($activityTypeId, 'Integer'), 2 => array($contributionId, 'Integer')); $sourceContactId = CRM_Core_DAO::singleValueQuery($activityQuery, $params); // for on behalf contribution source is individual and contributor is organization if ($sourceContactId && $sourceContactId != $contributorId) { $relationshipTypeIds = CRM_Core_PseudoConstant::relationshipType('name'); // get rel type id for employee of relation foreach ($relationshipTypeIds as $id => $typeVals) { if ($typeVals['name_a_b'] == 'Employee of') { $relationshipTypeId = $id; break; } } require_once 'CRM/Contact/DAO/Relationship.php'; $rel = new CRM_Contact_DAO_Relationship(); $rel->relationship_type_id = $relationshipTypeId; $rel->contact_id_a = $sourceContactId; $rel->contact_id_b = $contributorId; if ($rel->find(true)) { $ids['individual_id'] = $rel->contact_id_a; $ids['organization_id'] = $rel->contact_id_b; } } } return $ids; }
/** * take the input parameter list as specified in the data model and * convert it into the same format that we use in QF and BAO object * * @param array $params Associative array of property name/value * pairs to insert in new contact. * @param array $values The reformatted properties that we can use internally * ' * * @return array|CRM_Error * @access public */ function _civicrm_relationship_format_params(&$params, &$values) { // copy all the relationship fields as is $fields = CRM_Contact_DAO_Relationship::fields(); _civicrm_store_values($fields, $params, $values); $relationTypes = CRM_Core_PseudoConstant::relationshipType('name', TRUE); foreach ($params as $key => $value) { // ignore empty values or empty arrays etc require_once 'CRM/Utils/System.php'; if (CRM_Utils_System::isNull($value)) { continue; } switch ($key) { case 'contact_id_a': case 'contact_id_b': require_once 'CRM/Utils/Rule.php'; if (!CRM_Utils_Rule::integer($value)) { return civicrm_create_error("contact_id not valid: {$value}"); } $dao = new CRM_Core_DAO(); $qParams = array(); $svq = $dao->singleValueQuery("SELECT id FROM civicrm_contact WHERE id = {$value}", $qParams); if (!$svq) { return civicrm_create_error("Invalid Contact ID: There is no contact record with contact_id = {$value}."); } break; case 'start_date': case 'end_date': if (!CRM_Utils_Rule::qfDate($value)) { return civicrm_create_error("{$key} not a valid date: {$value}"); } break; case 'relationship_type': foreach ($relationTypes as $relTypId => $relValue) { if (CRM_Utils_Array::key(ucfirst($value), $relValue)) { $relationshipTypeId = $relTypId; break; } } if ($relationshipTypeId) { if (CRM_Utils_Array::value('relationship_type_id', $values) && $relationshipTypeId != $values['relationship_type_id']) { return civicrm_create_error('Mismatched Relationship Type and Relationship Type Id'); } $values['relationship_type_id'] = $params['relationship_type_id'] = $relationshipTypeId; } else { return civicrm_create_error('Invalid Relationship Type'); } case 'relationship_type_id': if ($key == 'relationship_type_id' && !array_key_exists($value, $relationTypes)) { return civicrm_create_error("{$key} not a valid: {$value}"); } // execute for both relationship_type and relationship_type_id $relation = $relationTypes[$params['relationship_type_id']]; require_once 'CRM/Contact/BAO/Contact.php'; if ($relation['contact_type_a'] && $relation['contact_type_a'] != CRM_Contact_BAO_Contact::getContactType($params['contact_id_a'])) { return civicrm_create_error("Contact ID :{$params['contact_id_a']} is not of contact type {$relation['contact_type_a']}"); } if ($relation['contact_type_b'] && $relation['contact_type_b'] != CRM_Contact_BAO_Contact::getContactType($params['contact_id_b'])) { return civicrm_create_error("Contact ID :{$params['contact_id_b']} is not of contact type {$relation['contact_type_b']}"); } break; default: break; } } if (array_key_exists('note', $params)) { $values['note'] = $params['note']; } _civicrm_custom_format_params($params, $values, 'Relationship'); return array(); }
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(); }
/** * Function perform two task. * 1. Merge two duplicate contacts cases - follow CRM-5758 rules. * 2. Merge two cases of same contact - follow CRM-5598 rules. * * @param int $mainContactId contact id of main contact record. * @param int $mainCaseId case id of main case record. * @param int $otherContactId contact id of record which is going to merge. * @param int $otherCaseId case id of record which is going to merge. * * @return void. * @static */ function mergeCases($mainContactId, $mainCaseId = NULL, $otherContactId = NULL, $otherCaseId = NULL, $changeClient = FALSE) { $moveToTrash = TRUE; $duplicateContacts = FALSE; if ($mainContactId && $otherContactId && $mainContactId != $otherContactId) { $duplicateContacts = TRUE; } $duplicateCases = FALSE; if ($mainCaseId && $otherCaseId && $mainCaseId != $otherCaseId) { $duplicateCases = TRUE; } $mainCaseIds = array(); if (!$duplicateContacts && !$duplicateCases) { return $mainCaseIds; } $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'name'); $activityStatuses = CRM_Core_PseudoConstant::activityStatus('name'); $processCaseIds = array($otherCaseId); if ($duplicateContacts && !$duplicateCases) { if ($changeClient) { $processCaseIds = array($mainCaseId); } else { //get all case ids for other contact. $processCaseIds = self::retrieveCaseIdsByContactId($otherContactId, TRUE); } if (!is_array($processCaseIds)) { return; } } $session = CRM_Core_Session::singleton(); $currentUserId = $session->get('userID'); // copy all cases and connect to main contact id. foreach ($processCaseIds as $otherCaseId) { if ($duplicateContacts) { $mainCase = CRM_Core_DAO::copyGeneric('CRM_Case_DAO_Case', array('id' => $otherCaseId)); $mainCaseId = $mainCase->id; if (!$mainCaseId) { continue; } $mainCase->free(); $mainCaseIds[] = $mainCaseId; //insert record for case contact. $otherCaseContact = new CRM_Case_DAO_CaseContact(); $otherCaseContact->case_id = $otherCaseId; $otherCaseContact->find(); while ($otherCaseContact->fetch()) { $mainCaseContact = new CRM_Case_DAO_CaseContact(); $mainCaseContact->case_id = $mainCaseId; $mainCaseContact->contact_id = $otherCaseContact->contact_id; if ($mainCaseContact->contact_id == $otherContactId) { $mainCaseContact->contact_id = $mainContactId; } //avoid duplicate object. if (!$mainCaseContact->find(TRUE)) { $mainCaseContact->save(); } $mainCaseContact->free(); } $otherCaseContact->free(); } elseif (!$otherContactId) { $otherContactId = $mainContactId; } if (!$mainCaseId || !$otherCaseId || !$mainContactId || !$otherContactId) { continue; } // get all activities for other case. $otherCaseActivities = array(); CRM_Core_DAO::commonRetrieveAll('CRM_Case_DAO_CaseActivity', 'case_id', $otherCaseId, $otherCaseActivities); //for duplicate cases do not process singleton activities. $otherActivityIds = $singletonActivityIds = array(); foreach ($otherCaseActivities as $caseActivityId => $otherIds) { $otherActId = CRM_Utils_Array::value('activity_id', $otherIds); if (!$otherActId || in_array($otherActId, $otherActivityIds)) { continue; } $otherActivityIds[] = $otherActId; } if ($duplicateCases) { if ($openCaseType = array_search('Open Case', $activityTypes)) { $sql = "\nSELECT id\n FROM civicrm_activity \n WHERE activity_type_id = {$openCaseType} \n AND id IN ( " . implode(',', array_values($otherActivityIds)) . ');'; $dao = CRM_Core_DAO::executeQuery($sql); while ($dao->fetch()) { $singletonActivityIds[] = $dao->id; } $dao->free(); } } // migrate all activities and connect to main contact. $copiedActivityIds = $activityMappingIds = array(); sort($otherActivityIds); foreach ($otherActivityIds as $otherActivityId) { //for duplicate cases - //do not migrate singleton activities. if (!$otherActivityId || in_array($otherActivityId, $singletonActivityIds)) { continue; } //migrate activity record. $otherActivity = new CRM_Activity_DAO_Activity(); $otherActivity->id = $otherActivityId; if (!$otherActivity->find(TRUE)) { continue; } $mainActVals = array(); $mainActivity = new CRM_Activity_DAO_Activity(); CRM_Core_DAO::storeValues($otherActivity, $mainActVals); $mainActivity->copyValues($mainActVals); $mainActivity->id = NULL; $mainActivity->activity_date_time = CRM_Utils_Date::isoToMysql($otherActivity->activity_date_time); //do check for merging contact, if ($mainActivity->source_contact_id == $otherContactId) { $mainActivity->source_contact_id = $mainContactId; } $mainActivity->source_record_id = CRM_Utils_Array::value($mainActivity->source_record_id, $activityMappingIds); $mainActivity->original_id = CRM_Utils_Array::value($mainActivity->original_id, $activityMappingIds); $mainActivity->parent_id = CRM_Utils_Array::value($mainActivity->parent_id, $activityMappingIds); $mainActivity->save(); $mainActivityId = $mainActivity->id; if (!$mainActivityId) { continue; } $activityMappingIds[$otherActivityId] = $mainActivityId; // insert log of all activites CRM_Activity_BAO_Activity::logActivityAction($mainActivity); $otherActivity->free(); $mainActivity->free(); $copiedActivityIds[] = $otherActivityId; //create case activity record. $mainCaseActivity = new CRM_Case_DAO_CaseActivity(); $mainCaseActivity->case_id = $mainCaseId; $mainCaseActivity->activity_id = $mainActivityId; $mainCaseActivity->save(); $mainCaseActivity->free(); //migrate target activities. $otherTargetActivity = new CRM_Activity_DAO_ActivityTarget(); $otherTargetActivity->activity_id = $otherActivityId; $otherTargetActivity->find(); while ($otherTargetActivity->fetch()) { $mainActivityTarget = new CRM_Activity_DAO_ActivityTarget(); $mainActivityTarget->activity_id = $mainActivityId; $mainActivityTarget->target_contact_id = $otherTargetActivity->target_contact_id; if ($mainActivityTarget->target_contact_id == $otherContactId) { $mainActivityTarget->target_contact_id = $mainContactId; } //avoid duplicate object. if (!$mainActivityTarget->find(TRUE)) { $mainActivityTarget->save(); } $mainActivityTarget->free(); } $otherTargetActivity->free(); //migrate assignee activities. $otherAssigneeActivity = new CRM_Activity_DAO_ActivityAssignment(); $otherAssigneeActivity->activity_id = $otherActivityId; $otherAssigneeActivity->find(); while ($otherAssigneeActivity->fetch()) { $mainAssigneeActivity = new CRM_Activity_DAO_ActivityAssignment(); $mainAssigneeActivity->activity_id = $mainActivityId; $mainAssigneeActivity->assignee_contact_id = $otherAssigneeActivity->assignee_contact_id; if ($mainAssigneeActivity->assignee_contact_id == $otherContactId) { $mainAssigneeActivity->assignee_contact_id = $mainContactId; } //avoid duplicate object. if (!$mainAssigneeActivity->find(TRUE)) { $mainAssigneeActivity->save(); } $mainAssigneeActivity->free(); } $otherAssigneeActivity->free(); } //copy case relationship. if ($duplicateContacts) { //migrate relationship records. $otherRelationship = new CRM_Contact_DAO_Relationship(); $otherRelationship->case_id = $otherCaseId; $otherRelationship->find(); $otherRelationshipIds = array(); while ($otherRelationship->fetch()) { $otherRelVals = array(); $updateOtherRel = FALSE; CRM_Core_DAO::storeValues($otherRelationship, $otherRelVals); $mainRelationship = new CRM_Contact_DAO_Relationship(); $mainRelationship->copyValues($otherRelVals); $mainRelationship->id = NULL; $mainRelationship->case_id = $mainCaseId; if ($mainRelationship->contact_id_a == $otherContactId) { $updateOtherRel = TRUE; $mainRelationship->contact_id_a = $mainContactId; } //case creator change only when we merge user contact. if ($mainRelationship->contact_id_b == $otherContactId) { //do not change creator for change client. if (!$changeClient) { $updateOtherRel = TRUE; $mainRelationship->contact_id_b = $currentUserId ? $currentUserId : $mainContactId; } } $mainRelationship->end_date = CRM_Utils_Date::isoToMysql($otherRelationship->end_date); $mainRelationship->start_date = CRM_Utils_Date::isoToMysql($otherRelationship->start_date); //avoid duplicate object. if (!$mainRelationship->find(TRUE)) { $mainRelationship->save(); } $mainRelationship->free(); //get the other relationship ids to update end date. if ($updateOtherRel) { $otherRelationshipIds[$otherRelationship->id] = $otherRelationship->id; } } $otherRelationship->free(); //update other relationships end dates if (!empty($otherRelationshipIds)) { $sql = 'UPDATE civicrm_relationship SET end_date = CURDATE() WHERE id IN ( ' . implode(',', $otherRelationshipIds) . ')'; CRM_Core_DAO::executeQuery($sql); } } //move other case to trash. $mergeCase = self::deleteCase($otherCaseId, $moveToTrash); if (!$mergeCase) { continue; } $mergeActSubject = $mergeActSubjectDetails = $mergeActType = ''; if ($changeClient) { $mainContactDisplayName = CRM_Contact_BAO_Contact::displayName($mainContactId); $otherContactDisplayName = CRM_Contact_BAO_Contact::displayName($otherContactId); $mergeActType = array_search('Reassigned Case', $activityTypes); $mergeActSubject = ts("Case %1 reassigned client from %2 to %3. New Case ID is %4.", array(1 => $otherCaseId, 2 => $otherContactDisplayName, 3 => $mainContactDisplayName, 4 => $mainCaseId)); } elseif ($duplicateContacts) { $mergeActType = array_search('Merge Case', $activityTypes); $mergeActSubject = ts("Case %1 copied from contact id %2 to contact id %3 via merge. New Case ID is %4.", array(1 => $otherCaseId, 2 => $otherContactId, 3 => $mainContactId, 4 => $mainCaseId)); } else { $mergeActType = array_search('Merge Case', $activityTypes); $mergeActSubject = ts("Case %1 merged into case %2", array(1 => $otherCaseId, 2 => $mainCaseId)); if (!empty($copiedActivityIds)) { $sql = ' SELECT id, subject, activity_date_time, activity_type_id FROM civicrm_activity WHERE id IN (' . implode(',', $copiedActivityIds) . ')'; $dao = CRM_Core_DAO::executeQuery($sql); while ($dao->fetch()) { $mergeActSubjectDetails .= "{$dao->activity_date_time} :: {$activityTypes[$dao->activity_type_id]}"; if ($dao->subject) { $mergeActSubjectDetails .= " :: {$dao->subject}"; } $mergeActSubjectDetails .= "<br />"; } } } //create merge activity record. $activityParams = array('subject' => $mergeActSubject, 'details' => $mergeActSubjectDetails, 'status_id' => array_search('Completed', $activityStatuses), 'activity_type_id' => $mergeActType, 'source_contact_id' => $mainContactId, 'activity_date_time' => date('YmdHis')); $mergeActivity = CRM_Activity_BAO_Activity::create($activityParams); $mergeActivityId = $mergeActivity->id; if (!$mergeActivityId) { continue; } $mergeActivity->free(); //connect merge activity to case. $mergeCaseAct = array('case_id' => $mainCaseId, 'activity_id' => $mergeActivityId); self::processCaseActivity($mergeCaseAct); } return $mainCaseIds; }
/** * returns the list of fields that can be exported * * @access public * return array */ function &export($prefix = false) { if (!$GLOBALS['_CRM_CONTACT_DAO_RELATIONSHIP']['_export']) { $GLOBALS['_CRM_CONTACT_DAO_RELATIONSHIP']['_export'] = array(); $fields =& CRM_Contact_DAO_Relationship::fields(); foreach ($fields as $name => $field) { if (CRM_Utils_Array::value('export', $field)) { if ($prefix) { $GLOBALS['_CRM_CONTACT_DAO_RELATIONSHIP']['_export']['relationship'] =& $fields[$name]; } else { $GLOBALS['_CRM_CONTACT_DAO_RELATIONSHIP']['_export'][$name] =& $fields[$name]; } } } } return $GLOBALS['_CRM_CONTACT_DAO_RELATIONSHIP']['_export']; }
/** * returns the list of fields that can be exported * * @access public * return array * @static */ static function &export($prefix = false) { if (!self::$_export) { self::$_export = array(); $fields = self::fields(); foreach ($fields as $name => $field) { if (CRM_Utils_Array::value('export', $field)) { if ($prefix) { self::$_export['relationship'] =& $fields[$name]; } else { self::$_export[$name] =& $fields[$name]; } } } } return self::$_export; }
/** * Get individual id for onbehalf contribution. * * @param int $contributionId * Contribution id. * @param int $contributorId * Contributor id. * * @return array * containing organization id and individual id */ public static function getOnbehalfIds($contributionId, $contributorId = NULL) { $ids = array(); if (!$contributionId) { return $ids; } // fetch contributor id if null if (!$contributorId) { $contributorId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'contact_id'); } $activityTypeIds = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name'); $activityTypeId = array_search('Contribution', $activityTypeIds); if ($activityTypeId && $contributorId) { $activityQuery = "\nSELECT civicrm_activity_contact.contact_id\n FROM civicrm_activity_contact\nINNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_activity.id\n WHERE civicrm_activity.activity_type_id = %1\n AND civicrm_activity.source_record_id = %2\n AND civicrm_activity_contact.record_type_id = %3\n"; $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name'); $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts); $params = array(1 => array($activityTypeId, 'Integer'), 2 => array($contributionId, 'Integer'), 3 => array($sourceID, 'Integer')); $sourceContactId = CRM_Core_DAO::singleValueQuery($activityQuery, $params); // for on behalf contribution source is individual and contributor is organization if ($sourceContactId && $sourceContactId != $contributorId) { $relationshipTypeIds = CRM_Core_PseudoConstant::relationshipType('name'); // get rel type id for employee of relation foreach ($relationshipTypeIds as $id => $typeVals) { if ($typeVals['name_a_b'] == 'Employee of') { $relationshipTypeId = $id; break; } } $rel = new CRM_Contact_DAO_Relationship(); $rel->relationship_type_id = $relationshipTypeId; $rel->contact_id_a = $sourceContactId; $rel->contact_id_b = $contributorId; if ($rel->find(TRUE)) { $ids['individual_id'] = $rel->contact_id_a; $ids['organization_id'] = $rel->contact_id_b; } } } return $ids; }
function mergeSameHousehold(&$rows) { # group selected contacts by type $individuals = array(); $households = array(); foreach ($rows as $contact_id => $row) { if ($row['contact_type'] == 'Household') { $households[$contact_id] = $row; } elseif ($row['contact_type'] == 'Individual') { $individuals[$contact_id] = $row; } } # exclude individuals belonging to selected households foreach ($households as $household_id => $row) { $dao = new CRM_Contact_DAO_Relationship(); $dao->contact_id_b = $household_id; $dao->find(); while ($dao->fetch()) { $individual_id = $dao->contact_id_a; if (array_key_exists($individual_id, $individuals)) { unset($individuals[$individual_id]); } } } # merge back individuals and households $rows = array_merge($individuals, $households); return $rows; }
public 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_Request::retrieve('rel_id', 'Positive', CRM_Core_DAO::$_nullObject); // 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::legacyCreateMultiple($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); }
/** * take the input parameter list as specified in the data model and * convert it into the same format that we use in QF and BAO object * * @param array $params Associative array of property name/value * pairs to insert in new contact. * @param array $values The reformatted properties that we can use internally * ' * * @throws Exception * @return array|CRM_Error * @access public */ function _civicrm_api3_relationship_format_params($params, &$values) { // copy all the relationship fields as is $fields = CRM_Contact_DAO_Relationship::fields(); _civicrm_api3_store_values($fields, $params, $values); $relationTypes = CRM_Core_PseudoConstant::relationshipType('name'); if (!empty($params['id'])) { $relation = new CRM_Contact_BAO_Relationship(); $relation->id = $params['id']; if (!$relation->find(TRUE)) { throw new Exception('Relationship id is not valid'); } else { if (isset($params['contact_id_a']) && $params['contact_id_a'] != $relation->contact_id_a || isset($params['contact_id_b']) && $params['contact_id_b'] != $relation->contact_id_b) { throw new Exception('Cannot change the contacts once relationship has been created'); } else { // since the BAO function is not std & won't accept just 'id' (aargh) let's // at least return our BAO here $values = array(); _civicrm_api3_object_to_array($relation, $values); $values = array_merge($values, $params); // and we need to reformat our date fields.... $dateFields = array('start_date', 'end_date'); foreach ($dateFields as $dateField) { $values[$dateField] = CRM_Utils_Date::processDate($values[$dateField]); } } } } foreach ($params as $key => $value) { // ignore empty values or empty arrays etc if (CRM_Utils_System::isNull($value)) { continue; } switch ($key) { case 'contact_id_a': case 'contact_id_b': if (!CRM_Utils_Rule::integer($value)) { throw new Exception("contact_id not valid: {$value}"); } $dao = new CRM_Core_DAO(); $qParams = array(); $svq = $dao->singleValueQuery("SELECT id FROM civicrm_contact WHERE id = {$value}", $qParams); if (!$svq) { throw new Exception("Invalid Contact ID: There is no contact record with contact_id = {$value}."); } break; case 'relationship_type': foreach ($relationTypes as $relTypId => $relValue) { if (CRM_Utils_Array::key(ucfirst($value), $relValue)) { $relationshipTypeId = $relTypId; break; } } if ($relationshipTypeId) { if (!empty($values['relationship_type_id']) && $relationshipTypeId != $values['relationship_type_id']) { throw new Exception('Mismatched Relationship Type and Relationship Type Id'); } $values['relationship_type_id'] = $params['relationship_type_id'] = $relationshipTypeId; } else { throw new Exception('Invalid Relationship Type'); } case 'relationship_type_id': if ($key == 'relationship_type_id' && !array_key_exists($value, $relationTypes)) { throw new Exception("{$key} not a valid: {$value}"); } // execute for both relationship_type and relationship_type_id $relation = $relationTypes[$params['relationship_type_id']]; if (!empty($params['contact_id_a']) && $relation['contact_type_a'] && $relation['contact_type_a'] != CRM_Contact_BAO_Contact::getContactType($params['contact_id_a'])) { throw new Exception("Contact ID :{$params['contact_id_a']} is not of contact type {$relation['contact_type_a']}"); } if (!empty($params['contact_id_b']) && $relation['contact_type_b'] && $relation['contact_type_b'] != CRM_Contact_BAO_Contact::getContactType($params['contact_id_b'])) { throw new Exception("Contact ID :{$params['contact_id_b']} is not of contact type {$relation['contact_type_b']}"); } break; default: break; } } if (array_key_exists('note', $params)) { $values['note'] = $params['note']; } _civicrm_api3_custom_format_params($params, $values, 'Relationship'); return array(); }
/** * Function to add/copy relationships, when new client is added for a case * * @param int $caseId case id * @param int $contactId contact id / new client id * * @return void */ static function addCaseRelationships($caseId, $contactId) { // get the case role / relationships for the case $caseRelationships = new CRM_Contact_DAO_Relationship(); $caseRelationships->case_id = $caseId; $caseRelationships->find(); $relationshipTypes = array(); // make sure we don't add duplicate relationships of same relationship type. while ($caseRelationships->fetch() && !in_array($caseRelationships->relationship_type_id, $relationshipTypes)) { $values = array(); CRM_Core_DAO::storeValues($caseRelationships, $values); // add relationship for new client. $newRelationship = new CRM_Contact_DAO_Relationship(); $newRelationship->copyValues($values); $newRelationship->id = NULL; $newRelationship->case_id = $caseId; $newRelationship->contact_id_a = $contactId; $newRelationship->end_date = CRM_Utils_Date::isoToMysql($caseRelationships->end_date); $newRelationship->start_date = CRM_Utils_Date::isoToMysql($caseRelationships->start_date); // another check to avoid duplicate relationship, in cases where client is removed and re-added again. if (!$newRelationship->find(TRUE)) { $newRelationship->save(); } $newRelationship->free(); // store relationship type of newly created relationship $relationshipTypes[] = $caseRelationships->relationship_type_id; } }
function createRelationship(&$params) { require_once 'CRM/Contact/DAO/Relationship.php'; $dao = new CRM_Contact_DAO_Relationship(); $dao->copyValues($params); // only create a relationship if it does not exist if (!$dao->find(true)) { $dao->save(); } return true; }