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 * Only called from import now... plus one place outside of core & tests.
146 * @todo - deprecate more aggressively - will involve copying to the import
147 * class, adding a deprecation notice here & removing from tests.
149 * Takes an associative array and creates a relationship object.
151 * @deprecated For single creates use the api instead (it's tested).
152 * For multiple a new variant of this function needs to be written and migrated to as this is a bit
155 * @param array $params
156 * (reference ) an assoc array of name/value pairs.
158 * The array that holds all the db ids.
159 * per http://wiki.civicrm.org/confluence/display/CRM/Database+layer
160 * "we are moving away from the $ids param "
163 * @throws \CRM_Core_Exception
165 public static function legacyCreateMultiple($params, $ids = []) {
166 // clarify that the only key ever pass in the ids array is 'contact'
167 // There is legacy handling for other keys but a universe search on
168 // calls to this function (not supported to be called from outside core)
169 // only returns 2 calls - one in CRM_Contact_Import_Parser_Contact
170 // and the other in jma grant applications (CRM_Grant_Form_Grant_Confirm)
171 // both only pass in contact as a key here.
172 $ids = ['contact' => $ids['contact']];
173 // Likewise neither place ever passed in relationshipID
174 $relationshipId = NULL;
175 // There is only ever one value passed in from the 2 places above that call
176 // this - by clarifying here like this we can cleanup within this
177 // function without having to do more universe searches.
178 $relatedContactIDs = [key($params['contact_check'])];
180 if (!$relationshipId) {
181 // creating a new relationship
182 foreach ($relatedContactIDs as $relatedContactID) {
183 // check if the relationship is valid between contacts.
184 // step 1: check if the relationship is valid if not valid skip and keep the count
185 // step 2: check the if two contacts already have a relationship if yes skip and keep the count
186 // step 3: if valid relationship then add the relation and keep the count
189 $contactFields = self
::setContactABFromIDs($params, $ids, $relatedContactID);
190 $errors = self
::checkValidRelationship($contactFields, $ids, $relatedContactID);
195 //CRM-16978:check duplicate relationship as per case id.
196 // https://issues.civicrm.org/jira/browse/CRM-16978
197 if ($caseId = CRM_Utils_Array
::value('case_id', $params)) {
198 CRM_Core_Error
::deprecatedWarning('this code is believed to be unreachable');
199 $contactFields['case_id'] = $caseId;
202 self
::checkDuplicateRelationship(
204 CRM_Utils_Array
::value('contact', $ids),
212 $singleInstanceParams = array_merge($params, $contactFields);
213 $relationship = self
::add($singleInstanceParams);
215 // editing the relationship
218 // do not add to recent items for import, CRM-4399
219 if (!(!empty($params['skipRecentView']))) {
220 self
::addRecent($params, $relationship);
227 * This is the function that check/add if the relationship created is valid.
229 * @param array $params
230 * Array of name/value pairs.
232 * The array that holds all the db ids.
234 * @return CRM_Contact_BAO_Relationship
236 * @throws \CiviCRM_API3_Exception
238 public static function add($params, $ids = []) {
239 $params['id'] = CRM_Utils_Array
::value('relationship', $ids, CRM_Utils_Array
::value('id', $params));
245 CRM_Utils_Hook
::pre($hook, 'Relationship', $params['id'], $params);
247 $relationshipTypes = $params['relationship_type_id'] ??
NULL;
248 // explode the string with _ to get the relationship type id
249 // and to know which contact has to be inserted in
250 // contact_id_a and which one in contact_id_b
251 list($relationshipTypeID) = explode('_', $relationshipTypes);
253 $relationship = new CRM_Contact_BAO_Relationship();
254 if (!empty($params['id'])) {
255 $relationship->id
= $params['id'];
256 // Only load the relationship if we're missing required params
257 $requiredParams = ['contact_id_a', 'contact_id_b', 'relationship_type_id'];
258 foreach ($requiredParams as $requiredKey) {
259 if (!isset($params[$requiredKey])) {
260 $relationship->find(TRUE);
266 $relationship->copyValues($params);
267 // @todo we could probably set $params['relationship_type_id'] above but it's unclear
268 // what that would do with the code below this. So for now be conservative and set it manually.
269 if (!empty($relationshipTypeID)) {
270 $relationship->relationship_type_id
= $relationshipTypeID;
273 $params['contact_id_a'] = $relationship->contact_id_a
;
274 $params['contact_id_b'] = $relationship->contact_id_b
;
276 // check if the relationship type is Head of Household then update the
277 // household's primary contact with this contact.
279 $headOfHouseHoldID = civicrm_api3('RelationshipType', 'getvalue', [
281 'name_a_b' => "Head of Household for",
283 if ($relationshipTypeID == $headOfHouseHoldID) {
284 CRM_Contact_BAO_Household
::updatePrimaryContact($relationship->contact_id_b
, $relationship->contact_id_a
);
287 catch (Exception
$e) {
288 // No "Head of Household" relationship found so we skip specific processing
291 if (!empty($params['id']) && self
::isCurrentEmployerNeedingToBeCleared($relationship->toArray(), $params['id'], $relationshipTypeID)) {
292 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($relationship->contact_id_a
);
295 $dateFields = ['end_date', 'start_date'];
297 foreach (self
::getdefaults() as $defaultField => $defaultValue) {
298 if (isset($params[$defaultField])) {
299 if (in_array($defaultField, $dateFields)) {
300 $relationship->$defaultField = CRM_Utils_Date
::format(CRM_Utils_Array
::value($defaultField, $params));
301 if (!$relationship->$defaultField) {
302 $relationship->$defaultField = 'NULL';
306 $relationship->$defaultField = $params[$defaultField];
309 elseif (empty($params['id'])) {
310 $relationship->$defaultField = $defaultValue;
314 $relationship->save();
315 // is_current_employer is an optional parameter that triggers updating the employer_id field to reflect
316 // the relationship being updated. As of writing only truthy versions of the parameter are respected.
317 // https://github.com/civicrm/civicrm-core/pull/13331 attempted to cover both but stalled in QA
318 // so currently we have a cut down version.
319 if (!empty($params['is_current_employer'])) {
320 if (!$relationship->relationship_type_id ||
!$relationship->contact_id_a ||
!$relationship->contact_id_b
) {
321 $relationship->fetch();
323 if (self
::isRelationshipTypeCurrentEmployer($relationship->relationship_type_id
)) {
324 CRM_Contact_BAO_Contact_Utils
::setCurrentEmployer([$relationship->contact_id_a
=> $relationship->contact_id_b
]);
327 // add custom field values
328 if (!empty($params['custom'])) {
329 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_relationship', $relationship->id
);
332 CRM_Utils_Hook
::post($hook, 'Relationship', $relationship->id
, $relationship);
334 return $relationship;
338 * Add relationship to recent links.
340 * @param array $params
341 * @param CRM_Contact_DAO_Relationship $relationship
343 public static function addRecent($params, $relationship) {
344 $url = CRM_Utils_System
::url('civicrm/contact/view/rel',
345 "action=view&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&context=home"
347 $session = CRM_Core_Session
::singleton();
349 if (($session->get('userID') == $relationship->contact_id_a
) ||
350 CRM_Contact_BAO_Contact_Permission
::allow($relationship->contact_id_a
, CRM_Core_Permission
::EDIT
)
352 $rType = substr(CRM_Utils_Array
::value('relationship_type_id', $params), -3);
354 'editUrl' => CRM_Utils_System
::url('civicrm/contact/view/rel',
355 "action=update&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
357 'deleteUrl' => CRM_Utils_System
::url('civicrm/contact/view/rel',
358 "action=delete&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
362 $title = CRM_Contact_BAO_Contact
::displayName($relationship->contact_id_a
) . ' (' . CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType',
363 $relationship->relationship_type_id
, 'label_a_b'
364 ) . ' ' . CRM_Contact_BAO_Contact
::displayName($relationship->contact_id_b
) . ')';
366 CRM_Utils_Recent
::add($title,
370 $relationship->contact_id_a
,
377 * Load contact ids and relationship type id when doing a create call if not provided.
379 * There are are various checks done in create which require this information which is optional
382 * @param array $params
383 * Parameters passed to create call.
386 * Parameters with missing fields added if required.
388 public static function loadExistingRelationshipDetails($params) {
389 if (!empty($params['contact_id_a'])
390 && !empty($params['contact_id_b'])
391 && is_numeric($params['relationship_type_id'])) {
394 if (empty($params['id'])) {
398 $fieldsToFill = ['contact_id_a', 'contact_id_b', 'relationship_type_id'];
399 $result = CRM_Core_DAO
::executeQuery("SELECT " . implode(',', $fieldsToFill) . " FROM civicrm_relationship WHERE id = %1", [
405 while ($result->fetch()) {
406 foreach ($fieldsToFill as $field) {
407 $params[$field] = !empty($params[$field]) ?
$params[$field] : $result->$field;
414 * Resolve passed in contact IDs to contact_id_a & contact_id_b.
416 * @param array $params
418 * @param null $contactID
421 * @throws \CRM_Core_Exception
423 public static function setContactABFromIDs($params, $ids = [], $contactID = NULL) {
426 // $ids['contact'] is deprecated but comes from legacyCreateMultiple function.
427 if (empty($ids['contact'])) {
428 if (!empty($params['id'])) {
429 return self
::loadExistingRelationshipDetails($params);
431 throw new CRM_Core_Exception('Cannot create relationship, insufficient contact IDs provided');
433 if (isset($params['relationship_type_id']) && !is_numeric($params['relationship_type_id'])) {
434 $relationshipTypes = $params['relationship_type_id'] ??
NULL;
435 list($relationshipTypeID, $first) = explode('_', $relationshipTypes);
436 $returnFields['relationship_type_id'] = $relationshipTypeID;
438 foreach (['a', 'b'] as $contactLetter) {
439 if (empty($params['contact_' . $contactLetter])) {
440 if ($first == $contactLetter) {
441 $returnFields['contact_id_' . $contactLetter] = $ids['contact'] ??
NULL;
444 $returnFields['contact_id_' . $contactLetter] = $contactID;
450 return $returnFields;
454 * Specify defaults for creating a relationship.
457 * array of defaults for creating relationship
459 public static function getdefaults() {
462 'is_permission_a_b' => self
::NONE
,
463 'is_permission_b_a' => self
::NONE
,
465 'start_date' => 'NULL',
467 'end_date' => 'NULL',
472 * Check if there is data to create the object.
474 * @param array $params
479 public static function dataExists($params) {
480 CRM_Core_Error
::deprecatedFunctionWarning('obsolete');
481 return (isset($params['contact_check']) && is_array($params['contact_check']));
485 * Get get list of relationship type based on the contact type.
487 * @param int $contactId
488 * This is the contact id of the current contact.
489 * @param null $contactSuffix
490 * @param string $relationshipId
491 * The id of the existing relationship if any.
492 * @param string $contactType
495 * If true returns relationship types in both the direction.
496 * @param string $column
497 * Name/label that going to retrieve from db.
498 * @param bool $biDirectional
499 * @param array $contactSubType
500 * Includes relationship types between this subtype.
501 * @param bool $onlySubTypeRelationTypes
502 * If set only subtype which is passed by $contactSubType
503 * related relationship types get return
506 * array reference of all relationship types with context to current contact.
508 public static function getContactRelationshipType(
510 $contactSuffix = NULL,
511 $relationshipId = NULL,
515 $biDirectional = TRUE,
516 $contactSubType = NULL,
517 $onlySubTypeRelationTypes = FALSE
520 $relationshipType = [];
521 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType($column);
523 $otherContactType = NULL;
524 if ($relationshipId) {
525 $relationship = new CRM_Contact_DAO_Relationship();
526 $relationship->id
= $relationshipId;
527 if ($relationship->find(TRUE)) {
528 $contact = new CRM_Contact_DAO_Contact();
529 $contact->id
= ($relationship->contact_id_a
== $contactId) ?
$relationship->contact_id_b
: $relationship->contact_id_a
;
531 if ($contact->find(TRUE)) {
532 $otherContactType = $contact->contact_type
;
533 //CRM-5125 for contact subtype specific relationshiptypes
534 if ($contact->contact_sub_type
) {
535 $otherContactSubType = $contact->contact_sub_type
;
541 $contactSubType = (array) $contactSubType;
543 $contactType = CRM_Contact_BAO_Contact
::getContactType($contactId);
544 $contactSubType = CRM_Contact_BAO_Contact
::getContactSubType($contactId);
547 foreach ($allRelationshipType as $key => $value) {
548 // the contact type is required or matches
549 if (((!$value['contact_type_a']) ||
550 $value['contact_type_a'] == $contactType
552 // the other contact type is required or present or matches
553 ((!$value['contact_type_b']) ||
554 (!$otherContactType) ||
555 $value['contact_type_b'] == $otherContactType
557 (in_array($value['contact_sub_type_a'], $contactSubType) ||
558 (!$value['contact_sub_type_a'] && !$onlySubTypeRelationTypes)
561 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
564 if (((!$value['contact_type_b']) ||
565 $value['contact_type_b'] == $contactType
567 ((!$value['contact_type_a']) ||
568 (!$otherContactType) ||
569 $value['contact_type_a'] == $otherContactType
571 (in_array($value['contact_sub_type_b'], $contactSubType) ||
572 (!$value['contact_sub_type_b'] && !$onlySubTypeRelationTypes)
575 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
579 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
580 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
584 if ($biDirectional) {
585 $relationshipType = self
::removeRelationshipTypeDuplicates($relationshipType, $contactSuffix);
588 // sort the relationshipType in ascending order CRM-7736
589 asort($relationshipType);
590 return $relationshipType;
594 * Given a list of relationship types, return the list with duplicate types
595 * removed, being careful to retain only the duplicate which matches the given
596 * 'a_b' or 'b_a' suffix.
598 * @param array $relationshipTypeList A list of relationship types, in the format
599 * returned by self::getContactRelationshipType().
600 * @param string $suffix Either 'a_b' or 'b_a'; defaults to 'a_b'
602 * @return array The modified value of $relationshipType
604 public static function removeRelationshipTypeDuplicates($relationshipTypeList, $suffix = NULL) {
605 if (empty($suffix)) {
609 // Find those labels which are listed more than once.
610 $duplicateValues = array_diff_assoc($relationshipTypeList, array_unique($relationshipTypeList));
612 // For each duplicate label, find its keys, and remove from $relationshipType
613 // the key which does not match $suffix.
614 foreach ($duplicateValues as $value) {
615 $keys = array_keys($relationshipTypeList, $value);
616 foreach ($keys as $key) {
617 if (substr($key, -3) != $suffix) {
618 unset($relationshipTypeList[$key]);
622 return $relationshipTypeList;
626 * Delete current employer relationship.
631 * @return CRM_Contact_DAO_Relationship
633 public static function clearCurrentEmployer($id, $action) {
634 $relationship = new CRM_Contact_DAO_Relationship();
635 $relationship->id
= $id;
636 $relationship->find(TRUE);
638 //to delete relationship between household and individual \
639 //or between individual and organization
640 if (($action & CRM_Core_Action
::DISABLE
) ||
($action & CRM_Core_Action
::DELETE
)) {
641 $relTypes = CRM_Utils_Array
::index(['name_a_b'], CRM_Core_PseudoConstant
::relationshipType('name'));
643 (isset($relTypes['Employee of']) && $relationship->relationship_type_id
== $relTypes['Employee of']['id']) ||
644 (isset($relTypes['Household Member of']) && $relationship->relationship_type_id
== $relTypes['Household Member of']['id'])
646 $sharedContact = new CRM_Contact_DAO_Contact();
647 $sharedContact->id
= $relationship->contact_id_a
;
648 $sharedContact->find(TRUE);
651 // changed FROM "...relationship->relationship_type_id == 4..." TO "...relationship->relationship_type_id == 5..."
652 // As the system should be looking for type "employer of" (id 5) and not "sibling of" (id 4)
653 // 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.
654 $employerRelTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b');
656 if ($relationship->relationship_type_id
== $employerRelTypeId && $relationship->contact_id_b
== $sharedContact->employer_id
) {
657 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($relationship->contact_id_a
);
662 return $relationship;
666 * Delete the relationship.
671 * @return CRM_Contact_DAO_Relationship
673 * @throws \CRM_Core_Exception
674 * @throws \CiviCRM_API3_Exception
676 public static function del($id) {
677 // delete from relationship table
678 CRM_Utils_Hook
::pre('delete', 'Relationship', $id);
680 $relationship = self
::clearCurrentEmployer($id, CRM_Core_Action
::DELETE
);
681 $relationship->delete();
682 if (CRM_Core_Permission
::access('CiviMember')) {
683 // create $params array which isrequired to delete memberships
684 // of the related contacts.
686 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
687 'contact_check' => [$relationship->contact_id_b
=> 1],
691 // calling relatedMemberships to delete the memberships of
693 self
::relatedMemberships($relationship->contact_id_a
,
696 CRM_Core_Action
::DELETE
,
701 CRM_Core_Session
::setStatus(ts('Selected relationship has been deleted successfully.'), ts('Record Deleted'), 'success');
703 CRM_Utils_Hook
::post('delete', 'Relationship', $id, $relationship);
705 return $relationship;
709 * Disable/enable the relationship.
715 * @param array $params
717 * @param bool $active
719 * @throws \CRM_Core_Exception
720 * @throws \CiviCRM_API3_Exception
722 public static function disableEnableRelationship($id, $action, $params = [], $ids = [], $active = FALSE) {
723 $relationship = self
::clearCurrentEmployer($id, $action);
726 // create $params array which is required to delete memberships
727 // of the related contacts.
728 if (empty($params)) {
730 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
731 'contact_check' => [$relationship->contact_id_b
=> 1],
734 $contact_id_a = empty($params['contact_id_a']) ?
$relationship->contact_id_a
: $params['contact_id_a'];
735 // calling relatedMemberships to delete/add the memberships of
737 if ($action & CRM_Core_Action
::DISABLE
) {
738 // @todo this could call a subset of the function that just relates to
739 // cleaning up no-longer-inherited relationships
740 CRM_Contact_BAO_Relationship
::relatedMemberships($contact_id_a,
743 CRM_Core_Action
::DELETE
,
747 elseif ($action & CRM_Core_Action
::ENABLE
) {
748 $ids['contact'] = empty($ids['contact']) ?
$contact_id_a : $ids['contact'];
749 CRM_Contact_BAO_Relationship
::relatedMemberships($contact_id_a,
752 empty($params['id']) ? CRM_Core_Action
::ADD
: CRM_Core_Action
::UPDATE
,
760 * Delete the object records that are associated with this contact.
762 * @param int $contactId
763 * Id of the contact to delete.
765 public static function deleteContact($contactId) {
766 $relationship = new CRM_Contact_DAO_Relationship();
767 $relationship->contact_id_a
= $contactId;
768 $relationship->delete();
770 $relationship = new CRM_Contact_DAO_Relationship();
771 $relationship->contact_id_b
= $contactId;
772 $relationship->delete();
774 CRM_Contact_BAO_Household
::updatePrimaryContact(NULL, $contactId);
778 * Get the other contact in a relationship.
783 * $returns returns the contact ids in the relationship
785 * @return \CRM_Contact_DAO_Relationship
787 public static function getRelationshipByID($id) {
788 $relationship = new CRM_Contact_DAO_Relationship();
790 $relationship->id
= $id;
791 $relationship->selectAdd();
792 $relationship->selectAdd('contact_id_a, contact_id_b');
793 $relationship->find(TRUE);
795 return $relationship;
799 * Check if the relationship type selected between two contacts is correct.
801 * @param int $contact_a
803 * @param int $contact_b
805 * @param int $relationshipTypeId
806 * Relationship type id.
809 * true if it is valid relationship else false
811 public static function checkRelationshipType($contact_a, $contact_b, $relationshipTypeId) {
812 $relationshipType = new CRM_Contact_DAO_RelationshipType();
813 $relationshipType->id
= $relationshipTypeId;
814 $relationshipType->selectAdd();
815 $relationshipType->selectAdd('contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b');
816 if ($relationshipType->find(TRUE)) {
817 $contact_type_a = CRM_Contact_BAO_Contact
::getContactType($contact_a);
818 $contact_type_b = CRM_Contact_BAO_Contact
::getContactType($contact_b);
820 $contact_sub_type_a = CRM_Contact_BAO_Contact
::getContactSubType($contact_a);
821 $contact_sub_type_b = CRM_Contact_BAO_Contact
::getContactSubType($contact_b);
823 if (((!$relationshipType->contact_type_a
) ||
($relationshipType->contact_type_a
== $contact_type_a)) &&
824 ((!$relationshipType->contact_type_b
) ||
($relationshipType->contact_type_b
== $contact_type_b)) &&
825 ((!$relationshipType->contact_sub_type_a
) ||
(in_array($relationshipType->contact_sub_type_a
,
828 ((!$relationshipType->contact_sub_type_b
) ||
(in_array($relationshipType->contact_sub_type_b
,
842 * This function does the validtion for valid relationship.
844 * @param array $params
845 * This array contains the values there are subitted by the form.
847 * The array that holds all the db ids.
848 * @param int $contactId
849 * This is contact id for adding relationship.
853 public static function checkValidRelationship($params, $ids, $contactId) {
855 // function to check if the relationship selected is correct
856 // i.e. employer relationship can exit between Individual and Organization (not between Individual and Individual)
857 if (!CRM_Contact_BAO_Relationship
::checkRelationshipType($params['contact_id_a'], $params['contact_id_b'],
858 $params['relationship_type_id'])) {
859 $errors = 'Please select valid relationship between these two contacts.';
865 * This function checks for duplicate relationship.
867 * @param array $params
868 * An assoc array of name/value pairs.
870 * This the id of the contact whom we are adding relationship.
871 * @param int $contactId
872 * This is contact id for adding relationship.
873 * @param int $relationshipId
874 * This is relationship id for the contact.
877 * true if record exists else false
879 public static function checkDuplicateRelationship($params, $id, $contactId = 0, $relationshipId = 0) {
880 $relationshipTypeId = $params['relationship_type_id'] ??
NULL;
881 list($type) = explode('_', $relationshipTypeId);
885 FROM civicrm_relationship
886 WHERE relationship_type_id = " . CRM_Utils_Type
::escape($type, 'Integer');
889 * CRM-11792 - date fields from API are in ISO format, but this function
890 * supports date arrays BAO has increasingly standardised to ISO format
891 * so I believe this function should support ISO rather than make API
892 * format it - however, need to support array format for now to avoid breakage
893 * @ time of writing this function is called from Relationship::legacyCreateMultiple (twice)
894 * CRM_BAO_Contact_Utils::clearCurrentEmployer (seemingly without dates)
895 * CRM_Contact_Form_Task_AddToOrganization::postProcess &
896 * CRM_Contact_Form_Task_AddToHousehold::postProcess
897 * (I don't think the last 2 support dates but not sure
900 $dateFields = ['end_date', 'start_date'];
901 foreach ($dateFields as $dateField) {
902 if (array_key_exists($dateField, $params)) {
903 if (empty($params[$dateField]) ||
$params[$dateField] == 'null') {
904 //this is most likely coming from an api call & probably loaded
905 // from the DB to deal with some of the
906 // other myriad of excessive checks still in place both in
907 // the api & the create functions
908 $queryString .= " AND $dateField IS NULL";
911 elseif (is_array($params[$dateField])) {
912 $queryString .= " AND $dateField = " .
913 CRM_Utils_Type
::escape(CRM_Utils_Date
::format($params[$dateField]), 'Date');
916 $queryString .= " AND $dateField = " .
917 CRM_Utils_Type
::escape($params[$dateField], 'Date');
923 ' AND ( ( contact_id_a = ' . CRM_Utils_Type
::escape($id, 'Integer') .
924 ' AND contact_id_b = ' . CRM_Utils_Type
::escape($contactId, 'Integer') .
925 ' ) OR ( contact_id_a = ' . CRM_Utils_Type
::escape($contactId, 'Integer') .
926 ' AND contact_id_b = ' . CRM_Utils_Type
::escape($id, 'Integer') . " ) ) ";
928 //if caseId is provided, include it duplicate checking.
929 if ($caseId = CRM_Utils_Array
::value('case_id', $params)) {
930 $queryString .= ' AND case_id = ' . CRM_Utils_Type
::escape($caseId, 'Integer');
933 if ($relationshipId) {
934 $queryString .= ' AND id !=' . CRM_Utils_Type
::escape($relationshipId, 'Integer');
937 $relationship = CRM_Core_DAO
::executeQuery($queryString);
938 while ($relationship->fetch()) {
939 // Check whether the custom field values are identical.
940 if (self
::checkDuplicateCustomFields($params['custom'] ??
[], $relationship->id
)) {
948 * this function checks whether the values of the custom fields in $params are
949 * the same as the values of the custom fields of the relation with given
952 * @param array $params an assoc array of name/value pairs
953 * @param int $relationshipId ID of an existing duplicate relation
955 * @return boolean true if custom field values are identical
959 private static function checkDuplicateCustomFields($params, $relationshipId) {
960 // Get the custom values of the existing relationship.
961 $existingValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($relationshipId, 'Relationship');
962 // Create a similar array for the new relationship.
964 if (!is_array($params)) {
965 // No idea when this would happen....
966 CRM_Core_Error
::deprecatedWarning('params should be an array');
969 // $params seems to be an array, as it should be. Each value is again an array.
970 // This array contains one value (key -1), and this value seems to be
971 // an array with the information about the custom value.
972 foreach ($params as $value) {
973 foreach ($value as $customValue) {
974 $newValues[$customValue['custom_field_id']] = $customValue['value'];
979 // Calculate difference between arrays. If the only key-value pairs
980 // that are in one array but not in the other are empty, the
981 // custom fields are considered to be equal.
982 // See https://github.com/civicrm/civicrm-core/pull/6515#issuecomment-137985667
983 $diff1 = array_diff_assoc($existingValues, $newValues);
984 $diff2 = array_diff_assoc($newValues, $existingValues);
986 return !array_filter($diff1) && !array_filter($diff2);
990 * Update the is_active flag in the db.
993 * Id of the database record.
994 * @param bool $is_active
995 * Value we want to set the is_active field.
999 * @throws CiviCRM_API3_Exception
1001 public static function setIsActive($id, $is_active) {
1002 // as both the create & add functions have a bunch of logic in them that
1003 // doesn't seem to cope with a normal update we will call the api which
1004 // has tested handling for this
1005 // however, a longer term solution would be to simplify the add, create & api functions
1006 // to be more standard. It is debatable @ that point whether it's better to call the BAO
1007 // direct as the api is more tested.
1008 $result = civicrm_api('relationship', 'create', [
1010 'is_active' => $is_active,
1014 if (is_array($result) && !empty($result['is_error']) && $result['error_message'] != 'Duplicate Relationship') {
1015 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array
::value('error_code', $result, 'undefined'), $result);
1022 * Fetch a relationship object and store the values in the values array.
1024 * @param array $params
1025 * Input parameters to find object.
1026 * @param array $values
1027 * Output values of the object.
1030 * (reference) the values that could be potentially assigned to smarty
1032 public static function &getValues(&$params, &$values) {
1033 if (empty($params)) {
1038 // get the specific number of relationship or all relationships.
1039 if (!empty($params['numRelationship'])) {
1040 $v['data'] = &CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'], NULL, $params['numRelationship']);
1043 $v['data'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id']);
1046 // get the total count of relationships
1047 $v['totalCount'] = count($v['data']);
1049 $values['relationship']['data'] = &$v['data'];
1050 $values['relationship']['totalCount'] = &$v['totalCount'];
1056 * Helper function to form the sql for relationship retrieval.
1058 * @param int $contactId
1060 * @param int $status
1061 * (check const at top of file).
1062 * @param int $numRelationship
1063 * No of relationships to display (limit).
1065 * Get the no of relationships.
1066 * $param int $relationshipId relationship id
1067 * @param int $relationshipId
1068 * @param string $direction
1069 * The direction we are interested in a_b or b_a.
1070 * @param array $params
1071 * Array of extra values including relationship_type_id per api spec.
1074 * [select, from, where]
1076 * @throws \CRM_Core_Exception
1077 * @throws \CiviCRM_API3_Exception
1079 public static function makeURLClause($contactId, $status, $numRelationship, $count, $relationshipId, $direction, $params = []) {
1080 $select = $from = $where = '';
1084 if ($direction === 'a_b') {
1085 $select .= ' SELECT count(DISTINCT civicrm_relationship.id) as cnt1, 0 as cnt2 ';
1088 $select .= ' SELECT 0 as cnt1, count(DISTINCT civicrm_relationship.id) as cnt2 ';
1092 $select .= ' SELECT civicrm_relationship.id as civicrm_relationship_id,
1093 civicrm_contact.sort_name as sort_name,
1094 civicrm_contact.display_name as display_name,
1095 civicrm_contact.job_title as job_title,
1096 civicrm_contact.employer_id as employer_id,
1097 civicrm_contact.organization_name as organization_name,
1098 civicrm_address.street_address as street_address,
1099 civicrm_address.city as city,
1100 civicrm_address.postal_code as postal_code,
1101 civicrm_state_province.abbreviation as state,
1102 civicrm_country.name as country,
1103 civicrm_email.email as email,
1104 civicrm_contact.contact_type as contact_type,
1105 civicrm_contact.contact_sub_type as contact_sub_type,
1106 civicrm_phone.phone as phone,
1107 civicrm_contact.id as civicrm_contact_id,
1108 civicrm_relationship.contact_id_b as contact_id_b,
1109 civicrm_relationship.contact_id_a as contact_id_a,
1110 civicrm_relationship_type.id as civicrm_relationship_type_id,
1111 civicrm_relationship.start_date as start_date,
1112 civicrm_relationship.end_date as end_date,
1113 civicrm_relationship.description as description,
1114 civicrm_relationship.is_active as is_active,
1115 civicrm_relationship.is_permission_a_b as is_permission_a_b,
1116 civicrm_relationship.is_permission_b_a as is_permission_b_a,
1117 civicrm_relationship.case_id as case_id';
1119 if ($direction === 'a_b') {
1120 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
1121 civicrm_relationship_type.label_b_a as relation ';
1124 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
1125 civicrm_relationship_type.label_a_b as relation ';
1130 FROM civicrm_relationship
1131 INNER JOIN civicrm_relationship_type ON ( civicrm_relationship.relationship_type_id = civicrm_relationship_type.id )
1132 INNER JOIN civicrm_contact ';
1133 if ($direction === 'a_b') {
1134 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_a ) ';
1137 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_b ) ';
1142 LEFT JOIN civicrm_address ON (civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1)
1143 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
1144 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id AND civicrm_email.is_primary = 1)
1145 LEFT JOIN civicrm_state_province ON (civicrm_address.state_province_id = civicrm_state_province.id)
1146 LEFT JOIN civicrm_country ON (civicrm_address.country_id = civicrm_country.id)
1150 $where = 'WHERE ( 1 )';
1152 if ($direction === 'a_b') {
1153 $where .= ' AND civicrm_relationship.contact_id_b = ' . CRM_Utils_Type
::escape($contactId, 'Positive');
1156 $where .= ' AND civicrm_relationship.contact_id_a = ' . CRM_Utils_Type
::escape($contactId, 'Positive') . '
1157 AND civicrm_relationship.contact_id_a != civicrm_relationship.contact_id_b ';
1160 if ($relationshipId) {
1161 $where .= ' AND civicrm_relationship.id = ' . CRM_Utils_Type
::escape($relationshipId, 'Positive');
1164 $date = date('Y-m-d');
1165 if ($status == self
::PAST
) {
1166 //this case for showing past relationship
1167 $where .= ' AND civicrm_relationship.is_active = 1 ';
1168 $where .= " AND civicrm_relationship.end_date < '" . $date . "'";
1170 elseif ($status == self
::DISABLED
) {
1171 // this case for showing disabled relationship
1172 $where .= ' AND civicrm_relationship.is_active = 0 ';
1174 elseif ($status == self
::CURRENT
) {
1175 //this case for showing current relationship
1176 $where .= ' AND civicrm_relationship.is_active = 1 ';
1177 $where .= " AND (civicrm_relationship.end_date >= '" . $date . "' OR civicrm_relationship.end_date IS NULL) ";
1179 elseif ($status == self
::INACTIVE
) {
1180 //this case for showing inactive relationships
1181 $where .= " AND (civicrm_relationship.end_date < '" . $date . "'";
1182 $where .= ' OR civicrm_relationship.is_active = 0 )';
1186 $where .= ' AND civicrm_contact.is_deleted = 0';
1187 if (!empty($params['membership_type_id']) && empty($params['relationship_type_id'])) {
1188 $where .= self
::membershipTypeToRelationshipTypes($params, $direction);
1190 if (!empty($params['relationship_type_id'])) {
1191 if (is_array($params['relationship_type_id'])) {
1192 $where .= " AND " . CRM_Core_DAO
::createSQLFilter('relationship_type_id', $params['relationship_type_id'], 'Integer');
1195 $where .= ' AND relationship_type_id = ' . CRM_Utils_Type
::escape($params['relationship_type_id'], 'Positive');
1198 if ($direction === 'a_b') {
1199 $where .= ' ) UNION ';
1205 return [$select, $from, $where];
1209 * Get a list of relationships.
1211 * @param int $contactId
1213 * @param int $status
1214 * 1: Past 2: Disabled 3: Current.
1215 * @param int $numRelationship
1216 * No of relationships to display (limit).
1218 * Get the no of relationships.
1219 * @param int $relationshipId
1220 * @param array $links
1221 * the list of links to display
1222 * @param int $permissionMask
1223 * the permission mask to be applied for the actions
1224 * @param bool $permissionedContact
1225 * to return only permissioned Contact
1226 * @param array $params
1227 * @param bool $includeTotalCount
1228 * Should we return a count of total accessable relationships
1231 * relationship records
1233 * @throws \CRM_Core_Exception
1234 * @throws \CiviCRM_API3_Exception
1236 public static function getRelationship(
1238 $status = 0, $numRelationship = 0,
1239 $count = 0, $relationshipId = 0,
1240 $links = NULL, $permissionMask = NULL,
1241 $permissionedContact = FALSE,
1242 $params = [], $includeTotalCount = FALSE
1245 if (!$contactId && !$relationshipId) {
1249 list($select1, $from1, $where1) = self
::makeURLClause($contactId, $status, $numRelationship,
1250 $count, $relationshipId, 'a_b', $params
1252 list($select2, $from2, $where2) = self
::makeURLClause($contactId, $status, $numRelationship,
1253 $count, $relationshipId, 'b_a', $params
1256 $order = $limit = '';
1258 if (empty($params['sort'])) {
1259 $order = ' ORDER BY civicrm_relationship_type_id, sort_name ';
1262 $order = " ORDER BY {$params['sort']} ";
1266 if (!empty($params['offset']) && $params['offset'] > 0) {
1267 $offset = $params['offset'];
1270 if ($numRelationship) {
1271 $limit = " LIMIT {$offset}, $numRelationship";
1275 // building the query string
1276 $queryString = $select1 . $from1 . $where1 . $select2 . $from2 . $where2;
1278 $relationship = new CRM_Contact_DAO_Relationship();
1280 $relationship->query($queryString . $order . $limit);
1283 $relationshipCount = 0;
1284 while ($relationship->fetch()) {
1285 $relationshipCount +
= $relationship->cnt1 +
$relationship->cnt2
;
1287 return $relationshipCount;
1291 if ($includeTotalCount) {
1292 $values['total_relationships'] = CRM_Core_DAO
::singleValueQuery("SELECT count(*) FROM ({$queryString}) AS r");
1296 if ($status != self
::INACTIVE
) {
1298 $mask = array_sum(array_keys($links));
1299 if ($mask & CRM_Core_Action
::DISABLE
) {
1300 $mask -= CRM_Core_Action
::DISABLE
;
1302 if ($mask & CRM_Core_Action
::ENABLE
) {
1303 $mask -= CRM_Core_Action
::ENABLE
;
1306 if ($status == self
::CURRENT
) {
1307 $mask |
= CRM_Core_Action
::DISABLE
;
1309 elseif ($status == self
::DISABLED
) {
1310 $mask |
= CRM_Core_Action
::ENABLE
;
1313 // temporary hold the value of $mask.
1317 while ($relationship->fetch()) {
1318 $rid = $relationship->civicrm_relationship_id
;
1319 $cid = $relationship->civicrm_contact_id
;
1321 if ($permissionedContact &&
1322 (!CRM_Contact_BAO_Contact_Permission
::allow($cid))
1326 if ($status != self
::INACTIVE
&& $links) {
1327 // assign the original value to $mask
1329 // display action links if $cid has edit permission for the relationship.
1330 if (!($permissionMask & CRM_Core_Permission
::EDIT
) && CRM_Contact_BAO_Contact_Permission
::allow($cid, CRM_Core_Permission
::EDIT
)) {
1331 $permissions[] = CRM_Core_Permission
::EDIT
;
1332 $permissions[] = CRM_Core_Permission
::DELETE
;
1333 $permissionMask = CRM_Core_Action
::mask($permissions);
1335 $mask = $mask & $permissionMask;
1337 $values[$rid]['id'] = $rid;
1338 $values[$rid]['cid'] = $cid;
1339 $values[$rid]['contact_id_a'] = $relationship->contact_id_a
;
1340 $values[$rid]['contact_id_b'] = $relationship->contact_id_b
;
1341 $values[$rid]['contact_type'] = $relationship->contact_type
;
1342 $values[$rid]['contact_sub_type'] = $relationship->contact_sub_type
;
1343 $values[$rid]['relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1344 $values[$rid]['relation'] = $relationship->relation
;
1345 $values[$rid]['name'] = $relationship->sort_name
;
1346 $values[$rid]['display_name'] = $relationship->display_name
;
1347 $values[$rid]['job_title'] = $relationship->job_title
;
1348 $values[$rid]['email'] = $relationship->email
;
1349 $values[$rid]['phone'] = $relationship->phone
;
1350 $values[$rid]['employer_id'] = $relationship->employer_id
;
1351 $values[$rid]['organization_name'] = $relationship->organization_name
;
1352 $values[$rid]['country'] = $relationship->country
;
1353 $values[$rid]['city'] = $relationship->city
;
1354 $values[$rid]['state'] = $relationship->state
;
1355 $values[$rid]['start_date'] = $relationship->start_date
;
1356 $values[$rid]['end_date'] = $relationship->end_date
;
1357 $values[$rid]['description'] = $relationship->description
;
1358 $values[$rid]['is_active'] = $relationship->is_active
;
1359 $values[$rid]['is_permission_a_b'] = $relationship->is_permission_a_b
;
1360 $values[$rid]['is_permission_b_a'] = $relationship->is_permission_b_a
;
1361 $values[$rid]['case_id'] = $relationship->case_id
;
1364 $values[$rid]['status'] = $status;
1367 $values[$rid]['civicrm_relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1369 if ($relationship->contact_id_a
== $contactId) {
1370 $values[$rid]['rtype'] = 'a_b';
1373 $values[$rid]['rtype'] = 'b_a';
1379 'rtype' => $values[$rid]['rtype'],
1380 'cid' => $contactId,
1381 'cbid' => $values[$rid]['cid'],
1382 'caseid' => $values[$rid]['case_id'],
1383 'clientid' => $contactId,
1386 if ($status == self
::INACTIVE
) {
1387 // setting links for inactive relationships
1388 $mask = array_sum(array_keys($links));
1389 if (!$values[$rid]['is_active']) {
1390 $mask -= CRM_Core_Action
::DISABLE
;
1393 $mask -= CRM_Core_Action
::ENABLE
;
1394 $mask -= CRM_Core_Action
::DISABLE
;
1396 $mask = $mask & $permissionMask;
1399 // Give access to manage case link by copying to MAX_ACTION index temporarily, depending on case permission of user.
1400 if ($values[$rid]['case_id']) {
1401 // Borrowed logic from CRM_Case_Page_Tab
1402 $hasCaseAccess = FALSE;
1403 if (CRM_Core_Permission
::check('access all cases and activities')) {
1404 $hasCaseAccess = TRUE;
1407 $userCases = CRM_Case_BAO_Case
::getCases(FALSE);
1408 if (array_key_exists($values[$rid]['case_id'], $userCases)) {
1409 $hasCaseAccess = TRUE;
1413 if ($hasCaseAccess) {
1414 // give access by copying to MAX_ACTION temporarily, otherwise leave at NONE which won't display
1415 $links[CRM_Core_Action
::MAX_ACTION
] = $links[CRM_Core_Action
::NONE
];
1416 $links[CRM_Core_Action
::MAX_ACTION
]['name'] = ts('Manage Case #%1', [1 => $values[$rid]['case_id']]);
1417 $links[CRM_Core_Action
::MAX_ACTION
]['class'] = 'no-popup';
1419 // Also make sure we have the right client cid since can get here from multiple relationship tabs.
1420 if ($values[$rid]['rtype'] == 'b_a') {
1421 $replace['clientid'] = $values[$rid]['cid'];
1423 $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>';
1427 $values[$rid]['action'] = CRM_Core_Action
::formLink(
1433 'relationship.selector.row',
1436 unset($links[CRM_Core_Action
::MAX_ACTION
]);
1445 * Get list of relationship type based on the target contact type.
1446 * Both directions of relationships are included if their labels are not the same.
1448 * @param string $targetContactType
1449 * A valid contact type (may be Individual, Organization, Household).
1452 * array reference of all relationship types with context to current contact type.
1454 public static function getRelationType($targetContactType) {
1455 $relationshipType = [];
1456 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType();
1458 foreach ($allRelationshipType as $key => $type) {
1459 if ($type['contact_type_b'] == $targetContactType ||
empty($type['contact_type_b'])) {
1460 $relationshipType[$key . '_a_b'] = $type['label_a_b'];
1462 if (($type['contact_type_a'] == $targetContactType ||
empty($type['contact_type_a']))
1463 && $type['label_a_b'] != $type['label_b_a']
1465 $relationshipType[$key . '_b_a'] = $type['label_b_a'];
1469 return $relationshipType;
1473 * Create / update / delete membership for related contacts.
1475 * This function will create/update/delete membership for related
1476 * contact based on 1) contact have active membership 2) that
1477 * membership is is extedned by the same relationship type to that
1478 * of the existing relationship.
1480 * @param int $contactId
1482 * @param array $params
1483 * array of values submitted by POST.
1486 * @param \const|int $action which action called this function
1488 * @param bool $active
1490 * @throws \CRM_Core_Exception
1491 * @throws \CiviCRM_API3_Exception
1493 public static function relatedMemberships($contactId, $params, $ids, $action = CRM_Core_Action
::ADD
, $active = TRUE) {
1494 // Check the end date and set the status of the relationship
1496 $status = self
::CURRENT
;
1497 $targetContact = $targetContact = CRM_Utils_Array
::value('contact_check', $params, []);
1498 $today = date('Ymd');
1500 // If a relationship hasn't yet started, just return for now
1501 // TODO: handle edge-case of updating start_date of an existing relationship
1502 if (!empty($params['start_date'])) {
1503 $startDate = substr(CRM_Utils_Date
::format($params['start_date']), 0, 8);
1504 if ($today < $startDate) {
1509 if (!empty($params['end_date'])) {
1510 $endDate = substr(CRM_Utils_Date
::format($params['end_date']), 0, 8);
1511 if ($today > $endDate) {
1512 $status = self
::PAST
;
1516 if (($action & CRM_Core_Action
::ADD
) && ($status & self
::PAST
)) {
1517 // If relationship is PAST and action is ADD, do nothing.
1521 $rel = explode('_', $params['relationship_type_id']);
1523 $relTypeId = $rel[0];
1524 if (!empty($rel[1])) {
1525 $relDirection = "_{$rel[1]}_{$rel[2]}";
1528 // this call is coming from somewhere where the direction was resolved early on (e.g an api call)
1529 // so we can assume _a_b
1530 $relDirection = "_a_b";
1531 $targetContact = [$params['contact_id_b'] => 1];
1534 if (($action & CRM_Core_Action
::ADD
) ||
1535 ($action & CRM_Core_Action
::DELETE
)
1537 $contact = $contactId;
1539 elseif ($action & CRM_Core_Action
::UPDATE
) {
1540 $contact = (int) $ids['contact'];
1541 $targetContact = [$ids['contactTarget'] => 1];
1544 // Build the 'values' array for
1547 // This will allow us to check if either of the contacts in
1548 // relationship have active memberships.
1553 $values[$contact] = [
1554 'relatedContacts' => $targetContact,
1555 'relationshipTypeId' => $relTypeId,
1556 'relationshipTypeDirection' => $relDirection,
1559 if (!empty($targetContact)) {
1560 foreach ($targetContact as $cid => $donCare) {
1562 'relatedContacts' => [$contact => 1],
1563 'relationshipTypeId' => $relTypeId,
1566 $relTypeParams = ['id' => $relTypeId];
1567 $relTypeValues = [];
1568 CRM_Contact_BAO_RelationshipType
::retrieve($relTypeParams, $relTypeValues);
1570 if (CRM_Utils_Array
::value('name_a_b', $relTypeValues) == CRM_Utils_Array
::value('name_b_a', $relTypeValues)) {
1571 $values[$cid]['relationshipTypeDirection'] = '_a_b';
1574 $values[$cid]['relationshipTypeDirection'] = ($relDirection == '_a_b') ?
'_b_a' : '_a_b';
1579 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1581 $relationshipProcessor = new CRM_Member_Utils_RelationshipProcessor(array_keys($values), $active);
1582 foreach ($values as $cid => $details) {
1583 $relatedContacts = array_keys(CRM_Utils_Array
::value('relatedContacts', $details, []));
1584 $mainRelatedContactId = reset($relatedContacts);
1586 foreach ($relationshipProcessor->getRelationshipMembershipsForContact((int) $cid) as $membershipId => $membershipValues) {
1587 $membershipInherittedFromContactID = NULL;
1588 if (!empty($membershipValues['owner_membership_id'])) {
1589 // @todo - $membership already has this now.
1590 // Use get not getsingle so that we get e-notice noise but not a fatal is the membership has already been deleted.
1591 $inheritedFromMembership = civicrm_api3('Membership', 'get', ['id' => $membershipValues['owner_membership_id'], 'sequential' => 1])['values'][0];
1592 $membershipInherittedFromContactID = (int) $inheritedFromMembership['contact_id'];
1595 if ($action & CRM_Core_Action
::DELETE
) {
1596 // @todo don't return relTypeId here - but it seems to be used later in a cryptic way (hint cryptic is not a complement).
1597 list($relTypeId, $isDeletable) = self
::isInheritedMembershipInvalidated($membershipValues, $values, $cid);
1599 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipValues['owner_membership_id'], $membershipValues['contact_id']);
1603 if (($action & CRM_Core_Action
::UPDATE
) &&
1604 ($status & self
::PAST
) &&
1605 ($membershipValues['owner_membership_id'])
1607 // If relationship is PAST and action is UPDATE
1608 // then delete the RELATED membership
1609 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipValues['owner_membership_id'],
1610 $membershipValues['contact_id']
1615 // add / edit the memberships for related
1618 // @todo - all these lines get 'relTypeDirs' - but it's already a key in the $membership array.
1619 // Get the Membership Type Details.
1620 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipType($membershipValues['membership_type_id']);
1621 // Check if contact's relationship type exists in membership type
1623 if (!empty($membershipType['relationship_type_id'])) {
1624 $relTypeIds = (array) $membershipType['relationship_type_id'];
1626 if (!empty($membershipType['relationship_direction'])) {
1627 $relDirections = (array) $membershipType['relationship_direction'];
1629 foreach ($relTypeIds as $key => $value) {
1630 $relTypeDirs[] = $value . '_' . $relDirections[$key];
1632 $relTypeDir = $details['relationshipTypeId'] . $details['relationshipTypeDirection'];
1633 if (in_array($relTypeDir, $relTypeDirs)) {
1634 // Check if relationship being created/updated is
1635 // similar to that of membership type's
1638 $membershipValues['owner_membership_id'] = $membershipId;
1639 unset($membershipValues['id']);
1640 unset($membershipValues['contact_id']);
1641 unset($membershipValues['membership_id']);
1642 foreach ($details['relatedContacts'] as $relatedContactId => $donCare) {
1643 $membershipValues['contact_id'] = $relatedContactId;
1644 if ($deceasedStatusId &&
1645 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $relatedContactId, 'is_deceased')
1647 $membershipValues['status_id'] = $deceasedStatusId;
1648 $membershipValues['skipStatusCal'] = TRUE;
1651 if (in_array($action, [CRM_Core_Action
::UPDATE
, CRM_Core_Action
::ADD
, CRM_Core_Action
::ENABLE
])) {
1652 //if updated relationship is already related to contact don't delete existing inherited membership
1653 if (in_array((int) $relatedContactId, $membershipValues['inheriting_contact_ids'], TRUE)
1654 ||
$relatedContactId === $membershipValues['owner_contact_id']
1659 //delete the membership record for related
1660 //contact before creating new membership record.
1661 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $relatedContactId);
1663 //skip status calculation for pay later memberships.
1664 if ('Pending' === CRM_Core_PseudoConstant
::getName('CRM_Member_BAO_Membership', 'status_id', $membershipValues['status_id'])) {
1665 $membershipValues['skipStatusCal'] = TRUE;
1667 // As long as the membership itself was not created by inheritance from the same contact
1668 // that stands to inherit the membership we add an inherited membership.
1669 if ($membershipInherittedFromContactID !== (int) $membershipValues['contact_id']) {
1670 $membershipValues = self
::addInheritedMembership($membershipValues);
1674 elseif ($action & CRM_Core_Action
::UPDATE
) {
1675 // if action is update and updated relationship do
1676 // not match with the existing
1677 // membership=>relationship then we need to
1678 // change the status of the membership record to expired for
1679 // previous relationship -- CRM-12078.
1680 // CRM-16087 we need to pass ownerMembershipId to isRelatedMembershipExpired function
1681 if (empty($params['relationship_ids']) && !empty($params['id'])) {
1682 $relIds = [$params['id']];
1685 $relIds = $params['relationship_ids'] ??
NULL;
1687 if (self
::isRelatedMembershipExpired($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId,
1688 $relIds) && !empty($membershipValues['owner_membership_id']
1689 ) && !empty($values[$mainRelatedContactId]['memberships'][$membershipValues['owner_membership_id']])) {
1690 $membershipValues['status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus', 'Expired', 'id', 'label');
1691 $type = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $membershipValues['membership_type_id'], 'name', 'id');
1692 CRM_Member_BAO_Membership
::add($membershipValues);
1693 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');
1701 * Helper function to check whether the membership is expired or not.
1703 * Function takes a list of related membership types and if it is not also passed a
1704 * relationship ID of that types evaluates whether the membership status should be changed to expired.
1706 * @param array $membershipTypeRelationshipTypeIDs
1707 * Relation type IDs related to the given membership type.
1708 * @param int $contactId
1709 * @param int $mainRelatedContactId
1710 * @param int $relTypeId
1711 * @param array $relIds
1715 public static function isRelatedMembershipExpired($membershipTypeRelationshipTypeIDs, $contactId, $mainRelatedContactId, $relTypeId, $relIds) {
1716 if (empty($membershipTypeRelationshipTypeIDs) ||
in_array($relTypeId, $membershipTypeRelationshipTypeIDs)) {
1720 if (empty($relIds)) {
1725 1 => [$contactId, 'Integer'],
1726 2 => [$mainRelatedContactId, 'Integer'],
1729 if ($contactId == $mainRelatedContactId) {
1730 $recordsFound = (int) CRM_Core_DAO
::singleValueQuery("SELECT COUNT(*) FROM civicrm_relationship WHERE relationship_type_id IN ( " . implode(',', $membershipTypeRelationshipTypeIDs) . " ) AND
1731 contact_id_a IN ( %1 ) OR contact_id_b IN ( %1 ) AND id IN (" . implode(',', $relIds) . ")", $relParamas);
1732 if ($recordsFound) {
1738 $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);
1740 if ($recordsFound) {
1748 * Get Current Employer for Contact.
1750 * @param $contactIds
1754 * array of the current employer
1756 public static function getCurrentEmployer($contactIds) {
1757 $contacts = implode(',', $contactIds);
1760 SELECT organization_name, id, employer_id
1761 FROM civicrm_contact
1762 WHERE id IN ( {$contacts} )
1765 $dao = CRM_Core_DAO
::executeQuery($query);
1766 $currentEmployer = [];
1767 while ($dao->fetch()) {
1768 $currentEmployer[$dao->id
]['org_id'] = $dao->employer_id
;
1769 $currentEmployer[$dao->id
]['org_name'] = $dao->organization_name
;
1772 return $currentEmployer;
1776 * Function to return list of permissioned contacts for a given contact and relationship type.
1778 * @param int $contactID
1779 * contact id whose permissioned contacts are to be found.
1780 * @param int $relTypeId
1781 * one or more relationship type id's.
1782 * @param string $name
1783 * @param string $contactType
1788 public static function getPermissionedContacts($contactID, $relTypeId = NULL, $name = NULL, $contactType = NULL) {
1790 $args = [1 => [$contactID, 'Integer']];
1791 $relationshipTypeClause = $contactTypeClause = '';
1794 // @todo relTypeId is only ever passed in as an int. Change this to reflect that -
1795 // probably being overly conservative by not doing so but working on stable release.
1796 $relationshipTypeClause = 'AND cr.relationship_type_id IN (%2) ';
1797 $args[2] = [$relTypeId, 'String'];
1801 $contactTypeClause = ' AND cr.relationship_type_id = crt.id AND crt.contact_type_b = %3 ';
1802 $args[3] = [$contactType, 'String'];
1806 SELECT cc.id as id, cc.sort_name as name
1807 FROM civicrm_relationship cr, civicrm_contact cc, civicrm_relationship_type crt
1809 cr.contact_id_a = %1 AND
1810 cr.is_permission_a_b = 1 AND
1811 IF(cr.end_date IS NULL, 1, (DATEDIFF( CURDATE( ), cr.end_date ) <= 0)) AND
1812 cr.is_active = 1 AND
1813 cc.id = cr.contact_id_b AND
1815 $relationshipTypeClause
1819 if (!empty($name)) {
1820 $name = CRM_Utils_Type
::escape($name, 'String');
1822 AND cc.sort_name LIKE '%$name%'";
1825 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1826 while ($dao->fetch()) {
1827 $contacts[$dao->id
] = [
1828 'name' => $dao->name
,
1829 'value' => $dao->id
,
1837 * Merge relationships from otherContact to mainContact.
1839 * Called during contact merge operation
1841 * @param int $mainId
1842 * Contact id of main contact record.
1843 * @param int $otherId
1844 * Contact id of record which is going to merge.
1845 * @param array $sqls
1846 * (reference) array of sql statements to append to.
1848 * @see CRM_Dedupe_Merger::cpTables()
1850 public static function mergeRelationships($mainId, $otherId, &$sqls) {
1851 // Delete circular relationships
1852 $sqls[] = "DELETE FROM civicrm_relationship
1853 WHERE (contact_id_a = $mainId AND contact_id_b = $otherId AND case_id IS NULL)
1854 OR (contact_id_b = $mainId AND contact_id_a = $otherId AND case_id IS NULL)";
1856 // Delete relationship from other contact if main contact already has that relationship
1857 $sqls[] = "DELETE r2
1858 FROM civicrm_relationship r1, civicrm_relationship r2
1859 WHERE r1.relationship_type_id = r2.relationship_type_id
1861 AND r1.case_id IS NULL AND r2.case_id IS NULL
1863 r1.contact_id_a = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_b = r2.contact_id_b
1864 OR r1.contact_id_b = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_a = r2.contact_id_a
1866 (r1.contact_id_a = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_b = r2.contact_id_a
1867 OR r1.contact_id_b = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_a = r2.contact_id_b)
1868 AND r1.relationship_type_id IN (SELECT id FROM civicrm_relationship_type WHERE name_b_a = name_a_b)
1872 // Move relationships
1873 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_a = $mainId WHERE contact_id_a = $otherId";
1874 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_b = $mainId WHERE contact_id_b = $otherId";
1876 // Move current employer id (name will get updated later)
1877 $sqls[] = "UPDATE civicrm_contact SET employer_id = $mainId WHERE employer_id = $otherId";
1881 * Set 'is_valid' field to false for all relationships whose end date is in the past, ie. are expired.
1884 * True on success, false if error is encountered.
1885 * @throws \CiviCRM_API3_Exception
1887 public static function disableExpiredRelationships() {
1888 $query = "SELECT id FROM civicrm_relationship WHERE is_active = 1 AND end_date < CURDATE()";
1890 $dao = CRM_Core_DAO
::executeQuery($query);
1891 while ($dao->fetch()) {
1892 $result = CRM_Contact_BAO_Relationship
::setIsActive($dao->id
, FALSE);
1893 // Result will be NULL if error occurred. We abort early if error detected.
1894 if ($result == NULL) {
1902 * Function filters the query by possible relationships for the membership type.
1904 * It is intended to be called when constructing queries for the api (reciprocal & non-reciprocal)
1905 * and to add clauses to limit the return to those relationships which COULD inherit a membership type
1906 * (as opposed to those who inherit a particular membership
1908 * @param array $params
1910 * @param null $direction
1912 * @return array|void
1913 * @throws \CiviCRM_API3_Exception
1915 public static function membershipTypeToRelationshipTypes(&$params, $direction = NULL) {
1916 $membershipType = civicrm_api3('membership_type', 'getsingle', [
1917 'id' => $params['membership_type_id'],
1918 'return' => 'relationship_type_id, relationship_direction',
1920 $relationshipTypes = $membershipType['relationship_type_id'];
1921 if (empty($relationshipTypes)) {
1924 // if we don't have any contact data we can only filter on type
1925 if (empty($params['contact_id']) && empty($params['contact_id_a']) && empty($params['contact_id_a'])) {
1926 $params['relationship_type_id'] = ['IN' => $relationshipTypes];
1930 $relationshipDirections = (array) $membershipType['relationship_direction'];
1931 // if we have contact_id_a OR contact_id_b we can make a call here
1932 // if we have contact??
1933 foreach ($relationshipDirections as $index => $mtdirection) {
1934 if (isset($params['contact_id_a']) && $mtdirection == 'a_b' ||
$direction == 'a_b') {
1935 $types[] = $relationshipTypes[$index];
1937 if (isset($params['contact_id_b']) && $mtdirection == 'b_a' ||
$direction == 'b_a') {
1938 $types[] = $relationshipTypes[$index];
1941 if (!empty($types)) {
1942 $params['relationship_type_id'] = ['IN' => $types];
1944 elseif (!empty($clauses)) {
1945 return explode(' OR ', $clauses);
1948 // effectively setting it to return no results
1949 $params['relationship_type_id'] = 0;
1955 * Wrapper for contact relationship selector.
1957 * @param array $params
1958 * Associated array for params record id.
1961 * associated array of contact relationships
1962 * @throws \Exception
1964 public static function getContactRelationshipSelector(&$params) {
1965 // format the params
1966 $params['offset'] = ($params['page'] - 1) * $params['rp'];
1967 $params['sort'] = $params['sortBy'] ??
NULL;
1969 if ($params['context'] == 'past') {
1970 $relationshipStatus = CRM_Contact_BAO_Relationship
::INACTIVE
;
1972 elseif ($params['context'] == 'all') {
1973 $relationshipStatus = CRM_Contact_BAO_Relationship
::ALL
;
1976 $relationshipStatus = CRM_Contact_BAO_Relationship
::CURRENT
;
1979 // check logged in user for permission
1980 $page = new CRM_Core_Page();
1981 CRM_Contact_Page_View
::checkUserPermission($page, $params['contact_id']);
1982 $permissions = [$page->_permission
];
1983 if ($page->_permission
== CRM_Core_Permission
::EDIT
) {
1984 $permissions[] = CRM_Core_Permission
::DELETE
;
1986 $mask = CRM_Core_Action
::mask($permissions);
1988 $permissionedContacts = TRUE;
1989 if ($params['context'] != 'user') {
1990 $links = CRM_Contact_Page_View_Relationship
::links();
1993 $links = CRM_Contact_Page_View_UserDashBoard
::links();
1996 // get contact relationships
1997 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1998 $relationshipStatus,
1999 $params['rp'], 0, 0,
2001 $permissionedContacts,
2005 $contactRelationships = [];
2006 $params['total'] = $relationships['total_relationships'];
2007 unset($relationships['total_relationships']);
2008 if (!empty($relationships)) {
2010 $displayName = CRM_Contact_BAO_Contact
::displayName($params['contact_id']);
2013 foreach ($relationships as $relationshipId => $values) {
2016 $relationship['DT_RowId'] = $values['id'];
2017 $relationship['DT_RowClass'] = 'crm-entity';
2018 if ($values['is_active'] == 0) {
2019 $relationship['DT_RowClass'] .= ' disabled';
2022 $relationship['DT_RowAttr'] = [];
2023 $relationship['DT_RowAttr']['data-entity'] = 'relationship';
2024 $relationship['DT_RowAttr']['data-id'] = $values['id'];
2026 //Add image icon for related contacts: CRM-14919; CRM-19668
2027 $contactType = (!empty($values['contact_sub_type'])) ?
$values['contact_sub_type'] : $values['contact_type'];
2028 $icon = CRM_Contact_BAO_Contact_Utils
::getImage($contactType,
2032 $relationship['sort_name'] = $icon . ' ' . CRM_Utils_System
::href(
2034 'civicrm/contact/view',
2035 "reset=1&cid={$values['cid']}");
2037 $relationship['relation'] = CRM_Utils_Array
::value('case', $values, '') . CRM_Utils_System
::href(
2038 $values['relation'],
2039 'civicrm/contact/view/rel',
2040 "action=view&reset=1&cid={$values['cid']}&id={$values['id']}&rtype={$values['rtype']}");
2042 if (!empty($values['description'])) {
2043 $relationship['relation'] .= "<p class='description'>{$values['description']}</p>";
2046 if ($params['context'] == 'current') {
2047 $smarty = CRM_Core_Smarty
::singleton();
2051 'permContact' => $params['contact_id'],
2052 'permDisplayName' => $displayName,
2053 'otherContact' => $values['cid'],
2054 'otherDisplayName' => $values['display_name'],
2055 'columnKey' => 'sort_name',
2058 'permContact' => $values['cid'],
2059 'permDisplayName' => $values['display_name'],
2060 'otherContact' => $params['contact_id'],
2061 'otherDisplayName' => $displayName,
2062 'columnKey' => 'relation',
2066 foreach ($contactCombos as $combo) {
2067 foreach ([CRM_Contact_BAO_Relationship
::EDIT
, CRM_Contact_BAO_Relationship
::VIEW
] as $permType) {
2068 $smarty->assign('permType', $permType);
2069 if (($combo['permContact'] == $values['contact_id_a'] and $values['is_permission_a_b'] == $permType)
2070 ||
($combo['permContact'] == $values['contact_id_b'] and $values['is_permission_b_a'] == $permType)
2072 $smarty->assign('permDisplayName', $combo['permDisplayName']);
2073 $smarty->assign('otherDisplayName', $combo['otherDisplayName']);
2074 $relationship[$combo['columnKey']] .= $smarty->fetch('CRM/Contact/Page/View/RelationshipPerm.tpl');
2080 $relationship['start_date'] = CRM_Utils_Date
::customFormat($values['start_date']);
2081 $relationship['end_date'] = CRM_Utils_Date
::customFormat($values['end_date']);
2082 $relationship['city'] = $values['city'];
2083 $relationship['state'] = $values['state'];
2084 $relationship['email'] = $values['email'];
2085 $relationship['phone'] = $values['phone'];
2086 $relationship['links'] = $values['action'];
2088 array_push($contactRelationships, $relationship);
2092 $columnHeaders = self
::getColumnHeaders();
2094 CRM_Utils_Hook
::searchColumns('relationship.rows', $columnHeaders, $contactRelationships, $selector);
2096 $relationshipsDT = [];
2097 $relationshipsDT['data'] = $contactRelationships;
2098 $relationshipsDT['recordsTotal'] = $params['total'];
2099 $relationshipsDT['recordsFiltered'] = $params['total'];
2101 return $relationshipsDT;
2107 public static function getColumnHeaders() {
2110 'name' => ts('Relationship'),
2111 'sort' => 'relation',
2112 'direction' => CRM_Utils_Sort
::ASCENDING
,
2116 'sort' => 'sort_name',
2117 'direction' => CRM_Utils_Sort
::ASCENDING
,
2120 'name' => ts('Start'),
2121 'sort' => 'start_date',
2122 'direction' => CRM_Utils_Sort
::DONTCARE
,
2125 'name' => ts('End'),
2126 'sort' => 'end_date',
2127 'direction' => CRM_Utils_Sort
::DONTCARE
,
2130 'name' => ts('City'),
2132 'direction' => CRM_Utils_Sort
::DONTCARE
,
2135 'name' => ts('State/Prov'),
2137 'direction' => CRM_Utils_Sort
::DONTCARE
,
2140 'name' => ts('Email'),
2142 'direction' => CRM_Utils_Sort
::DONTCARE
,
2145 'name' => ts('Phone'),
2147 'direction' => CRM_Utils_Sort
::DONTCARE
,
2152 'direction' => CRM_Utils_Sort
::DONTCARE
,
2160 public static function buildOptions($fieldName, $context = NULL, $props = []) {
2161 // Quickform-specific format, for use when editing relationship type options in a popup from the contact relationship form
2162 if ($fieldName === 'relationship_type_id' && !empty($props['is_form'])) {
2163 return self
::getContactRelationshipType(
2164 $props['contact_id'] ??
NULL,
2165 $props['relationship_direction'] ??
'a_b',
2166 $props['relationship_id'] ??
NULL,
2167 $props['contact_type'] ??
NULL
2171 return parent
::buildOptions($fieldName, $context, $props);
2175 * Process the params from api, form and check if current
2176 * employer should be set or unset.
2178 * @param array $params
2179 * @param int $relationshipId
2180 * @param int|null $updatedRelTypeID
2183 * TRUE if current employer needs to be cleared.
2184 * @throws \CiviCRM_API3_Exception
2186 public static function isCurrentEmployerNeedingToBeCleared($params, $relationshipId, $updatedRelTypeID = NULL) {
2187 $existingTypeID = (int) CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Relationship', $relationshipId, 'relationship_type_id');
2188 $updatedRelTypeID = $updatedRelTypeID ?
$updatedRelTypeID : $existingTypeID;
2189 $currentEmployerID = (int) civicrm_api3('Contact', 'getvalue', ['return' => 'current_employer_id', 'id' => $params['contact_id_a']]);
2191 if ($currentEmployerID !== (int) $params['contact_id_b'] ||
!self
::isRelationshipTypeCurrentEmployer($existingTypeID)) {
2194 //Clear employer if relationship is expired.
2195 if (!empty($params['end_date']) && strtotime($params['end_date']) < time()) {
2198 //current employer checkbox is disabled on the form.
2199 //inactive or relationship type(employer of) is updated.
2200 if ((isset($params['is_current_employer']) && empty($params['is_current_employer']))
2201 ||
((isset($params['is_active']) && empty($params['is_active'])))
2202 ||
$existingTypeID != $updatedRelTypeID) {
2203 // If there are no other active employer relationships between the same 2 contacts...
2204 if (!civicrm_api3('Relationship', 'getcount', [
2206 'relationship_type_id' => $existingTypeID,
2207 'id' => ['<>' => $params['id']],
2208 'contact_id_a' => $params['contact_id_a'],
2209 'contact_id_b' => $params['contact_id_b'],
2219 * Is this a current employer relationship type.
2221 * @todo - this could use cached pseudoconstant lookups.
2223 * @param int $existingTypeID
2227 private static function isRelationshipTypeCurrentEmployer(int $existingTypeID): bool {
2228 $isCurrentEmployerRelationshipType = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType', $existingTypeID, 'name_b_a') === 'Employer of';
2229 return $isCurrentEmployerRelationshipType;
2233 * Is the inherited relationship invalidated by this relationship change.
2235 * @param $membershipValues
2236 * @param array $values
2240 * @throws \CiviCRM_API3_Exception
2242 private static function isInheritedMembershipInvalidated($membershipValues, array $values, $cid): array {
2243 // @todo most of this can go - it's just the weird historical returning of $relTypeId that it does.
2244 // now we have caching the parent fn can just call CRM_Member_BAO_MembershipType::getMembershipType
2245 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipType($membershipValues['membership_type_id']);
2246 $relTypeIds = $membershipType['relationship_type_id'];
2247 $membershipInheritedFrom = $membershipValues['owner_membership_id'] ??
NULL;
2248 if (!$membershipInheritedFrom ||
!in_array($values[$cid]['relationshipTypeId'], $relTypeIds)) {
2249 return [implode(',', $relTypeIds), FALSE];
2251 //CRM-16300 check if owner membership exist for related membership
2252 return [implode(',', $relTypeIds), !self
::isContactHasValidRelationshipToInheritMembershipType((int) $cid, (int) $membershipValues['membership_type_id'], (int) $membershipValues['owner_membership_id'])];
2256 * Is there a valid relationship confering this membership type on this contact.
2258 * @param int $contactID
2259 * @param int $membershipTypeID
2260 * @param int $parentMembershipID
2261 * Id of the membership being inherited.
2265 * @throws \CiviCRM_API3_Exception
2267 private static function isContactHasValidRelationshipToInheritMembershipType(int $contactID, int $membershipTypeID, int $parentMembershipID): bool {
2268 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipType($membershipTypeID);
2269 $existingRelationships = civicrm_api3('Relationship', 'get', [
2270 'contact_id_a' => $contactID,
2271 'contact_id_b' => $contactID,
2272 'relationship_type_id' => ['IN' => $membershipType['relationship_type_id']],
2273 'options' => ['or' => [['contact_id_a', 'contact_id_b']], 'limit' => 0],
2277 if (empty($existingRelationships)) {
2281 $membershipInheritedFromContactID = (int) civicrm_api3('Membership', 'getvalue', ['return' => 'contact_id', 'id' => $parentMembershipID]);
2282 // I don't think the api can correctly filter by start & end because of handling for NULL
2283 // so we filter them out here.
2284 foreach ($existingRelationships as $index => $existingRelationship) {
2285 $otherContactID = (int) (($contactID === (int) $existingRelationship['contact_id_a']) ?
$existingRelationship['contact_id_b'] : $existingRelationship['contact_id_a']);
2286 if (!empty($existingRelationship['start_date'])
2287 && strtotime($existingRelationship['start_date']) > time()
2289 unset($existingRelationships[$index]);
2292 if (!empty($existingRelationship['end_date'])
2293 && strtotime($existingRelationship['end_date']) < time()
2295 unset($existingRelationships[$index]);
2298 if ($membershipInheritedFromContactID !== $otherContactID
2300 // This is a weird scenario - they have been inheriting the membership
2301 // just not from this relationship - and some max_related calcs etc would be required
2302 // - ie because they are no longer inheriting from this relationship's 'allowance'
2303 // and now are inheriting from the other relationships 'allowance', if it has not
2304 // already hit 'max_related'
2305 // For now ignore here & hope it's handled elsewhere - at least that's consistent with
2306 // before this function was added.
2307 unset($existingRelationships[$index]);
2310 if (!civicrm_api3('Contact', 'getcount', ['id' => $otherContactID, 'is_deleted' => 0])) {
2311 // Can't inherit from a deleted contact.
2312 unset($existingRelationships[$index]);
2316 return !empty($existingRelationships);
2320 * Add an inherited membership, provided max related not exceeded.
2322 * @param array $membershipValues
2325 * @throws \CRM_Core_Exception
2327 protected static function addInheritedMembership($membershipValues) {
2330 FROM civicrm_membership
2331 LEFT JOIN civicrm_membership_status ON (civicrm_membership_status.id = civicrm_membership.status_id)
2332 WHERE membership_type_id = {$membershipValues['membership_type_id']}
2333 AND owner_membership_id = {$membershipValues['owner_membership_id']}
2334 AND is_current_member = 1";
2335 $result = CRM_Core_DAO
::singleValueQuery($query);
2336 if ($result < CRM_Utils_Array
::value('max_related', $membershipValues, PHP_INT_MAX
)) {
2337 // Convert custom_xx_id fields to custom_xx
2338 // See https://lab.civicrm.org/dev/membership/-/issues/37
2339 // This makes sure the value is copied and not the looked up value.
2340 // Which is the case when the custom field is a contact reference field.
2341 // The custom_xx contains the display name of the contact, instead of the contact id.
2342 // The contact id is then available in custom_xx_id.
2343 foreach ($membershipValues as $field => $value) {
2344 if (stripos($field, 'custom_') !== 0) {
2345 // No a custom field
2348 $custom_id = substr($field, 7);
2349 if (substr($custom_id, -3) === '_id') {
2350 $custom_id = substr($custom_id, 0, -3);
2351 unset($membershipValues[$field]);
2352 $membershipValues['custom_' . $custom_id] = $value;
2356 civicrm_api3('Membership', 'create', $membershipValues);
2358 return $membershipValues;