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