Merge pull request #22900 from MegaphoneJon/paymentprocessor-error-bubble-up
[civicrm-core.git] / CRM / Contact / BAO / Relationship.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
bfa4da96 13 * Class CRM_Contact_BAO_Relationship.
6a488035
TO
14 */
15class CRM_Contact_BAO_Relationship extends CRM_Contact_DAO_Relationship {
16
17 /**
fe482240 18 * Various constants to indicate different type of relationships.
6a488035
TO
19 *
20 * @var int
21 */
a4dc03f7 22 const ALL = 0, PAST = 1, DISABLED = 2, CURRENT = 4, INACTIVE = 8;
6a488035 23
f871c3a9
AS
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
16b745b0
MWMC
30 /**
31 * The list of column headers
32 * @var array
33 */
34 private static $columnHeaders;
35
7ecf6275 36 /**
d49c2966 37 * Create function - use the API instead.
bfa4da96 38 *
2da59b29 39 * Note that the previous create function has been renamed 'legacyCreateMultiple'
7ecf6275 40 * and this is new in 4.6
2da59b29 41 * All existing calls have been changed to legacyCreateMultiple except the api call - however, it is recommended
bfa4da96
EM
42 * that you call that as the end to end testing here is based on the api & refactoring may still be done.
43 *
16b10e64 44 * @param array $params
bfa4da96 45 *
7ecf6275
EM
46 * @return \CRM_Contact_BAO_Relationship
47 * @throws \CRM_Core_Exception
48 */
49 public static function create(&$params) {
609d8c32 50
4f9f6ede 51 $extendedParams = self::loadExistingRelationshipDetails($params);
609d8c32
TM
52 // When id is specified we always wan't to update, so we don't need to
53 // check for duplicate relations.
4f9f6ede 54 if (!isset($params['id']) && self::checkDuplicateRelationship($extendedParams, $extendedParams['contact_id_a'], $extendedParams['contact_id_b'], CRM_Utils_Array::value('id', $extendedParams, 0))) {
7ecf6275
EM
55 throw new CRM_Core_Exception('Duplicate Relationship');
56 }
4f9f6ede 57 $params = $extendedParams;
22aca6b7
EM
58 if (!CRM_Contact_BAO_Relationship::checkRelationshipType($params['contact_id_a'], $params['contact_id_b'],
59 $params['relationship_type_id'])) {
936e43d6 60 throw new CRM_Core_Exception('Invalid Relationship');
7ecf6275
EM
61 }
62 $relationship = self::add($params);
936e43d6 63 if (!empty($params['contact_id_a'])) {
52335bb5 64 $ids = [
04ad3598
EM
65 'contactTarget' => $relationship->contact_id_b,
66 'contact' => $params['contact_id_a'],
52335bb5 67 ];
6c25ede2 68
690c56c3 69 //CRM-16087 removed additional call to function relatedMemberships which is already called by disableEnableRelationship
7a44a255 70 //resulting in membership being created twice
6946fcbf 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 }
91244f1d 79 $id = empty($params['id']) ? $relationship->id : $params['id'];
80 self::disableEnableRelationship($id, $action, $params, $ids, $active);
6c25ede2 81 }
04ad3598 82
aeacb9a9
MM
83 if (empty($params['skipRecentView'])) {
84 self::addRecent($params, $relationship);
85 }
86
7ecf6275
EM
87 return $relationship;
88 }
7f3647bc 89
2da59b29 90 /**
d49c2966 91 * Create multiple relationships for one contact.
2da59b29 92 *
d49c2966
EM
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.
2da59b29
EM
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;
52335bb5 111 $relationshipIDs = [];
2da59b29
EM
112 foreach ($secondaryContactIDs as $secondaryContactID) {
113 try {
114 $params['contact_id_' . $secondaryContactLetter] = $secondaryContactID;
115 $relationship = civicrm_api3('relationship', 'create', $params);
d49c2966 116 $relationshipIDs[] = $relationship['id'];
bfa4da96 117 $valid++;
2da59b29
EM
118 }
119 catch (CiviCRM_API3_Exception $e) {
120 switch ($e->getMessage()) {
bfa4da96
EM
121 case 'Duplicate Relationship':
122 $duplicate++;
2da59b29
EM
123 break;
124
bfa4da96
EM
125 case 'Invalid Relationship':
126 $invalid++;
2da59b29
EM
127 break;
128
129 default:
130 throw new CRM_Core_Exception('unknown relationship create error ' . $e->getMessage());
131 }
132 }
133 }
134
52335bb5 135 return [
d49c2966
EM
136 'valid' => $valid,
137 'invalid' => $invalid,
138 'duplicate' => $duplicate,
139 'saved' => $saved,
140 'relationship_ids' => $relationshipIDs,
52335bb5 141 ];
2da59b29
EM
142 }
143
6a488035 144 /**
152f6da6
EM
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 *
fe482240 150 * Takes an associative array and creates a relationship object.
52335bb5 151 *
7ecf6275
EM
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
6a488035 155 *
77c5b619
TO
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.
16b10e64 160 * per http://wiki.civicrm.org/confluence/display/CRM/Database+layer
26dcc9eb 161 * "we are moving away from the $ids param "
6a488035 162 *
52335bb5 163 * @return array
164 * @throws \CRM_Core_Exception
6a488035 165 */
12e94880 166 public static function legacyCreateMultiple($params, $ids = []) {
3b9a6946 167 CRM_Core_Error::deprecatedFunctionWarning('api v4');
dab33b37
EM
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.
41a5dfaf
EM
174 $contactID = $ids['contact'];
175 unset($ids);
12e94880
EM
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.
e76b1107
EM
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
41a5dfaf
EM
187 [$contactFields['relationship_type_id'], $firstLetter, $secondLetter] = explode('_', $params['relationship_type_id']);
188 $contactFields['contact_id_' . $firstLetter] = $contactID;
189 $contactFields['contact_id_' . $secondLetter] = $relatedContactID;
22aca6b7
EM
190 if (!CRM_Contact_BAO_Relationship::checkRelationshipType($contactFields['contact_id_a'], $contactFields['contact_id_b'],
191 $contactFields['relationship_type_id'])) {
e76b1107
EM
192 return [0, 0];
193 }
2001204e 194
e76b1107
EM
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;
6a488035 200 }
e76b1107
EM
201 if (
202 self::checkDuplicateRelationship(
203 $contactFields,
41a5dfaf 204 $contactID,
e76b1107
EM
205 // step 2
206 $relatedContactID
207 )
208 ) {
209 return [0, 1];
210 }
211
212 $singleInstanceParams = array_merge($params, $contactFields);
213 $relationship = self::add($singleInstanceParams);
6a488035
TO
214
215 // do not add to recent items for import, CRM-4399
22aca6b7 216 if (empty($params['skipRecentView'])) {
7ecf6275 217 self::addRecent($params, $relationship);
6a488035
TO
218 }
219
12e94880 220 return [1, 0];
6a488035
TO
221 }
222
223 /**
bfa4da96 224 * This is the function that check/add if the relationship created is valid.
6a488035 225 *
77c5b619 226 * @param array $params
f42bcfb1 227 * Array of name/value pairs.
77c5b619
TO
228 * @param array $ids
229 * The array that holds all the db ids.
6a488035 230 *
c490a46a 231 * @return CRM_Contact_BAO_Relationship
f42bcfb1
MD
232 *
233 * @throws \CiviCRM_API3_Exception
6a488035 234 */
4535334c 235 public static function add($params, $ids = []) {
e5ccee43 236 $params['id'] = CRM_Utils_Array::value('relationship', $ids, CRM_Utils_Array::value('id', $params));
f0fc26a5 237
49f8272d 238 $hook = 'create';
e5ccee43 239 if ($params['id']) {
49f8272d 240 $hook = 'edit';
6a488035 241 }
e5ccee43 242 CRM_Utils_Hook::pre($hook, 'Relationship', $params['id'], $params);
6a488035 243
9c1bc317 244 $relationshipTypes = $params['relationship_type_id'] ?? NULL;
f0fc26a5
DL
245 // explode the string with _ to get the relationship type id
246 // and to know which contact has to be inserted in
6a488035 247 // contact_id_a and which one in contact_id_b
50288497
MWMC
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;
6a488035 272
f0fc26a5
DL
273 // check if the relationship type is Head of Household then update the
274 // household's primary contact with this contact.
eabf1c29
MWMC
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
df0c42cc 286 }
f42bcfb1 287
50288497
MWMC
288 if (!empty($params['id']) && self::isCurrentEmployerNeedingToBeCleared($relationship->toArray(), $params['id'], $relationshipTypeID)) {
289 CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($relationship->contact_id_a);
290 }
6a488035 291
52335bb5 292 $dateFields = ['end_date', 'start_date'];
6a488035 293
9b873358
TO
294 foreach (self::getdefaults() as $defaultField => $defaultValue) {
295 if (isset($params[$defaultField])) {
296 if (in_array($defaultField, $dateFields)) {
6a488035 297 $relationship->$defaultField = CRM_Utils_Date::format(CRM_Utils_Array::value($defaultField, $params));
9b873358 298 if (!$relationship->$defaultField) {
6a488035
TO
299 $relationship->$defaultField = 'NULL';
300 }
301 }
92e4c2a5 302 else {
6a488035
TO
303 $relationship->$defaultField = $params[$defaultField];
304 }
305 }
e5ccee43 306 elseif (empty($params['id'])) {
6a488035
TO
307 $relationship->$defaultField = $defaultValue;
308 }
309 }
310
311 $relationship->save();
f42bcfb1
MD
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 }
6a488035 324 // add custom field values
a7488080 325 if (!empty($params['custom'])) {
6a488035
TO
326 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_relationship', $relationship->id);
327 }
328
5c208c3f 329 CRM_Utils_Hook::post($hook, 'Relationship', $relationship->id, $relationship);
6a488035
TO
330
331 return $relationship;
332 }
7ecf6275
EM
333
334 /**
fe482240 335 * Add relationship to recent links.
bfa4da96 336 *
7ecf6275
EM
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();
52335bb5 345 $recentOther = [];
7ecf6275
EM
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);
52335bb5 350 $recentOther = [
7ecf6275
EM
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 ),
52335bb5 357 ];
7ecf6275
EM
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
d49c2966
EM
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
52335bb5 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 => [
d49c2966
EM
398 $params['id'],
399 'Integer',
52335bb5 400 ],
401 ]);
d49c2966
EM
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
6a488035 410 /**
d49c2966 411 * Specify defaults for creating a relationship.
6a488035 412 *
a6c01b45
CW
413 * @return array
414 * array of defaults for creating relationship
6a488035 415 */
00be9182 416 public static function getdefaults() {
52335bb5 417 return [
0c1bf04e 418 'is_active' => 1,
f871c3a9
AS
419 'is_permission_a_b' => self::NONE,
420 'is_permission_b_a' => self::NONE,
6a488035
TO
421 'description' => '',
422 'start_date' => 'NULL',
423 'case_id' => NULL,
424 'end_date' => 'NULL',
52335bb5 425 ];
6a488035
TO
426 }
427
6a488035 428 /**
fe482240 429 * Check if there is data to create the object.
6a488035 430 *
77c5b619 431 * @param array $params
6a488035 432 *
4dd83d9e 433 * @deprecated
c301f76e 434 * @return bool
6a488035 435 */
e01bf597 436 public static function dataExists($params) {
4dd83d9e 437 CRM_Core_Error::deprecatedFunctionWarning('obsolete');
e01bf597 438 return (isset($params['contact_check']) && is_array($params['contact_check']));
6a488035
TO
439 }
440
441 /**
100fef9d 442 * Get get list of relationship type based on the contact type.
6a488035 443 *
77c5b619
TO
444 * @param int $contactId
445 * This is the contact id of the current contact.
fd31fa4c 446 * @param null $contactSuffix
77c5b619
TO
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.
fd31fa4c 455 * @param bool $biDirectional
4091c7e7 456 * @param array $contactSubType
bfa4da96 457 * Includes relationship types between this subtype.
77c5b619 458 * @param bool $onlySubTypeRelationTypes
bfa4da96
EM
459 * If set only subtype which is passed by $contactSubType
460 * related relationship types get return
6a488035 461 *
a6c01b45
CW
462 * @return array
463 * array reference of all relationship types with context to current contact.
6a488035 464 */
c301f76e 465 public static function getContactRelationshipType(
51ccfbbe 466 $contactId = NULL,
6a488035
TO
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 ) {
d49c2966 476
52335bb5 477 $relationshipType = [];
6a488035
TO
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();
b277f8d1 486 $contact->id = ($relationship->contact_id_a == $contactId) ? $relationship->contact_id_b : $relationship->contact_id_a;
6a488035
TO
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
318c4e1c 498 $contactSubType = (array) $contactSubType;
6a488035
TO
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 ) &&
91c0d0d8 514 (in_array($value['contact_sub_type_a'], $contactSubType) ||
91c0d0d8 515 (!$value['contact_sub_type_a'] && !$onlySubTypeRelationTypes)
6a488035
TO
516 )
517 ) {
518 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
519 }
6a488035
TO
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 ) &&
91c0d0d8 528 (in_array($value['contact_sub_type_b'], $contactSubType) ||
91c0d0d8 529 (!$value['contact_sub_type_b'] && !$onlySubTypeRelationTypes)
6a488035
TO
530 )
531 ) {
532 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
533 }
6a488035
TO
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) {
02e028a0 542 $relationshipType = self::removeRelationshipTypeDuplicates($relationshipType, $contactSuffix);
6a488035
TO
543 }
544
545 // sort the relationshipType in ascending order CRM-7736
546 asort($relationshipType);
547 return $relationshipType;
548 }
549
02e028a0
AS
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
86538308 582 /**
98a06ae0
EM
583 * Delete current employer relationship.
584 *
100fef9d 585 * @param int $id
98a06ae0 586 * @param int $action
86538308
EM
587 *
588 * @return CRM_Contact_DAO_Relationship
589 */
00be9182 590 public static function clearCurrentEmployer($id, $action) {
6a488035
TO
591 $relationship = new CRM_Contact_DAO_Relationship();
592 $relationship->id = $id;
593 $relationship->find(TRUE);
594
595 //to delete relationship between household and individual \
98a06ae0 596 //or between individual and organization
6a488035 597 if (($action & CRM_Core_Action::DISABLE) || ($action & CRM_Core_Action::DELETE)) {
52335bb5 598 $relTypes = CRM_Utils_Array::index(['name_a_b'], CRM_Core_PseudoConstant::relationshipType('name'));
81d1f764
MM
599 if (
600 (isset($relTypes['Employee of']) && $relationship->relationship_type_id == $relTypes['Employee of']['id']) ||
69ed0eb1 601 (isset($relTypes['Household Member of']) && $relationship->relationship_type_id == $relTypes['Household Member of']['id'])
7f3647bc 602 ) {
05802b8e
DG
603 $sharedContact = new CRM_Contact_DAO_Contact();
604 $sharedContact->id = $relationship->contact_id_a;
605 $sharedContact->find(TRUE);
606
dead2d66 607 $employerRelTypeId = CRM_Contact_BAO_RelationshipType::getEmployeeRelationshipTypeID();
3421dcee 608 if ($relationship->relationship_type_id == $employerRelTypeId && $relationship->contact_id_b == $sharedContact->employer_id) {
05802b8e
DG
609 CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($relationship->contact_id_a);
610 }
3421dcee 611
6a488035
TO
612 }
613 }
7f3647bc 614 return $relationship;
6a488035
TO
615 }
616
617 /**
fe482240 618 * Delete the relationship.
6a488035 619 *
77c5b619
TO
620 * @param int $id
621 * Relationship id.
6a488035 622 *
310c2031 623 * @return CRM_Contact_DAO_Relationship
624 *
52335bb5 625 * @throws \CRM_Core_Exception
310c2031 626 * @throws \CiviCRM_API3_Exception
6a488035 627 */
00be9182 628 public static function del($id) {
6a488035 629 // delete from relationship table
be12df5a 630 CRM_Utils_Hook::pre('delete', 'Relationship', $id);
6a488035
TO
631
632 $relationship = self::clearCurrentEmployer($id, CRM_Core_Action::DELETE);
310c2031 633 $relationship->delete();
6a488035
TO
634 if (CRM_Core_Permission::access('CiviMember')) {
635 // create $params array which isrequired to delete memberships
636 // of the related contacts.
52335bb5 637 $params = [
6a488035 638 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
52335bb5 639 'contact_check' => [$relationship->contact_id_b => 1],
640 ];
6a488035 641
52335bb5 642 $ids = [];
6a488035
TO
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
6a488035
TO
653 CRM_Core_Session::setStatus(ts('Selected relationship has been deleted successfully.'), ts('Record Deleted'), 'success');
654
5c208c3f 655 CRM_Utils_Hook::post('delete', 'Relationship', $id, $relationship);
6a488035 656
6a488035
TO
657 return $relationship;
658 }
659
660 /**
98a06ae0 661 * Disable/enable the relationship.
6a488035 662 *
77c5b619
TO
663 * @param int $id
664 * Relationship id.
6a488035 665 *
7a44a255
EM
666 * @param int $action
667 * @param array $params
668 * @param array $ids
669 * @param bool $active
52335bb5 670 *
671 * @throws \CRM_Core_Exception
310c2031 672 * @throws \CiviCRM_API3_Exception
6a488035 673 */
52335bb5 674 public static function disableEnableRelationship($id, $action, $params = [], $ids = [], $active = FALSE) {
6a488035 675 $relationship = self::clearCurrentEmployer($id, $action);
25f1372e 676
1b5fad8a 677 if ($id) {
25f1372e 678 // create $params array which is required to delete memberships
6a488035 679 // of the related contacts.
690c56c3 680 if (empty($params)) {
52335bb5 681 $params = [
690c56c3 682 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
52335bb5 683 'contact_check' => [$relationship->contact_id_b => 1],
684 ];
690c56c3 685 }
690c56c3 686 $contact_id_a = empty($params['contact_id_a']) ? $relationship->contact_id_a : $params['contact_id_a'];
6a488035
TO
687 // calling relatedMemberships to delete/add the memberships of
688 // related contacts.
689 if ($action & CRM_Core_Action::DISABLE) {
310c2031 690 // @todo this could call a subset of the function that just relates to
691 // cleaning up no-longer-inherited relationships
690c56c3 692 CRM_Contact_BAO_Relationship::relatedMemberships($contact_id_a,
6a488035
TO
693 $params,
694 $ids,
695 CRM_Core_Action::DELETE,
690c56c3 696 $active
6a488035
TO
697 );
698 }
699 elseif ($action & CRM_Core_Action::ENABLE) {
91244f1d 700 $ids['contact'] = empty($ids['contact']) ? $contact_id_a : $ids['contact'];
690c56c3 701 CRM_Contact_BAO_Relationship::relatedMemberships($contact_id_a,
6a488035
TO
702 $params,
703 $ids,
690c56c3 704 empty($params['id']) ? CRM_Core_Action::ADD : CRM_Core_Action::UPDATE,
705 $active
6a488035
TO
706 );
707 }
708 }
709 }
710
711 /**
fe482240 712 * Delete the object records that are associated with this contact.
6a488035 713 *
77c5b619
TO
714 * @param int $contactId
715 * Id of the contact to delete.
6a488035 716 */
00be9182 717 public static function deleteContact($contactId) {
6a488035
TO
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 /**
fe482240 730 * Get the other contact in a relationship.
6a488035 731 *
77c5b619
TO
732 * @param int $id
733 * Relationship id.
6a488035 734 *
bb088986 735 * $returns returns the contact ids in the relationship
77b97be7
EM
736 *
737 * @return \CRM_Contact_DAO_Relationship
6a488035 738 */
eff45dce 739 public static function getRelationshipByID($id) {
6a488035
TO
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 /**
fe482240 751 * Check if the relationship type selected between two contacts is correct.
6a488035 752 *
77c5b619
TO
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.
6a488035 759 *
c301f76e 760 * @return bool
a6c01b45 761 * true if it is valid relationship else false
6a488035 762 */
00be9182 763 public static function checkRelationshipType($contact_a, $contact_b, $relationshipTypeId) {
6a488035
TO
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,
7f3647bc
TO
778 $contact_sub_type_a
779 ))) &&
6a488035 780 ((!$relationshipType->contact_sub_type_b) || (in_array($relationshipType->contact_sub_type_b,
7f3647bc
TO
781 $contact_sub_type_b
782 )))
6a488035
TO
783 ) {
784 return TRUE;
785 }
786 else {
787 return FALSE;
788 }
789 }
790 return FALSE;
791 }
792
793 /**
fe482240 794 * This function does the validtion for valid relationship.
6a488035 795 *
77c5b619
TO
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.
6a488035 802 *
22aca6b7
EM
803 * @deprecated
804 *
2a6da8d7 805 * @return string
6a488035 806 */
7ecf6275 807 public static function checkValidRelationship($params, $ids, $contactId) {
6a488035 808 $errors = '';
22aca6b7 809 CRM_Core_Error::deprecatedFunctionWarning('no alternative');
6a488035
TO
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)
c4dcea5b
EM
812 if (!CRM_Contact_BAO_Relationship::checkRelationshipType($params['contact_id_a'], $params['contact_id_b'],
813 $params['relationship_type_id'])) {
6a488035
TO
814 $errors = 'Please select valid relationship between these two contacts.';
815 }
816 return $errors;
817 }
818
819 /**
fe482240 820 * This function checks for duplicate relationship.
6a488035 821 *
77c5b619 822 * @param array $params
22b28b5c 823 * An assoc array of name/value pairs.
77c5b619
TO
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.
6a488035 830 *
c301f76e 831 * @return bool
a6c01b45 832 * true if record exists else false
6a488035 833 */
22b28b5c 834 public static function checkDuplicateRelationship($params, $id, $contactId = 0, $relationshipId = 0) {
9c1bc317 835 $relationshipTypeId = $params['relationship_type_id'] ?? NULL;
decc60a0 836 list($type) = explode('_', $relationshipTypeId);
6a488035 837
f0fc26a5
DL
838 $queryString = "
839SELECT id
840FROM civicrm_relationship
841WHERE relationship_type_id = " . CRM_Utils_Type::escape($type, 'Integer');
6a488035
TO
842
843 /*
e70a7fc0
TO
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
2da59b29 848 * @ time of writing this function is called from Relationship::legacyCreateMultiple (twice)
e70a7fc0
TO
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 */
6a488035 854
52335bb5 855 $dateFields = ['end_date', 'start_date'];
9b873358 856 foreach ($dateFields as $dateField) {
22e263ad 857 if (array_key_exists($dateField, $params)) {
9b873358 858 if (empty($params[$dateField]) || $params[$dateField] == 'null') {
f0fc26a5
DL
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
6a488035
TO
863 $queryString .= " AND $dateField IS NULL";
864 continue;
865 }
9b873358 866 elseif (is_array($params[$dateField])) {
f0fc26a5
DL
867 $queryString .= " AND $dateField = " .
868 CRM_Utils_Type::escape(CRM_Utils_Date::format($params[$dateField]), 'Date');
6a488035 869 }
f0fc26a5
DL
870 else {
871 $queryString .= " AND $dateField = " .
872 CRM_Utils_Type::escape($params[$dateField], 'Date');
6a488035
TO
873 }
874 }
875 }
876
877 $queryString .=
22b28b5c
EM
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') . " ) ) ";
6a488035
TO
882
883 //if caseId is provided, include it duplicate checking.
884 if ($caseId = CRM_Utils_Array::value('case_id', $params)) {
22b28b5c 885 $queryString .= ' AND case_id = ' . CRM_Utils_Type::escape($caseId, 'Integer');
6a488035
TO
886 }
887
888 if ($relationshipId) {
22b28b5c 889 $queryString .= ' AND id !=' . CRM_Utils_Type::escape($relationshipId, 'Integer');
6a488035
TO
890 }
891
a36bd2a4 892 $relationship = CRM_Core_DAO::executeQuery($queryString);
6b284952
JV
893 while ($relationship->fetch()) {
894 // Check whether the custom field values are identical.
355e2775 895 if (self::checkDuplicateCustomFields($params['custom'] ?? [], $relationship->id)) {
6b284952
JV
896 return TRUE;
897 }
898 }
6b284952
JV
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 *
355e2775 907 * @param array $params an assoc array of name/value pairs
6b284952
JV
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 */
355e2775 914 private static function checkDuplicateCustomFields($params, $relationshipId) {
e312bf62 915 // Get the custom values of the existing relationship.
6b284952 916 $existingValues = CRM_Core_BAO_CustomValueTable::getEntityValues($relationshipId, 'Relationship');
e312bf62 917 // Create a similar array for the new relationship.
52335bb5 918 $newValues = [];
355e2775
EM
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.
1bedc18d
JV
925 // This array contains one value (key -1), and this value seems to be
926 // an array with the information about the custom value.
355e2775 927 foreach ($params as $value) {
1bedc18d
JV
928 foreach ($value as $customValue) {
929 $newValues[$customValue['custom_field_id']] = $customValue['value'];
930 }
6b284952
JV
931 }
932 }
e312bf62
JV
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);
6a488035
TO
942 }
943
944 /**
fe482240 945 * Update the is_active flag in the db.
6a488035 946 *
77c5b619
TO
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.
6a488035 951 *
52335bb5 952 * @return bool
953 *
77b97be7 954 * @throws CiviCRM_API3_Exception
6a488035 955 */
00be9182 956 public static function setIsActive($id, $is_active) {
49f8272d
E
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.
52335bb5 963 $result = civicrm_api('relationship', 'create', [
80109b10 964 'id' => $id,
965 'is_active' => $is_active,
966 'version' => 3,
52335bb5 967 ]);
80109b10 968
338ca861 969 if (is_array($result) && !empty($result['is_error']) && $result['error_message'] != 'Duplicate Relationship') {
80109b10 970 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array::value('error_code', $result, 'undefined'), $result);
971 }
49f8272d 972
6a488035
TO
973 return TRUE;
974 }
975
976 /**
98a06ae0 977 * Fetch a relationship object and store the values in the values array.
6a488035 978 *
77c5b619
TO
979 * @param array $params
980 * Input parameters to find object.
981 * @param array $values
982 * Output values of the object.
6a488035 983 *
a6c01b45
CW
984 * @return array
985 * (reference) the values that could be potentially assigned to smarty
6a488035 986 */
ba6f8b4c 987 public static function &getValues($params, &$values) {
6a488035
TO
988 if (empty($params)) {
989 return NULL;
990 }
52335bb5 991 $v = [];
6a488035
TO
992
993 // get the specific number of relationship or all relationships.
a7488080 994 if (!empty($params['numRelationship'])) {
6a488035
TO
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
c23fcc07 1002 $v['totalCount'] = count($v['data']);
6a488035
TO
1003
1004 $values['relationship']['data'] = &$v['data'];
1005 $values['relationship']['totalCount'] = &$v['totalCount'];
1006
1007 return $v;
1008 }
1009
1010 /**
fe482240 1011 * Helper function to form the sql for relationship retrieval.
6a488035 1012 *
77c5b619
TO
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.
6a488035 1021 * $param int $relationshipId relationship id
100fef9d 1022 * @param int $relationshipId
77c5b619
TO
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.
6a488035 1027 *
77b97be7 1028 * @return array
76e7a76c 1029 * [select, from, where]
923dfabb 1030 *
1031 * @throws \CRM_Core_Exception
1032 * @throws \CiviCRM_API3_Exception
6a488035 1033 */
52335bb5 1034 public static function makeURLClause($contactId, $status, $numRelationship, $count, $relationshipId, $direction, $params = []) {
6a488035
TO
1035 $select = $from = $where = '';
1036
1037 $select = '( ';
1038 if ($count) {
923dfabb 1039 if ($direction === 'a_b') {
6a488035
TO
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,
c6c691a5 1059 civicrm_contact.contact_type as contact_type,
20be4ac3 1060 civicrm_contact.contact_sub_type as contact_sub_type,
6a488035
TO
1061 civicrm_phone.phone as phone,
1062 civicrm_contact.id as civicrm_contact_id,
6a488035
TO
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.description as description,
1069 civicrm_relationship.is_active as is_active,
1070 civicrm_relationship.is_permission_a_b as is_permission_a_b,
1071 civicrm_relationship.is_permission_b_a as is_permission_b_a,
1072 civicrm_relationship.case_id as case_id';
1073
923dfabb 1074 if ($direction === 'a_b') {
6a488035 1075 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
c6c691a5 1076 civicrm_relationship_type.label_b_a as relation ';
6a488035
TO
1077 }
1078 else {
1079 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
c6c691a5 1080 civicrm_relationship_type.label_a_b as relation ';
6a488035
TO
1081 }
1082 }
1083
923dfabb 1084 $from = '
6a488035
TO
1085 FROM civicrm_relationship
1086INNER JOIN civicrm_relationship_type ON ( civicrm_relationship.relationship_type_id = civicrm_relationship_type.id )
923dfabb 1087INNER JOIN civicrm_contact ';
1088 if ($direction === 'a_b') {
6a488035
TO
1089 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_a ) ';
1090 }
1091 else {
1092 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_b ) ';
1093 }
b7d19957
CR
1094
1095 if (!$count) {
923dfabb 1096 $from .= '
6a488035
TO
1097LEFT JOIN civicrm_address ON (civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1)
1098LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
1099LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id AND civicrm_email.is_primary = 1)
1100LEFT JOIN civicrm_state_province ON (civicrm_address.state_province_id = civicrm_state_province.id)
1101LEFT JOIN civicrm_country ON (civicrm_address.country_id = civicrm_country.id)
923dfabb 1102';
b7d19957
CR
1103 }
1104
6a488035
TO
1105 $where = 'WHERE ( 1 )';
1106 if ($contactId) {
923dfabb 1107 if ($direction === 'a_b') {
6a488035
TO
1108 $where .= ' AND civicrm_relationship.contact_id_b = ' . CRM_Utils_Type::escape($contactId, 'Positive');
1109 }
1110 else {
075fa74e 1111 $where .= ' AND civicrm_relationship.contact_id_a = ' . CRM_Utils_Type::escape($contactId, 'Positive') . '
1112 AND civicrm_relationship.contact_id_a != civicrm_relationship.contact_id_b ';
6a488035
TO
1113 }
1114 }
1115 if ($relationshipId) {
1116 $where .= ' AND civicrm_relationship.id = ' . CRM_Utils_Type::escape($relationshipId, 'Positive');
1117 }
1118
1119 $date = date('Y-m-d');
1120 if ($status == self::PAST) {
1121 //this case for showing past relationship
1122 $where .= ' AND civicrm_relationship.is_active = 1 ';
1123 $where .= " AND civicrm_relationship.end_date < '" . $date . "'";
1124 }
1125 elseif ($status == self::DISABLED) {
1126 // this case for showing disabled relationship
1127 $where .= ' AND civicrm_relationship.is_active = 0 ';
1128 }
1129 elseif ($status == self::CURRENT) {
1130 //this case for showing current relationship
1131 $where .= ' AND civicrm_relationship.is_active = 1 ';
1132 $where .= " AND (civicrm_relationship.end_date >= '" . $date . "' OR civicrm_relationship.end_date IS NULL) ";
1133 }
1134 elseif ($status == self::INACTIVE) {
1135 //this case for showing inactive relationships
1136 $where .= " AND (civicrm_relationship.end_date < '" . $date . "'";
1137 $where .= ' OR civicrm_relationship.is_active = 0 )';
1138 }
1139
1140 // CRM-6181
1141 $where .= ' AND civicrm_contact.is_deleted = 0';
22e263ad 1142 if (!empty($params['membership_type_id']) && empty($params['relationship_type_id'])) {
c9c41397 1143 $where .= self::membershipTypeToRelationshipTypes($params, $direction);
1144 }
22e263ad
TO
1145 if (!empty($params['relationship_type_id'])) {
1146 if (is_array($params['relationship_type_id'])) {
7f3647bc 1147 $where .= " AND " . CRM_Core_DAO::createSQLFilter('relationship_type_id', $params['relationship_type_id'], 'Integer');
75638074 1148 }
1149 else {
1150 $where .= ' AND relationship_type_id = ' . CRM_Utils_Type::escape($params['relationship_type_id'], 'Positive');
1151 }
1152 }
923dfabb 1153 if ($direction === 'a_b') {
6a488035
TO
1154 $where .= ' ) UNION ';
1155 }
1156 else {
1157 $where .= ' ) ';
1158 }
1159
52335bb5 1160 return [$select, $from, $where];
6a488035
TO
1161 }
1162
1163 /**
fe482240 1164 * Get a list of relationships.
6a488035 1165 *
77c5b619
TO
1166 * @param int $contactId
1167 * Contact id.
1168 * @param int $status
1169 * 1: Past 2: Disabled 3: Current.
1170 * @param int $numRelationship
1171 * No of relationships to display (limit).
1172 * @param int $count
1173 * Get the no of relationships.
77b97be7 1174 * @param int $relationshipId
76e7a76c
CW
1175 * @param array $links
1176 * the list of links to display
1177 * @param int $permissionMask
1178 * the permission mask to be applied for the actions
77b97be7 1179 * @param bool $permissionedContact
76e7a76c 1180 * to return only permissioned Contact
77b97be7 1181 * @param array $params
644587aa
SL
1182 * @param bool $includeTotalCount
1183 * Should we return a count of total accessable relationships
77b97be7
EM
1184 *
1185 * @return array|int
76e7a76c 1186 * relationship records
923dfabb 1187 *
1188 * @throws \CRM_Core_Exception
1189 * @throws \CiviCRM_API3_Exception
6a488035 1190 */
c301f76e 1191 public static function getRelationship(
51ccfbbe 1192 $contactId = NULL,
7f3647bc
TO
1193 $status = 0, $numRelationship = 0,
1194 $count = 0, $relationshipId = 0,
1195 $links = NULL, $permissionMask = NULL,
75638074 1196 $permissionedContact = FALSE,
52335bb5 1197 $params = [], $includeTotalCount = FALSE
6a488035 1198 ) {
52335bb5 1199 $values = [];
6a488035
TO
1200 if (!$contactId && !$relationshipId) {
1201 return $values;
1202 }
1203
1204 list($select1, $from1, $where1) = self::makeURLClause($contactId, $status, $numRelationship,
75638074 1205 $count, $relationshipId, 'a_b', $params
6a488035
TO
1206 );
1207 list($select2, $from2, $where2) = self::makeURLClause($contactId, $status, $numRelationship,
75638074 1208 $count, $relationshipId, 'b_a', $params
6a488035
TO
1209 );
1210
1211 $order = $limit = '';
1212 if (!$count) {
40458f6c 1213 if (empty($params['sort'])) {
1214 $order = ' ORDER BY civicrm_relationship_type_id, sort_name ';
1215 }
1216 else {
1217 $order = " ORDER BY {$params['sort']} ";
1218 }
1219
1220 $offset = 0;
630d1aaa 1221 if (!empty($params['offset']) && $params['offset'] > 0) {
40458f6c 1222 $offset = $params['offset'];
1223 }
6a488035
TO
1224
1225 if ($numRelationship) {
40458f6c 1226 $limit = " LIMIT {$offset}, $numRelationship";
6a488035
TO
1227 }
1228 }
1229
1230 // building the query string
e729799a 1231 $queryString = $select1 . $from1 . $where1 . $select2 . $from2 . $where2;
6a488035
TO
1232
1233 $relationship = new CRM_Contact_DAO_Relationship();
1234
e729799a 1235 $relationship->query($queryString . $order . $limit);
52335bb5 1236 $row = [];
6a488035
TO
1237 if ($count) {
1238 $relationshipCount = 0;
1239 while ($relationship->fetch()) {
1240 $relationshipCount += $relationship->cnt1 + $relationship->cnt2;
1241 }
1242 return $relationshipCount;
1243 }
1244 else {
1245
644587aa 1246 if ($includeTotalCount) {
e729799a 1247 $values['total_relationships'] = CRM_Core_DAO::singleValueQuery("SELECT count(*) FROM ({$queryString}) AS r");
644587aa
SL
1248 }
1249
6a488035
TO
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 }
6a488035 1267 }
75b35151 1268 // temporary hold the value of $mask.
1269 $tempMask = $mask;
6a488035 1270 }
c23fcc07 1271
6a488035
TO
1272 while ($relationship->fetch()) {
1273 $rid = $relationship->civicrm_relationship_id;
1274 $cid = $relationship->civicrm_contact_id;
a93664c8 1275
dc15bb38 1276 if ($permissionedContact &&
a93664c8 1277 (!CRM_Contact_BAO_Contact_Permission::allow($cid))
6a488035
TO
1278 ) {
1279 continue;
1280 }
75b35151 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 }
6a488035
TO
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;
c6c691a5 1296 $values[$rid]['contact_type'] = $relationship->contact_type;
20be4ac3 1297 $values[$rid]['contact_sub_type'] = $relationship->contact_sub_type;
6a488035
TO
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]['description'] = $relationship->description;
1313 $values[$rid]['is_active'] = $relationship->is_active;
1314 $values[$rid]['is_permission_a_b'] = $relationship->is_permission_a_b;
1315 $values[$rid]['is_permission_b_a'] = $relationship->is_permission_b_a;
1316 $values[$rid]['case_id'] = $relationship->case_id;
1317
1318 if ($status) {
1319 $values[$rid]['status'] = $status;
1320 }
1321
1322 $values[$rid]['civicrm_relationship_type_id'] = $relationship->civicrm_relationship_type_id;
1323
1324 if ($relationship->contact_id_a == $contactId) {
1325 $values[$rid]['rtype'] = 'a_b';
1326 }
1327 else {
1328 $values[$rid]['rtype'] = 'b_a';
1329 }
1330
1331 if ($links) {
52335bb5 1332 $replace = [
6a488035
TO
1333 'id' => $rid,
1334 'rtype' => $values[$rid]['rtype'],
1335 'cid' => $contactId,
1336 'cbid' => $values[$rid]['cid'],
1337 'caseid' => $values[$rid]['case_id'],
1338 'clientid' => $contactId,
52335bb5 1339 ];
6a488035
TO
1340
1341 if ($status == self::INACTIVE) {
1342 // setting links for inactive relationships
1343 $mask = array_sum(array_keys($links));
1344 if (!$values[$rid]['is_active']) {
1345 $mask -= CRM_Core_Action::DISABLE;
1346 }
1347 else {
1348 $mask -= CRM_Core_Action::ENABLE;
1349 $mask -= CRM_Core_Action::DISABLE;
1350 }
cd056f13 1351 $mask = $mask & $permissionMask;
6a488035
TO
1352 }
1353
1354 // Give access to manage case link by copying to MAX_ACTION index temporarily, depending on case permission of user.
1355 if ($values[$rid]['case_id']) {
1356 // Borrowed logic from CRM_Case_Page_Tab
1357 $hasCaseAccess = FALSE;
1358 if (CRM_Core_Permission::check('access all cases and activities')) {
1359 $hasCaseAccess = TRUE;
1360 }
1361 else {
1362 $userCases = CRM_Case_BAO_Case::getCases(FALSE);
1363 if (array_key_exists($values[$rid]['case_id'], $userCases)) {
1364 $hasCaseAccess = TRUE;
1365 }
1366 }
1367
1368 if ($hasCaseAccess) {
1369 // give access by copying to MAX_ACTION temporarily, otherwise leave at NONE which won't display
1370 $links[CRM_Core_Action::MAX_ACTION] = $links[CRM_Core_Action::NONE];
52335bb5 1371 $links[CRM_Core_Action::MAX_ACTION]['name'] = ts('Manage Case #%1', [1 => $values[$rid]['case_id']]);
f89f2102 1372 $links[CRM_Core_Action::MAX_ACTION]['class'] = 'no-popup';
6a488035
TO
1373
1374 // Also make sure we have the right client cid since can get here from multiple relationship tabs.
1375 if ($values[$rid]['rtype'] == 'b_a') {
1376 $replace['clientid'] = $values[$rid]['cid'];
1377 }
13a3d214 1378 $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>';
6a488035
TO
1379 }
1380 }
1381
87dab4a4 1382 $values[$rid]['action'] = CRM_Core_Action::formLink(
1cfa04c4
EM
1383 $links,
1384 $mask,
87dab4a4
AH
1385 $replace,
1386 ts('more'),
1387 FALSE,
1388 'relationship.selector.row',
1389 'Relationship',
1390 $rid);
6a488035
TO
1391 unset($links[CRM_Core_Action::MAX_ACTION]);
1392 }
1393 }
1394
6a488035
TO
1395 return $values;
1396 }
1397 }
1398
1399 /**
7cf463d9
M
1400 * Get list of relationship type based on the target contact type.
1401 * Both directions of relationships are included if their labels are not the same.
6a488035 1402 *
77c5b619 1403 * @param string $targetContactType
7cf463d9 1404 * A valid contact type (may be Individual, Organization, Household).
6a488035 1405 *
a6c01b45 1406 * @return array
7cf463d9 1407 * array reference of all relationship types with context to current contact type.
6a488035 1408 */
69078420 1409 public static function getRelationType($targetContactType) {
52335bb5 1410 $relationshipType = [];
6a488035
TO
1411 $allRelationshipType = CRM_Core_PseudoConstant::relationshipType();
1412
1413 foreach ($allRelationshipType as $key => $type) {
7b1ed533 1414 if ($type['contact_type_b'] == $targetContactType || empty($type['contact_type_b'])) {
6a488035
TO
1415 $relationshipType[$key . '_a_b'] = $type['label_a_b'];
1416 }
7cf463d9
M
1417 if (($type['contact_type_a'] == $targetContactType || empty($type['contact_type_a']))
1418 && $type['label_a_b'] != $type['label_b_a']
1419 ) {
1420 $relationshipType[$key . '_b_a'] = $type['label_b_a'];
1421 }
6a488035
TO
1422 }
1423
1424 return $relationshipType;
1425 }
1426
1427 /**
100fef9d 1428 * Create / update / delete membership for related contacts.
6a488035
TO
1429 *
1430 * This function will create/update/delete membership for related
1431 * contact based on 1) contact have active membership 2) that
1432 * membership is is extedned by the same relationship type to that
1433 * of the existing relationship.
1434 *
5a4f6742
CW
1435 * @param int $contactId
1436 * contact id.
1437 * @param array $params
1438 * array of values submitted by POST.
1439 * @param array $ids
1440 * array of ids.
bfa4da96 1441 * @param \const|int $action which action called this function
6a488035 1442 *
dd244018 1443 * @param bool $active
6a488035 1444 *
bfa4da96 1445 * @throws \CRM_Core_Exception
0a2663fd 1446 * @throws \CiviCRM_API3_Exception
6a488035 1447 */
5c34e41f 1448 public static function relatedMemberships($contactId, $params, $ids, $action = CRM_Core_Action::ADD, $active = TRUE) {
6a488035 1449 // Check the end date and set the status of the relationship
decc60a0 1450 // accordingly.
6a488035 1451 $status = self::CURRENT;
52335bb5 1452 $targetContact = $targetContact = CRM_Utils_Array::value('contact_check', $params, []);
45089d88
CW
1453 $today = date('Ymd');
1454
1455 // If a relationship hasn't yet started, just return for now
1456 // TODO: handle edge-case of updating start_date of an existing relationship
1457 if (!empty($params['start_date'])) {
1458 $startDate = substr(CRM_Utils_Date::format($params['start_date']), 0, 8);
1459 if ($today < $startDate) {
1460 return;
1461 }
1462 }
6a488035
TO
1463
1464 if (!empty($params['end_date'])) {
45089d88 1465 $endDate = substr(CRM_Utils_Date::format($params['end_date']), 0, 8);
6a488035
TO
1466 if ($today > $endDate) {
1467 $status = self::PAST;
1468 }
1469 }
1470
45089d88
CW
1471 if (($action & CRM_Core_Action::ADD) && ($status & self::PAST)) {
1472 // If relationship is PAST and action is ADD, do nothing.
6a488035
TO
1473 return;
1474 }
1475
1476 $rel = explode('_', $params['relationship_type_id']);
1477
7f3647bc 1478 $relTypeId = $rel[0];
decc60a0
EM
1479 if (!empty($rel[1])) {
1480 $relDirection = "_{$rel[1]}_{$rel[2]}";
1481 }
1482 else {
1483 // this call is coming from somewhere where the direction was resolved early on (e.g an api call)
1484 // so we can assume _a_b
1485 $relDirection = "_a_b";
52335bb5 1486 $targetContact = [$params['contact_id_b'] => 1];
decc60a0 1487 }
04ad3598 1488
6a488035
TO
1489 if (($action & CRM_Core_Action::ADD) ||
1490 ($action & CRM_Core_Action::DELETE)
1491 ) {
1492 $contact = $contactId;
6a488035
TO
1493 }
1494 elseif ($action & CRM_Core_Action::UPDATE) {
6345c936 1495 $contact = (int) $ids['contact'];
52335bb5 1496 $targetContact = [$ids['contactTarget'] => 1];
6a488035
TO
1497 }
1498
1499 // Build the 'values' array for
1500 // 1. ContactA
1501 // 2. ContactB
1502 // This will allow us to check if either of the contacts in
1503 // relationship have active memberships.
1504
52335bb5 1505 $values = [];
6a488035
TO
1506
1507 // 1. ContactA
52335bb5 1508 $values[$contact] = [
6a488035
TO
1509 'relatedContacts' => $targetContact,
1510 'relationshipTypeId' => $relTypeId,
1511 'relationshipTypeDirection' => $relDirection,
52335bb5 1512 ];
6a488035
TO
1513 // 2. ContactB
1514 if (!empty($targetContact)) {
1515 foreach ($targetContact as $cid => $donCare) {
52335bb5 1516 $values[$cid] = [
1517 'relatedContacts' => [$contact => 1],
6a488035 1518 'relationshipTypeId' => $relTypeId,
52335bb5 1519 ];
6a488035 1520
52335bb5 1521 $relTypeParams = ['id' => $relTypeId];
1522 $relTypeValues = [];
6a488035
TO
1523 CRM_Contact_BAO_RelationshipType::retrieve($relTypeParams, $relTypeValues);
1524
1525 if (CRM_Utils_Array::value('name_a_b', $relTypeValues) == CRM_Utils_Array::value('name_b_a', $relTypeValues)) {
1526 $values[$cid]['relationshipTypeDirection'] = '_a_b';
1527 }
1528 else {
1529 $values[$cid]['relationshipTypeDirection'] = ($relDirection == '_a_b') ? '_b_a' : '_a_b';
1530 }
1531 }
1532 }
1533
73a949e4 1534 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant::membershipStatus());
bd655ee6 1535
6345c936 1536 $relationshipProcessor = new CRM_Member_Utils_RelationshipProcessor(array_keys($values), $active);
6a488035 1537 foreach ($values as $cid => $details) {
52335bb5 1538 $relatedContacts = array_keys(CRM_Utils_Array::value('relatedContacts', $details, []));
ee17a760 1539 $mainRelatedContactId = reset($relatedContacts);
6a488035 1540
6345c936 1541 foreach ($relationshipProcessor->getRelationshipMembershipsForContact((int) $cid) as $membershipId => $membershipValues) {
0a2663fd 1542 $membershipInherittedFromContactID = NULL;
1543 if (!empty($membershipValues['owner_membership_id'])) {
6345c936 1544 // @todo - $membership already has this now.
0a2663fd 1545 // Use get not getsingle so that we get e-notice noise but not a fatal is the membership has already been deleted.
1546 $inheritedFromMembership = civicrm_api3('Membership', 'get', ['id' => $membershipValues['owner_membership_id'], 'sequential' => 1])['values'][0];
1547 $membershipInherittedFromContactID = (int) $inheritedFromMembership['contact_id'];
1548 }
52335bb5 1549 $relTypeIds = [];
6a488035 1550 if ($action & CRM_Core_Action::DELETE) {
98fd6fc8 1551 // @todo don't return relTypeId here - but it seems to be used later in a cryptic way (hint cryptic is not a complement).
310c2031 1552 list($relTypeId, $isDeletable) = self::isInheritedMembershipInvalidated($membershipValues, $values, $cid);
98fd6fc8 1553 if ($isDeletable) {
73a949e4 1554 CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipValues['owner_membership_id'], $membershipValues['contact_id']);
6a488035
TO
1555 }
1556 continue;
1557 }
1558 if (($action & CRM_Core_Action::UPDATE) &&
1559 ($status & self::PAST) &&
1560 ($membershipValues['owner_membership_id'])
1561 ) {
1562 // If relationship is PAST and action is UPDATE
1563 // then delete the RELATED membership
1564 CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipValues['owner_membership_id'],
73a949e4 1565 $membershipValues['contact_id']
6a488035
TO
1566 );
1567 continue;
1568 }
1569
1570 // add / edit the memberships for related
1571 // contacts.
1572
6345c936 1573 // @todo - all these lines get 'relTypeDirs' - but it's already a key in the $membership array.
6a488035 1574 // Get the Membership Type Details.
563f6487 1575 $membershipType = CRM_Member_BAO_MembershipType::getMembershipType($membershipValues['membership_type_id']);
6a488035 1576 // Check if contact's relationship type exists in membership type
52335bb5 1577 $relTypeDirs = [];
a7488080 1578 if (!empty($membershipType['relationship_type_id'])) {
563f6487 1579 $relTypeIds = (array) $membershipType['relationship_type_id'];
6a488035 1580 }
a7488080 1581 if (!empty($membershipType['relationship_direction'])) {
563f6487 1582 $relDirections = (array) $membershipType['relationship_direction'];
6a488035
TO
1583 }
1584 foreach ($relTypeIds as $key => $value) {
1585 $relTypeDirs[] = $value . '_' . $relDirections[$key];
1586 }
1587 $relTypeDir = $details['relationshipTypeId'] . $details['relationshipTypeDirection'];
1588 if (in_array($relTypeDir, $relTypeDirs)) {
1589 // Check if relationship being created/updated is
1590 // similar to that of membership type's
1591 // relationship.
1592
1593 $membershipValues['owner_membership_id'] = $membershipId;
1594 unset($membershipValues['id']);
6a488035
TO
1595 unset($membershipValues['contact_id']);
1596 unset($membershipValues['membership_id']);
1597 foreach ($details['relatedContacts'] as $relatedContactId => $donCare) {
1598 $membershipValues['contact_id'] = $relatedContactId;
1599 if ($deceasedStatusId &&
1600 CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $relatedContactId, 'is_deceased')
1601 ) {
1602 $membershipValues['status_id'] = $deceasedStatusId;
1603 $membershipValues['skipStatusCal'] = TRUE;
1604 }
6a488035 1605
6345c936 1606 if (in_array($action, [CRM_Core_Action::UPDATE, CRM_Core_Action::ADD, CRM_Core_Action::ENABLE])) {
e72dea83 1607 //if updated relationship is already related to contact don't delete existing inherited membership
6345c936 1608 if (in_array((int) $relatedContactId, $membershipValues['inheriting_contact_ids'], TRUE)
1609 || $relatedContactId === $membershipValues['owner_contact_id']
1610 ) {
e72dea83 1611 continue;
1612 }
1613
1614 //delete the membership record for related
1615 //contact before creating new membership record.
1616 CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipId, $relatedContactId);
1617 }
00538ec6 1618 //skip status calculation for pay later memberships.
6345c936 1619 if ('Pending' === CRM_Core_PseudoConstant::getName('CRM_Member_BAO_Membership', 'status_id', $membershipValues['status_id'])) {
00538ec6
JP
1620 $membershipValues['skipStatusCal'] = TRUE;
1621 }
0a2663fd 1622 // As long as the membership itself was not created by inheritance from the same contact
1623 // that stands to inherit the membership we add an inherited membership.
1624 if ($membershipInherittedFromContactID !== (int) $membershipValues['contact_id']) {
1625 $membershipValues = self::addInheritedMembership($membershipValues);
1626 }
6a488035
TO
1627 }
1628 }
1629 elseif ($action & CRM_Core_Action::UPDATE) {
1630 // if action is update and updated relationship do
1631 // not match with the existing
1632 // membership=>relationship then we need to
e62adec9 1633 // change the status of the membership record to expired for
1634 // previous relationship -- CRM-12078.
1635 // CRM-16087 we need to pass ownerMembershipId to isRelatedMembershipExpired function
690c56c3 1636 if (empty($params['relationship_ids']) && !empty($params['id'])) {
52335bb5 1637 $relIds = [$params['id']];
690c56c3 1638 }
1639 else {
9c1bc317 1640 $relIds = $params['relationship_ids'] ?? NULL;
690c56c3 1641 }
e62adec9 1642 if (self::isRelatedMembershipExpired($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId,
52335bb5 1643 $relIds) && !empty($membershipValues['owner_membership_id']
1644 ) && !empty($values[$mainRelatedContactId]['memberships'][$membershipValues['owner_membership_id']])) {
e62adec9 1645 $membershipValues['status_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', 'Expired', 'id', 'label');
1646 $type = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $membershipValues['membership_type_id'], 'name', 'id');
1647 CRM_Member_BAO_Membership::add($membershipValues);
1836ab9e 1648 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');
6a488035
TO
1649 }
1650 }
1651 }
1652 }
1653 }
1654
1655 /**
e62adec9 1656 * Helper function to check whether the membership is expired or not.
6616f7c1
EM
1657 *
1658 * Function takes a list of related membership types and if it is not also passed a
e62adec9 1659 * relationship ID of that types evaluates whether the membership status should be changed to expired.
6616f7c1
EM
1660 *
1661 * @param array $membershipTypeRelationshipTypeIDs
1662 * Relation type IDs related to the given membership type.
1663 * @param int $contactId
1664 * @param int $mainRelatedContactId
1665 * @param int $relTypeId
1666 * @param array $relIds
1667 *
1668 * @return bool
6a488035 1669 */
e62adec9 1670 public static function isRelatedMembershipExpired($membershipTypeRelationshipTypeIDs, $contactId, $mainRelatedContactId, $relTypeId, $relIds) {
6616f7c1 1671 if (empty($membershipTypeRelationshipTypeIDs) || in_array($relTypeId, $membershipTypeRelationshipTypeIDs)) {
eec8d770 1672 return FALSE;
6a488035
TO
1673 }
1674
1675 if (empty($relIds)) {
1676 return FALSE;
1677 }
1678
52335bb5 1679 $relParamas = [
1680 1 => [$contactId, 'Integer'],
1681 2 => [$mainRelatedContactId, 'Integer'],
1682 ];
6a488035
TO
1683
1684 if ($contactId == $mainRelatedContactId) {
6616f7c1
EM
1685 $recordsFound = (int) CRM_Core_DAO::singleValueQuery("SELECT COUNT(*) FROM civicrm_relationship WHERE relationship_type_id IN ( " . implode(',', $membershipTypeRelationshipTypeIDs) . " ) AND
1686contact_id_a IN ( %1 ) OR contact_id_b IN ( %1 ) AND id IN (" . implode(',', $relIds) . ")", $relParamas);
6a488035
TO
1687 if ($recordsFound) {
1688 return FALSE;
1689 }
1690 return TRUE;
1691 }
1692
6616f7c1 1693 $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);
6a488035
TO
1694
1695 if ($recordsFound) {
1696 return FALSE;
1697 }
1698
1699 return TRUE;
1700 }
1701
1702 /**
fe482240 1703 * Get Current Employer for Contact.
6a488035 1704 *
3fd42bb5 1705 * @param array $contactIds
77c5b619 1706 * Contact Ids.
6a488035 1707 *
a6c01b45
CW
1708 * @return array
1709 * array of the current employer
6a488035 1710 */
00be9182 1711 public static function getCurrentEmployer($contactIds) {
6a488035
TO
1712 $contacts = implode(',', $contactIds);
1713
1714 $query = "
1715SELECT organization_name, id, employer_id
1716FROM civicrm_contact
1717WHERE id IN ( {$contacts} )
1718";
1719
33621c4f 1720 $dao = CRM_Core_DAO::executeQuery($query);
52335bb5 1721 $currentEmployer = [];
6a488035
TO
1722 while ($dao->fetch()) {
1723 $currentEmployer[$dao->id]['org_id'] = $dao->employer_id;
1724 $currentEmployer[$dao->id]['org_name'] = $dao->organization_name;
1725 }
1726
1727 return $currentEmployer;
1728 }
1729
7f3647bc 1730 /**
fe482240 1731 * Function to return list of permissioned contacts for a given contact and relationship type.
7f3647bc 1732 *
5a4f6742
CW
1733 * @param int $contactID
1734 * contact id whose permissioned contacts are to be found.
b0076fe6 1735 * @param int $relTypeId
5a4f6742
CW
1736 * one or more relationship type id's.
1737 * @param string $name
33260076 1738 * @param string $contactType
7f3647bc 1739 *
a6c01b45 1740 * @return array
16b10e64 1741 * Array of contacts
7f3647bc 1742 */
33260076 1743 public static function getPermissionedContacts($contactID, $relTypeId = NULL, $name = NULL, $contactType = NULL) {
52335bb5 1744 $contacts = [];
1745 $args = [1 => [$contactID, 'Integer']];
33260076 1746 $relationshipTypeClause = $contactTypeClause = '';
51e89def 1747
6a488035 1748 if ($relTypeId) {
b0076fe6
EM
1749 // @todo relTypeId is only ever passed in as an int. Change this to reflect that -
1750 // probably being overly conservative by not doing so but working on stable release.
1751 $relationshipTypeClause = 'AND cr.relationship_type_id IN (%2) ';
52335bb5 1752 $args[2] = [$relTypeId, 'String'];
b0076fe6 1753 }
33260076 1754
1755 if ($contactType) {
1756 $contactTypeClause = ' AND cr.relationship_type_id = crt.id AND crt.contact_type_b = %3 ';
52335bb5 1757 $args[3] = [$contactType, 'String'];
33260076 1758 }
1759
4779abb3 1760 $query = "
6a488035 1761SELECT cc.id as id, cc.sort_name as name
33260076 1762FROM civicrm_relationship cr, civicrm_contact cc, civicrm_relationship_type crt
49f8272d 1763WHERE
51e89def 1764cr.contact_id_a = %1 AND
51e89def 1765cr.is_permission_a_b = 1 AND
6a488035
TO
1766IF(cr.end_date IS NULL, 1, (DATEDIFF( CURDATE( ), cr.end_date ) <= 0)) AND
1767cr.is_active = 1 AND
7ecf6275 1768cc.id = cr.contact_id_b AND
b0076fe6
EM
1769cc.is_deleted = 0
1770$relationshipTypeClause
33260076 1771$contactTypeClause
b0076fe6 1772";
51e89def 1773
4779abb3 1774 if (!empty($name)) {
1775 $name = CRM_Utils_Type::escape($name, 'String');
1776 $query .= "
49f8272d 1777AND cc.sort_name LIKE '%$name%'";
4779abb3 1778 }
6a488035 1779
4779abb3 1780 $dao = CRM_Core_DAO::executeQuery($query, $args);
1781 while ($dao->fetch()) {
52335bb5 1782 $contacts[$dao->id] = [
4779abb3 1783 'name' => $dao->name,
1784 'value' => $dao->id,
52335bb5 1785 ];
4779abb3 1786 }
b0076fe6 1787
51e89def 1788 return $contacts;
6a488035
TO
1789 }
1790
6a488035 1791 /**
fe482240 1792 * Merge relationships from otherContact to mainContact.
bfa4da96 1793 *
6a488035
TO
1794 * Called during contact merge operation
1795 *
77c5b619
TO
1796 * @param int $mainId
1797 * Contact id of main contact record.
1798 * @param int $otherId
1799 * Contact id of record which is going to merge.
1800 * @param array $sqls
1801 * (reference) array of sql statements to append to.
6a488035
TO
1802 *
1803 * @see CRM_Dedupe_Merger::cpTables()
6a488035 1804 */
00be9182 1805 public static function mergeRelationships($mainId, $otherId, &$sqls) {
6a488035
TO
1806 // Delete circular relationships
1807 $sqls[] = "DELETE FROM civicrm_relationship
6ce3ea65
JJ
1808 WHERE (contact_id_a = $mainId AND contact_id_b = $otherId AND case_id IS NULL)
1809 OR (contact_id_b = $mainId AND contact_id_a = $otherId AND case_id IS NULL)";
6a488035
TO
1810
1811 // Delete relationship from other contact if main contact already has that relationship
1812 $sqls[] = "DELETE r2
1813 FROM civicrm_relationship r1, civicrm_relationship r2
1814 WHERE r1.relationship_type_id = r2.relationship_type_id
1815 AND r1.id <> r2.id
6ce3ea65 1816 AND r1.case_id IS NULL AND r2.case_id IS NULL
6a488035
TO
1817 AND (
1818 r1.contact_id_a = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_b = r2.contact_id_b
1819 OR r1.contact_id_b = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_a = r2.contact_id_a
1820 OR (
1821 (r1.contact_id_a = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_b = r2.contact_id_a
1822 OR r1.contact_id_b = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_a = r2.contact_id_b)
1823 AND r1.relationship_type_id IN (SELECT id FROM civicrm_relationship_type WHERE name_b_a = name_a_b)
1824 )
1825 )";
1826
1827 // Move relationships
1828 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_a = $mainId WHERE contact_id_a = $otherId";
1829 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_b = $mainId WHERE contact_id_b = $otherId";
1830
1831 // Move current employer id (name will get updated later)
1832 $sqls[] = "UPDATE civicrm_contact SET employer_id = $mainId WHERE employer_id = $otherId";
1833 }
1834
1835 /**
1836 * Set 'is_valid' field to false for all relationships whose end date is in the past, ie. are expired.
1837 *
72b3a70c
CW
1838 * @return bool
1839 * True on success, false if error is encountered.
f42bcfb1 1840 * @throws \CiviCRM_API3_Exception
6a488035 1841 */
00be9182 1842 public static function disableExpiredRelationships() {
6a488035
TO
1843 $query = "SELECT id FROM civicrm_relationship WHERE is_active = 1 AND end_date < CURDATE()";
1844
1845 $dao = CRM_Core_DAO::executeQuery($query);
1846 while ($dao->fetch()) {
1847 $result = CRM_Contact_BAO_Relationship::setIsActive($dao->id, FALSE);
1848 // Result will be NULL if error occurred. We abort early if error detected.
1849 if ($result == NULL) {
1850 return FALSE;
1851 }
1852 }
1853 return TRUE;
1854 }
c9c41397 1855
1856 /**
fe482240 1857 * Function filters the query by possible relationships for the membership type.
98a06ae0 1858 *
c9c41397 1859 * It is intended to be called when constructing queries for the api (reciprocal & non-reciprocal)
1860 * and to add clauses to limit the return to those relationships which COULD inherit a membership type
1861 * (as opposed to those who inherit a particular membership
1862 *
77c5b619
TO
1863 * @param array $params
1864 * Api input array.
5e21e0f3 1865 * @param string $direction
77b97be7 1866 *
c301f76e 1867 * @return array|void
52335bb5 1868 * @throws \CiviCRM_API3_Exception
c9c41397 1869 */
00be9182 1870 public static function membershipTypeToRelationshipTypes(&$params, $direction = NULL) {
52335bb5 1871 $membershipType = civicrm_api3('membership_type', 'getsingle', [
353ffa53
TO
1872 'id' => $params['membership_type_id'],
1873 'return' => 'relationship_type_id, relationship_direction',
52335bb5 1874 ]);
c9c41397 1875 $relationshipTypes = $membershipType['relationship_type_id'];
22e263ad 1876 if (empty($relationshipTypes)) {
c301f76e 1877 return NULL;
f201289d 1878 }
c9c41397 1879 // if we don't have any contact data we can only filter on type
22e263ad 1880 if (empty($params['contact_id']) && empty($params['contact_id_a']) && empty($params['contact_id_a'])) {
52335bb5 1881 $params['relationship_type_id'] = ['IN' => $relationshipTypes];
c301f76e 1882 return NULL;
c9c41397 1883 }
1884 else {
1a9b2ee8 1885 $relationshipDirections = (array) $membershipType['relationship_direction'];
c9c41397 1886 // if we have contact_id_a OR contact_id_b we can make a call here
1887 // if we have contact??
1888 foreach ($relationshipDirections as $index => $mtdirection) {
7f3647bc 1889 if (isset($params['contact_id_a']) && $mtdirection == 'a_b' || $direction == 'a_b') {
c9c41397 1890 $types[] = $relationshipTypes[$index];
1891 }
7f3647bc 1892 if (isset($params['contact_id_b']) && $mtdirection == 'b_a' || $direction == 'b_a') {
c9c41397 1893 $types[] = $relationshipTypes[$index];
1894 }
1895 }
22e263ad 1896 if (!empty($types)) {
52335bb5 1897 $params['relationship_type_id'] = ['IN' => $types];
c9c41397 1898 }
7f3647bc 1899 elseif (!empty($clauses)) {
c9c41397 1900 return explode(' OR ', $clauses);
1901 }
92e4c2a5 1902 else {
c9c41397 1903 // effectively setting it to return no results
1904 $params['relationship_type_id'] = 0;
1905 }
1906 }
1907 }
40458f6c 1908
40458f6c 1909 /**
98a06ae0 1910 * Wrapper for contact relationship selector.
40458f6c 1911 *
77c5b619
TO
1912 * @param array $params
1913 * Associated array for params record id.
40458f6c 1914 *
a6c01b45
CW
1915 * @return array
1916 * associated array of contact relationships
52335bb5 1917 * @throws \Exception
40458f6c 1918 */
1919 public static function getContactRelationshipSelector(&$params) {
1920 // format the params
7f3647bc 1921 $params['offset'] = ($params['page'] - 1) * $params['rp'];
9c1bc317 1922 $params['sort'] = $params['sortBy'] ?? NULL;
40458f6c 1923
1924 if ($params['context'] == 'past') {
1925 $relationshipStatus = CRM_Contact_BAO_Relationship::INACTIVE;
1926 }
62e6afce 1927 elseif ($params['context'] == 'all') {
6c292184
TM
1928 $relationshipStatus = CRM_Contact_BAO_Relationship::ALL;
1929 }
40458f6c 1930 else {
1931 $relationshipStatus = CRM_Contact_BAO_Relationship::CURRENT;
1932 }
1933
1934 // check logged in user for permission
1935 $page = new CRM_Core_Page();
1936 CRM_Contact_Page_View::checkUserPermission($page, $params['contact_id']);
52335bb5 1937 $permissions = [$page->_permission];
40458f6c 1938 if ($page->_permission == CRM_Core_Permission::EDIT) {
1939 $permissions[] = CRM_Core_Permission::DELETE;
1940 }
1941 $mask = CRM_Core_Action::mask($permissions);
1942
a93664c8 1943 $permissionedContacts = TRUE;
d0592c3d 1944 if ($params['context'] != 'user') {
1945 $links = CRM_Contact_Page_View_Relationship::links();
d0592c3d 1946 }
1947 else {
1948 $links = CRM_Contact_Page_View_UserDashBoard::links();
d0592c3d 1949 $mask = NULL;
1950 }
40458f6c 1951 // get contact relationships
1952 $relationships = CRM_Contact_BAO_Relationship::getRelationship($params['contact_id'],
1953 $relationshipStatus,
1954 $params['rp'], 0, 0,
d0592c3d 1955 $links, $mask,
1956 $permissionedContacts,
644587aa 1957 $params, TRUE
40458f6c 1958 );
1959
52335bb5 1960 $contactRelationships = [];
644587aa
SL
1961 $params['total'] = $relationships['total_relationships'];
1962 unset($relationships['total_relationships']);
40458f6c 1963 if (!empty($relationships)) {
40458f6c 1964
1250f3d8
AH
1965 $displayName = CRM_Contact_BAO_Contact::displayName($params['contact_id']);
1966
40458f6c 1967 // format params
1968 foreach ($relationships as $relationshipId => $values) {
52335bb5 1969 $relationship = [];
7d12de7f 1970
febb6506 1971 $relationship['DT_RowId'] = $values['id'];
7d12de7f
JL
1972 $relationship['DT_RowClass'] = 'crm-entity';
1973 if ($values['is_active'] == 0) {
1974 $relationship['DT_RowClass'] .= ' disabled';
1975 }
1976
52335bb5 1977 $relationship['DT_RowAttr'] = [];
febb6506
JL
1978 $relationship['DT_RowAttr']['data-entity'] = 'relationship';
1979 $relationship['DT_RowAttr']['data-id'] = $values['id'];
7d12de7f 1980
20be4ac3
BS
1981 //Add image icon for related contacts: CRM-14919; CRM-19668
1982 $contactType = (!empty($values['contact_sub_type'])) ? $values['contact_sub_type'] : $values['contact_type'];
1983 $icon = CRM_Contact_BAO_Contact_Utils::getImage($contactType,
67e4fb51
N
1984 FALSE,
1985 $values['cid']
1986 );
7d12de7f 1987 $relationship['sort_name'] = $icon . ' ' . CRM_Utils_System::href(
7f3647bc
TO
1988 $values['name'],
1989 'civicrm/contact/view',
1990 "reset=1&cid={$values['cid']}");
40458f6c 1991
0a61e567 1992 $relationship['relation'] = CRM_Utils_Array::value('case', $values, '') . CRM_Utils_System::href(
52335bb5 1993 $values['relation'],
1994 'civicrm/contact/view/rel',
1995 "action=view&reset=1&cid={$values['cid']}&id={$values['id']}&rtype={$values['rtype']}");
40458f6c 1996
66229fd5
AS
1997 if (!empty($values['description'])) {
1998 $relationship['relation'] .= "<p class='description'>{$values['description']}</p>";
1999 }
2000
d0592c3d 2001 if ($params['context'] == 'current') {
fee0416f
AH
2002 $smarty = CRM_Core_Smarty::singleton();
2003
2004 $contactCombos = [
2005 [
2006 'permContact' => $params['contact_id'],
2007 'permDisplayName' => $displayName,
2008 'otherContact' => $values['cid'],
2009 'otherDisplayName' => $values['display_name'],
2010 'columnKey' => 'sort_name',
2011 ],
2012 [
2013 'permContact' => $values['cid'],
2014 'permDisplayName' => $values['display_name'],
2015 'otherContact' => $params['contact_id'],
2016 'otherDisplayName' => $displayName,
2017 'columnKey' => 'relation',
2018 ],
2019 ];
2020
2021 foreach ($contactCombos as $combo) {
2022 foreach ([CRM_Contact_BAO_Relationship::EDIT, CRM_Contact_BAO_Relationship::VIEW] as $permType) {
2023 $smarty->assign('permType', $permType);
2024 if (($combo['permContact'] == $values['contact_id_a'] and $values['is_permission_a_b'] == $permType)
2025 || ($combo['permContact'] == $values['contact_id_b'] and $values['is_permission_b_a'] == $permType)
2026 ) {
2027 $smarty->assign('permDisplayName', $combo['permDisplayName']);
2028 $smarty->assign('otherDisplayName', $combo['otherDisplayName']);
2029 $relationship[$combo['columnKey']] .= $smarty->fetch('CRM/Contact/Page/View/RelationshipPerm.tpl');
2030 }
2031 }
f871c3a9 2032 }
40458f6c 2033 }
2034
7d12de7f
JL
2035 $relationship['start_date'] = CRM_Utils_Date::customFormat($values['start_date']);
2036 $relationship['end_date'] = CRM_Utils_Date::customFormat($values['end_date']);
2037 $relationship['city'] = $values['city'];
2038 $relationship['state'] = $values['state'];
2039 $relationship['email'] = $values['email'];
2040 $relationship['phone'] = $values['phone'];
2041 $relationship['links'] = $values['action'];
2042
2043 array_push($contactRelationships, $relationship);
40458f6c 2044 }
2045 }
7d12de7f 2046
16b745b0
MWMC
2047 $columnHeaders = self::getColumnHeaders();
2048 $selector = NULL;
2049 CRM_Utils_Hook::searchColumns('relationship.rows', $columnHeaders, $contactRelationships, $selector);
2050
52335bb5 2051 $relationshipsDT = [];
7d12de7f
JL
2052 $relationshipsDT['data'] = $contactRelationships;
2053 $relationshipsDT['recordsTotal'] = $params['total'];
2054 $relationshipsDT['recordsFiltered'] = $params['total'];
2055
2056 return $relationshipsDT;
40458f6c 2057 }
2058
16b745b0
MWMC
2059 /**
2060 * @return array
2061 */
2062 public static function getColumnHeaders() {
2063 return [
2064 'relation' => [
2065 'name' => ts('Relationship'),
2066 'sort' => 'relation',
2067 'direction' => CRM_Utils_Sort::ASCENDING,
2068 ],
2069 'sort_name' => [
2070 'name' => '',
2071 'sort' => 'sort_name',
2072 'direction' => CRM_Utils_Sort::ASCENDING,
2073 ],
2074 'start_date' => [
2075 'name' => ts('Start'),
2076 'sort' => 'start_date',
2077 'direction' => CRM_Utils_Sort::DONTCARE,
2078 ],
2079 'end_date' => [
2080 'name' => ts('End'),
2081 'sort' => 'end_date',
2082 'direction' => CRM_Utils_Sort::DONTCARE,
2083 ],
2084 'city' => [
2085 'name' => ts('City'),
2086 'sort' => 'city',
2087 'direction' => CRM_Utils_Sort::DONTCARE,
2088 ],
2089 'state' => [
2090 'name' => ts('State/Prov'),
2091 'sort' => 'state',
2092 'direction' => CRM_Utils_Sort::DONTCARE,
2093 ],
2094 'email' => [
2095 'name' => ts('Email'),
2096 'sort' => 'email',
2097 'direction' => CRM_Utils_Sort::DONTCARE,
2098 ],
2099 'phone' => [
2100 'name' => ts('Phone'),
2101 'sort' => 'phone',
2102 'direction' => CRM_Utils_Sort::DONTCARE,
2103 ],
2104 'links' => [
2105 'name' => '',
2106 'sort' => 'links',
2107 'direction' => CRM_Utils_Sort::DONTCARE,
2108 ],
2109 ];
2110 }
2111
89e45979
MD
2112 /**
2113 * @inheritdoc
2114 */
52335bb5 2115 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1ac9bb56
CW
2116 // Quickform-specific format, for use when editing relationship type options in a popup from the contact relationship form
2117 if ($fieldName === 'relationship_type_id' && !empty($props['is_form'])) {
2118 return self::getContactRelationshipType(
2119 $props['contact_id'] ?? NULL,
2120 $props['relationship_direction'] ?? 'a_b',
2121 $props['relationship_id'] ?? NULL,
2122 $props['contact_type'] ?? NULL
2123 );
89e45979
MD
2124 }
2125
2126 return parent::buildOptions($fieldName, $context, $props);
2127 }
2128
df0c42cc
JP
2129 /**
2130 * Process the params from api, form and check if current
2131 * employer should be set or unset.
2132 *
2133 * @param array $params
2134 * @param int $relationshipId
e97c66ff 2135 * @param int|null $updatedRelTypeID
df0c42cc
JP
2136 *
2137 * @return bool
2138 * TRUE if current employer needs to be cleared.
f42bcfb1 2139 * @throws \CiviCRM_API3_Exception
df0c42cc
JP
2140 */
2141 public static function isCurrentEmployerNeedingToBeCleared($params, $relationshipId, $updatedRelTypeID = NULL) {
f42bcfb1 2142 $existingTypeID = (int) CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Relationship', $relationshipId, 'relationship_type_id');
df0c42cc 2143 $updatedRelTypeID = $updatedRelTypeID ? $updatedRelTypeID : $existingTypeID;
0c578c02 2144 $currentEmployerID = (int) civicrm_api3('Contact', 'getvalue', ['return' => 'current_employer_id', 'id' => $params['contact_id_a']]);
df0c42cc 2145
0c578c02 2146 if ($currentEmployerID !== (int) $params['contact_id_b'] || !self::isRelationshipTypeCurrentEmployer($existingTypeID)) {
df0c42cc
JP
2147 return FALSE;
2148 }
2149 //Clear employer if relationship is expired.
2150 if (!empty($params['end_date']) && strtotime($params['end_date']) < time()) {
2151 return TRUE;
2152 }
2153 //current employer checkbox is disabled on the form.
2154 //inactive or relationship type(employer of) is updated.
2155 if ((isset($params['is_current_employer']) && empty($params['is_current_employer']))
2156 || ((isset($params['is_active']) && empty($params['is_active'])))
2157 || $existingTypeID != $updatedRelTypeID) {
0c578c02
MD
2158 // If there are no other active employer relationships between the same 2 contacts...
2159 if (!civicrm_api3('Relationship', 'getcount', [
2160 'is_active' => 1,
2161 'relationship_type_id' => $existingTypeID,
2162 'id' => ['<>' => $params['id']],
2163 'contact_id_a' => $params['contact_id_a'],
2164 'contact_id_b' => $params['contact_id_b'],
2165 ])) {
2166 return TRUE;
2167 }
df0c42cc
JP
2168 }
2169
2170 return FALSE;
2171 }
2172
f42bcfb1
MD
2173 /**
2174 * Is this a current employer relationship type.
2175 *
2176 * @todo - this could use cached pseudoconstant lookups.
2177 *
2178 * @param int $existingTypeID
2179 *
2180 * @return bool
2181 */
2182 private static function isRelationshipTypeCurrentEmployer(int $existingTypeID): bool {
2183 $isCurrentEmployerRelationshipType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', $existingTypeID, 'name_b_a') === 'Employer of';
2184 return $isCurrentEmployerRelationshipType;
2185 }
2186
98fd6fc8 2187 /**
2188 * Is the inherited relationship invalidated by this relationship change.
2189 *
3fd42bb5 2190 * @param array $membershipValues
98fd6fc8 2191 * @param array $values
2192 * @param int $cid
98fd6fc8 2193 *
2194 * @return array
eb151aab 2195 * @throws \CiviCRM_API3_Exception
98fd6fc8 2196 */
310c2031 2197 private static function isInheritedMembershipInvalidated($membershipValues, array $values, $cid): array {
2198 // @todo most of this can go - it's just the weird historical returning of $relTypeId that it does.
2199 // now we have caching the parent fn can just call CRM_Member_BAO_MembershipType::getMembershipType
eb151aab 2200 $membershipType = CRM_Member_BAO_MembershipType::getMembershipType($membershipValues['membership_type_id']);
2201 $relTypeIds = $membershipType['relationship_type_id'];
310c2031 2202 $membershipInheritedFrom = $membershipValues['owner_membership_id'] ?? NULL;
2203 if (!$membershipInheritedFrom || !in_array($values[$cid]['relationshipTypeId'], $relTypeIds)) {
eb151aab 2204 return [implode(',', $relTypeIds), FALSE];
2205 }
2206 //CRM-16300 check if owner membership exist for related membership
310c2031 2207 return [implode(',', $relTypeIds), !self::isContactHasValidRelationshipToInheritMembershipType((int) $cid, (int) $membershipValues['membership_type_id'], (int) $membershipValues['owner_membership_id'])];
2208 }
2209
2210 /**
2211 * Is there a valid relationship confering this membership type on this contact.
2212 *
2213 * @param int $contactID
2214 * @param int $membershipTypeID
2215 * @param int $parentMembershipID
2216 * Id of the membership being inherited.
2217 *
2218 * @return bool
2219 *
2220 * @throws \CiviCRM_API3_Exception
2221 */
2222 private static function isContactHasValidRelationshipToInheritMembershipType(int $contactID, int $membershipTypeID, int $parentMembershipID): bool {
2223 $membershipType = CRM_Member_BAO_MembershipType::getMembershipType($membershipTypeID);
2224 $existingRelationships = civicrm_api3('Relationship', 'get', [
2225 'contact_id_a' => $contactID,
2226 'contact_id_b' => $contactID,
2227 'relationship_type_id' => ['IN' => $membershipType['relationship_type_id']],
2228 'options' => ['or' => [['contact_id_a', 'contact_id_b']], 'limit' => 0],
2229 'is_active' => 1,
2230 ])['values'];
2231
2232 if (empty($existingRelationships)) {
2233 return FALSE;
2234 }
2235
2236 $membershipInheritedFromContactID = (int) civicrm_api3('Membership', 'getvalue', ['return' => 'contact_id', 'id' => $parentMembershipID]);
2237 // I don't think the api can correctly filter by start & end because of handling for NULL
2238 // so we filter them out here.
2239 foreach ($existingRelationships as $index => $existingRelationship) {
2240 $otherContactID = (int) (($contactID === (int) $existingRelationship['contact_id_a']) ? $existingRelationship['contact_id_b'] : $existingRelationship['contact_id_a']);
2241 if (!empty($existingRelationship['start_date'])
2242 && strtotime($existingRelationship['start_date']) > time()
2243 ) {
2244 unset($existingRelationships[$index]);
2245 continue;
2246 }
2247 if (!empty($existingRelationship['end_date'])
2248 && strtotime($existingRelationship['end_date']) < time()
2249 ) {
2250 unset($existingRelationships[$index]);
2251 continue;
2252 }
2253 if ($membershipInheritedFromContactID !== $otherContactID
2254 ) {
2255 // This is a weird scenario - they have been inheriting the membership
2256 // just not from this relationship - and some max_related calcs etc would be required
2257 // - ie because they are no longer inheriting from this relationship's 'allowance'
2258 // and now are inheriting from the other relationships 'allowance', if it has not
2259 // already hit 'max_related'
2260 // For now ignore here & hope it's handled elsewhere - at least that's consistent with
2261 // before this function was added.
2262 unset($existingRelationships[$index]);
2263 continue;
2264 }
2265 if (!civicrm_api3('Contact', 'getcount', ['id' => $otherContactID, 'is_deleted' => 0])) {
2266 // Can't inherit from a deleted contact.
2267 unset($existingRelationships[$index]);
2268 continue;
2269 }
2270 }
2271 return !empty($existingRelationships);
98fd6fc8 2272 }
2273
52494648 2274 /**
2275 * Add an inherited membership, provided max related not exceeded.
2276 *
2277 * @param array $membershipValues
2278 *
2279 * @return array
2280 * @throws \CRM_Core_Exception
2281 */
2282 protected static function addInheritedMembership($membershipValues) {
2283 $query = "
2284SELECT count(*)
2285 FROM civicrm_membership
2286 LEFT JOIN civicrm_membership_status ON (civicrm_membership_status.id = civicrm_membership.status_id)
2287 WHERE membership_type_id = {$membershipValues['membership_type_id']}
2288 AND owner_membership_id = {$membershipValues['owner_membership_id']}
2289 AND is_current_member = 1";
2290 $result = CRM_Core_DAO::singleValueQuery($query);
2291 if ($result < CRM_Utils_Array::value('max_related', $membershipValues, PHP_INT_MAX)) {
3566c1c3
JJ
2292 // Convert custom_xx_id fields to custom_xx
2293 // See https://lab.civicrm.org/dev/membership/-/issues/37
2294 // This makes sure the value is copied and not the looked up value.
2295 // Which is the case when the custom field is a contact reference field.
2296 // The custom_xx contains the display name of the contact, instead of the contact id.
2297 // The contact id is then available in custom_xx_id.
2298 foreach ($membershipValues as $field => $value) {
2299 if (stripos($field, 'custom_') !== 0) {
2300 // No a custom field
2301 continue;
2302 }
2303 $custom_id = substr($field, 7);
2304 if (substr($custom_id, -3) === '_id') {
2305 $custom_id = substr($custom_id, 0, -3);
2306 unset($membershipValues[$field]);
2307 $membershipValues['custom_' . $custom_id] = $value;
2308 }
2309 }
2310
058180bb 2311 civicrm_api3('Membership', 'create', $membershipValues);
52494648 2312 }
2313 return $membershipValues;
2314 }
2315
6a488035 2316}