3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
13 * Class CRM_Contact_BAO_Relationship.
15 class CRM_Contact_BAO_Relationship
extends CRM_Contact_DAO_Relationship
{
18 * Various constants to indicate different type of relationships.
22 const ALL
= 0, PAST
= 1, DISABLED
= 2, CURRENT
= 4, INACTIVE
= 8;
25 * Constants for is_permission fields.
26 * Note: the slightly non-obvious ordering is due to history...
28 const NONE
= 0, EDIT
= 1, VIEW
= 2;
31 * The list of column headers
34 private static $columnHeaders;
37 * Create function - use the API instead.
39 * Note that the previous create function has been renamed 'legacyCreateMultiple'
40 * and this is new in 4.6
41 * All existing calls have been changed to legacyCreateMultiple except the api call - however, it is recommended
42 * that you call that as the end to end testing here is based on the api & refactoring may still be done.
44 * @param array $params
46 * @return \CRM_Contact_BAO_Relationship
47 * @throws \CRM_Core_Exception
49 public static function create(&$params) {
51 $extendedParams = self
::loadExistingRelationshipDetails($params);
52 // When id is specified we always wan't to update, so we don't need to
53 // check for duplicate relations.
54 if (!isset($params['id']) && self
::checkDuplicateRelationship($extendedParams, $extendedParams['contact_id_a'], $extendedParams['contact_id_b'], CRM_Utils_Array
::value('id', $extendedParams, 0))) {
55 throw new CRM_Core_Exception('Duplicate Relationship');
57 $params = $extendedParams;
58 if (self
::checkValidRelationship($params, $params, 0)) {
59 throw new CRM_Core_Exception('Invalid Relationship');
61 $relationship = self
::add($params);
62 if (!empty($params['contact_id_a'])) {
64 'contactTarget' => $relationship->contact_id_b
,
65 'contact' => $params['contact_id_a'],
68 //CRM-16087 removed additional call to function relatedMemberships which is already called by disableEnableRelationship
69 //resulting in membership being created twice
70 if (array_key_exists('is_active', $params) && empty($params['is_active'])) {
71 $action = CRM_Core_Action
::DISABLE
;
75 $action = CRM_Core_Action
::ENABLE
;
78 $id = empty($params['id']) ?
$relationship->id
: $params['id'];
79 self
::disableEnableRelationship($id, $action, $params, $ids, $active);
82 if (empty($params['skipRecentView'])) {
83 self
::addRecent($params, $relationship);
90 * Create multiple relationships for one contact.
92 * The relationship details are the same for each relationship except the secondary contact
95 * @param array $params
96 * Parameters for creating multiple relationships.
97 * The parameters are the same as for relationship create function except that the non-primary
98 * end of the relationship should be an array of one or more contact IDs.
99 * @param string $primaryContactLetter
100 * a or b to denote the primary contact for this action. The secondary may be multiple contacts
101 * and should be an array.
104 * @throws \CRM_Core_Exception
106 public static function createMultiple($params, $primaryContactLetter) {
107 $secondaryContactLetter = ($primaryContactLetter == 'a') ?
'b' : 'a';
108 $secondaryContactIDs = $params['contact_id_' . $secondaryContactLetter];
109 $valid = $invalid = $duplicate = $saved = 0;
110 $relationshipIDs = [];
111 foreach ($secondaryContactIDs as $secondaryContactID) {
113 $params['contact_id_' . $secondaryContactLetter] = $secondaryContactID;
114 $relationship = civicrm_api3('relationship', 'create', $params);
115 $relationshipIDs[] = $relationship['id'];
118 catch (CiviCRM_API3_Exception
$e) {
119 switch ($e->getMessage()) {
120 case 'Duplicate Relationship':
124 case 'Invalid Relationship':
129 throw new CRM_Core_Exception('unknown relationship create error ' . $e->getMessage());
136 'invalid' => $invalid,
137 'duplicate' => $duplicate,
139 'relationship_ids' => $relationshipIDs,
144 * Takes an associative array and creates a relationship object.
146 * @deprecated For single creates use the api instead (it's tested).
147 * For multiple a new variant of this function needs to be written and migrated to as this is a bit
150 * @param array $params
151 * (reference ) an assoc array of name/value pairs.
153 * The array that holds all the db ids.
154 * per http://wiki.civicrm.org/confluence/display/CRM/Database+layer
155 * "we are moving away from the $ids param "
158 * @throws \CRM_Core_Exception
160 public static function legacyCreateMultiple(&$params, $ids = []) {
161 $valid = $invalid = $duplicate = $saved = 0;
162 $relationships = $relationshipIds = [];
163 $relationshipId = CRM_Utils_Array
::value('relationship', $ids, CRM_Utils_Array
::value('id', $params));
165 //CRM-9015 - the hooks are called here & in add (since add doesn't call create)
166 // but in future should be tidied per ticket
167 if (empty($relationshipId)) {
174 // @todo pre hook is called from add - remove it from here
175 CRM_Utils_Hook
::pre($hook, 'Relationship', $relationshipId, $params);
177 if (!$relationshipId) {
178 // creating a new relationship
179 $dataExists = self
::dataExists($params);
181 return [FALSE, TRUE, FALSE, FALSE, NULL];
183 $relationshipIds = [];
184 foreach ($params['contact_check'] as $key => $value) {
185 // check if the relationship is valid between contacts.
186 // step 1: check if the relationship is valid if not valid skip and keep the count
187 // step 2: check the if two contacts already have a relationship if yes skip and keep the count
188 // step 3: if valid relationship then add the relation and keep the count
191 $contactFields = self
::setContactABFromIDs($params, $ids, $key);
192 $errors = self
::checkValidRelationship($contactFields, $ids, $key);
198 //CRM-16978:check duplicate relationship as per case id.
199 if ($caseId = CRM_Utils_Array
::value('case_id', $params)) {
200 $contactFields['case_id'] = $caseId;
203 self
::checkDuplicateRelationship(
205 CRM_Utils_Array
::value('contact', $ids),
214 $singleInstanceParams = array_merge($params, $contactFields);
215 $relationship = self
::add($singleInstanceParams);
216 $relationshipIds[] = $relationship->id
;
217 $relationships[$relationship->id
] = $relationship;
220 // editing the relationship
223 // check for duplicate relationship
224 // @todo this code doesn't cope well with updates - causes e-Notices.
225 // API has a lot of code to work around
226 // this but should review this code & remove the extra handling from the api
227 // it seems doubtful any of this is relevant if the contact fields & relationship
228 // type fields are not set
230 self
::checkDuplicateRelationship(
232 CRM_Utils_Array
::value('contact', $ids),
233 $ids['contactTarget'],
238 return [$valid, $invalid, $duplicate, $saved, NULL];
241 $validContacts = TRUE;
242 //validate contacts in update mode also.
243 $contactFields = self
::setContactABFromIDs($params, $ids, $ids['contactTarget']);
244 if (!empty($ids['contact']) && !empty($ids['contactTarget'])) {
245 if (self
::checkValidRelationship($contactFields, $ids, $ids['contactTarget'])) {
246 $validContacts = FALSE;
250 if ($validContacts) {
251 // editing an existing relationship
252 $singleInstanceParams = array_merge($params, $contactFields);
253 $relationship = self
::add($singleInstanceParams, $ids, $ids['contactTarget']);
254 $relationshipIds[] = $relationship->id
;
255 $relationships[$relationship->id
] = $relationship;
260 // do not add to recent items for import, CRM-4399
261 if (!(!empty($params['skipRecentView']) ||
$invalid ||
$duplicate)) {
262 self
::addRecent($params, $relationship);
265 return [$valid, $invalid, $duplicate, $saved, $relationshipIds, $relationships];
269 * This is the function that check/add if the relationship created is valid.
271 * @param array $params
272 * Array of name/value pairs.
274 * The array that holds all the db ids.
275 * @param int $contactId
276 * This is contact id for adding relationship.
278 * @return CRM_Contact_BAO_Relationship
280 * @throws \CiviCRM_API3_Exception
282 public static function add($params, $ids = [], $contactId = NULL) {
283 $params['id'] = CRM_Utils_Array
::value('relationship', $ids, CRM_Utils_Array
::value('id', $params));
289 CRM_Utils_Hook
::pre($hook, 'Relationship', $params['id'], $params);
291 $relationshipTypes = $params['relationship_type_id'] ??
NULL;
292 // explode the string with _ to get the relationship type id
293 // and to know which contact has to be inserted in
294 // contact_id_a and which one in contact_id_b
295 list($relationshipTypeID) = explode('_', $relationshipTypes);
297 $relationship = new CRM_Contact_BAO_Relationship();
298 if (!empty($params['id'])) {
299 $relationship->id
= $params['id'];
300 // Only load the relationship if we're missing required params
301 $requiredParams = ['contact_id_a', 'contact_id_b', 'relationship_type_id'];
302 foreach ($requiredParams as $requiredKey) {
303 if (!isset($params[$requiredKey])) {
304 $relationship->find(TRUE);
310 $relationship->copyValues($params);
311 // @todo we could probably set $params['relationship_type_id'] above but it's unclear
312 // what that would do with the code below this. So for now be conservative and set it manually.
313 if (!empty($relationshipTypeID)) {
314 $relationship->relationship_type_id
= $relationshipTypeID;
317 $params['contact_id_a'] = $relationship->contact_id_a
;
318 $params['contact_id_b'] = $relationship->contact_id_b
;
320 // check if the relationship type is Head of Household then update the
321 // household's primary contact with this contact.
323 $headOfHouseHoldID = civicrm_api3('RelationshipType', 'getvalue', [
325 'name_a_b' => "Head of Household for",
327 if ($relationshipTypeID == $headOfHouseHoldID) {
328 CRM_Contact_BAO_Household
::updatePrimaryContact($relationship->contact_id_b
, $relationship->contact_id_a
);
331 catch (Exception
$e) {
332 // No "Head of Household" relationship found so we skip specific processing
335 if (!empty($params['id']) && self
::isCurrentEmployerNeedingToBeCleared($relationship->toArray(), $params['id'], $relationshipTypeID)) {
336 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($relationship->contact_id_a
);
339 $dateFields = ['end_date', 'start_date'];
341 foreach (self
::getdefaults() as $defaultField => $defaultValue) {
342 if (isset($params[$defaultField])) {
343 if (in_array($defaultField, $dateFields)) {
344 $relationship->$defaultField = CRM_Utils_Date
::format(CRM_Utils_Array
::value($defaultField, $params));
345 if (!$relationship->$defaultField) {
346 $relationship->$defaultField = 'NULL';
350 $relationship->$defaultField = $params[$defaultField];
353 elseif (empty($params['id'])) {
354 $relationship->$defaultField = $defaultValue;
358 $relationship->save();
359 // is_current_employer is an optional parameter that triggers updating the employer_id field to reflect
360 // the relationship being updated. As of writing only truthy versions of the parameter are respected.
361 // https://github.com/civicrm/civicrm-core/pull/13331 attempted to cover both but stalled in QA
362 // so currently we have a cut down version.
363 if (!empty($params['is_current_employer'])) {
364 if (!$relationship->relationship_type_id ||
!$relationship->contact_id_a ||
!$relationship->contact_id_b
) {
365 $relationship->fetch();
367 if (self
::isRelationshipTypeCurrentEmployer($relationship->relationship_type_id
)) {
368 CRM_Contact_BAO_Contact_Utils
::setCurrentEmployer([$relationship->contact_id_a
=> $relationship->contact_id_b
]);
371 // add custom field values
372 if (!empty($params['custom'])) {
373 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_relationship', $relationship->id
);
376 CRM_Utils_Hook
::post($hook, 'Relationship', $relationship->id
, $relationship);
378 return $relationship;
382 * Add relationship to recent links.
384 * @param array $params
385 * @param CRM_Contact_DAO_Relationship $relationship
387 public static function addRecent($params, $relationship) {
388 $url = CRM_Utils_System
::url('civicrm/contact/view/rel',
389 "action=view&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&context=home"
391 $session = CRM_Core_Session
::singleton();
393 if (($session->get('userID') == $relationship->contact_id_a
) ||
394 CRM_Contact_BAO_Contact_Permission
::allow($relationship->contact_id_a
, CRM_Core_Permission
::EDIT
)
396 $rType = substr(CRM_Utils_Array
::value('relationship_type_id', $params), -3);
398 'editUrl' => CRM_Utils_System
::url('civicrm/contact/view/rel',
399 "action=update&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
401 'deleteUrl' => CRM_Utils_System
::url('civicrm/contact/view/rel',
402 "action=delete&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
406 $title = CRM_Contact_BAO_Contact
::displayName($relationship->contact_id_a
) . ' (' . CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType',
407 $relationship->relationship_type_id
, 'label_a_b'
408 ) . ' ' . CRM_Contact_BAO_Contact
::displayName($relationship->contact_id_b
) . ')';
410 CRM_Utils_Recent
::add($title,
414 $relationship->contact_id_a
,
421 * Load contact ids and relationship type id when doing a create call if not provided.
423 * There are are various checks done in create which require this information which is optional
426 * @param array $params
427 * Parameters passed to create call.
430 * Parameters with missing fields added if required.
432 public static function loadExistingRelationshipDetails($params) {
433 if (!empty($params['contact_id_a'])
434 && !empty($params['contact_id_b'])
435 && is_numeric($params['relationship_type_id'])) {
438 if (empty($params['id'])) {
442 $fieldsToFill = ['contact_id_a', 'contact_id_b', 'relationship_type_id'];
443 $result = CRM_Core_DAO
::executeQuery("SELECT " . implode(',', $fieldsToFill) . " FROM civicrm_relationship WHERE id = %1", [
449 while ($result->fetch()) {
450 foreach ($fieldsToFill as $field) {
451 $params[$field] = !empty($params[$field]) ?
$params[$field] : $result->$field;
458 * Resolve passed in contact IDs to contact_id_a & contact_id_b.
460 * @param array $params
462 * @param null $contactID
465 * @throws \CRM_Core_Exception
467 public static function setContactABFromIDs($params, $ids = [], $contactID = NULL) {
470 // $ids['contact'] is deprecated but comes from legacyCreateMultiple function.
471 if (empty($ids['contact'])) {
472 if (!empty($params['id'])) {
473 return self
::loadExistingRelationshipDetails($params);
475 throw new CRM_Core_Exception('Cannot create relationship, insufficient contact IDs provided');
477 if (isset($params['relationship_type_id']) && !is_numeric($params['relationship_type_id'])) {
478 $relationshipTypes = $params['relationship_type_id'] ??
NULL;
479 list($relationshipTypeID, $first) = explode('_', $relationshipTypes);
480 $returnFields['relationship_type_id'] = $relationshipTypeID;
482 foreach (['a', 'b'] as $contactLetter) {
483 if (empty($params['contact_' . $contactLetter])) {
484 if ($first == $contactLetter) {
485 $returnFields['contact_id_' . $contactLetter] = $ids['contact'] ??
NULL;
488 $returnFields['contact_id_' . $contactLetter] = $contactID;
494 return $returnFields;
498 * Specify defaults for creating a relationship.
501 * array of defaults for creating relationship
503 public static function getdefaults() {
506 'is_permission_a_b' => self
::NONE
,
507 'is_permission_b_a' => self
::NONE
,
509 'start_date' => 'NULL',
511 'end_date' => 'NULL',
516 * Check if there is data to create the object.
518 * @param array $params
522 public static function dataExists($params) {
523 return (isset($params['contact_check']) && is_array($params['contact_check']));
527 * Get get list of relationship type based on the contact type.
529 * @param int $contactId
530 * This is the contact id of the current contact.
531 * @param null $contactSuffix
532 * @param string $relationshipId
533 * The id of the existing relationship if any.
534 * @param string $contactType
537 * If true returns relationship types in both the direction.
538 * @param string $column
539 * Name/label that going to retrieve from db.
540 * @param bool $biDirectional
541 * @param array $contactSubType
542 * Includes relationship types between this subtype.
543 * @param bool $onlySubTypeRelationTypes
544 * If set only subtype which is passed by $contactSubType
545 * related relationship types get return
548 * array reference of all relationship types with context to current contact.
550 public static function getContactRelationshipType(
552 $contactSuffix = NULL,
553 $relationshipId = NULL,
557 $biDirectional = TRUE,
558 $contactSubType = NULL,
559 $onlySubTypeRelationTypes = FALSE
562 $relationshipType = [];
563 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType($column);
565 $otherContactType = NULL;
566 if ($relationshipId) {
567 $relationship = new CRM_Contact_DAO_Relationship();
568 $relationship->id
= $relationshipId;
569 if ($relationship->find(TRUE)) {
570 $contact = new CRM_Contact_DAO_Contact();
571 $contact->id
= ($relationship->contact_id_a
== $contactId) ?
$relationship->contact_id_b
: $relationship->contact_id_a
;
573 if ($contact->find(TRUE)) {
574 $otherContactType = $contact->contact_type
;
575 //CRM-5125 for contact subtype specific relationshiptypes
576 if ($contact->contact_sub_type
) {
577 $otherContactSubType = $contact->contact_sub_type
;
583 $contactSubType = (array) $contactSubType;
585 $contactType = CRM_Contact_BAO_Contact
::getContactType($contactId);
586 $contactSubType = CRM_Contact_BAO_Contact
::getContactSubType($contactId);
589 foreach ($allRelationshipType as $key => $value) {
590 // the contact type is required or matches
591 if (((!$value['contact_type_a']) ||
592 $value['contact_type_a'] == $contactType
594 // the other contact type is required or present or matches
595 ((!$value['contact_type_b']) ||
596 (!$otherContactType) ||
597 $value['contact_type_b'] == $otherContactType
599 (in_array($value['contact_sub_type_a'], $contactSubType) ||
600 (!$value['contact_sub_type_a'] && !$onlySubTypeRelationTypes)
603 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
606 if (((!$value['contact_type_b']) ||
607 $value['contact_type_b'] == $contactType
609 ((!$value['contact_type_a']) ||
610 (!$otherContactType) ||
611 $value['contact_type_a'] == $otherContactType
613 (in_array($value['contact_sub_type_b'], $contactSubType) ||
614 (!$value['contact_sub_type_b'] && !$onlySubTypeRelationTypes)
617 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
621 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
622 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
626 if ($biDirectional) {
627 $relationshipType = self
::removeRelationshipTypeDuplicates($relationshipType, $contactSuffix);
630 // sort the relationshipType in ascending order CRM-7736
631 asort($relationshipType);
632 return $relationshipType;
636 * Given a list of relationship types, return the list with duplicate types
637 * removed, being careful to retain only the duplicate which matches the given
638 * 'a_b' or 'b_a' suffix.
640 * @param array $relationshipTypeList A list of relationship types, in the format
641 * returned by self::getContactRelationshipType().
642 * @param string $suffix Either 'a_b' or 'b_a'; defaults to 'a_b'
644 * @return array The modified value of $relationshipType
646 public static function removeRelationshipTypeDuplicates($relationshipTypeList, $suffix = NULL) {
647 if (empty($suffix)) {
651 // Find those labels which are listed more than once.
652 $duplicateValues = array_diff_assoc($relationshipTypeList, array_unique($relationshipTypeList));
654 // For each duplicate label, find its keys, and remove from $relationshipType
655 // the key which does not match $suffix.
656 foreach ($duplicateValues as $value) {
657 $keys = array_keys($relationshipTypeList, $value);
658 foreach ($keys as $key) {
659 if (substr($key, -3) != $suffix) {
660 unset($relationshipTypeList[$key]);
664 return $relationshipTypeList;
668 * Delete current employer relationship.
673 * @return CRM_Contact_DAO_Relationship
675 public static function clearCurrentEmployer($id, $action) {
676 $relationship = new CRM_Contact_DAO_Relationship();
677 $relationship->id
= $id;
678 $relationship->find(TRUE);
680 //to delete relationship between household and individual \
681 //or between individual and organization
682 if (($action & CRM_Core_Action
::DISABLE
) ||
($action & CRM_Core_Action
::DELETE
)) {
683 $relTypes = CRM_Utils_Array
::index(['name_a_b'], CRM_Core_PseudoConstant
::relationshipType('name'));
685 (isset($relTypes['Employee of']) && $relationship->relationship_type_id
== $relTypes['Employee of']['id']) ||
686 (isset($relTypes['Household Member of']) && $relationship->relationship_type_id
== $relTypes['Household Member of']['id'])
688 $sharedContact = new CRM_Contact_DAO_Contact();
689 $sharedContact->id
= $relationship->contact_id_a
;
690 $sharedContact->find(TRUE);
693 // changed FROM "...relationship->relationship_type_id == 4..." TO "...relationship->relationship_type_id == 5..."
694 // As the system should be looking for type "employer of" (id 5) and not "sibling of" (id 4)
695 // As suggested by @davecivicrm, the employee relationship type id is fetched using the CRM_Core_DAO::getFieldValue() class and method, since these ids differ from system to system.
696 $employerRelTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b');
698 if ($relationship->relationship_type_id
== $employerRelTypeId && $relationship->contact_id_b
== $sharedContact->employer_id
) {
699 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($relationship->contact_id_a
);
704 return $relationship;
708 * Delete the relationship.
713 * @return CRM_Contact_DAO_Relationship
715 * @throws \CRM_Core_Exception
716 * @throws \CiviCRM_API3_Exception
718 public static function del($id) {
719 // delete from relationship table
720 CRM_Utils_Hook
::pre('delete', 'Relationship', $id, CRM_Core_DAO
::$_nullArray);
722 $relationship = self
::clearCurrentEmployer($id, CRM_Core_Action
::DELETE
);
723 $relationship->delete();
724 if (CRM_Core_Permission
::access('CiviMember')) {
725 // create $params array which isrequired to delete memberships
726 // of the related contacts.
728 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
729 'contact_check' => [$relationship->contact_id_b
=> 1],
733 // calling relatedMemberships to delete the memberships of
735 self
::relatedMemberships($relationship->contact_id_a
,
738 CRM_Core_Action
::DELETE
,
743 CRM_Core_Session
::setStatus(ts('Selected relationship has been deleted successfully.'), ts('Record Deleted'), 'success');
745 CRM_Utils_Hook
::post('delete', 'Relationship', $id, $relationship);
747 // delete the recently created Relationship
748 $relationshipRecent = [
750 'type' => 'Relationship',
752 CRM_Utils_Recent
::del($relationshipRecent);
754 return $relationship;
758 * Disable/enable the relationship.
764 * @param array $params
766 * @param bool $active
768 * @throws \CRM_Core_Exception
769 * @throws \CiviCRM_API3_Exception
771 public static function disableEnableRelationship($id, $action, $params = [], $ids = [], $active = FALSE) {
772 $relationship = self
::clearCurrentEmployer($id, $action);
775 // create $params array which is required to delete memberships
776 // of the related contacts.
777 if (empty($params)) {
779 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
780 'contact_check' => [$relationship->contact_id_b
=> 1],
783 $contact_id_a = empty($params['contact_id_a']) ?
$relationship->contact_id_a
: $params['contact_id_a'];
784 // calling relatedMemberships to delete/add the memberships of
786 if ($action & CRM_Core_Action
::DISABLE
) {
787 // @todo this could call a subset of the function that just relates to
788 // cleaning up no-longer-inherited relationships
789 CRM_Contact_BAO_Relationship
::relatedMemberships($contact_id_a,
792 CRM_Core_Action
::DELETE
,
796 elseif ($action & CRM_Core_Action
::ENABLE
) {
797 $ids['contact'] = empty($ids['contact']) ?
$contact_id_a : $ids['contact'];
798 CRM_Contact_BAO_Relationship
::relatedMemberships($contact_id_a,
801 empty($params['id']) ? CRM_Core_Action
::ADD
: CRM_Core_Action
::UPDATE
,
809 * Delete the object records that are associated with this contact.
811 * @param int $contactId
812 * Id of the contact to delete.
814 public static function deleteContact($contactId) {
815 $relationship = new CRM_Contact_DAO_Relationship();
816 $relationship->contact_id_a
= $contactId;
817 $relationship->delete();
819 $relationship = new CRM_Contact_DAO_Relationship();
820 $relationship->contact_id_b
= $contactId;
821 $relationship->delete();
823 CRM_Contact_BAO_Household
::updatePrimaryContact(NULL, $contactId);
827 * Get the other contact in a relationship.
832 * $returns returns the contact ids in the relationship
834 * @return \CRM_Contact_DAO_Relationship
836 public static function getRelationshipByID($id) {
837 $relationship = new CRM_Contact_DAO_Relationship();
839 $relationship->id
= $id;
840 $relationship->selectAdd();
841 $relationship->selectAdd('contact_id_a, contact_id_b');
842 $relationship->find(TRUE);
844 return $relationship;
848 * Check if the relationship type selected between two contacts is correct.
850 * @param int $contact_a
852 * @param int $contact_b
854 * @param int $relationshipTypeId
855 * Relationship type id.
858 * true if it is valid relationship else false
860 public static function checkRelationshipType($contact_a, $contact_b, $relationshipTypeId) {
861 $relationshipType = new CRM_Contact_DAO_RelationshipType();
862 $relationshipType->id
= $relationshipTypeId;
863 $relationshipType->selectAdd();
864 $relationshipType->selectAdd('contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b');
865 if ($relationshipType->find(TRUE)) {
866 $contact_type_a = CRM_Contact_BAO_Contact
::getContactType($contact_a);
867 $contact_type_b = CRM_Contact_BAO_Contact
::getContactType($contact_b);
869 $contact_sub_type_a = CRM_Contact_BAO_Contact
::getContactSubType($contact_a);
870 $contact_sub_type_b = CRM_Contact_BAO_Contact
::getContactSubType($contact_b);
872 if (((!$relationshipType->contact_type_a
) ||
($relationshipType->contact_type_a
== $contact_type_a)) &&
873 ((!$relationshipType->contact_type_b
) ||
($relationshipType->contact_type_b
== $contact_type_b)) &&
874 ((!$relationshipType->contact_sub_type_a
) ||
(in_array($relationshipType->contact_sub_type_a
,
877 ((!$relationshipType->contact_sub_type_b
) ||
(in_array($relationshipType->contact_sub_type_b
,
891 * This function does the validtion for valid relationship.
893 * @param array $params
894 * This array contains the values there are subitted by the form.
896 * The array that holds all the db ids.
897 * @param int $contactId
898 * This is contact id for adding relationship.
902 public static function checkValidRelationship($params, $ids, $contactId) {
904 // function to check if the relationship selected is correct
905 // i.e. employer relationship can exit between Individual and Organization (not between Individual and Individual)
906 if (!CRM_Contact_BAO_Relationship
::checkRelationshipType($params['contact_id_a'], $params['contact_id_b'],
907 $params['relationship_type_id'])) {
908 $errors = 'Please select valid relationship between these two contacts.';
914 * This function checks for duplicate relationship.
916 * @param array $params
917 * (reference ) an assoc array of name/value pairs.
919 * This the id of the contact whom we are adding relationship.
920 * @param int $contactId
921 * This is contact id for adding relationship.
922 * @param int $relationshipId
923 * This is relationship id for the contact.
926 * true if record exists else false
928 public static function checkDuplicateRelationship(&$params, $id, $contactId = 0, $relationshipId = 0) {
929 $relationshipTypeId = $params['relationship_type_id'] ??
NULL;
930 list($type) = explode('_', $relationshipTypeId);
934 FROM civicrm_relationship
935 WHERE relationship_type_id = " . CRM_Utils_Type
::escape($type, 'Integer');
938 * CRM-11792 - date fields from API are in ISO format, but this function
939 * supports date arrays BAO has increasingly standardised to ISO format
940 * so I believe this function should support ISO rather than make API
941 * format it - however, need to support array format for now to avoid breakage
942 * @ time of writing this function is called from Relationship::legacyCreateMultiple (twice)
943 * CRM_BAO_Contact_Utils::clearCurrentEmployer (seemingly without dates)
944 * CRM_Contact_Form_Task_AddToOrganization::postProcess &
945 * CRM_Contact_Form_Task_AddToHousehold::postProcess
946 * (I don't think the last 2 support dates but not sure
949 $dateFields = ['end_date', 'start_date'];
950 foreach ($dateFields as $dateField) {
951 if (array_key_exists($dateField, $params)) {
952 if (empty($params[$dateField]) ||
$params[$dateField] == 'null') {
953 //this is most likely coming from an api call & probably loaded
954 // from the DB to deal with some of the
955 // other myriad of excessive checks still in place both in
956 // the api & the create functions
957 $queryString .= " AND $dateField IS NULL";
960 elseif (is_array($params[$dateField])) {
961 $queryString .= " AND $dateField = " .
962 CRM_Utils_Type
::escape(CRM_Utils_Date
::format($params[$dateField]), 'Date');
965 $queryString .= " AND $dateField = " .
966 CRM_Utils_Type
::escape($params[$dateField], 'Date');
972 " AND ( ( contact_id_a = " . CRM_Utils_Type
::escape($id, 'Integer') .
973 " AND contact_id_b = " . CRM_Utils_Type
::escape($contactId, 'Integer') .
974 " ) OR ( contact_id_a = " . CRM_Utils_Type
::escape($contactId, 'Integer') .
975 " AND contact_id_b = " . CRM_Utils_Type
::escape($id, 'Integer') . " ) ) ";
977 //if caseId is provided, include it duplicate checking.
978 if ($caseId = CRM_Utils_Array
::value('case_id', $params)) {
979 $queryString .= " AND case_id = " . CRM_Utils_Type
::escape($caseId, 'Integer');
982 if ($relationshipId) {
983 $queryString .= " AND id !=" . CRM_Utils_Type
::escape($relationshipId, 'Integer');
986 $relationship = new CRM_Contact_BAO_Relationship();
987 $relationship->query($queryString);
988 while ($relationship->fetch()) {
989 // Check whether the custom field values are identical.
990 $result = self
::checkDuplicateCustomFields($params, $relationship->id
);
999 * this function checks whether the values of the custom fields in $params are
1000 * the same as the values of the custom fields of the relation with given
1003 * @param array $params (reference) an assoc array of name/value pairs
1004 * @param int $relationshipId ID of an existing duplicate relation
1006 * @return boolean true if custom field values are identical
1010 private static function checkDuplicateCustomFields(&$params, $relationshipId) {
1011 // Get the custom values of the existing relationship.
1012 $existingValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($relationshipId, 'Relationship');
1013 // Create a similar array for the new relationship.
1015 if (array_key_exists('custom', $params)) {
1016 // $params['custom'] seems to be an array. Each value is again an array.
1017 // This array contains one value (key -1), and this value seems to be
1018 // an array with the information about the custom value.
1019 foreach ($params['custom'] as $value) {
1020 foreach ($value as $customValue) {
1021 $newValues[$customValue['custom_field_id']] = $customValue['value'];
1026 // Calculate difference between arrays. If the only key-value pairs
1027 // that are in one array but not in the other are empty, the
1028 // custom fields are considered to be equal.
1029 // See https://github.com/civicrm/civicrm-core/pull/6515#issuecomment-137985667
1030 $diff1 = array_diff_assoc($existingValues, $newValues);
1031 $diff2 = array_diff_assoc($newValues, $existingValues);
1033 return !array_filter($diff1) && !array_filter($diff2);
1037 * Update the is_active flag in the db.
1040 * Id of the database record.
1041 * @param bool $is_active
1042 * Value we want to set the is_active field.
1046 * @throws CiviCRM_API3_Exception
1048 public static function setIsActive($id, $is_active) {
1049 // as both the create & add functions have a bunch of logic in them that
1050 // doesn't seem to cope with a normal update we will call the api which
1051 // has tested handling for this
1052 // however, a longer term solution would be to simplify the add, create & api functions
1053 // to be more standard. It is debatable @ that point whether it's better to call the BAO
1054 // direct as the api is more tested.
1055 $result = civicrm_api('relationship', 'create', [
1057 'is_active' => $is_active,
1061 if (is_array($result) && !empty($result['is_error']) && $result['error_message'] != 'Duplicate Relationship') {
1062 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array
::value('error_code', $result, 'undefined'), $result);
1069 * Fetch a relationship object and store the values in the values array.
1071 * @param array $params
1072 * Input parameters to find object.
1073 * @param array $values
1074 * Output values of the object.
1077 * (reference) the values that could be potentially assigned to smarty
1079 public static function &getValues(&$params, &$values) {
1080 if (empty($params)) {
1085 // get the specific number of relationship or all relationships.
1086 if (!empty($params['numRelationship'])) {
1087 $v['data'] = &CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'], NULL, $params['numRelationship']);
1090 $v['data'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id']);
1093 // get the total count of relationships
1094 $v['totalCount'] = count($v['data']);
1096 $values['relationship']['data'] = &$v['data'];
1097 $values['relationship']['totalCount'] = &$v['totalCount'];
1103 * Helper function to form the sql for relationship retrieval.
1105 * @param int $contactId
1107 * @param int $status
1108 * (check const at top of file).
1109 * @param int $numRelationship
1110 * No of relationships to display (limit).
1112 * Get the no of relationships.
1113 * $param int $relationshipId relationship id
1114 * @param int $relationshipId
1115 * @param string $direction
1116 * The direction we are interested in a_b or b_a.
1117 * @param array $params
1118 * Array of extra values including relationship_type_id per api spec.
1121 * [select, from, where]
1123 * @throws \CRM_Core_Exception
1124 * @throws \CiviCRM_API3_Exception
1126 public static function makeURLClause($contactId, $status, $numRelationship, $count, $relationshipId, $direction, $params = []) {
1127 $select = $from = $where = '';
1131 if ($direction === 'a_b') {
1132 $select .= ' SELECT count(DISTINCT civicrm_relationship.id) as cnt1, 0 as cnt2 ';
1135 $select .= ' SELECT 0 as cnt1, count(DISTINCT civicrm_relationship.id) as cnt2 ';
1139 $select .= ' SELECT civicrm_relationship.id as civicrm_relationship_id,
1140 civicrm_contact.sort_name as sort_name,
1141 civicrm_contact.display_name as display_name,
1142 civicrm_contact.job_title as job_title,
1143 civicrm_contact.employer_id as employer_id,
1144 civicrm_contact.organization_name as organization_name,
1145 civicrm_address.street_address as street_address,
1146 civicrm_address.city as city,
1147 civicrm_address.postal_code as postal_code,
1148 civicrm_state_province.abbreviation as state,
1149 civicrm_country.name as country,
1150 civicrm_email.email as email,
1151 civicrm_contact.contact_type as contact_type,
1152 civicrm_contact.contact_sub_type as contact_sub_type,
1153 civicrm_phone.phone as phone,
1154 civicrm_contact.id as civicrm_contact_id,
1155 civicrm_relationship.contact_id_b as contact_id_b,
1156 civicrm_relationship.contact_id_a as contact_id_a,
1157 civicrm_relationship_type.id as civicrm_relationship_type_id,
1158 civicrm_relationship.start_date as start_date,
1159 civicrm_relationship.end_date as end_date,
1160 civicrm_relationship.description as description,
1161 civicrm_relationship.is_active as is_active,
1162 civicrm_relationship.is_permission_a_b as is_permission_a_b,
1163 civicrm_relationship.is_permission_b_a as is_permission_b_a,
1164 civicrm_relationship.case_id as case_id';
1166 if ($direction === 'a_b') {
1167 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
1168 civicrm_relationship_type.label_b_a as relation ';
1171 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
1172 civicrm_relationship_type.label_a_b as relation ';
1177 FROM civicrm_relationship
1178 INNER JOIN civicrm_relationship_type ON ( civicrm_relationship.relationship_type_id = civicrm_relationship_type.id )
1179 INNER JOIN civicrm_contact ';
1180 if ($direction === 'a_b') {
1181 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_a ) ';
1184 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_b ) ';
1189 LEFT JOIN civicrm_address ON (civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1)
1190 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
1191 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id AND civicrm_email.is_primary = 1)
1192 LEFT JOIN civicrm_state_province ON (civicrm_address.state_province_id = civicrm_state_province.id)
1193 LEFT JOIN civicrm_country ON (civicrm_address.country_id = civicrm_country.id)
1197 $where = 'WHERE ( 1 )';
1199 if ($direction === 'a_b') {
1200 $where .= ' AND civicrm_relationship.contact_id_b = ' . CRM_Utils_Type
::escape($contactId, 'Positive');
1203 $where .= ' AND civicrm_relationship.contact_id_a = ' . CRM_Utils_Type
::escape($contactId, 'Positive') . '
1204 AND civicrm_relationship.contact_id_a != civicrm_relationship.contact_id_b ';
1207 if ($relationshipId) {
1208 $where .= ' AND civicrm_relationship.id = ' . CRM_Utils_Type
::escape($relationshipId, 'Positive');
1211 $date = date('Y-m-d');
1212 if ($status == self
::PAST
) {
1213 //this case for showing past relationship
1214 $where .= ' AND civicrm_relationship.is_active = 1 ';
1215 $where .= " AND civicrm_relationship.end_date < '" . $date . "'";
1217 elseif ($status == self
::DISABLED
) {
1218 // this case for showing disabled relationship
1219 $where .= ' AND civicrm_relationship.is_active = 0 ';
1221 elseif ($status == self
::CURRENT
) {
1222 //this case for showing current relationship
1223 $where .= ' AND civicrm_relationship.is_active = 1 ';
1224 $where .= " AND (civicrm_relationship.end_date >= '" . $date . "' OR civicrm_relationship.end_date IS NULL) ";
1226 elseif ($status == self
::INACTIVE
) {
1227 //this case for showing inactive relationships
1228 $where .= " AND (civicrm_relationship.end_date < '" . $date . "'";
1229 $where .= ' OR civicrm_relationship.is_active = 0 )';
1233 $where .= ' AND civicrm_contact.is_deleted = 0';
1234 if (!empty($params['membership_type_id']) && empty($params['relationship_type_id'])) {
1235 $where .= self
::membershipTypeToRelationshipTypes($params, $direction);
1237 if (!empty($params['relationship_type_id'])) {
1238 if (is_array($params['relationship_type_id'])) {
1239 $where .= " AND " . CRM_Core_DAO
::createSQLFilter('relationship_type_id', $params['relationship_type_id'], 'Integer');
1242 $where .= ' AND relationship_type_id = ' . CRM_Utils_Type
::escape($params['relationship_type_id'], 'Positive');
1245 if ($direction === 'a_b') {
1246 $where .= ' ) UNION ';
1252 return [$select, $from, $where];
1256 * Get a list of relationships.
1258 * @param int $contactId
1260 * @param int $status
1261 * 1: Past 2: Disabled 3: Current.
1262 * @param int $numRelationship
1263 * No of relationships to display (limit).
1265 * Get the no of relationships.
1266 * @param int $relationshipId
1267 * @param array $links
1268 * the list of links to display
1269 * @param int $permissionMask
1270 * the permission mask to be applied for the actions
1271 * @param bool $permissionedContact
1272 * to return only permissioned Contact
1273 * @param array $params
1274 * @param bool $includeTotalCount
1275 * Should we return a count of total accessable relationships
1278 * relationship records
1280 * @throws \CRM_Core_Exception
1281 * @throws \CiviCRM_API3_Exception
1283 public static function getRelationship(
1285 $status = 0, $numRelationship = 0,
1286 $count = 0, $relationshipId = 0,
1287 $links = NULL, $permissionMask = NULL,
1288 $permissionedContact = FALSE,
1289 $params = [], $includeTotalCount = FALSE
1292 if (!$contactId && !$relationshipId) {
1296 list($select1, $from1, $where1) = self
::makeURLClause($contactId, $status, $numRelationship,
1297 $count, $relationshipId, 'a_b', $params
1299 list($select2, $from2, $where2) = self
::makeURLClause($contactId, $status, $numRelationship,
1300 $count, $relationshipId, 'b_a', $params
1303 $order = $limit = '';
1305 if (empty($params['sort'])) {
1306 $order = ' ORDER BY civicrm_relationship_type_id, sort_name ';
1309 $order = " ORDER BY {$params['sort']} ";
1313 if (!empty($params['offset']) && $params['offset'] > 0) {
1314 $offset = $params['offset'];
1317 if ($numRelationship) {
1318 $limit = " LIMIT {$offset}, $numRelationship";
1322 // building the query string
1323 $queryString = $select1 . $from1 . $where1 . $select2 . $from2 . $where2;
1325 $relationship = new CRM_Contact_DAO_Relationship();
1327 $relationship->query($queryString . $order . $limit);
1330 $relationshipCount = 0;
1331 while ($relationship->fetch()) {
1332 $relationshipCount +
= $relationship->cnt1 +
$relationship->cnt2
;
1334 return $relationshipCount;
1338 if ($includeTotalCount) {
1339 $values['total_relationships'] = CRM_Core_DAO
::singleValueQuery("SELECT count(*) FROM ({$queryString}) AS r");
1343 if ($status != self
::INACTIVE
) {
1345 $mask = array_sum(array_keys($links));
1346 if ($mask & CRM_Core_Action
::DISABLE
) {
1347 $mask -= CRM_Core_Action
::DISABLE
;
1349 if ($mask & CRM_Core_Action
::ENABLE
) {
1350 $mask -= CRM_Core_Action
::ENABLE
;
1353 if ($status == self
::CURRENT
) {
1354 $mask |
= CRM_Core_Action
::DISABLE
;
1356 elseif ($status == self
::DISABLED
) {
1357 $mask |
= CRM_Core_Action
::ENABLE
;
1360 // temporary hold the value of $mask.
1364 while ($relationship->fetch()) {
1365 $rid = $relationship->civicrm_relationship_id
;
1366 $cid = $relationship->civicrm_contact_id
;
1368 if ($permissionedContact &&
1369 (!CRM_Contact_BAO_Contact_Permission
::allow($cid))
1373 if ($status != self
::INACTIVE
&& $links) {
1374 // assign the original value to $mask
1376 // display action links if $cid has edit permission for the relationship.
1377 if (!($permissionMask & CRM_Core_Permission
::EDIT
) && CRM_Contact_BAO_Contact_Permission
::allow($cid, CRM_Core_Permission
::EDIT
)) {
1378 $permissions[] = CRM_Core_Permission
::EDIT
;
1379 $permissions[] = CRM_Core_Permission
::DELETE
;
1380 $permissionMask = CRM_Core_Action
::mask($permissions);
1382 $mask = $mask & $permissionMask;
1384 $values[$rid]['id'] = $rid;
1385 $values[$rid]['cid'] = $cid;
1386 $values[$rid]['contact_id_a'] = $relationship->contact_id_a
;
1387 $values[$rid]['contact_id_b'] = $relationship->contact_id_b
;
1388 $values[$rid]['contact_type'] = $relationship->contact_type
;
1389 $values[$rid]['contact_sub_type'] = $relationship->contact_sub_type
;
1390 $values[$rid]['relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1391 $values[$rid]['relation'] = $relationship->relation
;
1392 $values[$rid]['name'] = $relationship->sort_name
;
1393 $values[$rid]['display_name'] = $relationship->display_name
;
1394 $values[$rid]['job_title'] = $relationship->job_title
;
1395 $values[$rid]['email'] = $relationship->email
;
1396 $values[$rid]['phone'] = $relationship->phone
;
1397 $values[$rid]['employer_id'] = $relationship->employer_id
;
1398 $values[$rid]['organization_name'] = $relationship->organization_name
;
1399 $values[$rid]['country'] = $relationship->country
;
1400 $values[$rid]['city'] = $relationship->city
;
1401 $values[$rid]['state'] = $relationship->state
;
1402 $values[$rid]['start_date'] = $relationship->start_date
;
1403 $values[$rid]['end_date'] = $relationship->end_date
;
1404 $values[$rid]['description'] = $relationship->description
;
1405 $values[$rid]['is_active'] = $relationship->is_active
;
1406 $values[$rid]['is_permission_a_b'] = $relationship->is_permission_a_b
;
1407 $values[$rid]['is_permission_b_a'] = $relationship->is_permission_b_a
;
1408 $values[$rid]['case_id'] = $relationship->case_id
;
1411 $values[$rid]['status'] = $status;
1414 $values[$rid]['civicrm_relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1416 if ($relationship->contact_id_a
== $contactId) {
1417 $values[$rid]['rtype'] = 'a_b';
1420 $values[$rid]['rtype'] = 'b_a';
1426 'rtype' => $values[$rid]['rtype'],
1427 'cid' => $contactId,
1428 'cbid' => $values[$rid]['cid'],
1429 'caseid' => $values[$rid]['case_id'],
1430 'clientid' => $contactId,
1433 if ($status == self
::INACTIVE
) {
1434 // setting links for inactive relationships
1435 $mask = array_sum(array_keys($links));
1436 if (!$values[$rid]['is_active']) {
1437 $mask -= CRM_Core_Action
::DISABLE
;
1440 $mask -= CRM_Core_Action
::ENABLE
;
1441 $mask -= CRM_Core_Action
::DISABLE
;
1443 $mask = $mask & $permissionMask;
1446 // Give access to manage case link by copying to MAX_ACTION index temporarily, depending on case permission of user.
1447 if ($values[$rid]['case_id']) {
1448 // Borrowed logic from CRM_Case_Page_Tab
1449 $hasCaseAccess = FALSE;
1450 if (CRM_Core_Permission
::check('access all cases and activities')) {
1451 $hasCaseAccess = TRUE;
1454 $userCases = CRM_Case_BAO_Case
::getCases(FALSE);
1455 if (array_key_exists($values[$rid]['case_id'], $userCases)) {
1456 $hasCaseAccess = TRUE;
1460 if ($hasCaseAccess) {
1461 // give access by copying to MAX_ACTION temporarily, otherwise leave at NONE which won't display
1462 $links[CRM_Core_Action
::MAX_ACTION
] = $links[CRM_Core_Action
::NONE
];
1463 $links[CRM_Core_Action
::MAX_ACTION
]['name'] = ts('Manage Case #%1', [1 => $values[$rid]['case_id']]);
1464 $links[CRM_Core_Action
::MAX_ACTION
]['class'] = 'no-popup';
1466 // Also make sure we have the right client cid since can get here from multiple relationship tabs.
1467 if ($values[$rid]['rtype'] == 'b_a') {
1468 $replace['clientid'] = $values[$rid]['cid'];
1470 $values[$rid]['case'] = '<a href="' . CRM_Utils_System
::url('civicrm/case/ajax/details', sprintf('caseId=%d&cid=%d&snippet=4', $values[$rid]['case_id'], $values[$rid]['cid'])) . '" class="action-item crm-hover-button crm-summary-link"><i class="crm-i fa-folder-open-o" aria-hidden="true"></i></a>';
1474 $values[$rid]['action'] = CRM_Core_Action
::formLink(
1480 'relationship.selector.row',
1483 unset($links[CRM_Core_Action
::MAX_ACTION
]);
1492 * Get list of relationship type based on the target contact type.
1493 * Both directions of relationships are included if their labels are not the same.
1495 * @param string $targetContactType
1496 * A valid contact type (may be Individual, Organization, Household).
1499 * array reference of all relationship types with context to current contact type.
1501 public static function getRelationType($targetContactType) {
1502 $relationshipType = [];
1503 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType();
1505 foreach ($allRelationshipType as $key => $type) {
1506 if ($type['contact_type_b'] == $targetContactType ||
empty($type['contact_type_b'])) {
1507 $relationshipType[$key . '_a_b'] = $type['label_a_b'];
1509 if (($type['contact_type_a'] == $targetContactType ||
empty($type['contact_type_a']))
1510 && $type['label_a_b'] != $type['label_b_a']
1512 $relationshipType[$key . '_b_a'] = $type['label_b_a'];
1516 return $relationshipType;
1520 * Create / update / delete membership for related contacts.
1522 * This function will create/update/delete membership for related
1523 * contact based on 1) contact have active membership 2) that
1524 * membership is is extedned by the same relationship type to that
1525 * of the existing relationship.
1527 * @param int $contactId
1529 * @param array $params
1530 * array of values submitted by POST.
1533 * @param \const|int $action which action called this function
1535 * @param bool $active
1537 * @throws \CRM_Core_Exception
1538 * @throws \CiviCRM_API3_Exception
1540 public static function relatedMemberships($contactId, &$params, $ids, $action = CRM_Core_Action
::ADD
, $active = TRUE) {
1541 // Check the end date and set the status of the relationship
1543 $status = self
::CURRENT
;
1544 $targetContact = $targetContact = CRM_Utils_Array
::value('contact_check', $params, []);
1545 $today = date('Ymd');
1547 // If a relationship hasn't yet started, just return for now
1548 // TODO: handle edge-case of updating start_date of an existing relationship
1549 if (!empty($params['start_date'])) {
1550 $startDate = substr(CRM_Utils_Date
::format($params['start_date']), 0, 8);
1551 if ($today < $startDate) {
1556 if (!empty($params['end_date'])) {
1557 $endDate = substr(CRM_Utils_Date
::format($params['end_date']), 0, 8);
1558 if ($today > $endDate) {
1559 $status = self
::PAST
;
1563 if (($action & CRM_Core_Action
::ADD
) && ($status & self
::PAST
)) {
1564 // If relationship is PAST and action is ADD, do nothing.
1568 $rel = explode('_', $params['relationship_type_id']);
1570 $relTypeId = $rel[0];
1571 if (!empty($rel[1])) {
1572 $relDirection = "_{$rel[1]}_{$rel[2]}";
1575 // this call is coming from somewhere where the direction was resolved early on (e.g an api call)
1576 // so we can assume _a_b
1577 $relDirection = "_a_b";
1578 $targetContact = [$params['contact_id_b'] => 1];
1581 if (($action & CRM_Core_Action
::ADD
) ||
1582 ($action & CRM_Core_Action
::DELETE
)
1584 $contact = $contactId;
1586 elseif ($action & CRM_Core_Action
::UPDATE
) {
1587 $contact = (int) $ids['contact'];
1588 $targetContact = [$ids['contactTarget'] => 1];
1591 // Build the 'values' array for
1594 // This will allow us to check if either of the contacts in
1595 // relationship have active memberships.
1600 $values[$contact] = [
1601 'relatedContacts' => $targetContact,
1602 'relationshipTypeId' => $relTypeId,
1603 'relationshipTypeDirection' => $relDirection,
1606 if (!empty($targetContact)) {
1607 foreach ($targetContact as $cid => $donCare) {
1609 'relatedContacts' => [$contact => 1],
1610 'relationshipTypeId' => $relTypeId,
1613 $relTypeParams = ['id' => $relTypeId];
1614 $relTypeValues = [];
1615 CRM_Contact_BAO_RelationshipType
::retrieve($relTypeParams, $relTypeValues);
1617 if (CRM_Utils_Array
::value('name_a_b', $relTypeValues) == CRM_Utils_Array
::value('name_b_a', $relTypeValues)) {
1618 $values[$cid]['relationshipTypeDirection'] = '_a_b';
1621 $values[$cid]['relationshipTypeDirection'] = ($relDirection == '_a_b') ?
'_b_a' : '_a_b';
1626 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1628 $relationshipProcessor = new CRM_Member_Utils_RelationshipProcessor(array_keys($values), $active);
1629 foreach ($values as $cid => $details) {
1630 $relatedContacts = array_keys(CRM_Utils_Array
::value('relatedContacts', $details, []));
1631 $mainRelatedContactId = reset($relatedContacts);
1633 foreach ($relationshipProcessor->getRelationshipMembershipsForContact((int) $cid) as $membershipId => $membershipValues) {
1634 $membershipInherittedFromContactID = NULL;
1635 if (!empty($membershipValues['owner_membership_id'])) {
1636 // @todo - $membership already has this now.
1637 // Use get not getsingle so that we get e-notice noise but not a fatal is the membership has already been deleted.
1638 $inheritedFromMembership = civicrm_api3('Membership', 'get', ['id' => $membershipValues['owner_membership_id'], 'sequential' => 1])['values'][0];
1639 $membershipInherittedFromContactID = (int) $inheritedFromMembership['contact_id'];
1642 if ($action & CRM_Core_Action
::DELETE
) {
1643 // @todo don't return relTypeId here - but it seems to be used later in a cryptic way (hint cryptic is not a complement).
1644 list($relTypeId, $isDeletable) = self
::isInheritedMembershipInvalidated($membershipValues, $values, $cid);
1646 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipValues['owner_membership_id'], $membershipValues['contact_id']);
1650 if (($action & CRM_Core_Action
::UPDATE
) &&
1651 ($status & self
::PAST
) &&
1652 ($membershipValues['owner_membership_id'])
1654 // If relationship is PAST and action is UPDATE
1655 // then delete the RELATED membership
1656 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipValues['owner_membership_id'],
1657 $membershipValues['contact_id']
1662 // add / edit the memberships for related
1665 // @todo - all these lines get 'relTypeDirs' - but it's already a key in the $membership array.
1666 // Get the Membership Type Details.
1667 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipType($membershipValues['membership_type_id']);
1668 // Check if contact's relationship type exists in membership type
1670 if (!empty($membershipType['relationship_type_id'])) {
1671 $relTypeIds = (array) $membershipType['relationship_type_id'];
1673 if (!empty($membershipType['relationship_direction'])) {
1674 $relDirections = (array) $membershipType['relationship_direction'];
1676 foreach ($relTypeIds as $key => $value) {
1677 $relTypeDirs[] = $value . '_' . $relDirections[$key];
1679 $relTypeDir = $details['relationshipTypeId'] . $details['relationshipTypeDirection'];
1680 if (in_array($relTypeDir, $relTypeDirs)) {
1681 // Check if relationship being created/updated is
1682 // similar to that of membership type's
1685 $membershipValues['owner_membership_id'] = $membershipId;
1686 unset($membershipValues['id']);
1687 unset($membershipValues['contact_id']);
1688 unset($membershipValues['membership_id']);
1689 foreach ($details['relatedContacts'] as $relatedContactId => $donCare) {
1690 $membershipValues['contact_id'] = $relatedContactId;
1691 if ($deceasedStatusId &&
1692 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $relatedContactId, 'is_deceased')
1694 $membershipValues['status_id'] = $deceasedStatusId;
1695 $membershipValues['skipStatusCal'] = TRUE;
1698 if (in_array($action, [CRM_Core_Action
::UPDATE
, CRM_Core_Action
::ADD
, CRM_Core_Action
::ENABLE
])) {
1699 //if updated relationship is already related to contact don't delete existing inherited membership
1700 if (in_array((int) $relatedContactId, $membershipValues['inheriting_contact_ids'], TRUE)
1701 ||
$relatedContactId === $membershipValues['owner_contact_id']
1706 //delete the membership record for related
1707 //contact before creating new membership record.
1708 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $relatedContactId);
1710 //skip status calculation for pay later memberships.
1711 if ('Pending' === CRM_Core_PseudoConstant
::getName('CRM_Member_BAO_Membership', 'status_id', $membershipValues['status_id'])) {
1712 $membershipValues['skipStatusCal'] = TRUE;
1714 // As long as the membership itself was not created by inheritance from the same contact
1715 // that stands to inherit the membership we add an inherited membership.
1716 if ($membershipInherittedFromContactID !== (int) $membershipValues['contact_id']) {
1717 $membershipValues = self
::addInheritedMembership($membershipValues);
1721 elseif ($action & CRM_Core_Action
::UPDATE
) {
1722 // if action is update and updated relationship do
1723 // not match with the existing
1724 // membership=>relationship then we need to
1725 // change the status of the membership record to expired for
1726 // previous relationship -- CRM-12078.
1727 // CRM-16087 we need to pass ownerMembershipId to isRelatedMembershipExpired function
1728 if (empty($params['relationship_ids']) && !empty($params['id'])) {
1729 $relIds = [$params['id']];
1732 $relIds = $params['relationship_ids'] ??
NULL;
1734 if (self
::isRelatedMembershipExpired($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId,
1735 $relIds) && !empty($membershipValues['owner_membership_id']
1736 ) && !empty($values[$mainRelatedContactId]['memberships'][$membershipValues['owner_membership_id']])) {
1737 $membershipValues['status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus', 'Expired', 'id', 'label');
1738 $type = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $membershipValues['membership_type_id'], 'name', 'id');
1739 CRM_Member_BAO_Membership
::add($membershipValues);
1740 CRM_Core_Session
::setStatus(ts("Inherited membership %1 status was changed to Expired due to the change in relationship type.", [1 => $type]), ts('Record Updated'), 'alert');
1748 * Helper function to check whether the membership is expired or not.
1750 * Function takes a list of related membership types and if it is not also passed a
1751 * relationship ID of that types evaluates whether the membership status should be changed to expired.
1753 * @param array $membershipTypeRelationshipTypeIDs
1754 * Relation type IDs related to the given membership type.
1755 * @param int $contactId
1756 * @param int $mainRelatedContactId
1757 * @param int $relTypeId
1758 * @param array $relIds
1762 public static function isRelatedMembershipExpired($membershipTypeRelationshipTypeIDs, $contactId, $mainRelatedContactId, $relTypeId, $relIds) {
1763 if (empty($membershipTypeRelationshipTypeIDs) ||
in_array($relTypeId, $membershipTypeRelationshipTypeIDs)) {
1767 if (empty($relIds)) {
1772 1 => [$contactId, 'Integer'],
1773 2 => [$mainRelatedContactId, 'Integer'],
1776 if ($contactId == $mainRelatedContactId) {
1777 $recordsFound = (int) CRM_Core_DAO
::singleValueQuery("SELECT COUNT(*) FROM civicrm_relationship WHERE relationship_type_id IN ( " . implode(',', $membershipTypeRelationshipTypeIDs) . " ) AND
1778 contact_id_a IN ( %1 ) OR contact_id_b IN ( %1 ) AND id IN (" . implode(',', $relIds) . ")", $relParamas);
1779 if ($recordsFound) {
1785 $recordsFound = (int) CRM_Core_DAO
::singleValueQuery("SELECT COUNT(*) FROM civicrm_relationship WHERE relationship_type_id IN ( " . implode(',', $membershipTypeRelationshipTypeIDs) . " ) AND contact_id_a IN ( %1, %2 ) AND contact_id_b IN ( %1, %2 ) AND id NOT IN (" . implode(',', $relIds) . ")", $relParamas);
1787 if ($recordsFound) {
1795 * Get Current Employer for Contact.
1797 * @param $contactIds
1801 * array of the current employer
1803 public static function getCurrentEmployer($contactIds) {
1804 $contacts = implode(',', $contactIds);
1807 SELECT organization_name, id, employer_id
1808 FROM civicrm_contact
1809 WHERE id IN ( {$contacts} )
1812 $dao = CRM_Core_DAO
::executeQuery($query);
1813 $currentEmployer = [];
1814 while ($dao->fetch()) {
1815 $currentEmployer[$dao->id
]['org_id'] = $dao->employer_id
;
1816 $currentEmployer[$dao->id
]['org_name'] = $dao->organization_name
;
1819 return $currentEmployer;
1823 * Function to return list of permissioned contacts for a given contact and relationship type.
1825 * @param int $contactID
1826 * contact id whose permissioned contacts are to be found.
1827 * @param int $relTypeId
1828 * one or more relationship type id's.
1829 * @param string $name
1830 * @param string $contactType
1835 public static function getPermissionedContacts($contactID, $relTypeId = NULL, $name = NULL, $contactType = NULL) {
1837 $args = [1 => [$contactID, 'Integer']];
1838 $relationshipTypeClause = $contactTypeClause = '';
1841 // @todo relTypeId is only ever passed in as an int. Change this to reflect that -
1842 // probably being overly conservative by not doing so but working on stable release.
1843 $relationshipTypeClause = 'AND cr.relationship_type_id IN (%2) ';
1844 $args[2] = [$relTypeId, 'String'];
1848 $contactTypeClause = ' AND cr.relationship_type_id = crt.id AND crt.contact_type_b = %3 ';
1849 $args[3] = [$contactType, 'String'];
1853 SELECT cc.id as id, cc.sort_name as name
1854 FROM civicrm_relationship cr, civicrm_contact cc, civicrm_relationship_type crt
1856 cr.contact_id_a = %1 AND
1857 cr.is_permission_a_b = 1 AND
1858 IF(cr.end_date IS NULL, 1, (DATEDIFF( CURDATE( ), cr.end_date ) <= 0)) AND
1859 cr.is_active = 1 AND
1860 cc.id = cr.contact_id_b AND
1862 $relationshipTypeClause
1866 if (!empty($name)) {
1867 $name = CRM_Utils_Type
::escape($name, 'String');
1869 AND cc.sort_name LIKE '%$name%'";
1872 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1873 while ($dao->fetch()) {
1874 $contacts[$dao->id
] = [
1875 'name' => $dao->name
,
1876 'value' => $dao->id
,
1884 * Merge relationships from otherContact to mainContact.
1886 * Called during contact merge operation
1888 * @param int $mainId
1889 * Contact id of main contact record.
1890 * @param int $otherId
1891 * Contact id of record which is going to merge.
1892 * @param array $sqls
1893 * (reference) array of sql statements to append to.
1895 * @see CRM_Dedupe_Merger::cpTables()
1897 public static function mergeRelationships($mainId, $otherId, &$sqls) {
1898 // Delete circular relationships
1899 $sqls[] = "DELETE FROM civicrm_relationship
1900 WHERE (contact_id_a = $mainId AND contact_id_b = $otherId)
1901 OR (contact_id_b = $mainId AND contact_id_a = $otherId)";
1903 // Delete relationship from other contact if main contact already has that relationship
1904 $sqls[] = "DELETE r2
1905 FROM civicrm_relationship r1, civicrm_relationship r2
1906 WHERE r1.relationship_type_id = r2.relationship_type_id
1909 r1.contact_id_a = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_b = r2.contact_id_b
1910 OR r1.contact_id_b = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_a = r2.contact_id_a
1912 (r1.contact_id_a = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_b = r2.contact_id_a
1913 OR r1.contact_id_b = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_a = r2.contact_id_b)
1914 AND r1.relationship_type_id IN (SELECT id FROM civicrm_relationship_type WHERE name_b_a = name_a_b)
1918 // Move relationships
1919 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_a = $mainId WHERE contact_id_a = $otherId";
1920 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_b = $mainId WHERE contact_id_b = $otherId";
1922 // Move current employer id (name will get updated later)
1923 $sqls[] = "UPDATE civicrm_contact SET employer_id = $mainId WHERE employer_id = $otherId";
1927 * Set 'is_valid' field to false for all relationships whose end date is in the past, ie. are expired.
1930 * True on success, false if error is encountered.
1931 * @throws \CiviCRM_API3_Exception
1933 public static function disableExpiredRelationships() {
1934 $query = "SELECT id FROM civicrm_relationship WHERE is_active = 1 AND end_date < CURDATE()";
1936 $dao = CRM_Core_DAO
::executeQuery($query);
1937 while ($dao->fetch()) {
1938 $result = CRM_Contact_BAO_Relationship
::setIsActive($dao->id
, FALSE);
1939 // Result will be NULL if error occurred. We abort early if error detected.
1940 if ($result == NULL) {
1948 * Function filters the query by possible relationships for the membership type.
1950 * It is intended to be called when constructing queries for the api (reciprocal & non-reciprocal)
1951 * and to add clauses to limit the return to those relationships which COULD inherit a membership type
1952 * (as opposed to those who inherit a particular membership
1954 * @param array $params
1956 * @param null $direction
1958 * @return array|void
1959 * @throws \CiviCRM_API3_Exception
1961 public static function membershipTypeToRelationshipTypes(&$params, $direction = NULL) {
1962 $membershipType = civicrm_api3('membership_type', 'getsingle', [
1963 'id' => $params['membership_type_id'],
1964 'return' => 'relationship_type_id, relationship_direction',
1966 $relationshipTypes = $membershipType['relationship_type_id'];
1967 if (empty($relationshipTypes)) {
1970 // if we don't have any contact data we can only filter on type
1971 if (empty($params['contact_id']) && empty($params['contact_id_a']) && empty($params['contact_id_a'])) {
1972 $params['relationship_type_id'] = ['IN' => $relationshipTypes];
1976 $relationshipDirections = (array) $membershipType['relationship_direction'];
1977 // if we have contact_id_a OR contact_id_b we can make a call here
1978 // if we have contact??
1979 foreach ($relationshipDirections as $index => $mtdirection) {
1980 if (isset($params['contact_id_a']) && $mtdirection == 'a_b' ||
$direction == 'a_b') {
1981 $types[] = $relationshipTypes[$index];
1983 if (isset($params['contact_id_b']) && $mtdirection == 'b_a' ||
$direction == 'b_a') {
1984 $types[] = $relationshipTypes[$index];
1987 if (!empty($types)) {
1988 $params['relationship_type_id'] = ['IN' => $types];
1990 elseif (!empty($clauses)) {
1991 return explode(' OR ', $clauses);
1994 // effectively setting it to return no results
1995 $params['relationship_type_id'] = 0;
2001 * Wrapper for contact relationship selector.
2003 * @param array $params
2004 * Associated array for params record id.
2007 * associated array of contact relationships
2008 * @throws \Exception
2010 public static function getContactRelationshipSelector(&$params) {
2011 // format the params
2012 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2013 $params['sort'] = $params['sortBy'] ??
NULL;
2015 if ($params['context'] == 'past') {
2016 $relationshipStatus = CRM_Contact_BAO_Relationship
::INACTIVE
;
2018 elseif ($params['context'] == 'all') {
2019 $relationshipStatus = CRM_Contact_BAO_Relationship
::ALL
;
2022 $relationshipStatus = CRM_Contact_BAO_Relationship
::CURRENT
;
2025 // check logged in user for permission
2026 $page = new CRM_Core_Page();
2027 CRM_Contact_Page_View
::checkUserPermission($page, $params['contact_id']);
2028 $permissions = [$page->_permission
];
2029 if ($page->_permission
== CRM_Core_Permission
::EDIT
) {
2030 $permissions[] = CRM_Core_Permission
::DELETE
;
2032 $mask = CRM_Core_Action
::mask($permissions);
2034 $permissionedContacts = TRUE;
2035 if ($params['context'] != 'user') {
2036 $links = CRM_Contact_Page_View_Relationship
::links();
2039 $links = CRM_Contact_Page_View_UserDashBoard
::links();
2042 // get contact relationships
2043 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
2044 $relationshipStatus,
2045 $params['rp'], 0, 0,
2047 $permissionedContacts,
2051 $contactRelationships = [];
2052 $params['total'] = $relationships['total_relationships'];
2053 unset($relationships['total_relationships']);
2054 if (!empty($relationships)) {
2056 $displayName = CRM_Contact_BAO_Contact
::displayName($params['contact_id']);
2059 foreach ($relationships as $relationshipId => $values) {
2062 $relationship['DT_RowId'] = $values['id'];
2063 $relationship['DT_RowClass'] = 'crm-entity';
2064 if ($values['is_active'] == 0) {
2065 $relationship['DT_RowClass'] .= ' disabled';
2068 $relationship['DT_RowAttr'] = [];
2069 $relationship['DT_RowAttr']['data-entity'] = 'relationship';
2070 $relationship['DT_RowAttr']['data-id'] = $values['id'];
2072 //Add image icon for related contacts: CRM-14919; CRM-19668
2073 $contactType = (!empty($values['contact_sub_type'])) ?
$values['contact_sub_type'] : $values['contact_type'];
2074 $icon = CRM_Contact_BAO_Contact_Utils
::getImage($contactType,
2078 $relationship['sort_name'] = $icon . ' ' . CRM_Utils_System
::href(
2080 'civicrm/contact/view',
2081 "reset=1&cid={$values['cid']}");
2083 $relationship['relation'] = CRM_Utils_Array
::value('case', $values, '') . CRM_Utils_System
::href(
2084 $values['relation'],
2085 'civicrm/contact/view/rel',
2086 "action=view&reset=1&cid={$values['cid']}&id={$values['id']}&rtype={$values['rtype']}");
2088 if (!empty($values['description'])) {
2089 $relationship['relation'] .= "<p class='description'>{$values['description']}</p>";
2092 if ($params['context'] == 'current') {
2093 $smarty = CRM_Core_Smarty
::singleton();
2097 'permContact' => $params['contact_id'],
2098 'permDisplayName' => $displayName,
2099 'otherContact' => $values['cid'],
2100 'otherDisplayName' => $values['display_name'],
2101 'columnKey' => 'sort_name',
2104 'permContact' => $values['cid'],
2105 'permDisplayName' => $values['display_name'],
2106 'otherContact' => $params['contact_id'],
2107 'otherDisplayName' => $displayName,
2108 'columnKey' => 'relation',
2112 foreach ($contactCombos as $combo) {
2113 foreach ([CRM_Contact_BAO_Relationship
::EDIT
, CRM_Contact_BAO_Relationship
::VIEW
] as $permType) {
2114 $smarty->assign('permType', $permType);
2115 if (($combo['permContact'] == $values['contact_id_a'] and $values['is_permission_a_b'] == $permType)
2116 ||
($combo['permContact'] == $values['contact_id_b'] and $values['is_permission_b_a'] == $permType)
2118 $smarty->assign('permDisplayName', $combo['permDisplayName']);
2119 $smarty->assign('otherDisplayName', $combo['otherDisplayName']);
2120 $relationship[$combo['columnKey']] .= $smarty->fetch('CRM/Contact/Page/View/RelationshipPerm.tpl');
2126 $relationship['start_date'] = CRM_Utils_Date
::customFormat($values['start_date']);
2127 $relationship['end_date'] = CRM_Utils_Date
::customFormat($values['end_date']);
2128 $relationship['city'] = $values['city'];
2129 $relationship['state'] = $values['state'];
2130 $relationship['email'] = $values['email'];
2131 $relationship['phone'] = $values['phone'];
2132 $relationship['links'] = $values['action'];
2134 array_push($contactRelationships, $relationship);
2138 $columnHeaders = self
::getColumnHeaders();
2140 CRM_Utils_Hook
::searchColumns('relationship.rows', $columnHeaders, $contactRelationships, $selector);
2142 $relationshipsDT = [];
2143 $relationshipsDT['data'] = $contactRelationships;
2144 $relationshipsDT['recordsTotal'] = $params['total'];
2145 $relationshipsDT['recordsFiltered'] = $params['total'];
2147 return $relationshipsDT;
2153 public static function getColumnHeaders() {
2156 'name' => ts('Relationship'),
2157 'sort' => 'relation',
2158 'direction' => CRM_Utils_Sort
::ASCENDING
,
2162 'sort' => 'sort_name',
2163 'direction' => CRM_Utils_Sort
::ASCENDING
,
2166 'name' => ts('Start'),
2167 'sort' => 'start_date',
2168 'direction' => CRM_Utils_Sort
::DONTCARE
,
2171 'name' => ts('End'),
2172 'sort' => 'end_date',
2173 'direction' => CRM_Utils_Sort
::DONTCARE
,
2176 'name' => ts('City'),
2178 'direction' => CRM_Utils_Sort
::DONTCARE
,
2181 'name' => ts('State/Prov'),
2183 'direction' => CRM_Utils_Sort
::DONTCARE
,
2186 'name' => ts('Email'),
2188 'direction' => CRM_Utils_Sort
::DONTCARE
,
2191 'name' => ts('Phone'),
2193 'direction' => CRM_Utils_Sort
::DONTCARE
,
2198 'direction' => CRM_Utils_Sort
::DONTCARE
,
2206 public static function buildOptions($fieldName, $context = NULL, $props = []) {
2207 if ($fieldName === 'relationship_type_id') {
2208 return self
::buildRelationshipTypeOptions($props);
2211 return parent
::buildOptions($fieldName, $context, $props);
2215 * Builds a list of options available for relationship types
2217 * @param array $params
2218 * - contact_type: Limits by contact type on the "A" side
2219 * - relationship_id: Used to find the value for contact type for "B" side.
2220 * If contact_a matches provided contact_id then type of contact_b will
2221 * be used. Otherwise uses type of contact_a. Must be used with contact_id
2222 * - contact_id: Limits by contact types of this contact on the "A" side
2223 * - is_form: Returns array with keys indexed for use in a quickform
2224 * - relationship_direction: For relationship types with duplicate names
2225 * on both sides, defines which option should be returned, a_b or b_a
2229 public static function buildRelationshipTypeOptions($params = []) {
2230 $contactId = $params['contact_id'] ??
NULL;
2231 $direction = CRM_Utils_Array
::value('relationship_direction', $params, 'a_b');
2232 $relationshipId = $params['relationship_id'] ??
NULL;
2233 $contactType = $params['contact_type'] ??
NULL;
2234 $isForm = $params['is_form'] ??
NULL;
2237 // getContactRelationshipType will return an empty set if these are not set
2238 if (!$contactId && !$relationshipId && !$contactType) {
2242 $labels = self
::getContactRelationshipType(
2255 $names = self
::getContactRelationshipType(
2264 // ensure $names contains only entries in $labels
2265 $names = array_intersect_key($names, $labels);
2267 $nameToLabels = array_combine($names, $labels);
2269 return $nameToLabels;
2273 * Process the params from api, form and check if current
2274 * employer should be set or unset.
2276 * @param array $params
2277 * @param int $relationshipId
2278 * @param int|null $updatedRelTypeID
2281 * TRUE if current employer needs to be cleared.
2282 * @throws \CiviCRM_API3_Exception
2284 public static function isCurrentEmployerNeedingToBeCleared($params, $relationshipId, $updatedRelTypeID = NULL) {
2285 $existingTypeID = (int) CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Relationship', $relationshipId, 'relationship_type_id');
2286 $updatedRelTypeID = $updatedRelTypeID ?
$updatedRelTypeID : $existingTypeID;
2287 $currentEmployerID = (int) civicrm_api3('Contact', 'getvalue', ['return' => 'current_employer_id', 'id' => $params['contact_id_a']]);
2289 if ($currentEmployerID !== (int) $params['contact_id_b'] ||
!self
::isRelationshipTypeCurrentEmployer($existingTypeID)) {
2292 //Clear employer if relationship is expired.
2293 if (!empty($params['end_date']) && strtotime($params['end_date']) < time()) {
2296 //current employer checkbox is disabled on the form.
2297 //inactive or relationship type(employer of) is updated.
2298 if ((isset($params['is_current_employer']) && empty($params['is_current_employer']))
2299 ||
((isset($params['is_active']) && empty($params['is_active'])))
2300 ||
$existingTypeID != $updatedRelTypeID) {
2301 // If there are no other active employer relationships between the same 2 contacts...
2302 if (!civicrm_api3('Relationship', 'getcount', [
2304 'relationship_type_id' => $existingTypeID,
2305 'id' => ['<>' => $params['id']],
2306 'contact_id_a' => $params['contact_id_a'],
2307 'contact_id_b' => $params['contact_id_b'],
2317 * Is this a current employer relationship type.
2319 * @todo - this could use cached pseudoconstant lookups.
2321 * @param int $existingTypeID
2325 private static function isRelationshipTypeCurrentEmployer(int $existingTypeID): bool {
2326 $isCurrentEmployerRelationshipType = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType', $existingTypeID, 'name_b_a') === 'Employer of';
2327 return $isCurrentEmployerRelationshipType;
2331 * Is the inherited relationship invalidated by this relationship change.
2333 * @param $membershipValues
2334 * @param array $values
2338 * @throws \CiviCRM_API3_Exception
2340 private static function isInheritedMembershipInvalidated($membershipValues, array $values, $cid): array {
2341 // @todo most of this can go - it's just the weird historical returning of $relTypeId that it does.
2342 // now we have caching the parent fn can just call CRM_Member_BAO_MembershipType::getMembershipType
2343 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipType($membershipValues['membership_type_id']);
2344 $relTypeIds = $membershipType['relationship_type_id'];
2345 $membershipInheritedFrom = $membershipValues['owner_membership_id'] ??
NULL;
2346 if (!$membershipInheritedFrom ||
!in_array($values[$cid]['relationshipTypeId'], $relTypeIds)) {
2347 return [implode(',', $relTypeIds), FALSE];
2349 //CRM-16300 check if owner membership exist for related membership
2350 return [implode(',', $relTypeIds), !self
::isContactHasValidRelationshipToInheritMembershipType((int) $cid, (int) $membershipValues['membership_type_id'], (int) $membershipValues['owner_membership_id'])];
2354 * Is there a valid relationship confering this membership type on this contact.
2356 * @param int $contactID
2357 * @param int $membershipTypeID
2358 * @param int $parentMembershipID
2359 * Id of the membership being inherited.
2363 * @throws \CiviCRM_API3_Exception
2365 private static function isContactHasValidRelationshipToInheritMembershipType(int $contactID, int $membershipTypeID, int $parentMembershipID): bool {
2366 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipType($membershipTypeID);
2367 $existingRelationships = civicrm_api3('Relationship', 'get', [
2368 'contact_id_a' => $contactID,
2369 'contact_id_b' => $contactID,
2370 'relationship_type_id' => ['IN' => $membershipType['relationship_type_id']],
2371 'options' => ['or' => [['contact_id_a', 'contact_id_b']], 'limit' => 0],
2375 if (empty($existingRelationships)) {
2379 $membershipInheritedFromContactID = (int) civicrm_api3('Membership', 'getvalue', ['return' => 'contact_id', 'id' => $parentMembershipID]);
2380 // I don't think the api can correctly filter by start & end because of handling for NULL
2381 // so we filter them out here.
2382 foreach ($existingRelationships as $index => $existingRelationship) {
2383 $otherContactID = (int) (($contactID === (int) $existingRelationship['contact_id_a']) ?
$existingRelationship['contact_id_b'] : $existingRelationship['contact_id_a']);
2384 if (!empty($existingRelationship['start_date'])
2385 && strtotime($existingRelationship['start_date']) > time()
2387 unset($existingRelationships[$index]);
2390 if (!empty($existingRelationship['end_date'])
2391 && strtotime($existingRelationship['end_date']) < time()
2393 unset($existingRelationships[$index]);
2396 if ($membershipInheritedFromContactID !== $otherContactID
2398 // This is a weird scenario - they have been inheriting the membership
2399 // just not from this relationship - and some max_related calcs etc would be required
2400 // - ie because they are no longer inheriting from this relationship's 'allowance'
2401 // and now are inheriting from the other relationships 'allowance', if it has not
2402 // already hit 'max_related'
2403 // For now ignore here & hope it's handled elsewhere - at least that's consistent with
2404 // before this function was added.
2405 unset($existingRelationships[$index]);
2408 if (!civicrm_api3('Contact', 'getcount', ['id' => $otherContactID, 'is_deleted' => 0])) {
2409 // Can't inherit from a deleted contact.
2410 unset($existingRelationships[$index]);
2414 return !empty($existingRelationships);
2418 * Add an inherited membership, provided max related not exceeded.
2420 * @param array $membershipValues
2423 * @throws \CRM_Core_Exception
2425 protected static function addInheritedMembership($membershipValues) {
2428 FROM civicrm_membership
2429 LEFT JOIN civicrm_membership_status ON (civicrm_membership_status.id = civicrm_membership.status_id)
2430 WHERE membership_type_id = {$membershipValues['membership_type_id']}
2431 AND owner_membership_id = {$membershipValues['owner_membership_id']}
2432 AND is_current_member = 1";
2433 $result = CRM_Core_DAO
::singleValueQuery($query);
2434 if ($result < CRM_Utils_Array
::value('max_related', $membershipValues, PHP_INT_MAX
)) {
2435 CRM_Member_BAO_Membership
::create($membershipValues);
2437 return $membershipValues;