define format at one place
[civicrm-core.git] / CRM / Contact / BAO / Relationship.php
... / ...
CommitLineData
1<?php
2/*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12/**
13 * Class CRM_Contact_BAO_Relationship.
14 */
15class CRM_Contact_BAO_Relationship extends CRM_Contact_DAO_Relationship {
16
17 /**
18 * Various constants to indicate different type of relationships.
19 *
20 * @var int
21 */
22 const ALL = 0, PAST = 1, DISABLED = 2, CURRENT = 4, INACTIVE = 8;
23
24 /**
25 * Constants for is_permission fields.
26 * Note: the slightly non-obvious ordering is due to history...
27 */
28 const NONE = 0, EDIT = 1, VIEW = 2;
29
30 /**
31 * The list of column headers
32 * @var array
33 */
34 private static $columnHeaders;
35
36 /**
37 * Create function - use the API instead.
38 *
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.
43 *
44 * @param array $params
45 *
46 * @return \CRM_Contact_BAO_Relationship
47 * @throws \CRM_Core_Exception
48 */
49 public static function create(&$params) {
50
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');
56 }
57 $params = $extendedParams;
58 if (!CRM_Contact_BAO_Relationship::checkRelationshipType($params['contact_id_a'], $params['contact_id_b'],
59 $params['relationship_type_id'])) {
60 throw new CRM_Core_Exception('Invalid Relationship');
61 }
62 $relationship = self::add($params);
63 if (!empty($params['contact_id_a'])) {
64 $ids = [
65 'contactTarget' => $relationship->contact_id_b,
66 'contact' => $params['contact_id_a'],
67 ];
68
69 //CRM-16087 removed additional call to function relatedMemberships which is already called by disableEnableRelationship
70 //resulting in membership being created twice
71 if (array_key_exists('is_active', $params) && empty($params['is_active'])) {
72 $action = CRM_Core_Action::DISABLE;
73 $active = FALSE;
74 }
75 else {
76 $action = CRM_Core_Action::ENABLE;
77 $active = TRUE;
78 }
79 $id = empty($params['id']) ? $relationship->id : $params['id'];
80 self::disableEnableRelationship($id, $action, $params, $ids, $active);
81 }
82
83 if (empty($params['skipRecentView'])) {
84 self::addRecent($params, $relationship);
85 }
86
87 return $relationship;
88 }
89
90 /**
91 * Create multiple relationships for one contact.
92 *
93 * The relationship details are the same for each relationship except the secondary contact
94 * id can be an array.
95 *
96 * @param array $params
97 * Parameters for creating multiple relationships.
98 * The parameters are the same as for relationship create function except that the non-primary
99 * end of the relationship should be an array of one or more contact IDs.
100 * @param string $primaryContactLetter
101 * a or b to denote the primary contact for this action. The secondary may be multiple contacts
102 * and should be an array.
103 *
104 * @return array
105 * @throws \CRM_Core_Exception
106 */
107 public static function createMultiple($params, $primaryContactLetter) {
108 $secondaryContactLetter = ($primaryContactLetter == 'a') ? 'b' : 'a';
109 $secondaryContactIDs = $params['contact_id_' . $secondaryContactLetter];
110 $valid = $invalid = $duplicate = $saved = 0;
111 $relationshipIDs = [];
112 foreach ($secondaryContactIDs as $secondaryContactID) {
113 try {
114 $params['contact_id_' . $secondaryContactLetter] = $secondaryContactID;
115 $relationship = civicrm_api3('relationship', 'create', $params);
116 $relationshipIDs[] = $relationship['id'];
117 $valid++;
118 }
119 catch (CiviCRM_API3_Exception $e) {
120 switch ($e->getMessage()) {
121 case 'Duplicate Relationship':
122 $duplicate++;
123 break;
124
125 case 'Invalid Relationship':
126 $invalid++;
127 break;
128
129 default:
130 throw new CRM_Core_Exception('unknown relationship create error ' . $e->getMessage());
131 }
132 }
133 }
134
135 return [
136 'valid' => $valid,
137 'invalid' => $invalid,
138 'duplicate' => $duplicate,
139 'saved' => $saved,
140 'relationship_ids' => $relationshipIDs,
141 ];
142 }
143
144 /**
145 * Only called from import now... plus one place outside of core & tests.
146 *
147 * @todo - deprecate more aggressively - will involve copying to the import
148 * class, adding a deprecation notice here & removing from tests.
149 *
150 * Takes an associative array and creates a relationship object.
151 *
152 * @deprecated For single creates use the api instead (it's tested).
153 * For multiple a new variant of this function needs to be written and migrated to as this is a bit
154 * nasty
155 *
156 * @param array $params
157 * (reference ) an assoc array of name/value pairs.
158 * @param array $ids
159 * The array that holds all the db ids.
160 * per http://wiki.civicrm.org/confluence/display/CRM/Database+layer
161 * "we are moving away from the $ids param "
162 *
163 * @return array
164 * @throws \CRM_Core_Exception
165 */
166 public static function legacyCreateMultiple($params, $ids = []) {
167 CRM_Core_Error::deprecatedFunctionWarning('api v4');
168 // clarify that the only key ever pass in the ids array is 'contact'
169 // There is legacy handling for other keys but a universe search on
170 // calls to this function (not supported to be called from outside core)
171 // only returns 2 calls - one in CRM_Contact_Import_Parser_Contact
172 // and the other in jma grant applications (CRM_Grant_Form_Grant_Confirm)
173 // both only pass in contact as a key here.
174 $contactID = $ids['contact'];
175 unset($ids);
176 // There is only ever one value passed in from the 2 places above that call
177 // this - by clarifying here like this we can cleanup within this
178 // function without having to do more universe searches.
179 $relatedContactID = key($params['contact_check']);
180
181 // check if the relationship is valid between contacts.
182 // step 1: check if the relationship is valid if not valid skip and keep the count
183 // step 2: check the if two contacts already have a relationship if yes skip and keep the count
184 // step 3: if valid relationship then add the relation and keep the count
185
186 // step 1
187 [$contactFields['relationship_type_id'], $firstLetter, $secondLetter] = explode('_', $params['relationship_type_id']);
188 $contactFields['contact_id_' . $firstLetter] = $contactID;
189 $contactFields['contact_id_' . $secondLetter] = $relatedContactID;
190 if (!CRM_Contact_BAO_Relationship::checkRelationshipType($contactFields['contact_id_a'], $contactFields['contact_id_b'],
191 $contactFields['relationship_type_id'])) {
192 return [0, 0];
193 }
194
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;
200 }
201 if (
202 self::checkDuplicateRelationship(
203 $contactFields,
204 $contactID,
205 // step 2
206 $relatedContactID
207 )
208 ) {
209 return [0, 1];
210 }
211
212 $singleInstanceParams = array_merge($params, $contactFields);
213 $relationship = self::add($singleInstanceParams);
214
215 // do not add to recent items for import, CRM-4399
216 if (empty($params['skipRecentView'])) {
217 self::addRecent($params, $relationship);
218 }
219
220 return [1, 0];
221 }
222
223 /**
224 * This is the function that check/add if the relationship created is valid.
225 *
226 * @param array $params
227 * Array of name/value pairs.
228 * @param array $ids
229 * The array that holds all the db ids.
230 *
231 * @return CRM_Contact_BAO_Relationship
232 *
233 * @throws \CiviCRM_API3_Exception
234 */
235 public static function add($params, $ids = []) {
236 $params['id'] = CRM_Utils_Array::value('relationship', $ids, CRM_Utils_Array::value('id', $params));
237
238 $hook = 'create';
239 if ($params['id']) {
240 $hook = 'edit';
241 }
242 CRM_Utils_Hook::pre($hook, 'Relationship', $params['id'], $params);
243
244 $relationshipTypes = $params['relationship_type_id'] ?? '';
245 // explode the string with _ to get the relationship type id
246 // and to know which contact has to be inserted in
247 // contact_id_a and which one in contact_id_b
248 list($relationshipTypeID) = explode('_', $relationshipTypes);
249
250 $relationship = new CRM_Contact_BAO_Relationship();
251 if (!empty($params['id'])) {
252 $relationship->id = $params['id'];
253 // Only load the relationship if we're missing required params
254 $requiredParams = ['contact_id_a', 'contact_id_b', 'relationship_type_id'];
255 foreach ($requiredParams as $requiredKey) {
256 if (!isset($params[$requiredKey])) {
257 $relationship->find(TRUE);
258 break;
259 }
260 }
261
262 }
263 $relationship->copyValues($params);
264 // @todo we could probably set $params['relationship_type_id'] above but it's unclear
265 // what that would do with the code below this. So for now be conservative and set it manually.
266 if (!empty($relationshipTypeID)) {
267 $relationship->relationship_type_id = $relationshipTypeID;
268 }
269
270 $params['contact_id_a'] = $relationship->contact_id_a;
271 $params['contact_id_b'] = $relationship->contact_id_b;
272
273 // check if the relationship type is Head of Household then update the
274 // household's primary contact with this contact.
275 try {
276 $headOfHouseHoldID = civicrm_api3('RelationshipType', 'getvalue', [
277 'return' => "id",
278 'name_a_b' => "Head of Household for",
279 ]);
280 if ($relationshipTypeID == $headOfHouseHoldID) {
281 CRM_Contact_BAO_Household::updatePrimaryContact($relationship->contact_id_b, $relationship->contact_id_a);
282 }
283 }
284 catch (Exception $e) {
285 // No "Head of Household" relationship found so we skip specific processing
286 }
287
288 if (!empty($params['id']) && self::isCurrentEmployerNeedingToBeCleared($relationship->toArray(), $params['id'], $relationshipTypeID)) {
289 CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($relationship->contact_id_a);
290 }
291
292 $dateFields = ['end_date', 'start_date'];
293
294 foreach (self::getdefaults() as $defaultField => $defaultValue) {
295 if (isset($params[$defaultField])) {
296 if (in_array($defaultField, $dateFields)) {
297 $relationship->$defaultField = CRM_Utils_Date::format(CRM_Utils_Array::value($defaultField, $params));
298 if (!$relationship->$defaultField) {
299 $relationship->$defaultField = 'NULL';
300 }
301 }
302 else {
303 $relationship->$defaultField = $params[$defaultField];
304 }
305 }
306 elseif (empty($params['id'])) {
307 $relationship->$defaultField = $defaultValue;
308 }
309 }
310
311 $relationship->save();
312 // is_current_employer is an optional parameter that triggers updating the employer_id field to reflect
313 // the relationship being updated. As of writing only truthy versions of the parameter are respected.
314 // https://github.com/civicrm/civicrm-core/pull/13331 attempted to cover both but stalled in QA
315 // so currently we have a cut down version.
316 if (!empty($params['is_current_employer'])) {
317 if (!$relationship->relationship_type_id || !$relationship->contact_id_a || !$relationship->contact_id_b) {
318 $relationship->fetch();
319 }
320 if (self::isRelationshipTypeCurrentEmployer($relationship->relationship_type_id)) {
321 CRM_Contact_BAO_Contact_Utils::setCurrentEmployer([$relationship->contact_id_a => $relationship->contact_id_b]);
322 }
323 }
324 // add custom field values
325 if (!empty($params['custom'])) {
326 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_relationship', $relationship->id);
327 }
328
329 CRM_Utils_Hook::post($hook, 'Relationship', $relationship->id, $relationship);
330
331 return $relationship;
332 }
333
334 /**
335 * Add relationship to recent links.
336 *
337 * @param array $params
338 * @param CRM_Contact_DAO_Relationship $relationship
339 */
340 public static function addRecent($params, $relationship) {
341 $url = CRM_Utils_System::url('civicrm/contact/view/rel',
342 "action=view&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&context=home"
343 );
344 $session = CRM_Core_Session::singleton();
345 $recentOther = [];
346 if (($session->get('userID') == $relationship->contact_id_a) ||
347 CRM_Contact_BAO_Contact_Permission::allow($relationship->contact_id_a, CRM_Core_Permission::EDIT)
348 ) {
349 $rType = substr(CRM_Utils_Array::value('relationship_type_id', $params), -3);
350 $recentOther = [
351 'editUrl' => CRM_Utils_System::url('civicrm/contact/view/rel',
352 "action=update&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
353 ),
354 'deleteUrl' => CRM_Utils_System::url('civicrm/contact/view/rel',
355 "action=delete&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
356 ),
357 ];
358 }
359 $title = CRM_Contact_BAO_Contact::displayName($relationship->contact_id_a) . ' (' . CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType',
360 $relationship->relationship_type_id, 'label_a_b'
361 ) . ' ' . CRM_Contact_BAO_Contact::displayName($relationship->contact_id_b) . ')';
362
363 CRM_Utils_Recent::add($title,
364 $url,
365 $relationship->id,
366 'Relationship',
367 $relationship->contact_id_a,
368 NULL,
369 $recentOther
370 );
371 }
372
373 /**
374 * Load contact ids and relationship type id when doing a create call if not provided.
375 *
376 * There are are various checks done in create which require this information which is optional
377 * when using id.
378 *
379 * @param array $params
380 * Parameters passed to create call.
381 *
382 * @return array
383 * Parameters with missing fields added if required.
384 */
385 public static function loadExistingRelationshipDetails($params) {
386 if (!empty($params['contact_id_a'])
387 && !empty($params['contact_id_b'])
388 && is_numeric($params['relationship_type_id'])) {
389 return $params;
390 }
391 if (empty($params['id'])) {
392 return $params;
393 }
394
395 $fieldsToFill = ['contact_id_a', 'contact_id_b', 'relationship_type_id'];
396 $result = CRM_Core_DAO::executeQuery("SELECT " . implode(',', $fieldsToFill) . " FROM civicrm_relationship WHERE id = %1", [
397 1 => [
398 $params['id'],
399 'Integer',
400 ],
401 ]);
402 while ($result->fetch()) {
403 foreach ($fieldsToFill as $field) {
404 $params[$field] = !empty($params[$field]) ? $params[$field] : $result->$field;
405 }
406 }
407 return $params;
408 }
409
410 /**
411 * Specify defaults for creating a relationship.
412 *
413 * @return array
414 * array of defaults for creating relationship
415 */
416 public static function getdefaults() {
417 return [
418 'is_active' => 1,
419 'is_permission_a_b' => self::NONE,
420 'is_permission_b_a' => self::NONE,
421 'description' => '',
422 'start_date' => 'NULL',
423 'case_id' => NULL,
424 'end_date' => 'NULL',
425 ];
426 }
427
428 /**
429 * Check if there is data to create the object.
430 *
431 * @param array $params
432 *
433 * @deprecated
434 * @return bool
435 */
436 public static function dataExists($params) {
437 CRM_Core_Error::deprecatedFunctionWarning('obsolete');
438 return (isset($params['contact_check']) && is_array($params['contact_check']));
439 }
440
441 /**
442 * Get get list of relationship type based on the contact type.
443 *
444 * @param int $contactId
445 * This is the contact id of the current contact.
446 * @param null $contactSuffix
447 * @param string $relationshipId
448 * The id of the existing relationship if any.
449 * @param string $contactType
450 * Contact type.
451 * @param bool $all
452 * If true returns relationship types in both the direction.
453 * @param string $column
454 * Name/label that going to retrieve from db.
455 * @param bool $biDirectional
456 * @param array $contactSubType
457 * Includes relationship types between this subtype.
458 * @param bool $onlySubTypeRelationTypes
459 * If set only subtype which is passed by $contactSubType
460 * related relationship types get return
461 *
462 * @return array
463 * array reference of all relationship types with context to current contact.
464 */
465 public static function getContactRelationshipType(
466 $contactId = NULL,
467 $contactSuffix = NULL,
468 $relationshipId = NULL,
469 $contactType = NULL,
470 $all = FALSE,
471 $column = 'label',
472 $biDirectional = TRUE,
473 $contactSubType = NULL,
474 $onlySubTypeRelationTypes = FALSE
475 ) {
476
477 $relationshipType = [];
478 $allRelationshipType = CRM_Core_PseudoConstant::relationshipType($column);
479
480 $otherContactType = NULL;
481 if ($relationshipId) {
482 $relationship = new CRM_Contact_DAO_Relationship();
483 $relationship->id = $relationshipId;
484 if ($relationship->find(TRUE)) {
485 $contact = new CRM_Contact_DAO_Contact();
486 $contact->id = ($relationship->contact_id_a == $contactId) ? $relationship->contact_id_b : $relationship->contact_id_a;
487
488 if ($contact->find(TRUE)) {
489 $otherContactType = $contact->contact_type;
490 //CRM-5125 for contact subtype specific relationshiptypes
491 if ($contact->contact_sub_type) {
492 $otherContactSubType = $contact->contact_sub_type;
493 }
494 }
495 }
496 }
497
498 $contactSubType = (array) $contactSubType;
499 if ($contactId) {
500 $contactType = CRM_Contact_BAO_Contact::getContactType($contactId);
501 $contactSubType = CRM_Contact_BAO_Contact::getContactSubType($contactId);
502 }
503
504 foreach ($allRelationshipType as $key => $value) {
505 // the contact type is required or matches
506 if (((!$value['contact_type_a']) ||
507 $value['contact_type_a'] == $contactType
508 ) &&
509 // the other contact type is required or present or matches
510 ((!$value['contact_type_b']) ||
511 (!$otherContactType) ||
512 $value['contact_type_b'] == $otherContactType
513 ) &&
514 (in_array($value['contact_sub_type_a'], $contactSubType) ||
515 (!$value['contact_sub_type_a'] && !$onlySubTypeRelationTypes)
516 )
517 ) {
518 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
519 }
520
521 if (((!$value['contact_type_b']) ||
522 $value['contact_type_b'] == $contactType
523 ) &&
524 ((!$value['contact_type_a']) ||
525 (!$otherContactType) ||
526 $value['contact_type_a'] == $otherContactType
527 ) &&
528 (in_array($value['contact_sub_type_b'], $contactSubType) ||
529 (!$value['contact_sub_type_b'] && !$onlySubTypeRelationTypes)
530 )
531 ) {
532 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
533 }
534
535 if ($all) {
536 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
537 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
538 }
539 }
540
541 if ($biDirectional) {
542 $relationshipType = self::removeRelationshipTypeDuplicates($relationshipType, $contactSuffix);
543 }
544
545 // sort the relationshipType in ascending order CRM-7736
546 asort($relationshipType);
547 return $relationshipType;
548 }
549
550 /**
551 * Given a list of relationship types, return the list with duplicate types
552 * removed, being careful to retain only the duplicate which matches the given
553 * 'a_b' or 'b_a' suffix.
554 *
555 * @param array $relationshipTypeList A list of relationship types, in the format
556 * returned by self::getContactRelationshipType().
557 * @param string $suffix Either 'a_b' or 'b_a'; defaults to 'a_b'
558 *
559 * @return array The modified value of $relationshipType
560 */
561 public static function removeRelationshipTypeDuplicates($relationshipTypeList, $suffix = NULL) {
562 if (empty($suffix)) {
563 $suffix = 'a_b';
564 }
565
566 // Find those labels which are listed more than once.
567 $duplicateValues = array_diff_assoc($relationshipTypeList, array_unique($relationshipTypeList));
568
569 // For each duplicate label, find its keys, and remove from $relationshipType
570 // the key which does not match $suffix.
571 foreach ($duplicateValues as $value) {
572 $keys = array_keys($relationshipTypeList, $value);
573 foreach ($keys as $key) {
574 if (substr($key, -3) != $suffix) {
575 unset($relationshipTypeList[$key]);
576 }
577 }
578 }
579 return $relationshipTypeList;
580 }
581
582 /**
583 * Delete current employer relationship.
584 *
585 * @param int $id
586 * @param int $action
587 *
588 * @return CRM_Contact_DAO_Relationship
589 */
590 public static function clearCurrentEmployer($id, $action) {
591 $relationship = new CRM_Contact_DAO_Relationship();
592 $relationship->id = $id;
593 $relationship->find(TRUE);
594
595 //to delete relationship between household and individual \
596 //or between individual and organization
597 if (($action & CRM_Core_Action::DISABLE) || ($action & CRM_Core_Action::DELETE)) {
598 $relTypes = CRM_Utils_Array::index(['name_a_b'], CRM_Core_PseudoConstant::relationshipType('name'));
599 if (
600 (isset($relTypes['Employee of']) && $relationship->relationship_type_id == $relTypes['Employee of']['id']) ||
601 (isset($relTypes['Household Member of']) && $relationship->relationship_type_id == $relTypes['Household Member of']['id'])
602 ) {
603 $sharedContact = new CRM_Contact_DAO_Contact();
604 $sharedContact->id = $relationship->contact_id_a;
605 $sharedContact->find(TRUE);
606
607 $employerRelTypeId = CRM_Contact_BAO_RelationshipType::getEmployeeRelationshipTypeID();
608 if ($relationship->relationship_type_id == $employerRelTypeId && $relationship->contact_id_b == $sharedContact->employer_id) {
609 CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($relationship->contact_id_a);
610 }
611
612 }
613 }
614 return $relationship;
615 }
616
617 /**
618 * Delete the relationship.
619 *
620 * @param int $id
621 * Relationship id.
622 *
623 * @return CRM_Contact_DAO_Relationship
624 *
625 * @throws \CRM_Core_Exception
626 * @throws \CiviCRM_API3_Exception
627 */
628 public static function del($id) {
629 // delete from relationship table
630 CRM_Utils_Hook::pre('delete', 'Relationship', $id);
631
632 $relationship = self::clearCurrentEmployer($id, CRM_Core_Action::DELETE);
633 $relationship->delete();
634 if (CRM_Core_Permission::access('CiviMember')) {
635 // create $params array which isrequired to delete memberships
636 // of the related contacts.
637 $params = [
638 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
639 'contact_check' => [$relationship->contact_id_b => 1],
640 ];
641
642 $ids = [];
643 // calling relatedMemberships to delete the memberships of
644 // related contacts.
645 self::relatedMemberships($relationship->contact_id_a,
646 $params,
647 $ids,
648 CRM_Core_Action::DELETE,
649 FALSE
650 );
651 }
652
653 CRM_Core_Session::setStatus(ts('Selected relationship has been deleted successfully.'), ts('Record Deleted'), 'success');
654
655 CRM_Utils_Hook::post('delete', 'Relationship', $id, $relationship);
656
657 return $relationship;
658 }
659
660 /**
661 * Disable/enable the relationship.
662 *
663 * @param int $id
664 * Relationship id.
665 *
666 * @param int $action
667 * @param array $params
668 * @param array $ids
669 * @param bool $active
670 *
671 * @throws \CRM_Core_Exception
672 * @throws \CiviCRM_API3_Exception
673 */
674 public static function disableEnableRelationship($id, $action, $params = [], $ids = [], $active = FALSE) {
675 $relationship = self::clearCurrentEmployer($id, $action);
676
677 if ($id) {
678 // create $params array which is required to delete memberships
679 // of the related contacts.
680 if (empty($params)) {
681 $params = [
682 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
683 'contact_check' => [$relationship->contact_id_b => 1],
684 ];
685 }
686 $contact_id_a = empty($params['contact_id_a']) ? $relationship->contact_id_a : $params['contact_id_a'];
687 // calling relatedMemberships to delete/add the memberships of
688 // related contacts.
689 if ($action & CRM_Core_Action::DISABLE) {
690 // @todo this could call a subset of the function that just relates to
691 // cleaning up no-longer-inherited relationships
692 CRM_Contact_BAO_Relationship::relatedMemberships($contact_id_a,
693 $params,
694 $ids,
695 CRM_Core_Action::DELETE,
696 $active
697 );
698 }
699 elseif ($action & CRM_Core_Action::ENABLE) {
700 $ids['contact'] = empty($ids['contact']) ? $contact_id_a : $ids['contact'];
701 CRM_Contact_BAO_Relationship::relatedMemberships($contact_id_a,
702 $params,
703 $ids,
704 empty($params['id']) ? CRM_Core_Action::ADD : CRM_Core_Action::UPDATE,
705 $active
706 );
707 }
708 }
709 }
710
711 /**
712 * Delete the object records that are associated with this contact.
713 *
714 * @param int $contactId
715 * Id of the contact to delete.
716 */
717 public static function deleteContact($contactId) {
718 $relationship = new CRM_Contact_DAO_Relationship();
719 $relationship->contact_id_a = $contactId;
720 $relationship->delete();
721
722 $relationship = new CRM_Contact_DAO_Relationship();
723 $relationship->contact_id_b = $contactId;
724 $relationship->delete();
725
726 CRM_Contact_BAO_Household::updatePrimaryContact(NULL, $contactId);
727 }
728
729 /**
730 * Get the other contact in a relationship.
731 *
732 * @param int $id
733 * Relationship id.
734 *
735 * $returns returns the contact ids in the relationship
736 *
737 * @return \CRM_Contact_DAO_Relationship
738 */
739 public static function getRelationshipByID($id) {
740 $relationship = new CRM_Contact_DAO_Relationship();
741
742 $relationship->id = $id;
743 $relationship->selectAdd();
744 $relationship->selectAdd('contact_id_a, contact_id_b');
745 $relationship->find(TRUE);
746
747 return $relationship;
748 }
749
750 /**
751 * Check if the relationship type selected between two contacts is correct.
752 *
753 * @param int $contact_a
754 * 1st contact id.
755 * @param int $contact_b
756 * 2nd contact id.
757 * @param int $relationshipTypeId
758 * Relationship type id.
759 *
760 * @return bool
761 * true if it is valid relationship else false
762 */
763 public static function checkRelationshipType($contact_a, $contact_b, $relationshipTypeId) {
764 $relationshipType = new CRM_Contact_DAO_RelationshipType();
765 $relationshipType->id = $relationshipTypeId;
766 $relationshipType->selectAdd();
767 $relationshipType->selectAdd('contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b');
768 if ($relationshipType->find(TRUE)) {
769 $contact_type_a = CRM_Contact_BAO_Contact::getContactType($contact_a);
770 $contact_type_b = CRM_Contact_BAO_Contact::getContactType($contact_b);
771
772 $contact_sub_type_a = CRM_Contact_BAO_Contact::getContactSubType($contact_a);
773 $contact_sub_type_b = CRM_Contact_BAO_Contact::getContactSubType($contact_b);
774
775 if (((!$relationshipType->contact_type_a) || ($relationshipType->contact_type_a == $contact_type_a)) &&
776 ((!$relationshipType->contact_type_b) || ($relationshipType->contact_type_b == $contact_type_b)) &&
777 ((!$relationshipType->contact_sub_type_a) || (in_array($relationshipType->contact_sub_type_a,
778 $contact_sub_type_a
779 ))) &&
780 ((!$relationshipType->contact_sub_type_b) || (in_array($relationshipType->contact_sub_type_b,
781 $contact_sub_type_b
782 )))
783 ) {
784 return TRUE;
785 }
786 else {
787 return FALSE;
788 }
789 }
790 return FALSE;
791 }
792
793 /**
794 * This function does the validtion for valid relationship.
795 *
796 * @param array $params
797 * This array contains the values there are subitted by the form.
798 * @param array $ids
799 * The array that holds all the db ids.
800 * @param int $contactId
801 * This is contact id for adding relationship.
802 *
803 * @deprecated
804 *
805 * @return string
806 */
807 public static function checkValidRelationship($params, $ids, $contactId) {
808 $errors = '';
809 CRM_Core_Error::deprecatedFunctionWarning('no alternative');
810 // function to check if the relationship selected is correct
811 // i.e. employer relationship can exit between Individual and Organization (not between Individual and Individual)
812 if (!CRM_Contact_BAO_Relationship::checkRelationshipType($params['contact_id_a'], $params['contact_id_b'],
813 $params['relationship_type_id'])) {
814 $errors = 'Please select valid relationship between these two contacts.';
815 }
816 return $errors;
817 }
818
819 /**
820 * This function checks for duplicate relationship.
821 *
822 * @param array $params
823 * An assoc array of name/value pairs.
824 * @param int $id
825 * This the id of the contact whom we are adding relationship.
826 * @param int $contactId
827 * This is contact id for adding relationship.
828 * @param int $relationshipId
829 * This is relationship id for the contact.
830 *
831 * @return bool
832 * true if record exists else false
833 */
834 public static function checkDuplicateRelationship($params, $id, $contactId = 0, $relationshipId = 0) {
835 $relationshipTypeId = $params['relationship_type_id'] ?? NULL;
836 list($type) = explode('_', $relationshipTypeId);
837
838 $queryString = "
839SELECT id
840FROM civicrm_relationship
841WHERE relationship_type_id = " . CRM_Utils_Type::escape($type, 'Integer');
842
843 /*
844 * CRM-11792 - date fields from API are in ISO format, but this function
845 * supports date arrays BAO has increasingly standardised to ISO format
846 * so I believe this function should support ISO rather than make API
847 * format it - however, need to support array format for now to avoid breakage
848 * @ time of writing this function is called from Relationship::legacyCreateMultiple (twice)
849 * CRM_BAO_Contact_Utils::clearCurrentEmployer (seemingly without dates)
850 * CRM_Contact_Form_Task_AddToOrganization::postProcess &
851 * CRM_Contact_Form_Task_AddToHousehold::postProcess
852 * (I don't think the last 2 support dates but not sure
853 */
854
855 $dateFields = ['end_date', 'start_date'];
856 foreach ($dateFields as $dateField) {
857 if (array_key_exists($dateField, $params)) {
858 if (empty($params[$dateField]) || $params[$dateField] == 'null') {
859 //this is most likely coming from an api call & probably loaded
860 // from the DB to deal with some of the
861 // other myriad of excessive checks still in place both in
862 // the api & the create functions
863 $queryString .= " AND $dateField IS NULL";
864 continue;
865 }
866 elseif (is_array($params[$dateField])) {
867 $queryString .= " AND $dateField = " .
868 CRM_Utils_Type::escape(CRM_Utils_Date::format($params[$dateField]), 'Date');
869 }
870 else {
871 $queryString .= " AND $dateField = " .
872 CRM_Utils_Type::escape($params[$dateField], 'Date');
873 }
874 }
875 }
876
877 $queryString .=
878 ' AND ( ( contact_id_a = ' . CRM_Utils_Type::escape($id, 'Integer') .
879 ' AND contact_id_b = ' . CRM_Utils_Type::escape($contactId, 'Integer') .
880 ' ) OR ( contact_id_a = ' . CRM_Utils_Type::escape($contactId, 'Integer') .
881 ' AND contact_id_b = ' . CRM_Utils_Type::escape($id, 'Integer') . " ) ) ";
882
883 //if caseId is provided, include it duplicate checking.
884 if ($caseId = CRM_Utils_Array::value('case_id', $params)) {
885 $queryString .= ' AND case_id = ' . CRM_Utils_Type::escape($caseId, 'Integer');
886 }
887
888 if ($relationshipId) {
889 $queryString .= ' AND id !=' . CRM_Utils_Type::escape($relationshipId, 'Integer');
890 }
891
892 $relationship = CRM_Core_DAO::executeQuery($queryString);
893 while ($relationship->fetch()) {
894 // Check whether the custom field values are identical.
895 if (self::checkDuplicateCustomFields($params['custom'] ?? [], $relationship->id)) {
896 return TRUE;
897 }
898 }
899 return FALSE;
900 }
901
902 /**
903 * this function checks whether the values of the custom fields in $params are
904 * the same as the values of the custom fields of the relation with given
905 * $relationshipId.
906 *
907 * @param array $params an assoc array of name/value pairs
908 * @param int $relationshipId ID of an existing duplicate relation
909 *
910 * @return boolean true if custom field values are identical
911 * @access private
912 * @static
913 */
914 private static function checkDuplicateCustomFields($params, $relationshipId) {
915 // Get the custom values of the existing relationship.
916 $existingValues = CRM_Core_BAO_CustomValueTable::getEntityValues($relationshipId, 'Relationship');
917 // Create a similar array for the new relationship.
918 $newValues = [];
919 if (!is_array($params)) {
920 // No idea when this would happen....
921 CRM_Core_Error::deprecatedWarning('params should be an array');
922 }
923 else {
924 // $params seems to be an array, as it should be. Each value is again an array.
925 // This array contains one value (key -1), and this value seems to be
926 // an array with the information about the custom value.
927 foreach ($params as $value) {
928 foreach ($value as $customValue) {
929 $newValues[$customValue['custom_field_id']] = $customValue['value'];
930 }
931 }
932 }
933
934 // Calculate difference between arrays. If the only key-value pairs
935 // that are in one array but not in the other are empty, the
936 // custom fields are considered to be equal.
937 // See https://github.com/civicrm/civicrm-core/pull/6515#issuecomment-137985667
938 $diff1 = array_diff_assoc($existingValues, $newValues);
939 $diff2 = array_diff_assoc($newValues, $existingValues);
940
941 return !array_filter($diff1) && !array_filter($diff2);
942 }
943
944 /**
945 * Update the is_active flag in the db.
946 *
947 * @param int $id
948 * Id of the database record.
949 * @param bool $is_active
950 * Value we want to set the is_active field.
951 *
952 * @return bool
953 *
954 * @throws CiviCRM_API3_Exception
955 */
956 public static function setIsActive($id, $is_active) {
957 // as both the create & add functions have a bunch of logic in them that
958 // doesn't seem to cope with a normal update we will call the api which
959 // has tested handling for this
960 // however, a longer term solution would be to simplify the add, create & api functions
961 // to be more standard. It is debatable @ that point whether it's better to call the BAO
962 // direct as the api is more tested.
963 $result = civicrm_api('relationship', 'create', [
964 'id' => $id,
965 'is_active' => $is_active,
966 'version' => 3,
967 ]);
968
969 if (is_array($result) && !empty($result['is_error']) && $result['error_message'] != 'Duplicate Relationship') {
970 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array::value('error_code', $result, 'undefined'), $result);
971 }
972
973 return TRUE;
974 }
975
976 /**
977 * Fetch a relationship object and store the values in the values array.
978 *
979 * @param array $params
980 * Input parameters to find object.
981 * @param array $values
982 * Output values of the object.
983 *
984 * @return array
985 * (reference) the values that could be potentially assigned to smarty
986 */
987 public static function &getValues($params, &$values) {
988 if (empty($params)) {
989 return NULL;
990 }
991 $v = [];
992
993 // get the specific number of relationship or all relationships.
994 if (!empty($params['numRelationship'])) {
995 $v['data'] = &CRM_Contact_BAO_Relationship::getRelationship($params['contact_id'], NULL, $params['numRelationship']);
996 }
997 else {
998 $v['data'] = CRM_Contact_BAO_Relationship::getRelationship($params['contact_id']);
999 }
1000
1001 // get the total count of relationships
1002 $v['totalCount'] = count($v['data']);
1003
1004 $values['relationship']['data'] = &$v['data'];
1005 $values['relationship']['totalCount'] = &$v['totalCount'];
1006
1007 return $v;
1008 }
1009
1010 /**
1011 * Helper function to form the sql for relationship retrieval.
1012 *
1013 * @param int $contactId
1014 * Contact id.
1015 * @param int $status
1016 * (check const at top of file).
1017 * @param int $numRelationship
1018 * No of relationships to display (limit).
1019 * @param int $count
1020 * Get the no of relationships.
1021 * $param int $relationshipId relationship id
1022 * @param int $relationshipId
1023 * @param string $direction
1024 * The direction we are interested in a_b or b_a.
1025 * @param array $params
1026 * Array of extra values including relationship_type_id per api spec.
1027 *
1028 * @return array
1029 * [select, from, where]
1030 *
1031 * @throws \CRM_Core_Exception
1032 * @throws \CiviCRM_API3_Exception
1033 */
1034 public static function makeURLClause($contactId, $status, $numRelationship, $count, $relationshipId, $direction, $params = []) {
1035 $select = $from = $where = '';
1036
1037 $select = '( ';
1038 if ($count) {
1039 if ($direction === 'a_b') {
1040 $select .= ' SELECT count(DISTINCT civicrm_relationship.id) as cnt1, 0 as cnt2 ';
1041 }
1042 else {
1043 $select .= ' SELECT 0 as cnt1, count(DISTINCT civicrm_relationship.id) as cnt2 ';
1044 }
1045 }
1046 else {
1047 $select .= ' SELECT civicrm_relationship.id as civicrm_relationship_id,
1048 civicrm_contact.sort_name as sort_name,
1049 civicrm_contact.display_name as display_name,
1050 civicrm_contact.job_title as job_title,
1051 civicrm_contact.employer_id as employer_id,
1052 civicrm_contact.organization_name as organization_name,
1053 civicrm_address.street_address as street_address,
1054 civicrm_address.city as city,
1055 civicrm_address.postal_code as postal_code,
1056 civicrm_state_province.abbreviation as state,
1057 civicrm_country.name as country,
1058 civicrm_email.email as email,
1059 civicrm_contact.contact_type as contact_type,
1060 civicrm_contact.contact_sub_type as contact_sub_type,
1061 civicrm_phone.phone as phone,
1062 civicrm_contact.id as civicrm_contact_id,
1063 civicrm_relationship.contact_id_b as contact_id_b,
1064 civicrm_relationship.contact_id_a as contact_id_a,
1065 civicrm_relationship_type.id as civicrm_relationship_type_id,
1066 civicrm_relationship.start_date as start_date,
1067 civicrm_relationship.end_date as end_date,
1068 civicrm_relationship.created_date as created_date,
1069 civicrm_relationship.modified_date as modified_date,
1070 civicrm_relationship.description as description,
1071 civicrm_relationship.is_active as is_active,
1072 civicrm_relationship.is_permission_a_b as is_permission_a_b,
1073 civicrm_relationship.is_permission_b_a as is_permission_b_a,
1074 civicrm_relationship.case_id as case_id';
1075
1076 if ($direction === 'a_b') {
1077 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
1078 civicrm_relationship_type.label_b_a as relation ';
1079 }
1080 else {
1081 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
1082 civicrm_relationship_type.label_a_b as relation ';
1083 }
1084 }
1085
1086 $from = '
1087 FROM civicrm_relationship
1088INNER JOIN civicrm_relationship_type ON ( civicrm_relationship.relationship_type_id = civicrm_relationship_type.id )
1089INNER JOIN civicrm_contact ';
1090 if ($direction === 'a_b') {
1091 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_a ) ';
1092 }
1093 else {
1094 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_b ) ';
1095 }
1096
1097 if (!$count) {
1098 $from .= '
1099LEFT JOIN civicrm_address ON (civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1)
1100LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
1101LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id AND civicrm_email.is_primary = 1)
1102LEFT JOIN civicrm_state_province ON (civicrm_address.state_province_id = civicrm_state_province.id)
1103LEFT JOIN civicrm_country ON (civicrm_address.country_id = civicrm_country.id)
1104';
1105 }
1106
1107 $where = 'WHERE ( 1 )';
1108 if ($contactId) {
1109 if ($direction === 'a_b') {
1110 $where .= ' AND civicrm_relationship.contact_id_b = ' . CRM_Utils_Type::escape($contactId, 'Positive');
1111 }
1112 else {
1113 $where .= ' AND civicrm_relationship.contact_id_a = ' . CRM_Utils_Type::escape($contactId, 'Positive') . '
1114 AND civicrm_relationship.contact_id_a != civicrm_relationship.contact_id_b ';
1115 }
1116 }
1117 if ($relationshipId) {
1118 $where .= ' AND civicrm_relationship.id = ' . CRM_Utils_Type::escape($relationshipId, 'Positive');
1119 }
1120
1121 $date = date('Y-m-d');
1122 if ($status == self::PAST) {
1123 //this case for showing past relationship
1124 $where .= ' AND civicrm_relationship.is_active = 1 ';
1125 $where .= " AND civicrm_relationship.end_date < '" . $date . "'";
1126 }
1127 elseif ($status == self::DISABLED) {
1128 // this case for showing disabled relationship
1129 $where .= ' AND civicrm_relationship.is_active = 0 ';
1130 }
1131 elseif ($status == self::CURRENT) {
1132 //this case for showing current relationship
1133 $where .= ' AND civicrm_relationship.is_active = 1 ';
1134 $where .= " AND (civicrm_relationship.end_date >= '" . $date . "' OR civicrm_relationship.end_date IS NULL) ";
1135 }
1136 elseif ($status == self::INACTIVE) {
1137 //this case for showing inactive relationships
1138 $where .= " AND (civicrm_relationship.end_date < '" . $date . "'";
1139 $where .= ' OR civicrm_relationship.is_active = 0 )';
1140 }
1141
1142 // CRM-6181
1143 $where .= ' AND civicrm_contact.is_deleted = 0';
1144 if (!empty($params['membership_type_id']) && empty($params['relationship_type_id'])) {
1145 $where .= self::membershipTypeToRelationshipTypes($params, $direction);
1146 }
1147 if (!empty($params['relationship_type_id'])) {
1148 if (is_array($params['relationship_type_id'])) {
1149 $where .= " AND " . CRM_Core_DAO::createSQLFilter('relationship_type_id', $params['relationship_type_id'], 'Integer');
1150 }
1151 else {
1152 $where .= ' AND relationship_type_id = ' . CRM_Utils_Type::escape($params['relationship_type_id'], 'Positive');
1153 }
1154 }
1155 if ($direction === 'a_b') {
1156 $where .= ' ) UNION ';
1157 }
1158 else {
1159 $where .= ' ) ';
1160 }
1161
1162 return [$select, $from, $where];
1163 }
1164
1165 /**
1166 * Get a list of relationships.
1167 *
1168 * @param int $contactId
1169 * Contact id.
1170 * @param int $status
1171 * 1: Past 2: Disabled 3: Current.
1172 * @param int $numRelationship
1173 * No of relationships to display (limit).
1174 * @param int $count
1175 * Get the no of relationships.
1176 * @param int $relationshipId
1177 * @param array $links
1178 * the list of links to display
1179 * @param int $permissionMask
1180 * the permission mask to be applied for the actions
1181 * @param bool $permissionedContact
1182 * to return only permissioned Contact
1183 * @param array $params
1184 * @param bool $includeTotalCount
1185 * Should we return a count of total accessable relationships
1186 *
1187 * @return array|int
1188 * relationship records
1189 *
1190 * @throws \CRM_Core_Exception
1191 * @throws \CiviCRM_API3_Exception
1192 */
1193 public static function getRelationship(
1194 $contactId = NULL,
1195 $status = 0, $numRelationship = 0,
1196 $count = 0, $relationshipId = 0,
1197 $links = NULL, $permissionMask = NULL,
1198 $permissionedContact = FALSE,
1199 $params = [], $includeTotalCount = FALSE
1200 ) {
1201 $values = [];
1202 if (!$contactId && !$relationshipId) {
1203 return $values;
1204 }
1205
1206 list($select1, $from1, $where1) = self::makeURLClause($contactId, $status, $numRelationship,
1207 $count, $relationshipId, 'a_b', $params
1208 );
1209 list($select2, $from2, $where2) = self::makeURLClause($contactId, $status, $numRelationship,
1210 $count, $relationshipId, 'b_a', $params
1211 );
1212
1213 $order = $limit = '';
1214 if (!$count) {
1215 if (empty($params['sort'])) {
1216 $order = ' ORDER BY civicrm_relationship_type_id, sort_name ';
1217 }
1218 else {
1219 $order = " ORDER BY {$params['sort']} ";
1220 }
1221
1222 $offset = 0;
1223 if (!empty($params['offset']) && $params['offset'] > 0) {
1224 $offset = $params['offset'];
1225 }
1226
1227 if ($numRelationship) {
1228 $limit = " LIMIT {$offset}, $numRelationship";
1229 }
1230 }
1231
1232 // building the query string
1233 $queryString = $select1 . $from1 . $where1 . $select2 . $from2 . $where2;
1234
1235 $relationship = CRM_Core_DAO::executeQuery($queryString . $order . $limit);
1236 $row = [];
1237 if ($count) {
1238 $relationshipCount = 0;
1239 while ($relationship->fetch()) {
1240 $relationshipCount += $relationship->cnt1 + $relationship->cnt2;
1241 }
1242 return $relationshipCount;
1243 }
1244 else {
1245
1246 if ($includeTotalCount) {
1247 $values['total_relationships'] = CRM_Core_DAO::singleValueQuery("SELECT count(*) FROM ({$queryString}) AS r");
1248 }
1249
1250 $mask = NULL;
1251 if ($status != self::INACTIVE) {
1252 if ($links) {
1253 $mask = array_sum(array_keys($links));
1254 if ($mask & CRM_Core_Action::DISABLE) {
1255 $mask -= CRM_Core_Action::DISABLE;
1256 }
1257 if ($mask & CRM_Core_Action::ENABLE) {
1258 $mask -= CRM_Core_Action::ENABLE;
1259 }
1260
1261 if ($status == self::CURRENT) {
1262 $mask |= CRM_Core_Action::DISABLE;
1263 }
1264 elseif ($status == self::DISABLED) {
1265 $mask |= CRM_Core_Action::ENABLE;
1266 }
1267 }
1268 // temporary hold the value of $mask.
1269 $tempMask = $mask;
1270 }
1271
1272 while ($relationship->fetch()) {
1273 $rid = $relationship->civicrm_relationship_id;
1274 $cid = $relationship->civicrm_contact_id;
1275
1276 if ($permissionedContact &&
1277 (!CRM_Contact_BAO_Contact_Permission::allow($cid))
1278 ) {
1279 continue;
1280 }
1281 if ($status != self::INACTIVE && $links) {
1282 // assign the original value to $mask
1283 $mask = $tempMask;
1284 // display action links if $cid has edit permission for the relationship.
1285 if (!($permissionMask & CRM_Core_Permission::EDIT) && CRM_Contact_BAO_Contact_Permission::allow($cid, CRM_Core_Permission::EDIT)) {
1286 $permissions[] = CRM_Core_Permission::EDIT;
1287 $permissions[] = CRM_Core_Permission::DELETE;
1288 $permissionMask = CRM_Core_Action::mask($permissions);
1289 }
1290 $mask = $mask & $permissionMask;
1291 }
1292 $values[$rid]['id'] = $rid;
1293 $values[$rid]['cid'] = $cid;
1294 $values[$rid]['contact_id_a'] = $relationship->contact_id_a;
1295 $values[$rid]['contact_id_b'] = $relationship->contact_id_b;
1296 $values[$rid]['contact_type'] = $relationship->contact_type;
1297 $values[$rid]['contact_sub_type'] = $relationship->contact_sub_type;
1298 $values[$rid]['relationship_type_id'] = $relationship->civicrm_relationship_type_id;
1299 $values[$rid]['relation'] = $relationship->relation;
1300 $values[$rid]['name'] = $relationship->sort_name;
1301 $values[$rid]['display_name'] = $relationship->display_name;
1302 $values[$rid]['job_title'] = $relationship->job_title;
1303 $values[$rid]['email'] = $relationship->email;
1304 $values[$rid]['phone'] = $relationship->phone;
1305 $values[$rid]['employer_id'] = $relationship->employer_id;
1306 $values[$rid]['organization_name'] = $relationship->organization_name;
1307 $values[$rid]['country'] = $relationship->country;
1308 $values[$rid]['city'] = $relationship->city;
1309 $values[$rid]['state'] = $relationship->state;
1310 $values[$rid]['start_date'] = $relationship->start_date;
1311 $values[$rid]['end_date'] = $relationship->end_date;
1312 $values[$rid]['created_date'] = $relationship->created_date;
1313 $values[$rid]['modified_date'] = $relationship->modified_date;
1314 $values[$rid]['description'] = $relationship->description;
1315 $values[$rid]['is_active'] = $relationship->is_active;
1316 $values[$rid]['is_permission_a_b'] = $relationship->is_permission_a_b;
1317 $values[$rid]['is_permission_b_a'] = $relationship->is_permission_b_a;
1318 $values[$rid]['case_id'] = $relationship->case_id;
1319
1320 if ($status) {
1321 $values[$rid]['status'] = $status;
1322 }
1323
1324 $values[$rid]['civicrm_relationship_type_id'] = $relationship->civicrm_relationship_type_id;
1325
1326 if ($relationship->contact_id_a == $contactId) {
1327 $values[$rid]['rtype'] = 'a_b';
1328 }
1329 else {
1330 $values[$rid]['rtype'] = 'b_a';
1331 }
1332
1333 if ($links) {
1334 $replace = [
1335 'id' => $rid,
1336 'rtype' => $values[$rid]['rtype'],
1337 'cid' => $contactId,
1338 'cbid' => $values[$rid]['cid'],
1339 'caseid' => $values[$rid]['case_id'],
1340 'clientid' => $contactId,
1341 ];
1342
1343 if ($status == self::INACTIVE) {
1344 // setting links for inactive relationships
1345 $mask = array_sum(array_keys($links));
1346 if (!$values[$rid]['is_active']) {
1347 $mask -= CRM_Core_Action::DISABLE;
1348 }
1349 else {
1350 $mask -= CRM_Core_Action::ENABLE;
1351 $mask -= CRM_Core_Action::DISABLE;
1352 }
1353 $mask = $mask & $permissionMask;
1354 }
1355
1356 // Give access to manage case link by copying to MAX_ACTION index temporarily, depending on case permission of user.
1357 if ($values[$rid]['case_id']) {
1358 // Borrowed logic from CRM_Case_Page_Tab
1359 $hasCaseAccess = FALSE;
1360 if (CRM_Core_Permission::check('access all cases and activities')) {
1361 $hasCaseAccess = TRUE;
1362 }
1363 else {
1364 $userCases = CRM_Case_BAO_Case::getCases(FALSE);
1365 if (array_key_exists($values[$rid]['case_id'], $userCases)) {
1366 $hasCaseAccess = TRUE;
1367 }
1368 }
1369
1370 if ($hasCaseAccess) {
1371 // give access by copying to MAX_ACTION temporarily, otherwise leave at NONE which won't display
1372 $links[CRM_Core_Action::MAX_ACTION] = $links[CRM_Core_Action::NONE];
1373 $links[CRM_Core_Action::MAX_ACTION]['name'] = ts('Manage Case #%1', [1 => $values[$rid]['case_id']]);
1374 $links[CRM_Core_Action::MAX_ACTION]['class'] = 'no-popup';
1375
1376 // Also make sure we have the right client cid since can get here from multiple relationship tabs.
1377 if ($values[$rid]['rtype'] == 'b_a') {
1378 $replace['clientid'] = $values[$rid]['cid'];
1379 }
1380 $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>';
1381 }
1382 }
1383
1384 $values[$rid]['action'] = CRM_Core_Action::formLink(
1385 $links,
1386 $mask,
1387 $replace,
1388 ts('more'),
1389 FALSE,
1390 'relationship.selector.row',
1391 'Relationship',
1392 $rid);
1393 unset($links[CRM_Core_Action::MAX_ACTION]);
1394 }
1395 }
1396
1397 return $values;
1398 }
1399 }
1400
1401 /**
1402 * Get list of relationship type based on the target contact type.
1403 * Both directions of relationships are included if their labels are not the same.
1404 *
1405 * @param string $targetContactType
1406 * A valid contact type (may be Individual, Organization, Household).
1407 *
1408 * @return array
1409 * array reference of all relationship types with context to current contact type.
1410 */
1411 public static function getRelationType($targetContactType) {
1412 $relationshipType = [];
1413 $allRelationshipType = CRM_Core_PseudoConstant::relationshipType();
1414
1415 foreach ($allRelationshipType as $key => $type) {
1416 if ($type['contact_type_b'] == $targetContactType || empty($type['contact_type_b'])) {
1417 $relationshipType[$key . '_a_b'] = $type['label_a_b'];
1418 }
1419 if (($type['contact_type_a'] == $targetContactType || empty($type['contact_type_a']))
1420 && $type['label_a_b'] != $type['label_b_a']
1421 ) {
1422 $relationshipType[$key . '_b_a'] = $type['label_b_a'];
1423 }
1424 }
1425
1426 return $relationshipType;
1427 }
1428
1429 /**
1430 * Create / update / delete membership for related contacts.
1431 *
1432 * This function will create/update/delete membership for related
1433 * contact based on 1) contact have active membership 2) that
1434 * membership is is extedned by the same relationship type to that
1435 * of the existing relationship.
1436 *
1437 * @param int $contactId
1438 * contact id.
1439 * @param array $params
1440 * array of values submitted by POST.
1441 * @param array $ids
1442 * array of ids.
1443 * @param \const|int $action which action called this function
1444 *
1445 * @param bool $active
1446 *
1447 * @throws \CRM_Core_Exception
1448 * @throws \CiviCRM_API3_Exception
1449 */
1450 public static function relatedMemberships($contactId, $params, $ids, $action = CRM_Core_Action::ADD, $active = TRUE) {
1451 // Check the end date and set the status of the relationship
1452 // accordingly.
1453 $status = self::CURRENT;
1454 $targetContact = $targetContact = CRM_Utils_Array::value('contact_check', $params, []);
1455 $today = date('Ymd');
1456
1457 // If a relationship hasn't yet started, just return for now
1458 // TODO: handle edge-case of updating start_date of an existing relationship
1459 if (!empty($params['start_date'])) {
1460 $startDate = substr(CRM_Utils_Date::format($params['start_date']), 0, 8);
1461 if ($today < $startDate) {
1462 return;
1463 }
1464 }
1465
1466 if (!empty($params['end_date'])) {
1467 $endDate = substr(CRM_Utils_Date::format($params['end_date']), 0, 8);
1468 if ($today > $endDate) {
1469 $status = self::PAST;
1470 }
1471 }
1472
1473 if (($action & CRM_Core_Action::ADD) && ($status & self::PAST)) {
1474 // If relationship is PAST and action is ADD, do nothing.
1475 return;
1476 }
1477
1478 $rel = explode('_', $params['relationship_type_id']);
1479
1480 $relTypeId = $rel[0];
1481 if (!empty($rel[1])) {
1482 $relDirection = "_{$rel[1]}_{$rel[2]}";
1483 }
1484 else {
1485 // this call is coming from somewhere where the direction was resolved early on (e.g an api call)
1486 // so we can assume _a_b
1487 $relDirection = "_a_b";
1488 $targetContact = [$params['contact_id_b'] => 1];
1489 }
1490
1491 if (($action & CRM_Core_Action::ADD) ||
1492 ($action & CRM_Core_Action::DELETE)
1493 ) {
1494 $contact = $contactId;
1495 }
1496 elseif ($action & CRM_Core_Action::UPDATE) {
1497 $contact = (int) $ids['contact'];
1498 $targetContact = [$ids['contactTarget'] => 1];
1499 }
1500
1501 // Build the 'values' array for
1502 // 1. ContactA
1503 // 2. ContactB
1504 // This will allow us to check if either of the contacts in
1505 // relationship have active memberships.
1506
1507 $values = [];
1508
1509 // 1. ContactA
1510 $values[$contact] = [
1511 'relatedContacts' => $targetContact,
1512 'relationshipTypeId' => $relTypeId,
1513 'relationshipTypeDirection' => $relDirection,
1514 ];
1515 // 2. ContactB
1516 if (!empty($targetContact)) {
1517 foreach ($targetContact as $cid => $donCare) {
1518 $values[$cid] = [
1519 'relatedContacts' => [$contact => 1],
1520 'relationshipTypeId' => $relTypeId,
1521 ];
1522
1523 $relTypeParams = ['id' => $relTypeId];
1524 $relTypeValues = [];
1525 CRM_Contact_BAO_RelationshipType::retrieve($relTypeParams, $relTypeValues);
1526
1527 if (CRM_Utils_Array::value('name_a_b', $relTypeValues) == CRM_Utils_Array::value('name_b_a', $relTypeValues)) {
1528 $values[$cid]['relationshipTypeDirection'] = '_a_b';
1529 }
1530 else {
1531 $values[$cid]['relationshipTypeDirection'] = ($relDirection == '_a_b') ? '_b_a' : '_a_b';
1532 }
1533 }
1534 }
1535
1536 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant::membershipStatus());
1537
1538 $relationshipProcessor = new CRM_Member_Utils_RelationshipProcessor(array_keys($values), $active);
1539 foreach ($values as $cid => $details) {
1540 $relatedContacts = array_keys(CRM_Utils_Array::value('relatedContacts', $details, []));
1541 $mainRelatedContactId = reset($relatedContacts);
1542
1543 foreach ($relationshipProcessor->getRelationshipMembershipsForContact((int) $cid) as $membershipId => $membershipValues) {
1544 $membershipInherittedFromContactID = NULL;
1545 if (!empty($membershipValues['owner_membership_id'])) {
1546 // @todo - $membership already has this now.
1547 // Use get not getsingle so that we get e-notice noise but not a fatal is the membership has already been deleted.
1548 $inheritedFromMembership = civicrm_api3('Membership', 'get', ['id' => $membershipValues['owner_membership_id'], 'sequential' => 1])['values'][0];
1549 $membershipInherittedFromContactID = (int) $inheritedFromMembership['contact_id'];
1550 }
1551 $relTypeIds = [];
1552 if ($action & CRM_Core_Action::DELETE) {
1553 // @todo don't return relTypeId here - but it seems to be used later in a cryptic way (hint cryptic is not a complement).
1554 list($relTypeId, $isDeletable) = self::isInheritedMembershipInvalidated($membershipValues, $values, $cid);
1555 if ($isDeletable) {
1556 CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipValues['owner_membership_id'], $membershipValues['contact_id']);
1557 }
1558 continue;
1559 }
1560 if (($action & CRM_Core_Action::UPDATE) &&
1561 ($status & self::PAST) &&
1562 ($membershipValues['owner_membership_id'])
1563 ) {
1564 // If relationship is PAST and action is UPDATE
1565 // then delete the RELATED membership
1566 CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipValues['owner_membership_id'],
1567 $membershipValues['contact_id']
1568 );
1569 continue;
1570 }
1571
1572 // add / edit the memberships for related
1573 // contacts.
1574
1575 // @todo - all these lines get 'relTypeDirs' - but it's already a key in the $membership array.
1576 // Get the Membership Type Details.
1577 $membershipType = CRM_Member_BAO_MembershipType::getMembershipType($membershipValues['membership_type_id']);
1578 // Check if contact's relationship type exists in membership type
1579 $relTypeDirs = [];
1580 if (!empty($membershipType['relationship_type_id'])) {
1581 $relTypeIds = (array) $membershipType['relationship_type_id'];
1582 }
1583 if (!empty($membershipType['relationship_direction'])) {
1584 $relDirections = (array) $membershipType['relationship_direction'];
1585 }
1586 foreach ($relTypeIds as $key => $value) {
1587 $relTypeDirs[] = $value . '_' . $relDirections[$key];
1588 }
1589 $relTypeDir = $details['relationshipTypeId'] . $details['relationshipTypeDirection'];
1590 if (in_array($relTypeDir, $relTypeDirs)) {
1591 // Check if relationship being created/updated is
1592 // similar to that of membership type's
1593 // relationship.
1594
1595 $membershipValues['owner_membership_id'] = $membershipId;
1596 unset($membershipValues['id']);
1597 unset($membershipValues['contact_id']);
1598 unset($membershipValues['membership_id']);
1599 foreach ($details['relatedContacts'] as $relatedContactId => $donCare) {
1600 $membershipValues['contact_id'] = $relatedContactId;
1601 if ($deceasedStatusId &&
1602 CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $relatedContactId, 'is_deceased')
1603 ) {
1604 $membershipValues['status_id'] = $deceasedStatusId;
1605 $membershipValues['skipStatusCal'] = TRUE;
1606 }
1607
1608 if (in_array($action, [CRM_Core_Action::UPDATE, CRM_Core_Action::ADD, CRM_Core_Action::ENABLE])) {
1609 //if updated relationship is already related to contact don't delete existing inherited membership
1610 if (in_array((int) $relatedContactId, $membershipValues['inheriting_contact_ids'], TRUE)
1611 || $relatedContactId === $membershipValues['owner_contact_id']
1612 ) {
1613 continue;
1614 }
1615
1616 //delete the membership record for related
1617 //contact before creating new membership record.
1618 CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipId, $relatedContactId);
1619 }
1620 //skip status calculation for pay later memberships.
1621 if ('Pending' === CRM_Core_PseudoConstant::getName('CRM_Member_BAO_Membership', 'status_id', $membershipValues['status_id'])) {
1622 $membershipValues['skipStatusCal'] = TRUE;
1623 }
1624 // As long as the membership itself was not created by inheritance from the same contact
1625 // that stands to inherit the membership we add an inherited membership.
1626 if ($membershipInherittedFromContactID !== (int) $membershipValues['contact_id']) {
1627 $membershipValues = self::addInheritedMembership($membershipValues);
1628 }
1629 }
1630 }
1631 elseif ($action & CRM_Core_Action::UPDATE) {
1632 // if action is update and updated relationship do
1633 // not match with the existing
1634 // membership=>relationship then we need to
1635 // change the status of the membership record to expired for
1636 // previous relationship -- CRM-12078.
1637 // CRM-16087 we need to pass ownerMembershipId to isRelatedMembershipExpired function
1638 if (empty($params['relationship_ids']) && !empty($params['id'])) {
1639 $relIds = [$params['id']];
1640 }
1641 else {
1642 $relIds = $params['relationship_ids'] ?? NULL;
1643 }
1644 if (self::isRelatedMembershipExpired($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId,
1645 $relIds) && !empty($membershipValues['owner_membership_id']
1646 ) && !empty($values[$mainRelatedContactId]['memberships'][$membershipValues['owner_membership_id']])) {
1647 $membershipValues['status_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', 'Expired', 'id', 'label');
1648 $type = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $membershipValues['membership_type_id'], 'name', 'id');
1649 CRM_Member_BAO_Membership::add($membershipValues);
1650 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');
1651 }
1652 }
1653 }
1654 }
1655 }
1656
1657 /**
1658 * Helper function to check whether the membership is expired or not.
1659 *
1660 * Function takes a list of related membership types and if it is not also passed a
1661 * relationship ID of that types evaluates whether the membership status should be changed to expired.
1662 *
1663 * @param array $membershipTypeRelationshipTypeIDs
1664 * Relation type IDs related to the given membership type.
1665 * @param int $contactId
1666 * @param int $mainRelatedContactId
1667 * @param int $relTypeId
1668 * @param array $relIds
1669 *
1670 * @return bool
1671 */
1672 public static function isRelatedMembershipExpired($membershipTypeRelationshipTypeIDs, $contactId, $mainRelatedContactId, $relTypeId, $relIds) {
1673 if (empty($membershipTypeRelationshipTypeIDs) || in_array($relTypeId, $membershipTypeRelationshipTypeIDs)) {
1674 return FALSE;
1675 }
1676
1677 if (empty($relIds)) {
1678 return FALSE;
1679 }
1680
1681 $relParamas = [
1682 1 => [$contactId, 'Integer'],
1683 2 => [$mainRelatedContactId, 'Integer'],
1684 ];
1685
1686 if ($contactId == $mainRelatedContactId) {
1687 $recordsFound = (int) CRM_Core_DAO::singleValueQuery("SELECT COUNT(*) FROM civicrm_relationship WHERE relationship_type_id IN ( " . implode(',', $membershipTypeRelationshipTypeIDs) . " ) AND
1688contact_id_a IN ( %1 ) OR contact_id_b IN ( %1 ) AND id IN (" . implode(',', $relIds) . ")", $relParamas);
1689 if ($recordsFound) {
1690 return FALSE;
1691 }
1692 return TRUE;
1693 }
1694
1695 $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);
1696
1697 if ($recordsFound) {
1698 return FALSE;
1699 }
1700
1701 return TRUE;
1702 }
1703
1704 /**
1705 * Get Current Employer for Contact.
1706 *
1707 * @param array $contactIds
1708 * Contact Ids.
1709 *
1710 * @return array
1711 * array of the current employer
1712 */
1713 public static function getCurrentEmployer($contactIds) {
1714 $contacts = implode(',', $contactIds);
1715
1716 $query = "
1717SELECT organization_name, id, employer_id
1718FROM civicrm_contact
1719WHERE id IN ( {$contacts} )
1720";
1721
1722 $dao = CRM_Core_DAO::executeQuery($query);
1723 $currentEmployer = [];
1724 while ($dao->fetch()) {
1725 $currentEmployer[$dao->id]['org_id'] = $dao->employer_id;
1726 $currentEmployer[$dao->id]['org_name'] = $dao->organization_name;
1727 }
1728
1729 return $currentEmployer;
1730 }
1731
1732 /**
1733 * Function to return list of permissioned contacts for a given contact and relationship type.
1734 *
1735 * @param int $contactID
1736 * contact id whose permissioned contacts are to be found.
1737 * @param int $relTypeId
1738 * one or more relationship type id's.
1739 * @param string $name
1740 * @param string $contactType
1741 *
1742 * @return array
1743 * Array of contacts
1744 */
1745 public static function getPermissionedContacts($contactID, $relTypeId = NULL, $name = NULL, $contactType = NULL) {
1746 $contacts = [];
1747 $args = [1 => [$contactID, 'Integer']];
1748 $relationshipTypeClause = $contactTypeClause = '';
1749
1750 if ($relTypeId) {
1751 // @todo relTypeId is only ever passed in as an int. Change this to reflect that -
1752 // probably being overly conservative by not doing so but working on stable release.
1753 $relationshipTypeClause = 'AND cr.relationship_type_id IN (%2) ';
1754 $args[2] = [$relTypeId, 'String'];
1755 }
1756
1757 if ($contactType) {
1758 $contactTypeClause = ' AND cr.relationship_type_id = crt.id AND crt.contact_type_b = %3 ';
1759 $args[3] = [$contactType, 'String'];
1760 }
1761
1762 $query = "
1763SELECT cc.id as id, cc.sort_name as name
1764FROM civicrm_relationship cr, civicrm_contact cc, civicrm_relationship_type crt
1765WHERE
1766cr.contact_id_a = %1 AND
1767cr.is_permission_a_b = 1 AND
1768IF(cr.end_date IS NULL, 1, (DATEDIFF( CURDATE( ), cr.end_date ) <= 0)) AND
1769cr.is_active = 1 AND
1770cc.id = cr.contact_id_b AND
1771cc.is_deleted = 0
1772$relationshipTypeClause
1773$contactTypeClause
1774";
1775
1776 if (!empty($name)) {
1777 $name = CRM_Utils_Type::escape($name, 'String');
1778 $query .= "
1779AND cc.sort_name LIKE '%$name%'";
1780 }
1781
1782 $dao = CRM_Core_DAO::executeQuery($query, $args);
1783 while ($dao->fetch()) {
1784 $contacts[$dao->id] = [
1785 'name' => $dao->name,
1786 'value' => $dao->id,
1787 ];
1788 }
1789
1790 return $contacts;
1791 }
1792
1793 /**
1794 * Merge relationships from otherContact to mainContact.
1795 *
1796 * Called during contact merge operation
1797 *
1798 * @param int $mainId
1799 * Contact id of main contact record.
1800 * @param int $otherId
1801 * Contact id of record which is going to merge.
1802 * @param array $sqls
1803 * (reference) array of sql statements to append to.
1804 *
1805 * @see CRM_Dedupe_Merger::cpTables()
1806 */
1807 public static function mergeRelationships($mainId, $otherId, &$sqls) {
1808 // Delete circular relationships
1809 $sqls[] = "DELETE FROM civicrm_relationship
1810 WHERE (contact_id_a = $mainId AND contact_id_b = $otherId AND case_id IS NULL)
1811 OR (contact_id_b = $mainId AND contact_id_a = $otherId AND case_id IS NULL)";
1812
1813 // Delete relationship from other contact if main contact already has that relationship
1814 $sqls[] = "DELETE r2
1815 FROM civicrm_relationship r1, civicrm_relationship r2
1816 WHERE r1.relationship_type_id = r2.relationship_type_id
1817 AND r1.id <> r2.id
1818 AND r1.case_id IS NULL AND r2.case_id IS NULL
1819 AND (
1820 r1.contact_id_a = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_b = r2.contact_id_b
1821 OR r1.contact_id_b = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_a = r2.contact_id_a
1822 OR (
1823 (r1.contact_id_a = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_b = r2.contact_id_a
1824 OR r1.contact_id_b = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_a = r2.contact_id_b)
1825 AND r1.relationship_type_id IN (SELECT id FROM civicrm_relationship_type WHERE name_b_a = name_a_b)
1826 )
1827 )";
1828
1829 // Move relationships
1830 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_a = $mainId WHERE contact_id_a = $otherId";
1831 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_b = $mainId WHERE contact_id_b = $otherId";
1832
1833 // Move current employer id (name will get updated later)
1834 $sqls[] = "UPDATE civicrm_contact SET employer_id = $mainId WHERE employer_id = $otherId";
1835 }
1836
1837 /**
1838 * Set 'is_valid' field to false for all relationships whose end date is in the past, ie. are expired.
1839 *
1840 * @return bool
1841 * True on success, false if error is encountered.
1842 * @throws \CiviCRM_API3_Exception
1843 */
1844 public static function disableExpiredRelationships() {
1845 $query = "SELECT id FROM civicrm_relationship WHERE is_active = 1 AND end_date < CURDATE()";
1846
1847 $dao = CRM_Core_DAO::executeQuery($query);
1848 while ($dao->fetch()) {
1849 $result = CRM_Contact_BAO_Relationship::setIsActive($dao->id, FALSE);
1850 // Result will be NULL if error occurred. We abort early if error detected.
1851 if ($result == NULL) {
1852 return FALSE;
1853 }
1854 }
1855 return TRUE;
1856 }
1857
1858 /**
1859 * Function filters the query by possible relationships for the membership type.
1860 *
1861 * It is intended to be called when constructing queries for the api (reciprocal & non-reciprocal)
1862 * and to add clauses to limit the return to those relationships which COULD inherit a membership type
1863 * (as opposed to those who inherit a particular membership
1864 *
1865 * @param array $params
1866 * Api input array.
1867 * @param string $direction
1868 *
1869 * @return array|void
1870 * @throws \CiviCRM_API3_Exception
1871 */
1872 public static function membershipTypeToRelationshipTypes(&$params, $direction = NULL) {
1873 $membershipType = civicrm_api3('membership_type', 'getsingle', [
1874 'id' => $params['membership_type_id'],
1875 'return' => 'relationship_type_id, relationship_direction',
1876 ]);
1877 $relationshipTypes = $membershipType['relationship_type_id'];
1878 if (empty($relationshipTypes)) {
1879 return NULL;
1880 }
1881 // if we don't have any contact data we can only filter on type
1882 if (empty($params['contact_id']) && empty($params['contact_id_a']) && empty($params['contact_id_a'])) {
1883 $params['relationship_type_id'] = ['IN' => $relationshipTypes];
1884 return NULL;
1885 }
1886 else {
1887 $relationshipDirections = (array) $membershipType['relationship_direction'];
1888 // if we have contact_id_a OR contact_id_b we can make a call here
1889 // if we have contact??
1890 foreach ($relationshipDirections as $index => $mtdirection) {
1891 if (isset($params['contact_id_a']) && $mtdirection == 'a_b' || $direction == 'a_b') {
1892 $types[] = $relationshipTypes[$index];
1893 }
1894 if (isset($params['contact_id_b']) && $mtdirection == 'b_a' || $direction == 'b_a') {
1895 $types[] = $relationshipTypes[$index];
1896 }
1897 }
1898 if (!empty($types)) {
1899 $params['relationship_type_id'] = ['IN' => $types];
1900 }
1901 elseif (!empty($clauses)) {
1902 return explode(' OR ', $clauses);
1903 }
1904 else {
1905 // effectively setting it to return no results
1906 $params['relationship_type_id'] = 0;
1907 }
1908 }
1909 }
1910
1911 /**
1912 * Wrapper for contact relationship selector.
1913 *
1914 * @param array $params
1915 * Associated array for params record id.
1916 *
1917 * @return array
1918 * associated array of contact relationships
1919 * @throws \Exception
1920 */
1921 public static function getContactRelationshipSelector(&$params) {
1922 // format the params
1923 $params['offset'] = ($params['page'] - 1) * $params['rp'];
1924 $params['sort'] = $params['sortBy'] ?? NULL;
1925
1926 if ($params['context'] == 'past') {
1927 $relationshipStatus = CRM_Contact_BAO_Relationship::INACTIVE;
1928 }
1929 elseif ($params['context'] == 'all') {
1930 $relationshipStatus = CRM_Contact_BAO_Relationship::ALL;
1931 }
1932 else {
1933 $relationshipStatus = CRM_Contact_BAO_Relationship::CURRENT;
1934 }
1935
1936 // check logged in user for permission
1937 $page = new CRM_Core_Page();
1938 CRM_Contact_Page_View::checkUserPermission($page, $params['contact_id']);
1939 $permissions = [$page->_permission];
1940 if ($page->_permission == CRM_Core_Permission::EDIT) {
1941 $permissions[] = CRM_Core_Permission::DELETE;
1942 }
1943 $mask = CRM_Core_Action::mask($permissions);
1944
1945 $permissionedContacts = TRUE;
1946 if ($params['context'] != 'user') {
1947 $links = CRM_Contact_Page_View_Relationship::links();
1948 }
1949 else {
1950 $links = CRM_Contact_Page_View_UserDashBoard::links();
1951 $mask = NULL;
1952 }
1953 // get contact relationships
1954 $relationships = CRM_Contact_BAO_Relationship::getRelationship($params['contact_id'],
1955 $relationshipStatus,
1956 $params['rp'], 0, 0,
1957 $links, $mask,
1958 $permissionedContacts,
1959 $params, TRUE
1960 );
1961
1962 $contactRelationships = [];
1963 $params['total'] = $relationships['total_relationships'];
1964 unset($relationships['total_relationships']);
1965 if (!empty($relationships)) {
1966
1967 $displayName = CRM_Contact_BAO_Contact::displayName($params['contact_id']);
1968
1969 // format params
1970 foreach ($relationships as $relationshipId => $values) {
1971 $relationship = [];
1972
1973 $relationship['DT_RowId'] = $values['id'];
1974 $relationship['DT_RowClass'] = 'crm-entity';
1975 if ($values['is_active'] == 0) {
1976 $relationship['DT_RowClass'] .= ' disabled';
1977 }
1978
1979 $relationship['DT_RowAttr'] = [];
1980 $relationship['DT_RowAttr']['data-entity'] = 'relationship';
1981 $relationship['DT_RowAttr']['data-id'] = $values['id'];
1982
1983 //Add image icon for related contacts: CRM-14919; CRM-19668
1984 $contactType = (!empty($values['contact_sub_type'])) ? $values['contact_sub_type'] : $values['contact_type'];
1985 $icon = CRM_Contact_BAO_Contact_Utils::getImage($contactType,
1986 FALSE,
1987 $values['cid']
1988 );
1989 $relationship['sort_name'] = $icon . ' ' . CRM_Utils_System::href(
1990 $values['name'],
1991 'civicrm/contact/view',
1992 "reset=1&cid={$values['cid']}");
1993
1994 $relationship['relation'] = CRM_Utils_Array::value('case', $values, '') . CRM_Utils_System::href(
1995 $values['relation'],
1996 'civicrm/contact/view/rel',
1997 "action=view&reset=1&cid={$values['cid']}&id={$values['id']}&rtype={$values['rtype']}");
1998
1999 if (!empty($values['description'])) {
2000 $relationship['relation'] .= "<p class='description'>{$values['description']}</p>";
2001 }
2002
2003 if ($params['context'] == 'current') {
2004 $smarty = CRM_Core_Smarty::singleton();
2005
2006 $contactCombos = [
2007 [
2008 'permContact' => $params['contact_id'],
2009 'permDisplayName' => $displayName,
2010 'otherContact' => $values['cid'],
2011 'otherDisplayName' => $values['display_name'],
2012 'columnKey' => 'sort_name',
2013 ],
2014 [
2015 'permContact' => $values['cid'],
2016 'permDisplayName' => $values['display_name'],
2017 'otherContact' => $params['contact_id'],
2018 'otherDisplayName' => $displayName,
2019 'columnKey' => 'relation',
2020 ],
2021 ];
2022
2023 foreach ($contactCombos as $combo) {
2024 foreach ([CRM_Contact_BAO_Relationship::EDIT, CRM_Contact_BAO_Relationship::VIEW] as $permType) {
2025 $smarty->assign('permType', $permType);
2026 if (($combo['permContact'] == $values['contact_id_a'] and $values['is_permission_a_b'] == $permType)
2027 || ($combo['permContact'] == $values['contact_id_b'] and $values['is_permission_b_a'] == $permType)
2028 ) {
2029 $smarty->assign('permDisplayName', $combo['permDisplayName']);
2030 $smarty->assign('otherDisplayName', $combo['otherDisplayName']);
2031 $relationship[$combo['columnKey']] .= $smarty->fetch('CRM/Contact/Page/View/RelationshipPerm.tpl');
2032 }
2033 }
2034 }
2035 }
2036
2037 $relationship['start_date'] = CRM_Utils_Date::customFormat($values['start_date']);
2038 $relationship['end_date'] = CRM_Utils_Date::customFormat($values['end_date']);
2039 $relationship['city'] = $values['city'];
2040 $relationship['state'] = $values['state'];
2041 $relationship['email'] = $values['email'];
2042 $relationship['phone'] = $values['phone'];
2043 $relationship['links'] = $values['action'];
2044
2045 array_push($contactRelationships, $relationship);
2046 }
2047 }
2048
2049 $columnHeaders = self::getColumnHeaders();
2050 $selector = NULL;
2051 CRM_Utils_Hook::searchColumns('relationship.rows', $columnHeaders, $contactRelationships, $selector);
2052
2053 $relationshipsDT = [];
2054 $relationshipsDT['data'] = $contactRelationships;
2055 $relationshipsDT['recordsTotal'] = $params['total'];
2056 $relationshipsDT['recordsFiltered'] = $params['total'];
2057
2058 return $relationshipsDT;
2059 }
2060
2061 /**
2062 * @return array
2063 */
2064 public static function getColumnHeaders() {
2065 return [
2066 'relation' => [
2067 'name' => ts('Relationship'),
2068 'sort' => 'relation',
2069 'direction' => CRM_Utils_Sort::ASCENDING,
2070 ],
2071 'sort_name' => [
2072 'name' => '',
2073 'sort' => 'sort_name',
2074 'direction' => CRM_Utils_Sort::ASCENDING,
2075 ],
2076 'start_date' => [
2077 'name' => ts('Start'),
2078 'sort' => 'start_date',
2079 'direction' => CRM_Utils_Sort::DONTCARE,
2080 ],
2081 'end_date' => [
2082 'name' => ts('End'),
2083 'sort' => 'end_date',
2084 'direction' => CRM_Utils_Sort::DONTCARE,
2085 ],
2086 'city' => [
2087 'name' => ts('City'),
2088 'sort' => 'city',
2089 'direction' => CRM_Utils_Sort::DONTCARE,
2090 ],
2091 'state' => [
2092 'name' => ts('State/Prov'),
2093 'sort' => 'state',
2094 'direction' => CRM_Utils_Sort::DONTCARE,
2095 ],
2096 'email' => [
2097 'name' => ts('Email'),
2098 'sort' => 'email',
2099 'direction' => CRM_Utils_Sort::DONTCARE,
2100 ],
2101 'phone' => [
2102 'name' => ts('Phone'),
2103 'sort' => 'phone',
2104 'direction' => CRM_Utils_Sort::DONTCARE,
2105 ],
2106 'links' => [
2107 'name' => '',
2108 'sort' => 'links',
2109 'direction' => CRM_Utils_Sort::DONTCARE,
2110 ],
2111 ];
2112 }
2113
2114 /**
2115 * @inheritdoc
2116 */
2117 public static function buildOptions($fieldName, $context = NULL, $props = []) {
2118 // Quickform-specific format, for use when editing relationship type options in a popup from the contact relationship form
2119 if ($fieldName === 'relationship_type_id' && !empty($props['is_form'])) {
2120 return self::getContactRelationshipType(
2121 $props['contact_id'] ?? NULL,
2122 $props['relationship_direction'] ?? 'a_b',
2123 $props['relationship_id'] ?? NULL,
2124 $props['contact_type'] ?? NULL
2125 );
2126 }
2127
2128 return parent::buildOptions($fieldName, $context, $props);
2129 }
2130
2131 /**
2132 * Process the params from api, form and check if current
2133 * employer should be set or unset.
2134 *
2135 * @param array $params
2136 * @param int $relationshipId
2137 * @param int|null $updatedRelTypeID
2138 *
2139 * @return bool
2140 * TRUE if current employer needs to be cleared.
2141 * @throws \CiviCRM_API3_Exception
2142 */
2143 public static function isCurrentEmployerNeedingToBeCleared($params, $relationshipId, $updatedRelTypeID = NULL) {
2144 $existingTypeID = (int) CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Relationship', $relationshipId, 'relationship_type_id');
2145 $updatedRelTypeID = $updatedRelTypeID ? $updatedRelTypeID : $existingTypeID;
2146 $currentEmployerID = (int) civicrm_api3('Contact', 'getvalue', ['return' => 'current_employer_id', 'id' => $params['contact_id_a']]);
2147
2148 if ($currentEmployerID !== (int) $params['contact_id_b'] || !self::isRelationshipTypeCurrentEmployer($existingTypeID)) {
2149 return FALSE;
2150 }
2151 //Clear employer if relationship is expired.
2152 if (!empty($params['end_date']) && strtotime($params['end_date']) < time()) {
2153 return TRUE;
2154 }
2155 //current employer checkbox is disabled on the form.
2156 //inactive or relationship type(employer of) is updated.
2157 if ((isset($params['is_current_employer']) && empty($params['is_current_employer']))
2158 || ((isset($params['is_active']) && empty($params['is_active'])))
2159 || $existingTypeID != $updatedRelTypeID) {
2160 // If there are no other active employer relationships between the same 2 contacts...
2161 if (!civicrm_api3('Relationship', 'getcount', [
2162 'is_active' => 1,
2163 'relationship_type_id' => $existingTypeID,
2164 'id' => ['<>' => $params['id']],
2165 'contact_id_a' => $params['contact_id_a'],
2166 'contact_id_b' => $params['contact_id_b'],
2167 ])) {
2168 return TRUE;
2169 }
2170 }
2171
2172 return FALSE;
2173 }
2174
2175 /**
2176 * Is this a current employer relationship type.
2177 *
2178 * @todo - this could use cached pseudoconstant lookups.
2179 *
2180 * @param int $existingTypeID
2181 *
2182 * @return bool
2183 */
2184 private static function isRelationshipTypeCurrentEmployer(int $existingTypeID): bool {
2185 $isCurrentEmployerRelationshipType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', $existingTypeID, 'name_b_a') === 'Employer of';
2186 return $isCurrentEmployerRelationshipType;
2187 }
2188
2189 /**
2190 * Is the inherited relationship invalidated by this relationship change.
2191 *
2192 * @param array $membershipValues
2193 * @param array $values
2194 * @param int $cid
2195 *
2196 * @return array
2197 * @throws \CiviCRM_API3_Exception
2198 */
2199 private static function isInheritedMembershipInvalidated($membershipValues, array $values, $cid): array {
2200 // @todo most of this can go - it's just the weird historical returning of $relTypeId that it does.
2201 // now we have caching the parent fn can just call CRM_Member_BAO_MembershipType::getMembershipType
2202 $membershipType = CRM_Member_BAO_MembershipType::getMembershipType($membershipValues['membership_type_id']);
2203 $relTypeIds = $membershipType['relationship_type_id'];
2204 $membershipInheritedFrom = $membershipValues['owner_membership_id'] ?? NULL;
2205 if (!$membershipInheritedFrom || !in_array($values[$cid]['relationshipTypeId'], $relTypeIds)) {
2206 return [implode(',', $relTypeIds), FALSE];
2207 }
2208 //CRM-16300 check if owner membership exist for related membership
2209 return [implode(',', $relTypeIds), !self::isContactHasValidRelationshipToInheritMembershipType((int) $cid, (int) $membershipValues['membership_type_id'], (int) $membershipValues['owner_membership_id'])];
2210 }
2211
2212 /**
2213 * Is there a valid relationship confering this membership type on this contact.
2214 *
2215 * @param int $contactID
2216 * @param int $membershipTypeID
2217 * @param int $parentMembershipID
2218 * Id of the membership being inherited.
2219 *
2220 * @return bool
2221 *
2222 * @throws \CiviCRM_API3_Exception
2223 */
2224 private static function isContactHasValidRelationshipToInheritMembershipType(int $contactID, int $membershipTypeID, int $parentMembershipID): bool {
2225 $membershipType = CRM_Member_BAO_MembershipType::getMembershipType($membershipTypeID);
2226 $existingRelationships = civicrm_api3('Relationship', 'get', [
2227 'contact_id_a' => $contactID,
2228 'contact_id_b' => $contactID,
2229 'relationship_type_id' => ['IN' => $membershipType['relationship_type_id']],
2230 'options' => ['or' => [['contact_id_a', 'contact_id_b']], 'limit' => 0],
2231 'is_active' => 1,
2232 ])['values'];
2233
2234 if (empty($existingRelationships)) {
2235 return FALSE;
2236 }
2237
2238 $membershipInheritedFromContactID = (int) civicrm_api3('Membership', 'getvalue', ['return' => 'contact_id', 'id' => $parentMembershipID]);
2239 // I don't think the api can correctly filter by start & end because of handling for NULL
2240 // so we filter them out here.
2241 foreach ($existingRelationships as $index => $existingRelationship) {
2242 $otherContactID = (int) (($contactID === (int) $existingRelationship['contact_id_a']) ? $existingRelationship['contact_id_b'] : $existingRelationship['contact_id_a']);
2243 if (!empty($existingRelationship['start_date'])
2244 && strtotime($existingRelationship['start_date']) > time()
2245 ) {
2246 unset($existingRelationships[$index]);
2247 continue;
2248 }
2249 if (!empty($existingRelationship['end_date'])
2250 && strtotime($existingRelationship['end_date']) < time()
2251 ) {
2252 unset($existingRelationships[$index]);
2253 continue;
2254 }
2255 if ($membershipInheritedFromContactID !== $otherContactID
2256 ) {
2257 // This is a weird scenario - they have been inheriting the membership
2258 // just not from this relationship - and some max_related calcs etc would be required
2259 // - ie because they are no longer inheriting from this relationship's 'allowance'
2260 // and now are inheriting from the other relationships 'allowance', if it has not
2261 // already hit 'max_related'
2262 // For now ignore here & hope it's handled elsewhere - at least that's consistent with
2263 // before this function was added.
2264 unset($existingRelationships[$index]);
2265 continue;
2266 }
2267 if (!civicrm_api3('Contact', 'getcount', ['id' => $otherContactID, 'is_deleted' => 0])) {
2268 // Can't inherit from a deleted contact.
2269 unset($existingRelationships[$index]);
2270 continue;
2271 }
2272 }
2273 return !empty($existingRelationships);
2274 }
2275
2276 /**
2277 * Add an inherited membership, provided max related not exceeded.
2278 *
2279 * @param array $membershipValues
2280 *
2281 * @return array
2282 * @throws \CRM_Core_Exception
2283 */
2284 protected static function addInheritedMembership($membershipValues) {
2285 $query = "
2286SELECT count(*)
2287 FROM civicrm_membership
2288 LEFT JOIN civicrm_membership_status ON (civicrm_membership_status.id = civicrm_membership.status_id)
2289 WHERE membership_type_id = {$membershipValues['membership_type_id']}
2290 AND owner_membership_id = {$membershipValues['owner_membership_id']}
2291 AND is_current_member = 1";
2292 $result = CRM_Core_DAO::singleValueQuery($query);
2293 if ($result < CRM_Utils_Array::value('max_related', $membershipValues, PHP_INT_MAX)) {
2294 // Convert custom_xx_id fields to custom_xx
2295 // See https://lab.civicrm.org/dev/membership/-/issues/37
2296 // This makes sure the value is copied and not the looked up value.
2297 // Which is the case when the custom field is a contact reference field.
2298 // The custom_xx contains the display name of the contact, instead of the contact id.
2299 // The contact id is then available in custom_xx_id.
2300 foreach ($membershipValues as $field => $value) {
2301 if (stripos($field, 'custom_') !== 0) {
2302 // No a custom field
2303 continue;
2304 }
2305 $custom_id = substr($field, 7);
2306 if (substr($custom_id, -3) === '_id') {
2307 $custom_id = substr($custom_id, 0, -3);
2308 unset($membershipValues[$field]);
2309 $membershipValues['custom_' . $custom_id] = $value;
2310 }
2311 }
2312
2313 civicrm_api3('Membership', 'create', $membershipValues);
2314 }
2315 return $membershipValues;
2316 }
2317
2318}