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