define format at one place
[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
f21e34df 244 $relationshipTypes = $params['relationship_type_id'] ?? '';
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,
57315c8d
EM
1068 civicrm_relationship.created_date as created_date,
1069 civicrm_relationship.modified_date as modified_date,
6a488035
TO
1070 civicrm_relationship.description as description,
1071 civicrm_relationship.is_active as is_active,
1072 civicrm_relationship.is_permission_a_b as is_permission_a_b,
1073 civicrm_relationship.is_permission_b_a as is_permission_b_a,
1074 civicrm_relationship.case_id as case_id';
1075
923dfabb 1076 if ($direction === 'a_b') {
6a488035 1077 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
c6c691a5 1078 civicrm_relationship_type.label_b_a as relation ';
6a488035
TO
1079 }
1080 else {
1081 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
c6c691a5 1082 civicrm_relationship_type.label_a_b as relation ';
6a488035
TO
1083 }
1084 }
1085
923dfabb 1086 $from = '
6a488035
TO
1087 FROM civicrm_relationship
1088INNER JOIN civicrm_relationship_type ON ( civicrm_relationship.relationship_type_id = civicrm_relationship_type.id )
923dfabb 1089INNER JOIN civicrm_contact ';
1090 if ($direction === 'a_b') {
6a488035
TO
1091 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_a ) ';
1092 }
1093 else {
1094 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_b ) ';
1095 }
b7d19957
CR
1096
1097 if (!$count) {
923dfabb 1098 $from .= '
6a488035
TO
1099LEFT JOIN civicrm_address ON (civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1)
1100LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
1101LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id AND civicrm_email.is_primary = 1)
1102LEFT JOIN civicrm_state_province ON (civicrm_address.state_province_id = civicrm_state_province.id)
1103LEFT JOIN civicrm_country ON (civicrm_address.country_id = civicrm_country.id)
923dfabb 1104';
b7d19957
CR
1105 }
1106
6a488035
TO
1107 $where = 'WHERE ( 1 )';
1108 if ($contactId) {
923dfabb 1109 if ($direction === 'a_b') {
6a488035
TO
1110 $where .= ' AND civicrm_relationship.contact_id_b = ' . CRM_Utils_Type::escape($contactId, 'Positive');
1111 }
1112 else {
075fa74e 1113 $where .= ' AND civicrm_relationship.contact_id_a = ' . CRM_Utils_Type::escape($contactId, 'Positive') . '
1114 AND civicrm_relationship.contact_id_a != civicrm_relationship.contact_id_b ';
6a488035
TO
1115 }
1116 }
1117 if ($relationshipId) {
1118 $where .= ' AND civicrm_relationship.id = ' . CRM_Utils_Type::escape($relationshipId, 'Positive');
1119 }
1120
1121 $date = date('Y-m-d');
1122 if ($status == self::PAST) {
1123 //this case for showing past relationship
1124 $where .= ' AND civicrm_relationship.is_active = 1 ';
1125 $where .= " AND civicrm_relationship.end_date < '" . $date . "'";
1126 }
1127 elseif ($status == self::DISABLED) {
1128 // this case for showing disabled relationship
1129 $where .= ' AND civicrm_relationship.is_active = 0 ';
1130 }
1131 elseif ($status == self::CURRENT) {
1132 //this case for showing current relationship
1133 $where .= ' AND civicrm_relationship.is_active = 1 ';
1134 $where .= " AND (civicrm_relationship.end_date >= '" . $date . "' OR civicrm_relationship.end_date IS NULL) ";
1135 }
1136 elseif ($status == self::INACTIVE) {
1137 //this case for showing inactive relationships
1138 $where .= " AND (civicrm_relationship.end_date < '" . $date . "'";
1139 $where .= ' OR civicrm_relationship.is_active = 0 )';
1140 }
1141
1142 // CRM-6181
1143 $where .= ' AND civicrm_contact.is_deleted = 0';
22e263ad 1144 if (!empty($params['membership_type_id']) && empty($params['relationship_type_id'])) {
c9c41397 1145 $where .= self::membershipTypeToRelationshipTypes($params, $direction);
1146 }
22e263ad
TO
1147 if (!empty($params['relationship_type_id'])) {
1148 if (is_array($params['relationship_type_id'])) {
7f3647bc 1149 $where .= " AND " . CRM_Core_DAO::createSQLFilter('relationship_type_id', $params['relationship_type_id'], 'Integer');
75638074 1150 }
1151 else {
1152 $where .= ' AND relationship_type_id = ' . CRM_Utils_Type::escape($params['relationship_type_id'], 'Positive');
1153 }
1154 }
923dfabb 1155 if ($direction === 'a_b') {
6a488035
TO
1156 $where .= ' ) UNION ';
1157 }
1158 else {
1159 $where .= ' ) ';
1160 }
1161
52335bb5 1162 return [$select, $from, $where];
6a488035
TO
1163 }
1164
1165 /**
fe482240 1166 * Get a list of relationships.
6a488035 1167 *
77c5b619
TO
1168 * @param int $contactId
1169 * Contact id.
1170 * @param int $status
1171 * 1: Past 2: Disabled 3: Current.
1172 * @param int $numRelationship
1173 * No of relationships to display (limit).
1174 * @param int $count
1175 * Get the no of relationships.
77b97be7 1176 * @param int $relationshipId
76e7a76c
CW
1177 * @param array $links
1178 * the list of links to display
1179 * @param int $permissionMask
1180 * the permission mask to be applied for the actions
77b97be7 1181 * @param bool $permissionedContact
76e7a76c 1182 * to return only permissioned Contact
77b97be7 1183 * @param array $params
644587aa
SL
1184 * @param bool $includeTotalCount
1185 * Should we return a count of total accessable relationships
77b97be7
EM
1186 *
1187 * @return array|int
76e7a76c 1188 * relationship records
923dfabb 1189 *
1190 * @throws \CRM_Core_Exception
1191 * @throws \CiviCRM_API3_Exception
6a488035 1192 */
c301f76e 1193 public static function getRelationship(
51ccfbbe 1194 $contactId = NULL,
7f3647bc
TO
1195 $status = 0, $numRelationship = 0,
1196 $count = 0, $relationshipId = 0,
1197 $links = NULL, $permissionMask = NULL,
75638074 1198 $permissionedContact = FALSE,
52335bb5 1199 $params = [], $includeTotalCount = FALSE
6a488035 1200 ) {
52335bb5 1201 $values = [];
6a488035
TO
1202 if (!$contactId && !$relationshipId) {
1203 return $values;
1204 }
1205
1206 list($select1, $from1, $where1) = self::makeURLClause($contactId, $status, $numRelationship,
75638074 1207 $count, $relationshipId, 'a_b', $params
6a488035
TO
1208 );
1209 list($select2, $from2, $where2) = self::makeURLClause($contactId, $status, $numRelationship,
75638074 1210 $count, $relationshipId, 'b_a', $params
6a488035
TO
1211 );
1212
1213 $order = $limit = '';
1214 if (!$count) {
40458f6c 1215 if (empty($params['sort'])) {
1216 $order = ' ORDER BY civicrm_relationship_type_id, sort_name ';
1217 }
1218 else {
1219 $order = " ORDER BY {$params['sort']} ";
1220 }
1221
1222 $offset = 0;
630d1aaa 1223 if (!empty($params['offset']) && $params['offset'] > 0) {
40458f6c 1224 $offset = $params['offset'];
1225 }
6a488035
TO
1226
1227 if ($numRelationship) {
40458f6c 1228 $limit = " LIMIT {$offset}, $numRelationship";
6a488035
TO
1229 }
1230 }
1231
1232 // building the query string
e729799a 1233 $queryString = $select1 . $from1 . $where1 . $select2 . $from2 . $where2;
6a488035 1234
57315c8d 1235 $relationship = CRM_Core_DAO::executeQuery($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;
57315c8d
EM
1312 $values[$rid]['created_date'] = $relationship->created_date;
1313 $values[$rid]['modified_date'] = $relationship->modified_date;
6a488035
TO
1314 $values[$rid]['description'] = $relationship->description;
1315 $values[$rid]['is_active'] = $relationship->is_active;
1316 $values[$rid]['is_permission_a_b'] = $relationship->is_permission_a_b;
1317 $values[$rid]['is_permission_b_a'] = $relationship->is_permission_b_a;
1318 $values[$rid]['case_id'] = $relationship->case_id;
1319
1320 if ($status) {
1321 $values[$rid]['status'] = $status;
1322 }
1323
1324 $values[$rid]['civicrm_relationship_type_id'] = $relationship->civicrm_relationship_type_id;
1325
1326 if ($relationship->contact_id_a == $contactId) {
1327 $values[$rid]['rtype'] = 'a_b';
1328 }
1329 else {
1330 $values[$rid]['rtype'] = 'b_a';
1331 }
1332
1333 if ($links) {
52335bb5 1334 $replace = [
6a488035
TO
1335 'id' => $rid,
1336 'rtype' => $values[$rid]['rtype'],
1337 'cid' => $contactId,
1338 'cbid' => $values[$rid]['cid'],
1339 'caseid' => $values[$rid]['case_id'],
1340 'clientid' => $contactId,
52335bb5 1341 ];
6a488035
TO
1342
1343 if ($status == self::INACTIVE) {
1344 // setting links for inactive relationships
1345 $mask = array_sum(array_keys($links));
1346 if (!$values[$rid]['is_active']) {
1347 $mask -= CRM_Core_Action::DISABLE;
1348 }
1349 else {
1350 $mask -= CRM_Core_Action::ENABLE;
1351 $mask -= CRM_Core_Action::DISABLE;
1352 }
cd056f13 1353 $mask = $mask & $permissionMask;
6a488035
TO
1354 }
1355
1356 // Give access to manage case link by copying to MAX_ACTION index temporarily, depending on case permission of user.
1357 if ($values[$rid]['case_id']) {
1358 // Borrowed logic from CRM_Case_Page_Tab
1359 $hasCaseAccess = FALSE;
1360 if (CRM_Core_Permission::check('access all cases and activities')) {
1361 $hasCaseAccess = TRUE;
1362 }
1363 else {
1364 $userCases = CRM_Case_BAO_Case::getCases(FALSE);
1365 if (array_key_exists($values[$rid]['case_id'], $userCases)) {
1366 $hasCaseAccess = TRUE;
1367 }
1368 }
1369
1370 if ($hasCaseAccess) {
1371 // give access by copying to MAX_ACTION temporarily, otherwise leave at NONE which won't display
1372 $links[CRM_Core_Action::MAX_ACTION] = $links[CRM_Core_Action::NONE];
52335bb5 1373 $links[CRM_Core_Action::MAX_ACTION]['name'] = ts('Manage Case #%1', [1 => $values[$rid]['case_id']]);
f89f2102 1374 $links[CRM_Core_Action::MAX_ACTION]['class'] = 'no-popup';
6a488035
TO
1375
1376 // Also make sure we have the right client cid since can get here from multiple relationship tabs.
1377 if ($values[$rid]['rtype'] == 'b_a') {
1378 $replace['clientid'] = $values[$rid]['cid'];
1379 }
13a3d214 1380 $values[$rid]['case'] = '<a href="' . CRM_Utils_System::url('civicrm/case/ajax/details', sprintf('caseId=%d&cid=%d&snippet=4', $values[$rid]['case_id'], $values[$rid]['cid'])) . '" class="action-item crm-hover-button crm-summary-link"><i class="crm-i fa-folder-open-o" aria-hidden="true"></i></a>';
6a488035
TO
1381 }
1382 }
1383
87dab4a4 1384 $values[$rid]['action'] = CRM_Core_Action::formLink(
1cfa04c4
EM
1385 $links,
1386 $mask,
87dab4a4
AH
1387 $replace,
1388 ts('more'),
1389 FALSE,
1390 'relationship.selector.row',
1391 'Relationship',
1392 $rid);
6a488035
TO
1393 unset($links[CRM_Core_Action::MAX_ACTION]);
1394 }
1395 }
1396
6a488035
TO
1397 return $values;
1398 }
1399 }
1400
1401 /**
7cf463d9
M
1402 * Get list of relationship type based on the target contact type.
1403 * Both directions of relationships are included if their labels are not the same.
6a488035 1404 *
77c5b619 1405 * @param string $targetContactType
7cf463d9 1406 * A valid contact type (may be Individual, Organization, Household).
6a488035 1407 *
a6c01b45 1408 * @return array
7cf463d9 1409 * array reference of all relationship types with context to current contact type.
6a488035 1410 */
69078420 1411 public static function getRelationType($targetContactType) {
52335bb5 1412 $relationshipType = [];
6a488035
TO
1413 $allRelationshipType = CRM_Core_PseudoConstant::relationshipType();
1414
1415 foreach ($allRelationshipType as $key => $type) {
7b1ed533 1416 if ($type['contact_type_b'] == $targetContactType || empty($type['contact_type_b'])) {
6a488035
TO
1417 $relationshipType[$key . '_a_b'] = $type['label_a_b'];
1418 }
7cf463d9
M
1419 if (($type['contact_type_a'] == $targetContactType || empty($type['contact_type_a']))
1420 && $type['label_a_b'] != $type['label_b_a']
1421 ) {
1422 $relationshipType[$key . '_b_a'] = $type['label_b_a'];
1423 }
6a488035
TO
1424 }
1425
1426 return $relationshipType;
1427 }
1428
1429 /**
100fef9d 1430 * Create / update / delete membership for related contacts.
6a488035
TO
1431 *
1432 * This function will create/update/delete membership for related
1433 * contact based on 1) contact have active membership 2) that
1434 * membership is is extedned by the same relationship type to that
1435 * of the existing relationship.
1436 *
5a4f6742
CW
1437 * @param int $contactId
1438 * contact id.
1439 * @param array $params
1440 * array of values submitted by POST.
1441 * @param array $ids
1442 * array of ids.
bfa4da96 1443 * @param \const|int $action which action called this function
6a488035 1444 *
dd244018 1445 * @param bool $active
6a488035 1446 *
bfa4da96 1447 * @throws \CRM_Core_Exception
0a2663fd 1448 * @throws \CiviCRM_API3_Exception
6a488035 1449 */
5c34e41f 1450 public static function relatedMemberships($contactId, $params, $ids, $action = CRM_Core_Action::ADD, $active = TRUE) {
6a488035 1451 // Check the end date and set the status of the relationship
decc60a0 1452 // accordingly.
6a488035 1453 $status = self::CURRENT;
52335bb5 1454 $targetContact = $targetContact = CRM_Utils_Array::value('contact_check', $params, []);
45089d88
CW
1455 $today = date('Ymd');
1456
1457 // If a relationship hasn't yet started, just return for now
1458 // TODO: handle edge-case of updating start_date of an existing relationship
1459 if (!empty($params['start_date'])) {
1460 $startDate = substr(CRM_Utils_Date::format($params['start_date']), 0, 8);
1461 if ($today < $startDate) {
1462 return;
1463 }
1464 }
6a488035
TO
1465
1466 if (!empty($params['end_date'])) {
45089d88 1467 $endDate = substr(CRM_Utils_Date::format($params['end_date']), 0, 8);
6a488035
TO
1468 if ($today > $endDate) {
1469 $status = self::PAST;
1470 }
1471 }
1472
45089d88
CW
1473 if (($action & CRM_Core_Action::ADD) && ($status & self::PAST)) {
1474 // If relationship is PAST and action is ADD, do nothing.
6a488035
TO
1475 return;
1476 }
1477
1478 $rel = explode('_', $params['relationship_type_id']);
1479
7f3647bc 1480 $relTypeId = $rel[0];
decc60a0
EM
1481 if (!empty($rel[1])) {
1482 $relDirection = "_{$rel[1]}_{$rel[2]}";
1483 }
1484 else {
1485 // this call is coming from somewhere where the direction was resolved early on (e.g an api call)
1486 // so we can assume _a_b
1487 $relDirection = "_a_b";
52335bb5 1488 $targetContact = [$params['contact_id_b'] => 1];
decc60a0 1489 }
04ad3598 1490
6a488035
TO
1491 if (($action & CRM_Core_Action::ADD) ||
1492 ($action & CRM_Core_Action::DELETE)
1493 ) {
1494 $contact = $contactId;
6a488035
TO
1495 }
1496 elseif ($action & CRM_Core_Action::UPDATE) {
6345c936 1497 $contact = (int) $ids['contact'];
52335bb5 1498 $targetContact = [$ids['contactTarget'] => 1];
6a488035
TO
1499 }
1500
1501 // Build the 'values' array for
1502 // 1. ContactA
1503 // 2. ContactB
1504 // This will allow us to check if either of the contacts in
1505 // relationship have active memberships.
1506
52335bb5 1507 $values = [];
6a488035
TO
1508
1509 // 1. ContactA
52335bb5 1510 $values[$contact] = [
6a488035
TO
1511 'relatedContacts' => $targetContact,
1512 'relationshipTypeId' => $relTypeId,
1513 'relationshipTypeDirection' => $relDirection,
52335bb5 1514 ];
6a488035
TO
1515 // 2. ContactB
1516 if (!empty($targetContact)) {
1517 foreach ($targetContact as $cid => $donCare) {
52335bb5 1518 $values[$cid] = [
1519 'relatedContacts' => [$contact => 1],
6a488035 1520 'relationshipTypeId' => $relTypeId,
52335bb5 1521 ];
6a488035 1522
52335bb5 1523 $relTypeParams = ['id' => $relTypeId];
1524 $relTypeValues = [];
6a488035
TO
1525 CRM_Contact_BAO_RelationshipType::retrieve($relTypeParams, $relTypeValues);
1526
1527 if (CRM_Utils_Array::value('name_a_b', $relTypeValues) == CRM_Utils_Array::value('name_b_a', $relTypeValues)) {
1528 $values[$cid]['relationshipTypeDirection'] = '_a_b';
1529 }
1530 else {
1531 $values[$cid]['relationshipTypeDirection'] = ($relDirection == '_a_b') ? '_b_a' : '_a_b';
1532 }
1533 }
1534 }
1535
73a949e4 1536 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant::membershipStatus());
bd655ee6 1537
6345c936 1538 $relationshipProcessor = new CRM_Member_Utils_RelationshipProcessor(array_keys($values), $active);
6a488035 1539 foreach ($values as $cid => $details) {
52335bb5 1540 $relatedContacts = array_keys(CRM_Utils_Array::value('relatedContacts', $details, []));
ee17a760 1541 $mainRelatedContactId = reset($relatedContacts);
6a488035 1542
6345c936 1543 foreach ($relationshipProcessor->getRelationshipMembershipsForContact((int) $cid) as $membershipId => $membershipValues) {
0a2663fd 1544 $membershipInherittedFromContactID = NULL;
1545 if (!empty($membershipValues['owner_membership_id'])) {
6345c936 1546 // @todo - $membership already has this now.
0a2663fd 1547 // Use get not getsingle so that we get e-notice noise but not a fatal is the membership has already been deleted.
1548 $inheritedFromMembership = civicrm_api3('Membership', 'get', ['id' => $membershipValues['owner_membership_id'], 'sequential' => 1])['values'][0];
1549 $membershipInherittedFromContactID = (int) $inheritedFromMembership['contact_id'];
1550 }
52335bb5 1551 $relTypeIds = [];
6a488035 1552 if ($action & CRM_Core_Action::DELETE) {
98fd6fc8 1553 // @todo don't return relTypeId here - but it seems to be used later in a cryptic way (hint cryptic is not a complement).
310c2031 1554 list($relTypeId, $isDeletable) = self::isInheritedMembershipInvalidated($membershipValues, $values, $cid);
98fd6fc8 1555 if ($isDeletable) {
73a949e4 1556 CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipValues['owner_membership_id'], $membershipValues['contact_id']);
6a488035
TO
1557 }
1558 continue;
1559 }
1560 if (($action & CRM_Core_Action::UPDATE) &&
1561 ($status & self::PAST) &&
1562 ($membershipValues['owner_membership_id'])
1563 ) {
1564 // If relationship is PAST and action is UPDATE
1565 // then delete the RELATED membership
1566 CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipValues['owner_membership_id'],
73a949e4 1567 $membershipValues['contact_id']
6a488035
TO
1568 );
1569 continue;
1570 }
1571
1572 // add / edit the memberships for related
1573 // contacts.
1574
6345c936 1575 // @todo - all these lines get 'relTypeDirs' - but it's already a key in the $membership array.
6a488035 1576 // Get the Membership Type Details.
563f6487 1577 $membershipType = CRM_Member_BAO_MembershipType::getMembershipType($membershipValues['membership_type_id']);
6a488035 1578 // Check if contact's relationship type exists in membership type
52335bb5 1579 $relTypeDirs = [];
a7488080 1580 if (!empty($membershipType['relationship_type_id'])) {
563f6487 1581 $relTypeIds = (array) $membershipType['relationship_type_id'];
6a488035 1582 }
a7488080 1583 if (!empty($membershipType['relationship_direction'])) {
563f6487 1584 $relDirections = (array) $membershipType['relationship_direction'];
6a488035
TO
1585 }
1586 foreach ($relTypeIds as $key => $value) {
1587 $relTypeDirs[] = $value . '_' . $relDirections[$key];
1588 }
1589 $relTypeDir = $details['relationshipTypeId'] . $details['relationshipTypeDirection'];
1590 if (in_array($relTypeDir, $relTypeDirs)) {
1591 // Check if relationship being created/updated is
1592 // similar to that of membership type's
1593 // relationship.
1594
1595 $membershipValues['owner_membership_id'] = $membershipId;
1596 unset($membershipValues['id']);
6a488035
TO
1597 unset($membershipValues['contact_id']);
1598 unset($membershipValues['membership_id']);
1599 foreach ($details['relatedContacts'] as $relatedContactId => $donCare) {
1600 $membershipValues['contact_id'] = $relatedContactId;
1601 if ($deceasedStatusId &&
1602 CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $relatedContactId, 'is_deceased')
1603 ) {
1604 $membershipValues['status_id'] = $deceasedStatusId;
1605 $membershipValues['skipStatusCal'] = TRUE;
1606 }
6a488035 1607
6345c936 1608 if (in_array($action, [CRM_Core_Action::UPDATE, CRM_Core_Action::ADD, CRM_Core_Action::ENABLE])) {
e72dea83 1609 //if updated relationship is already related to contact don't delete existing inherited membership
6345c936 1610 if (in_array((int) $relatedContactId, $membershipValues['inheriting_contact_ids'], TRUE)
1611 || $relatedContactId === $membershipValues['owner_contact_id']
1612 ) {
e72dea83 1613 continue;
1614 }
1615
1616 //delete the membership record for related
1617 //contact before creating new membership record.
1618 CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipId, $relatedContactId);
1619 }
00538ec6 1620 //skip status calculation for pay later memberships.
6345c936 1621 if ('Pending' === CRM_Core_PseudoConstant::getName('CRM_Member_BAO_Membership', 'status_id', $membershipValues['status_id'])) {
00538ec6
JP
1622 $membershipValues['skipStatusCal'] = TRUE;
1623 }
0a2663fd 1624 // As long as the membership itself was not created by inheritance from the same contact
1625 // that stands to inherit the membership we add an inherited membership.
1626 if ($membershipInherittedFromContactID !== (int) $membershipValues['contact_id']) {
1627 $membershipValues = self::addInheritedMembership($membershipValues);
1628 }
6a488035
TO
1629 }
1630 }
1631 elseif ($action & CRM_Core_Action::UPDATE) {
1632 // if action is update and updated relationship do
1633 // not match with the existing
1634 // membership=>relationship then we need to
e62adec9 1635 // change the status of the membership record to expired for
1636 // previous relationship -- CRM-12078.
1637 // CRM-16087 we need to pass ownerMembershipId to isRelatedMembershipExpired function
690c56c3 1638 if (empty($params['relationship_ids']) && !empty($params['id'])) {
52335bb5 1639 $relIds = [$params['id']];
690c56c3 1640 }
1641 else {
9c1bc317 1642 $relIds = $params['relationship_ids'] ?? NULL;
690c56c3 1643 }
e62adec9 1644 if (self::isRelatedMembershipExpired($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId,
52335bb5 1645 $relIds) && !empty($membershipValues['owner_membership_id']
1646 ) && !empty($values[$mainRelatedContactId]['memberships'][$membershipValues['owner_membership_id']])) {
e62adec9 1647 $membershipValues['status_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', 'Expired', 'id', 'label');
1648 $type = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $membershipValues['membership_type_id'], 'name', 'id');
1649 CRM_Member_BAO_Membership::add($membershipValues);
1836ab9e 1650 CRM_Core_Session::setStatus(ts("Inherited membership %1 status was changed to Expired due to the change in relationship type.", [1 => $type]), ts('Record Updated'), 'alert');
6a488035
TO
1651 }
1652 }
1653 }
1654 }
1655 }
1656
1657 /**
e62adec9 1658 * Helper function to check whether the membership is expired or not.
6616f7c1
EM
1659 *
1660 * Function takes a list of related membership types and if it is not also passed a
e62adec9 1661 * relationship ID of that types evaluates whether the membership status should be changed to expired.
6616f7c1
EM
1662 *
1663 * @param array $membershipTypeRelationshipTypeIDs
1664 * Relation type IDs related to the given membership type.
1665 * @param int $contactId
1666 * @param int $mainRelatedContactId
1667 * @param int $relTypeId
1668 * @param array $relIds
1669 *
1670 * @return bool
6a488035 1671 */
e62adec9 1672 public static function isRelatedMembershipExpired($membershipTypeRelationshipTypeIDs, $contactId, $mainRelatedContactId, $relTypeId, $relIds) {
6616f7c1 1673 if (empty($membershipTypeRelationshipTypeIDs) || in_array($relTypeId, $membershipTypeRelationshipTypeIDs)) {
eec8d770 1674 return FALSE;
6a488035
TO
1675 }
1676
1677 if (empty($relIds)) {
1678 return FALSE;
1679 }
1680
52335bb5 1681 $relParamas = [
1682 1 => [$contactId, 'Integer'],
1683 2 => [$mainRelatedContactId, 'Integer'],
1684 ];
6a488035
TO
1685
1686 if ($contactId == $mainRelatedContactId) {
6616f7c1
EM
1687 $recordsFound = (int) CRM_Core_DAO::singleValueQuery("SELECT COUNT(*) FROM civicrm_relationship WHERE relationship_type_id IN ( " . implode(',', $membershipTypeRelationshipTypeIDs) . " ) AND
1688contact_id_a IN ( %1 ) OR contact_id_b IN ( %1 ) AND id IN (" . implode(',', $relIds) . ")", $relParamas);
6a488035
TO
1689 if ($recordsFound) {
1690 return FALSE;
1691 }
1692 return TRUE;
1693 }
1694
6616f7c1 1695 $recordsFound = (int) CRM_Core_DAO::singleValueQuery("SELECT COUNT(*) FROM civicrm_relationship WHERE relationship_type_id IN ( " . implode(',', $membershipTypeRelationshipTypeIDs) . " ) AND contact_id_a IN ( %1, %2 ) AND contact_id_b IN ( %1, %2 ) AND id NOT IN (" . implode(',', $relIds) . ")", $relParamas);
6a488035
TO
1696
1697 if ($recordsFound) {
1698 return FALSE;
1699 }
1700
1701 return TRUE;
1702 }
1703
1704 /**
fe482240 1705 * Get Current Employer for Contact.
6a488035 1706 *
3fd42bb5 1707 * @param array $contactIds
77c5b619 1708 * Contact Ids.
6a488035 1709 *
a6c01b45
CW
1710 * @return array
1711 * array of the current employer
6a488035 1712 */
00be9182 1713 public static function getCurrentEmployer($contactIds) {
6a488035
TO
1714 $contacts = implode(',', $contactIds);
1715
1716 $query = "
1717SELECT organization_name, id, employer_id
1718FROM civicrm_contact
1719WHERE id IN ( {$contacts} )
1720";
1721
33621c4f 1722 $dao = CRM_Core_DAO::executeQuery($query);
52335bb5 1723 $currentEmployer = [];
6a488035
TO
1724 while ($dao->fetch()) {
1725 $currentEmployer[$dao->id]['org_id'] = $dao->employer_id;
1726 $currentEmployer[$dao->id]['org_name'] = $dao->organization_name;
1727 }
1728
1729 return $currentEmployer;
1730 }
1731
7f3647bc 1732 /**
fe482240 1733 * Function to return list of permissioned contacts for a given contact and relationship type.
7f3647bc 1734 *
5a4f6742
CW
1735 * @param int $contactID
1736 * contact id whose permissioned contacts are to be found.
b0076fe6 1737 * @param int $relTypeId
5a4f6742
CW
1738 * one or more relationship type id's.
1739 * @param string $name
33260076 1740 * @param string $contactType
7f3647bc 1741 *
a6c01b45 1742 * @return array
16b10e64 1743 * Array of contacts
7f3647bc 1744 */
33260076 1745 public static function getPermissionedContacts($contactID, $relTypeId = NULL, $name = NULL, $contactType = NULL) {
52335bb5 1746 $contacts = [];
1747 $args = [1 => [$contactID, 'Integer']];
33260076 1748 $relationshipTypeClause = $contactTypeClause = '';
51e89def 1749
6a488035 1750 if ($relTypeId) {
b0076fe6
EM
1751 // @todo relTypeId is only ever passed in as an int. Change this to reflect that -
1752 // probably being overly conservative by not doing so but working on stable release.
1753 $relationshipTypeClause = 'AND cr.relationship_type_id IN (%2) ';
52335bb5 1754 $args[2] = [$relTypeId, 'String'];
b0076fe6 1755 }
33260076 1756
1757 if ($contactType) {
1758 $contactTypeClause = ' AND cr.relationship_type_id = crt.id AND crt.contact_type_b = %3 ';
52335bb5 1759 $args[3] = [$contactType, 'String'];
33260076 1760 }
1761
4779abb3 1762 $query = "
6a488035 1763SELECT cc.id as id, cc.sort_name as name
33260076 1764FROM civicrm_relationship cr, civicrm_contact cc, civicrm_relationship_type crt
49f8272d 1765WHERE
51e89def 1766cr.contact_id_a = %1 AND
51e89def 1767cr.is_permission_a_b = 1 AND
6a488035
TO
1768IF(cr.end_date IS NULL, 1, (DATEDIFF( CURDATE( ), cr.end_date ) <= 0)) AND
1769cr.is_active = 1 AND
7ecf6275 1770cc.id = cr.contact_id_b AND
b0076fe6
EM
1771cc.is_deleted = 0
1772$relationshipTypeClause
33260076 1773$contactTypeClause
b0076fe6 1774";
51e89def 1775
4779abb3 1776 if (!empty($name)) {
1777 $name = CRM_Utils_Type::escape($name, 'String');
1778 $query .= "
49f8272d 1779AND cc.sort_name LIKE '%$name%'";
4779abb3 1780 }
6a488035 1781
4779abb3 1782 $dao = CRM_Core_DAO::executeQuery($query, $args);
1783 while ($dao->fetch()) {
52335bb5 1784 $contacts[$dao->id] = [
4779abb3 1785 'name' => $dao->name,
1786 'value' => $dao->id,
52335bb5 1787 ];
4779abb3 1788 }
b0076fe6 1789
51e89def 1790 return $contacts;
6a488035
TO
1791 }
1792
6a488035 1793 /**
fe482240 1794 * Merge relationships from otherContact to mainContact.
bfa4da96 1795 *
6a488035
TO
1796 * Called during contact merge operation
1797 *
77c5b619
TO
1798 * @param int $mainId
1799 * Contact id of main contact record.
1800 * @param int $otherId
1801 * Contact id of record which is going to merge.
1802 * @param array $sqls
1803 * (reference) array of sql statements to append to.
6a488035
TO
1804 *
1805 * @see CRM_Dedupe_Merger::cpTables()
6a488035 1806 */
00be9182 1807 public static function mergeRelationships($mainId, $otherId, &$sqls) {
6a488035
TO
1808 // Delete circular relationships
1809 $sqls[] = "DELETE FROM civicrm_relationship
6ce3ea65
JJ
1810 WHERE (contact_id_a = $mainId AND contact_id_b = $otherId AND case_id IS NULL)
1811 OR (contact_id_b = $mainId AND contact_id_a = $otherId AND case_id IS NULL)";
6a488035
TO
1812
1813 // Delete relationship from other contact if main contact already has that relationship
1814 $sqls[] = "DELETE r2
1815 FROM civicrm_relationship r1, civicrm_relationship r2
1816 WHERE r1.relationship_type_id = r2.relationship_type_id
1817 AND r1.id <> r2.id
6ce3ea65 1818 AND r1.case_id IS NULL AND r2.case_id IS NULL
6a488035
TO
1819 AND (
1820 r1.contact_id_a = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_b = r2.contact_id_b
1821 OR r1.contact_id_b = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_a = r2.contact_id_a
1822 OR (
1823 (r1.contact_id_a = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_b = r2.contact_id_a
1824 OR r1.contact_id_b = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_a = r2.contact_id_b)
1825 AND r1.relationship_type_id IN (SELECT id FROM civicrm_relationship_type WHERE name_b_a = name_a_b)
1826 )
1827 )";
1828
1829 // Move relationships
1830 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_a = $mainId WHERE contact_id_a = $otherId";
1831 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_b = $mainId WHERE contact_id_b = $otherId";
1832
1833 // Move current employer id (name will get updated later)
1834 $sqls[] = "UPDATE civicrm_contact SET employer_id = $mainId WHERE employer_id = $otherId";
1835 }
1836
1837 /**
1838 * Set 'is_valid' field to false for all relationships whose end date is in the past, ie. are expired.
1839 *
72b3a70c
CW
1840 * @return bool
1841 * True on success, false if error is encountered.
f42bcfb1 1842 * @throws \CiviCRM_API3_Exception
6a488035 1843 */
00be9182 1844 public static function disableExpiredRelationships() {
6a488035
TO
1845 $query = "SELECT id FROM civicrm_relationship WHERE is_active = 1 AND end_date < CURDATE()";
1846
1847 $dao = CRM_Core_DAO::executeQuery($query);
1848 while ($dao->fetch()) {
1849 $result = CRM_Contact_BAO_Relationship::setIsActive($dao->id, FALSE);
1850 // Result will be NULL if error occurred. We abort early if error detected.
1851 if ($result == NULL) {
1852 return FALSE;
1853 }
1854 }
1855 return TRUE;
1856 }
c9c41397 1857
1858 /**
fe482240 1859 * Function filters the query by possible relationships for the membership type.
98a06ae0 1860 *
c9c41397 1861 * It is intended to be called when constructing queries for the api (reciprocal & non-reciprocal)
1862 * and to add clauses to limit the return to those relationships which COULD inherit a membership type
1863 * (as opposed to those who inherit a particular membership
1864 *
77c5b619
TO
1865 * @param array $params
1866 * Api input array.
5e21e0f3 1867 * @param string $direction
77b97be7 1868 *
c301f76e 1869 * @return array|void
52335bb5 1870 * @throws \CiviCRM_API3_Exception
c9c41397 1871 */
00be9182 1872 public static function membershipTypeToRelationshipTypes(&$params, $direction = NULL) {
52335bb5 1873 $membershipType = civicrm_api3('membership_type', 'getsingle', [
353ffa53
TO
1874 'id' => $params['membership_type_id'],
1875 'return' => 'relationship_type_id, relationship_direction',
52335bb5 1876 ]);
c9c41397 1877 $relationshipTypes = $membershipType['relationship_type_id'];
22e263ad 1878 if (empty($relationshipTypes)) {
c301f76e 1879 return NULL;
f201289d 1880 }
c9c41397 1881 // if we don't have any contact data we can only filter on type
22e263ad 1882 if (empty($params['contact_id']) && empty($params['contact_id_a']) && empty($params['contact_id_a'])) {
52335bb5 1883 $params['relationship_type_id'] = ['IN' => $relationshipTypes];
c301f76e 1884 return NULL;
c9c41397 1885 }
1886 else {
1a9b2ee8 1887 $relationshipDirections = (array) $membershipType['relationship_direction'];
c9c41397 1888 // if we have contact_id_a OR contact_id_b we can make a call here
1889 // if we have contact??
1890 foreach ($relationshipDirections as $index => $mtdirection) {
7f3647bc 1891 if (isset($params['contact_id_a']) && $mtdirection == 'a_b' || $direction == 'a_b') {
c9c41397 1892 $types[] = $relationshipTypes[$index];
1893 }
7f3647bc 1894 if (isset($params['contact_id_b']) && $mtdirection == 'b_a' || $direction == 'b_a') {
c9c41397 1895 $types[] = $relationshipTypes[$index];
1896 }
1897 }
22e263ad 1898 if (!empty($types)) {
52335bb5 1899 $params['relationship_type_id'] = ['IN' => $types];
c9c41397 1900 }
7f3647bc 1901 elseif (!empty($clauses)) {
c9c41397 1902 return explode(' OR ', $clauses);
1903 }
92e4c2a5 1904 else {
c9c41397 1905 // effectively setting it to return no results
1906 $params['relationship_type_id'] = 0;
1907 }
1908 }
1909 }
40458f6c 1910
40458f6c 1911 /**
98a06ae0 1912 * Wrapper for contact relationship selector.
40458f6c 1913 *
77c5b619
TO
1914 * @param array $params
1915 * Associated array for params record id.
40458f6c 1916 *
a6c01b45
CW
1917 * @return array
1918 * associated array of contact relationships
52335bb5 1919 * @throws \Exception
40458f6c 1920 */
1921 public static function getContactRelationshipSelector(&$params) {
1922 // format the params
7f3647bc 1923 $params['offset'] = ($params['page'] - 1) * $params['rp'];
9c1bc317 1924 $params['sort'] = $params['sortBy'] ?? NULL;
40458f6c 1925
1926 if ($params['context'] == 'past') {
1927 $relationshipStatus = CRM_Contact_BAO_Relationship::INACTIVE;
1928 }
62e6afce 1929 elseif ($params['context'] == 'all') {
6c292184
TM
1930 $relationshipStatus = CRM_Contact_BAO_Relationship::ALL;
1931 }
40458f6c 1932 else {
1933 $relationshipStatus = CRM_Contact_BAO_Relationship::CURRENT;
1934 }
1935
1936 // check logged in user for permission
1937 $page = new CRM_Core_Page();
1938 CRM_Contact_Page_View::checkUserPermission($page, $params['contact_id']);
52335bb5 1939 $permissions = [$page->_permission];
40458f6c 1940 if ($page->_permission == CRM_Core_Permission::EDIT) {
1941 $permissions[] = CRM_Core_Permission::DELETE;
1942 }
1943 $mask = CRM_Core_Action::mask($permissions);
1944
a93664c8 1945 $permissionedContacts = TRUE;
d0592c3d 1946 if ($params['context'] != 'user') {
1947 $links = CRM_Contact_Page_View_Relationship::links();
d0592c3d 1948 }
1949 else {
1950 $links = CRM_Contact_Page_View_UserDashBoard::links();
d0592c3d 1951 $mask = NULL;
1952 }
40458f6c 1953 // get contact relationships
1954 $relationships = CRM_Contact_BAO_Relationship::getRelationship($params['contact_id'],
1955 $relationshipStatus,
1956 $params['rp'], 0, 0,
d0592c3d 1957 $links, $mask,
1958 $permissionedContacts,
644587aa 1959 $params, TRUE
40458f6c 1960 );
1961
52335bb5 1962 $contactRelationships = [];
644587aa
SL
1963 $params['total'] = $relationships['total_relationships'];
1964 unset($relationships['total_relationships']);
40458f6c 1965 if (!empty($relationships)) {
40458f6c 1966
1250f3d8
AH
1967 $displayName = CRM_Contact_BAO_Contact::displayName($params['contact_id']);
1968
40458f6c 1969 // format params
1970 foreach ($relationships as $relationshipId => $values) {
52335bb5 1971 $relationship = [];
7d12de7f 1972
febb6506 1973 $relationship['DT_RowId'] = $values['id'];
7d12de7f
JL
1974 $relationship['DT_RowClass'] = 'crm-entity';
1975 if ($values['is_active'] == 0) {
1976 $relationship['DT_RowClass'] .= ' disabled';
1977 }
1978
52335bb5 1979 $relationship['DT_RowAttr'] = [];
febb6506
JL
1980 $relationship['DT_RowAttr']['data-entity'] = 'relationship';
1981 $relationship['DT_RowAttr']['data-id'] = $values['id'];
7d12de7f 1982
20be4ac3
BS
1983 //Add image icon for related contacts: CRM-14919; CRM-19668
1984 $contactType = (!empty($values['contact_sub_type'])) ? $values['contact_sub_type'] : $values['contact_type'];
1985 $icon = CRM_Contact_BAO_Contact_Utils::getImage($contactType,
67e4fb51
N
1986 FALSE,
1987 $values['cid']
1988 );
7d12de7f 1989 $relationship['sort_name'] = $icon . ' ' . CRM_Utils_System::href(
7f3647bc
TO
1990 $values['name'],
1991 'civicrm/contact/view',
1992 "reset=1&cid={$values['cid']}");
40458f6c 1993
0a61e567 1994 $relationship['relation'] = CRM_Utils_Array::value('case', $values, '') . CRM_Utils_System::href(
52335bb5 1995 $values['relation'],
1996 'civicrm/contact/view/rel',
1997 "action=view&reset=1&cid={$values['cid']}&id={$values['id']}&rtype={$values['rtype']}");
40458f6c 1998
66229fd5
AS
1999 if (!empty($values['description'])) {
2000 $relationship['relation'] .= "<p class='description'>{$values['description']}</p>";
2001 }
2002
d0592c3d 2003 if ($params['context'] == 'current') {
fee0416f
AH
2004 $smarty = CRM_Core_Smarty::singleton();
2005
2006 $contactCombos = [
2007 [
2008 'permContact' => $params['contact_id'],
2009 'permDisplayName' => $displayName,
2010 'otherContact' => $values['cid'],
2011 'otherDisplayName' => $values['display_name'],
2012 'columnKey' => 'sort_name',
2013 ],
2014 [
2015 'permContact' => $values['cid'],
2016 'permDisplayName' => $values['display_name'],
2017 'otherContact' => $params['contact_id'],
2018 'otherDisplayName' => $displayName,
2019 'columnKey' => 'relation',
2020 ],
2021 ];
2022
2023 foreach ($contactCombos as $combo) {
2024 foreach ([CRM_Contact_BAO_Relationship::EDIT, CRM_Contact_BAO_Relationship::VIEW] as $permType) {
2025 $smarty->assign('permType', $permType);
2026 if (($combo['permContact'] == $values['contact_id_a'] and $values['is_permission_a_b'] == $permType)
2027 || ($combo['permContact'] == $values['contact_id_b'] and $values['is_permission_b_a'] == $permType)
2028 ) {
2029 $smarty->assign('permDisplayName', $combo['permDisplayName']);
2030 $smarty->assign('otherDisplayName', $combo['otherDisplayName']);
2031 $relationship[$combo['columnKey']] .= $smarty->fetch('CRM/Contact/Page/View/RelationshipPerm.tpl');
2032 }
2033 }
f871c3a9 2034 }
40458f6c 2035 }
2036
7d12de7f
JL
2037 $relationship['start_date'] = CRM_Utils_Date::customFormat($values['start_date']);
2038 $relationship['end_date'] = CRM_Utils_Date::customFormat($values['end_date']);
2039 $relationship['city'] = $values['city'];
2040 $relationship['state'] = $values['state'];
2041 $relationship['email'] = $values['email'];
2042 $relationship['phone'] = $values['phone'];
2043 $relationship['links'] = $values['action'];
2044
2045 array_push($contactRelationships, $relationship);
40458f6c 2046 }
2047 }
7d12de7f 2048
16b745b0
MWMC
2049 $columnHeaders = self::getColumnHeaders();
2050 $selector = NULL;
2051 CRM_Utils_Hook::searchColumns('relationship.rows', $columnHeaders, $contactRelationships, $selector);
2052
52335bb5 2053 $relationshipsDT = [];
7d12de7f
JL
2054 $relationshipsDT['data'] = $contactRelationships;
2055 $relationshipsDT['recordsTotal'] = $params['total'];
2056 $relationshipsDT['recordsFiltered'] = $params['total'];
2057
2058 return $relationshipsDT;
40458f6c 2059 }
2060
16b745b0
MWMC
2061 /**
2062 * @return array
2063 */
2064 public static function getColumnHeaders() {
2065 return [
2066 'relation' => [
2067 'name' => ts('Relationship'),
2068 'sort' => 'relation',
2069 'direction' => CRM_Utils_Sort::ASCENDING,
2070 ],
2071 'sort_name' => [
2072 'name' => '',
2073 'sort' => 'sort_name',
2074 'direction' => CRM_Utils_Sort::ASCENDING,
2075 ],
2076 'start_date' => [
2077 'name' => ts('Start'),
2078 'sort' => 'start_date',
2079 'direction' => CRM_Utils_Sort::DONTCARE,
2080 ],
2081 'end_date' => [
2082 'name' => ts('End'),
2083 'sort' => 'end_date',
2084 'direction' => CRM_Utils_Sort::DONTCARE,
2085 ],
2086 'city' => [
2087 'name' => ts('City'),
2088 'sort' => 'city',
2089 'direction' => CRM_Utils_Sort::DONTCARE,
2090 ],
2091 'state' => [
2092 'name' => ts('State/Prov'),
2093 'sort' => 'state',
2094 'direction' => CRM_Utils_Sort::DONTCARE,
2095 ],
2096 'email' => [
2097 'name' => ts('Email'),
2098 'sort' => 'email',
2099 'direction' => CRM_Utils_Sort::DONTCARE,
2100 ],
2101 'phone' => [
2102 'name' => ts('Phone'),
2103 'sort' => 'phone',
2104 'direction' => CRM_Utils_Sort::DONTCARE,
2105 ],
2106 'links' => [
2107 'name' => '',
2108 'sort' => 'links',
2109 'direction' => CRM_Utils_Sort::DONTCARE,
2110 ],
2111 ];
2112 }
2113
89e45979
MD
2114 /**
2115 * @inheritdoc
2116 */
52335bb5 2117 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1ac9bb56
CW
2118 // Quickform-specific format, for use when editing relationship type options in a popup from the contact relationship form
2119 if ($fieldName === 'relationship_type_id' && !empty($props['is_form'])) {
2120 return self::getContactRelationshipType(
2121 $props['contact_id'] ?? NULL,
2122 $props['relationship_direction'] ?? 'a_b',
2123 $props['relationship_id'] ?? NULL,
2124 $props['contact_type'] ?? NULL
2125 );
89e45979
MD
2126 }
2127
2128 return parent::buildOptions($fieldName, $context, $props);
2129 }
2130
df0c42cc
JP
2131 /**
2132 * Process the params from api, form and check if current
2133 * employer should be set or unset.
2134 *
2135 * @param array $params
2136 * @param int $relationshipId
e97c66ff 2137 * @param int|null $updatedRelTypeID
df0c42cc
JP
2138 *
2139 * @return bool
2140 * TRUE if current employer needs to be cleared.
f42bcfb1 2141 * @throws \CiviCRM_API3_Exception
df0c42cc
JP
2142 */
2143 public static function isCurrentEmployerNeedingToBeCleared($params, $relationshipId, $updatedRelTypeID = NULL) {
f42bcfb1 2144 $existingTypeID = (int) CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Relationship', $relationshipId, 'relationship_type_id');
df0c42cc 2145 $updatedRelTypeID = $updatedRelTypeID ? $updatedRelTypeID : $existingTypeID;
0c578c02 2146 $currentEmployerID = (int) civicrm_api3('Contact', 'getvalue', ['return' => 'current_employer_id', 'id' => $params['contact_id_a']]);
df0c42cc 2147
0c578c02 2148 if ($currentEmployerID !== (int) $params['contact_id_b'] || !self::isRelationshipTypeCurrentEmployer($existingTypeID)) {
df0c42cc
JP
2149 return FALSE;
2150 }
2151 //Clear employer if relationship is expired.
2152 if (!empty($params['end_date']) && strtotime($params['end_date']) < time()) {
2153 return TRUE;
2154 }
2155 //current employer checkbox is disabled on the form.
2156 //inactive or relationship type(employer of) is updated.
2157 if ((isset($params['is_current_employer']) && empty($params['is_current_employer']))
2158 || ((isset($params['is_active']) && empty($params['is_active'])))
2159 || $existingTypeID != $updatedRelTypeID) {
0c578c02
MD
2160 // If there are no other active employer relationships between the same 2 contacts...
2161 if (!civicrm_api3('Relationship', 'getcount', [
2162 'is_active' => 1,
2163 'relationship_type_id' => $existingTypeID,
2164 'id' => ['<>' => $params['id']],
2165 'contact_id_a' => $params['contact_id_a'],
2166 'contact_id_b' => $params['contact_id_b'],
2167 ])) {
2168 return TRUE;
2169 }
df0c42cc
JP
2170 }
2171
2172 return FALSE;
2173 }
2174
f42bcfb1
MD
2175 /**
2176 * Is this a current employer relationship type.
2177 *
2178 * @todo - this could use cached pseudoconstant lookups.
2179 *
2180 * @param int $existingTypeID
2181 *
2182 * @return bool
2183 */
2184 private static function isRelationshipTypeCurrentEmployer(int $existingTypeID): bool {
2185 $isCurrentEmployerRelationshipType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', $existingTypeID, 'name_b_a') === 'Employer of';
2186 return $isCurrentEmployerRelationshipType;
2187 }
2188
98fd6fc8 2189 /**
2190 * Is the inherited relationship invalidated by this relationship change.
2191 *
3fd42bb5 2192 * @param array $membershipValues
98fd6fc8 2193 * @param array $values
2194 * @param int $cid
98fd6fc8 2195 *
2196 * @return array
eb151aab 2197 * @throws \CiviCRM_API3_Exception
98fd6fc8 2198 */
310c2031 2199 private static function isInheritedMembershipInvalidated($membershipValues, array $values, $cid): array {
2200 // @todo most of this can go - it's just the weird historical returning of $relTypeId that it does.
2201 // now we have caching the parent fn can just call CRM_Member_BAO_MembershipType::getMembershipType
eb151aab 2202 $membershipType = CRM_Member_BAO_MembershipType::getMembershipType($membershipValues['membership_type_id']);
2203 $relTypeIds = $membershipType['relationship_type_id'];
310c2031 2204 $membershipInheritedFrom = $membershipValues['owner_membership_id'] ?? NULL;
2205 if (!$membershipInheritedFrom || !in_array($values[$cid]['relationshipTypeId'], $relTypeIds)) {
eb151aab 2206 return [implode(',', $relTypeIds), FALSE];
2207 }
2208 //CRM-16300 check if owner membership exist for related membership
310c2031 2209 return [implode(',', $relTypeIds), !self::isContactHasValidRelationshipToInheritMembershipType((int) $cid, (int) $membershipValues['membership_type_id'], (int) $membershipValues['owner_membership_id'])];
2210 }
2211
2212 /**
2213 * Is there a valid relationship confering this membership type on this contact.
2214 *
2215 * @param int $contactID
2216 * @param int $membershipTypeID
2217 * @param int $parentMembershipID
2218 * Id of the membership being inherited.
2219 *
2220 * @return bool
2221 *
2222 * @throws \CiviCRM_API3_Exception
2223 */
2224 private static function isContactHasValidRelationshipToInheritMembershipType(int $contactID, int $membershipTypeID, int $parentMembershipID): bool {
2225 $membershipType = CRM_Member_BAO_MembershipType::getMembershipType($membershipTypeID);
2226 $existingRelationships = civicrm_api3('Relationship', 'get', [
2227 'contact_id_a' => $contactID,
2228 'contact_id_b' => $contactID,
2229 'relationship_type_id' => ['IN' => $membershipType['relationship_type_id']],
2230 'options' => ['or' => [['contact_id_a', 'contact_id_b']], 'limit' => 0],
2231 'is_active' => 1,
2232 ])['values'];
2233
2234 if (empty($existingRelationships)) {
2235 return FALSE;
2236 }
2237
2238 $membershipInheritedFromContactID = (int) civicrm_api3('Membership', 'getvalue', ['return' => 'contact_id', 'id' => $parentMembershipID]);
2239 // I don't think the api can correctly filter by start & end because of handling for NULL
2240 // so we filter them out here.
2241 foreach ($existingRelationships as $index => $existingRelationship) {
2242 $otherContactID = (int) (($contactID === (int) $existingRelationship['contact_id_a']) ? $existingRelationship['contact_id_b'] : $existingRelationship['contact_id_a']);
2243 if (!empty($existingRelationship['start_date'])
2244 && strtotime($existingRelationship['start_date']) > time()
2245 ) {
2246 unset($existingRelationships[$index]);
2247 continue;
2248 }
2249 if (!empty($existingRelationship['end_date'])
2250 && strtotime($existingRelationship['end_date']) < time()
2251 ) {
2252 unset($existingRelationships[$index]);
2253 continue;
2254 }
2255 if ($membershipInheritedFromContactID !== $otherContactID
2256 ) {
2257 // This is a weird scenario - they have been inheriting the membership
2258 // just not from this relationship - and some max_related calcs etc would be required
2259 // - ie because they are no longer inheriting from this relationship's 'allowance'
2260 // and now are inheriting from the other relationships 'allowance', if it has not
2261 // already hit 'max_related'
2262 // For now ignore here & hope it's handled elsewhere - at least that's consistent with
2263 // before this function was added.
2264 unset($existingRelationships[$index]);
2265 continue;
2266 }
2267 if (!civicrm_api3('Contact', 'getcount', ['id' => $otherContactID, 'is_deleted' => 0])) {
2268 // Can't inherit from a deleted contact.
2269 unset($existingRelationships[$index]);
2270 continue;
2271 }
2272 }
2273 return !empty($existingRelationships);
98fd6fc8 2274 }
2275
52494648 2276 /**
2277 * Add an inherited membership, provided max related not exceeded.
2278 *
2279 * @param array $membershipValues
2280 *
2281 * @return array
2282 * @throws \CRM_Core_Exception
2283 */
2284 protected static function addInheritedMembership($membershipValues) {
2285 $query = "
2286SELECT count(*)
2287 FROM civicrm_membership
2288 LEFT JOIN civicrm_membership_status ON (civicrm_membership_status.id = civicrm_membership.status_id)
2289 WHERE membership_type_id = {$membershipValues['membership_type_id']}
2290 AND owner_membership_id = {$membershipValues['owner_membership_id']}
2291 AND is_current_member = 1";
2292 $result = CRM_Core_DAO::singleValueQuery($query);
2293 if ($result < CRM_Utils_Array::value('max_related', $membershipValues, PHP_INT_MAX)) {
3566c1c3
JJ
2294 // Convert custom_xx_id fields to custom_xx
2295 // See https://lab.civicrm.org/dev/membership/-/issues/37
2296 // This makes sure the value is copied and not the looked up value.
2297 // Which is the case when the custom field is a contact reference field.
2298 // The custom_xx contains the display name of the contact, instead of the contact id.
2299 // The contact id is then available in custom_xx_id.
2300 foreach ($membershipValues as $field => $value) {
2301 if (stripos($field, 'custom_') !== 0) {
2302 // No a custom field
2303 continue;
2304 }
2305 $custom_id = substr($field, 7);
2306 if (substr($custom_id, -3) === '_id') {
2307 $custom_id = substr($custom_id, 0, -3);
2308 unset($membershipValues[$field]);
2309 $membershipValues['custom_' . $custom_id] = $value;
2310 }
2311 }
2312
058180bb 2313 civicrm_api3('Membership', 'create', $membershipValues);
52494648 2314 }
2315 return $membershipValues;
2316 }
2317
6a488035 2318}