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