CRM_Utils_Recent - Use hook listener to delete items
[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 746
6a488035
TO
747 return $relationship;
748 }
749
750 /**
98a06ae0 751 * Disable/enable the relationship.
6a488035 752 *
77c5b619
TO
753 * @param int $id
754 * Relationship id.
6a488035 755 *
7a44a255
EM
756 * @param int $action
757 * @param array $params
758 * @param array $ids
759 * @param bool $active
52335bb5 760 *
761 * @throws \CRM_Core_Exception
310c2031 762 * @throws \CiviCRM_API3_Exception
6a488035 763 */
52335bb5 764 public static function disableEnableRelationship($id, $action, $params = [], $ids = [], $active = FALSE) {
6a488035 765 $relationship = self::clearCurrentEmployer($id, $action);
25f1372e 766
1b5fad8a 767 if ($id) {
25f1372e 768 // create $params array which is required to delete memberships
6a488035 769 // of the related contacts.
690c56c3 770 if (empty($params)) {
52335bb5 771 $params = [
690c56c3 772 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
52335bb5 773 'contact_check' => [$relationship->contact_id_b => 1],
774 ];
690c56c3 775 }
690c56c3 776 $contact_id_a = empty($params['contact_id_a']) ? $relationship->contact_id_a : $params['contact_id_a'];
6a488035
TO
777 // calling relatedMemberships to delete/add the memberships of
778 // related contacts.
779 if ($action & CRM_Core_Action::DISABLE) {
310c2031 780 // @todo this could call a subset of the function that just relates to
781 // cleaning up no-longer-inherited relationships
690c56c3 782 CRM_Contact_BAO_Relationship::relatedMemberships($contact_id_a,
6a488035
TO
783 $params,
784 $ids,
785 CRM_Core_Action::DELETE,
690c56c3 786 $active
6a488035
TO
787 );
788 }
789 elseif ($action & CRM_Core_Action::ENABLE) {
91244f1d 790 $ids['contact'] = empty($ids['contact']) ? $contact_id_a : $ids['contact'];
690c56c3 791 CRM_Contact_BAO_Relationship::relatedMemberships($contact_id_a,
6a488035
TO
792 $params,
793 $ids,
690c56c3 794 empty($params['id']) ? CRM_Core_Action::ADD : CRM_Core_Action::UPDATE,
795 $active
6a488035
TO
796 );
797 }
798 }
799 }
800
801 /**
fe482240 802 * Delete the object records that are associated with this contact.
6a488035 803 *
77c5b619
TO
804 * @param int $contactId
805 * Id of the contact to delete.
6a488035 806 */
00be9182 807 public static function deleteContact($contactId) {
6a488035
TO
808 $relationship = new CRM_Contact_DAO_Relationship();
809 $relationship->contact_id_a = $contactId;
810 $relationship->delete();
811
812 $relationship = new CRM_Contact_DAO_Relationship();
813 $relationship->contact_id_b = $contactId;
814 $relationship->delete();
815
816 CRM_Contact_BAO_Household::updatePrimaryContact(NULL, $contactId);
817 }
818
819 /**
fe482240 820 * Get the other contact in a relationship.
6a488035 821 *
77c5b619
TO
822 * @param int $id
823 * Relationship id.
6a488035 824 *
bb088986 825 * $returns returns the contact ids in the relationship
77b97be7
EM
826 *
827 * @return \CRM_Contact_DAO_Relationship
6a488035 828 */
eff45dce 829 public static function getRelationshipByID($id) {
6a488035
TO
830 $relationship = new CRM_Contact_DAO_Relationship();
831
832 $relationship->id = $id;
833 $relationship->selectAdd();
834 $relationship->selectAdd('contact_id_a, contact_id_b');
835 $relationship->find(TRUE);
836
837 return $relationship;
838 }
839
840 /**
fe482240 841 * Check if the relationship type selected between two contacts is correct.
6a488035 842 *
77c5b619
TO
843 * @param int $contact_a
844 * 1st contact id.
845 * @param int $contact_b
846 * 2nd contact id.
847 * @param int $relationshipTypeId
848 * Relationship type id.
6a488035 849 *
c301f76e 850 * @return bool
a6c01b45 851 * true if it is valid relationship else false
6a488035 852 */
00be9182 853 public static function checkRelationshipType($contact_a, $contact_b, $relationshipTypeId) {
6a488035
TO
854 $relationshipType = new CRM_Contact_DAO_RelationshipType();
855 $relationshipType->id = $relationshipTypeId;
856 $relationshipType->selectAdd();
857 $relationshipType->selectAdd('contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b');
858 if ($relationshipType->find(TRUE)) {
859 $contact_type_a = CRM_Contact_BAO_Contact::getContactType($contact_a);
860 $contact_type_b = CRM_Contact_BAO_Contact::getContactType($contact_b);
861
862 $contact_sub_type_a = CRM_Contact_BAO_Contact::getContactSubType($contact_a);
863 $contact_sub_type_b = CRM_Contact_BAO_Contact::getContactSubType($contact_b);
864
865 if (((!$relationshipType->contact_type_a) || ($relationshipType->contact_type_a == $contact_type_a)) &&
866 ((!$relationshipType->contact_type_b) || ($relationshipType->contact_type_b == $contact_type_b)) &&
867 ((!$relationshipType->contact_sub_type_a) || (in_array($relationshipType->contact_sub_type_a,
7f3647bc
TO
868 $contact_sub_type_a
869 ))) &&
6a488035 870 ((!$relationshipType->contact_sub_type_b) || (in_array($relationshipType->contact_sub_type_b,
7f3647bc
TO
871 $contact_sub_type_b
872 )))
6a488035
TO
873 ) {
874 return TRUE;
875 }
876 else {
877 return FALSE;
878 }
879 }
880 return FALSE;
881 }
882
883 /**
fe482240 884 * This function does the validtion for valid relationship.
6a488035 885 *
77c5b619
TO
886 * @param array $params
887 * This array contains the values there are subitted by the form.
888 * @param array $ids
889 * The array that holds all the db ids.
890 * @param int $contactId
891 * This is contact id for adding relationship.
6a488035 892 *
2a6da8d7 893 * @return string
6a488035 894 */
7ecf6275 895 public static function checkValidRelationship($params, $ids, $contactId) {
6a488035 896 $errors = '';
6a488035
TO
897 // function to check if the relationship selected is correct
898 // i.e. employer relationship can exit between Individual and Organization (not between Individual and Individual)
c4dcea5b
EM
899 if (!CRM_Contact_BAO_Relationship::checkRelationshipType($params['contact_id_a'], $params['contact_id_b'],
900 $params['relationship_type_id'])) {
6a488035
TO
901 $errors = 'Please select valid relationship between these two contacts.';
902 }
903 return $errors;
904 }
905
906 /**
fe482240 907 * This function checks for duplicate relationship.
6a488035 908 *
77c5b619
TO
909 * @param array $params
910 * (reference ) an assoc array of name/value pairs.
911 * @param int $id
912 * This the id of the contact whom we are adding relationship.
913 * @param int $contactId
914 * This is contact id for adding relationship.
915 * @param int $relationshipId
916 * This is relationship id for the contact.
6a488035 917 *
c301f76e 918 * @return bool
a6c01b45 919 * true if record exists else false
6a488035 920 */
00be9182 921 public static function checkDuplicateRelationship(&$params, $id, $contactId = 0, $relationshipId = 0) {
9c1bc317 922 $relationshipTypeId = $params['relationship_type_id'] ?? NULL;
decc60a0 923 list($type) = explode('_', $relationshipTypeId);
6a488035 924
f0fc26a5
DL
925 $queryString = "
926SELECT id
927FROM civicrm_relationship
928WHERE relationship_type_id = " . CRM_Utils_Type::escape($type, 'Integer');
6a488035
TO
929
930 /*
e70a7fc0
TO
931 * CRM-11792 - date fields from API are in ISO format, but this function
932 * supports date arrays BAO has increasingly standardised to ISO format
933 * so I believe this function should support ISO rather than make API
934 * format it - however, need to support array format for now to avoid breakage
2da59b29 935 * @ time of writing this function is called from Relationship::legacyCreateMultiple (twice)
e70a7fc0
TO
936 * CRM_BAO_Contact_Utils::clearCurrentEmployer (seemingly without dates)
937 * CRM_Contact_Form_Task_AddToOrganization::postProcess &
938 * CRM_Contact_Form_Task_AddToHousehold::postProcess
939 * (I don't think the last 2 support dates but not sure
940 */
6a488035 941
52335bb5 942 $dateFields = ['end_date', 'start_date'];
9b873358 943 foreach ($dateFields as $dateField) {
22e263ad 944 if (array_key_exists($dateField, $params)) {
9b873358 945 if (empty($params[$dateField]) || $params[$dateField] == 'null') {
f0fc26a5
DL
946 //this is most likely coming from an api call & probably loaded
947 // from the DB to deal with some of the
948 // other myriad of excessive checks still in place both in
949 // the api & the create functions
6a488035
TO
950 $queryString .= " AND $dateField IS NULL";
951 continue;
952 }
9b873358 953 elseif (is_array($params[$dateField])) {
f0fc26a5
DL
954 $queryString .= " AND $dateField = " .
955 CRM_Utils_Type::escape(CRM_Utils_Date::format($params[$dateField]), 'Date');
6a488035 956 }
f0fc26a5
DL
957 else {
958 $queryString .= " AND $dateField = " .
959 CRM_Utils_Type::escape($params[$dateField], 'Date');
6a488035
TO
960 }
961 }
962 }
963
964 $queryString .=
965 " AND ( ( contact_id_a = " . CRM_Utils_Type::escape($id, 'Integer') .
966 " AND contact_id_b = " . CRM_Utils_Type::escape($contactId, 'Integer') .
967 " ) OR ( contact_id_a = " . CRM_Utils_Type::escape($contactId, 'Integer') .
968 " AND contact_id_b = " . CRM_Utils_Type::escape($id, 'Integer') . " ) ) ";
969
970 //if caseId is provided, include it duplicate checking.
971 if ($caseId = CRM_Utils_Array::value('case_id', $params)) {
972 $queryString .= " AND case_id = " . CRM_Utils_Type::escape($caseId, 'Integer');
973 }
974
975 if ($relationshipId) {
976 $queryString .= " AND id !=" . CRM_Utils_Type::escape($relationshipId, 'Integer');
977 }
978
a36bd2a4 979 $relationship = CRM_Core_DAO::executeQuery($queryString);
6b284952
JV
980 while ($relationship->fetch()) {
981 // Check whether the custom field values are identical.
982 $result = self::checkDuplicateCustomFields($params, $relationship->id);
983 if ($result) {
6b284952
JV
984 return TRUE;
985 }
986 }
6b284952
JV
987 return FALSE;
988 }
989
990 /**
991 * this function checks whether the values of the custom fields in $params are
992 * the same as the values of the custom fields of the relation with given
993 * $relationshipId.
994 *
995 * @param array $params (reference) an assoc array of name/value pairs
996 * @param int $relationshipId ID of an existing duplicate relation
997 *
998 * @return boolean true if custom field values are identical
999 * @access private
1000 * @static
1001 */
1002 private static function checkDuplicateCustomFields(&$params, $relationshipId) {
e312bf62 1003 // Get the custom values of the existing relationship.
6b284952 1004 $existingValues = CRM_Core_BAO_CustomValueTable::getEntityValues($relationshipId, 'Relationship');
e312bf62 1005 // Create a similar array for the new relationship.
52335bb5 1006 $newValues = [];
317103ab 1007 if (isset($params['custom']) && is_array($params['custom'])) {
1bedc18d
JV
1008 // $params['custom'] seems to be an array. Each value is again an array.
1009 // This array contains one value (key -1), and this value seems to be
1010 // an array with the information about the custom value.
1011 foreach ($params['custom'] as $value) {
1012 foreach ($value as $customValue) {
1013 $newValues[$customValue['custom_field_id']] = $customValue['value'];
1014 }
6b284952
JV
1015 }
1016 }
e312bf62
JV
1017
1018 // Calculate difference between arrays. If the only key-value pairs
1019 // that are in one array but not in the other are empty, the
1020 // custom fields are considered to be equal.
1021 // See https://github.com/civicrm/civicrm-core/pull/6515#issuecomment-137985667
1022 $diff1 = array_diff_assoc($existingValues, $newValues);
1023 $diff2 = array_diff_assoc($newValues, $existingValues);
1024
1025 return !array_filter($diff1) && !array_filter($diff2);
6a488035
TO
1026 }
1027
1028 /**
fe482240 1029 * Update the is_active flag in the db.
6a488035 1030 *
77c5b619
TO
1031 * @param int $id
1032 * Id of the database record.
1033 * @param bool $is_active
1034 * Value we want to set the is_active field.
6a488035 1035 *
52335bb5 1036 * @return bool
1037 *
77b97be7 1038 * @throws CiviCRM_API3_Exception
6a488035 1039 */
00be9182 1040 public static function setIsActive($id, $is_active) {
49f8272d
E
1041 // as both the create & add functions have a bunch of logic in them that
1042 // doesn't seem to cope with a normal update we will call the api which
1043 // has tested handling for this
1044 // however, a longer term solution would be to simplify the add, create & api functions
1045 // to be more standard. It is debatable @ that point whether it's better to call the BAO
1046 // direct as the api is more tested.
52335bb5 1047 $result = civicrm_api('relationship', 'create', [
80109b10 1048 'id' => $id,
1049 'is_active' => $is_active,
1050 'version' => 3,
52335bb5 1051 ]);
80109b10 1052
338ca861 1053 if (is_array($result) && !empty($result['is_error']) && $result['error_message'] != 'Duplicate Relationship') {
80109b10 1054 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array::value('error_code', $result, 'undefined'), $result);
1055 }
49f8272d 1056
6a488035
TO
1057 return TRUE;
1058 }
1059
1060 /**
98a06ae0 1061 * Fetch a relationship object and store the values in the values array.
6a488035 1062 *
77c5b619
TO
1063 * @param array $params
1064 * Input parameters to find object.
1065 * @param array $values
1066 * Output values of the object.
6a488035 1067 *
a6c01b45
CW
1068 * @return array
1069 * (reference) the values that could be potentially assigned to smarty
6a488035 1070 */
00be9182 1071 public static function &getValues(&$params, &$values) {
6a488035
TO
1072 if (empty($params)) {
1073 return NULL;
1074 }
52335bb5 1075 $v = [];
6a488035
TO
1076
1077 // get the specific number of relationship or all relationships.
a7488080 1078 if (!empty($params['numRelationship'])) {
6a488035
TO
1079 $v['data'] = &CRM_Contact_BAO_Relationship::getRelationship($params['contact_id'], NULL, $params['numRelationship']);
1080 }
1081 else {
1082 $v['data'] = CRM_Contact_BAO_Relationship::getRelationship($params['contact_id']);
1083 }
1084
1085 // get the total count of relationships
c23fcc07 1086 $v['totalCount'] = count($v['data']);
6a488035
TO
1087
1088 $values['relationship']['data'] = &$v['data'];
1089 $values['relationship']['totalCount'] = &$v['totalCount'];
1090
1091 return $v;
1092 }
1093
1094 /**
fe482240 1095 * Helper function to form the sql for relationship retrieval.
6a488035 1096 *
77c5b619
TO
1097 * @param int $contactId
1098 * Contact id.
1099 * @param int $status
1100 * (check const at top of file).
1101 * @param int $numRelationship
1102 * No of relationships to display (limit).
1103 * @param int $count
1104 * Get the no of relationships.
6a488035 1105 * $param int $relationshipId relationship id
100fef9d 1106 * @param int $relationshipId
77c5b619
TO
1107 * @param string $direction
1108 * The direction we are interested in a_b or b_a.
1109 * @param array $params
1110 * Array of extra values including relationship_type_id per api spec.
6a488035 1111 *
77b97be7 1112 * @return array
76e7a76c 1113 * [select, from, where]
923dfabb 1114 *
1115 * @throws \CRM_Core_Exception
1116 * @throws \CiviCRM_API3_Exception
6a488035 1117 */
52335bb5 1118 public static function makeURLClause($contactId, $status, $numRelationship, $count, $relationshipId, $direction, $params = []) {
6a488035
TO
1119 $select = $from = $where = '';
1120
1121 $select = '( ';
1122 if ($count) {
923dfabb 1123 if ($direction === 'a_b') {
6a488035
TO
1124 $select .= ' SELECT count(DISTINCT civicrm_relationship.id) as cnt1, 0 as cnt2 ';
1125 }
1126 else {
1127 $select .= ' SELECT 0 as cnt1, count(DISTINCT civicrm_relationship.id) as cnt2 ';
1128 }
1129 }
1130 else {
1131 $select .= ' SELECT civicrm_relationship.id as civicrm_relationship_id,
1132 civicrm_contact.sort_name as sort_name,
1133 civicrm_contact.display_name as display_name,
1134 civicrm_contact.job_title as job_title,
1135 civicrm_contact.employer_id as employer_id,
1136 civicrm_contact.organization_name as organization_name,
1137 civicrm_address.street_address as street_address,
1138 civicrm_address.city as city,
1139 civicrm_address.postal_code as postal_code,
1140 civicrm_state_province.abbreviation as state,
1141 civicrm_country.name as country,
1142 civicrm_email.email as email,
c6c691a5 1143 civicrm_contact.contact_type as contact_type,
20be4ac3 1144 civicrm_contact.contact_sub_type as contact_sub_type,
6a488035
TO
1145 civicrm_phone.phone as phone,
1146 civicrm_contact.id as civicrm_contact_id,
6a488035
TO
1147 civicrm_relationship.contact_id_b as contact_id_b,
1148 civicrm_relationship.contact_id_a as contact_id_a,
1149 civicrm_relationship_type.id as civicrm_relationship_type_id,
1150 civicrm_relationship.start_date as start_date,
1151 civicrm_relationship.end_date as end_date,
1152 civicrm_relationship.description as description,
1153 civicrm_relationship.is_active as is_active,
1154 civicrm_relationship.is_permission_a_b as is_permission_a_b,
1155 civicrm_relationship.is_permission_b_a as is_permission_b_a,
1156 civicrm_relationship.case_id as case_id';
1157
923dfabb 1158 if ($direction === 'a_b') {
6a488035 1159 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
c6c691a5 1160 civicrm_relationship_type.label_b_a as relation ';
6a488035
TO
1161 }
1162 else {
1163 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
c6c691a5 1164 civicrm_relationship_type.label_a_b as relation ';
6a488035
TO
1165 }
1166 }
1167
923dfabb 1168 $from = '
6a488035
TO
1169 FROM civicrm_relationship
1170INNER JOIN civicrm_relationship_type ON ( civicrm_relationship.relationship_type_id = civicrm_relationship_type.id )
923dfabb 1171INNER JOIN civicrm_contact ';
1172 if ($direction === 'a_b') {
6a488035
TO
1173 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_a ) ';
1174 }
1175 else {
1176 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_b ) ';
1177 }
b7d19957
CR
1178
1179 if (!$count) {
923dfabb 1180 $from .= '
6a488035
TO
1181LEFT JOIN civicrm_address ON (civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1)
1182LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
1183LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id AND civicrm_email.is_primary = 1)
1184LEFT JOIN civicrm_state_province ON (civicrm_address.state_province_id = civicrm_state_province.id)
1185LEFT JOIN civicrm_country ON (civicrm_address.country_id = civicrm_country.id)
923dfabb 1186';
b7d19957
CR
1187 }
1188
6a488035
TO
1189 $where = 'WHERE ( 1 )';
1190 if ($contactId) {
923dfabb 1191 if ($direction === 'a_b') {
6a488035
TO
1192 $where .= ' AND civicrm_relationship.contact_id_b = ' . CRM_Utils_Type::escape($contactId, 'Positive');
1193 }
1194 else {
075fa74e 1195 $where .= ' AND civicrm_relationship.contact_id_a = ' . CRM_Utils_Type::escape($contactId, 'Positive') . '
1196 AND civicrm_relationship.contact_id_a != civicrm_relationship.contact_id_b ';
6a488035
TO
1197 }
1198 }
1199 if ($relationshipId) {
1200 $where .= ' AND civicrm_relationship.id = ' . CRM_Utils_Type::escape($relationshipId, 'Positive');
1201 }
1202
1203 $date = date('Y-m-d');
1204 if ($status == self::PAST) {
1205 //this case for showing past relationship
1206 $where .= ' AND civicrm_relationship.is_active = 1 ';
1207 $where .= " AND civicrm_relationship.end_date < '" . $date . "'";
1208 }
1209 elseif ($status == self::DISABLED) {
1210 // this case for showing disabled relationship
1211 $where .= ' AND civicrm_relationship.is_active = 0 ';
1212 }
1213 elseif ($status == self::CURRENT) {
1214 //this case for showing current relationship
1215 $where .= ' AND civicrm_relationship.is_active = 1 ';
1216 $where .= " AND (civicrm_relationship.end_date >= '" . $date . "' OR civicrm_relationship.end_date IS NULL) ";
1217 }
1218 elseif ($status == self::INACTIVE) {
1219 //this case for showing inactive relationships
1220 $where .= " AND (civicrm_relationship.end_date < '" . $date . "'";
1221 $where .= ' OR civicrm_relationship.is_active = 0 )';
1222 }
1223
1224 // CRM-6181
1225 $where .= ' AND civicrm_contact.is_deleted = 0';
22e263ad 1226 if (!empty($params['membership_type_id']) && empty($params['relationship_type_id'])) {
c9c41397 1227 $where .= self::membershipTypeToRelationshipTypes($params, $direction);
1228 }
22e263ad
TO
1229 if (!empty($params['relationship_type_id'])) {
1230 if (is_array($params['relationship_type_id'])) {
7f3647bc 1231 $where .= " AND " . CRM_Core_DAO::createSQLFilter('relationship_type_id', $params['relationship_type_id'], 'Integer');
75638074 1232 }
1233 else {
1234 $where .= ' AND relationship_type_id = ' . CRM_Utils_Type::escape($params['relationship_type_id'], 'Positive');
1235 }
1236 }
923dfabb 1237 if ($direction === 'a_b') {
6a488035
TO
1238 $where .= ' ) UNION ';
1239 }
1240 else {
1241 $where .= ' ) ';
1242 }
1243
52335bb5 1244 return [$select, $from, $where];
6a488035
TO
1245 }
1246
1247 /**
fe482240 1248 * Get a list of relationships.
6a488035 1249 *
77c5b619
TO
1250 * @param int $contactId
1251 * Contact id.
1252 * @param int $status
1253 * 1: Past 2: Disabled 3: Current.
1254 * @param int $numRelationship
1255 * No of relationships to display (limit).
1256 * @param int $count
1257 * Get the no of relationships.
77b97be7 1258 * @param int $relationshipId
76e7a76c
CW
1259 * @param array $links
1260 * the list of links to display
1261 * @param int $permissionMask
1262 * the permission mask to be applied for the actions
77b97be7 1263 * @param bool $permissionedContact
76e7a76c 1264 * to return only permissioned Contact
77b97be7 1265 * @param array $params
644587aa
SL
1266 * @param bool $includeTotalCount
1267 * Should we return a count of total accessable relationships
77b97be7
EM
1268 *
1269 * @return array|int
76e7a76c 1270 * relationship records
923dfabb 1271 *
1272 * @throws \CRM_Core_Exception
1273 * @throws \CiviCRM_API3_Exception
6a488035 1274 */
c301f76e 1275 public static function getRelationship(
51ccfbbe 1276 $contactId = NULL,
7f3647bc
TO
1277 $status = 0, $numRelationship = 0,
1278 $count = 0, $relationshipId = 0,
1279 $links = NULL, $permissionMask = NULL,
75638074 1280 $permissionedContact = FALSE,
52335bb5 1281 $params = [], $includeTotalCount = FALSE
6a488035 1282 ) {
52335bb5 1283 $values = [];
6a488035
TO
1284 if (!$contactId && !$relationshipId) {
1285 return $values;
1286 }
1287
1288 list($select1, $from1, $where1) = self::makeURLClause($contactId, $status, $numRelationship,
75638074 1289 $count, $relationshipId, 'a_b', $params
6a488035
TO
1290 );
1291 list($select2, $from2, $where2) = self::makeURLClause($contactId, $status, $numRelationship,
75638074 1292 $count, $relationshipId, 'b_a', $params
6a488035
TO
1293 );
1294
1295 $order = $limit = '';
1296 if (!$count) {
40458f6c 1297 if (empty($params['sort'])) {
1298 $order = ' ORDER BY civicrm_relationship_type_id, sort_name ';
1299 }
1300 else {
1301 $order = " ORDER BY {$params['sort']} ";
1302 }
1303
1304 $offset = 0;
630d1aaa 1305 if (!empty($params['offset']) && $params['offset'] > 0) {
40458f6c 1306 $offset = $params['offset'];
1307 }
6a488035
TO
1308
1309 if ($numRelationship) {
40458f6c 1310 $limit = " LIMIT {$offset}, $numRelationship";
6a488035
TO
1311 }
1312 }
1313
1314 // building the query string
e729799a 1315 $queryString = $select1 . $from1 . $where1 . $select2 . $from2 . $where2;
6a488035
TO
1316
1317 $relationship = new CRM_Contact_DAO_Relationship();
1318
e729799a 1319 $relationship->query($queryString . $order . $limit);
52335bb5 1320 $row = [];
6a488035
TO
1321 if ($count) {
1322 $relationshipCount = 0;
1323 while ($relationship->fetch()) {
1324 $relationshipCount += $relationship->cnt1 + $relationship->cnt2;
1325 }
1326 return $relationshipCount;
1327 }
1328 else {
1329
644587aa 1330 if ($includeTotalCount) {
e729799a 1331 $values['total_relationships'] = CRM_Core_DAO::singleValueQuery("SELECT count(*) FROM ({$queryString}) AS r");
644587aa
SL
1332 }
1333
6a488035
TO
1334 $mask = NULL;
1335 if ($status != self::INACTIVE) {
1336 if ($links) {
1337 $mask = array_sum(array_keys($links));
1338 if ($mask & CRM_Core_Action::DISABLE) {
1339 $mask -= CRM_Core_Action::DISABLE;
1340 }
1341 if ($mask & CRM_Core_Action::ENABLE) {
1342 $mask -= CRM_Core_Action::ENABLE;
1343 }
1344
1345 if ($status == self::CURRENT) {
1346 $mask |= CRM_Core_Action::DISABLE;
1347 }
1348 elseif ($status == self::DISABLED) {
1349 $mask |= CRM_Core_Action::ENABLE;
1350 }
6a488035 1351 }
75b35151 1352 // temporary hold the value of $mask.
1353 $tempMask = $mask;
6a488035 1354 }
c23fcc07 1355
6a488035
TO
1356 while ($relationship->fetch()) {
1357 $rid = $relationship->civicrm_relationship_id;
1358 $cid = $relationship->civicrm_contact_id;
a93664c8 1359
dc15bb38 1360 if ($permissionedContact &&
a93664c8 1361 (!CRM_Contact_BAO_Contact_Permission::allow($cid))
6a488035
TO
1362 ) {
1363 continue;
1364 }
75b35151 1365 if ($status != self::INACTIVE && $links) {
1366 // assign the original value to $mask
1367 $mask = $tempMask;
1368 // display action links if $cid has edit permission for the relationship.
1369 if (!($permissionMask & CRM_Core_Permission::EDIT) && CRM_Contact_BAO_Contact_Permission::allow($cid, CRM_Core_Permission::EDIT)) {
1370 $permissions[] = CRM_Core_Permission::EDIT;
1371 $permissions[] = CRM_Core_Permission::DELETE;
1372 $permissionMask = CRM_Core_Action::mask($permissions);
1373 }
1374 $mask = $mask & $permissionMask;
1375 }
6a488035
TO
1376 $values[$rid]['id'] = $rid;
1377 $values[$rid]['cid'] = $cid;
1378 $values[$rid]['contact_id_a'] = $relationship->contact_id_a;
1379 $values[$rid]['contact_id_b'] = $relationship->contact_id_b;
c6c691a5 1380 $values[$rid]['contact_type'] = $relationship->contact_type;
20be4ac3 1381 $values[$rid]['contact_sub_type'] = $relationship->contact_sub_type;
6a488035
TO
1382 $values[$rid]['relationship_type_id'] = $relationship->civicrm_relationship_type_id;
1383 $values[$rid]['relation'] = $relationship->relation;
1384 $values[$rid]['name'] = $relationship->sort_name;
1385 $values[$rid]['display_name'] = $relationship->display_name;
1386 $values[$rid]['job_title'] = $relationship->job_title;
1387 $values[$rid]['email'] = $relationship->email;
1388 $values[$rid]['phone'] = $relationship->phone;
1389 $values[$rid]['employer_id'] = $relationship->employer_id;
1390 $values[$rid]['organization_name'] = $relationship->organization_name;
1391 $values[$rid]['country'] = $relationship->country;
1392 $values[$rid]['city'] = $relationship->city;
1393 $values[$rid]['state'] = $relationship->state;
1394 $values[$rid]['start_date'] = $relationship->start_date;
1395 $values[$rid]['end_date'] = $relationship->end_date;
1396 $values[$rid]['description'] = $relationship->description;
1397 $values[$rid]['is_active'] = $relationship->is_active;
1398 $values[$rid]['is_permission_a_b'] = $relationship->is_permission_a_b;
1399 $values[$rid]['is_permission_b_a'] = $relationship->is_permission_b_a;
1400 $values[$rid]['case_id'] = $relationship->case_id;
1401
1402 if ($status) {
1403 $values[$rid]['status'] = $status;
1404 }
1405
1406 $values[$rid]['civicrm_relationship_type_id'] = $relationship->civicrm_relationship_type_id;
1407
1408 if ($relationship->contact_id_a == $contactId) {
1409 $values[$rid]['rtype'] = 'a_b';
1410 }
1411 else {
1412 $values[$rid]['rtype'] = 'b_a';
1413 }
1414
1415 if ($links) {
52335bb5 1416 $replace = [
6a488035
TO
1417 'id' => $rid,
1418 'rtype' => $values[$rid]['rtype'],
1419 'cid' => $contactId,
1420 'cbid' => $values[$rid]['cid'],
1421 'caseid' => $values[$rid]['case_id'],
1422 'clientid' => $contactId,
52335bb5 1423 ];
6a488035
TO
1424
1425 if ($status == self::INACTIVE) {
1426 // setting links for inactive relationships
1427 $mask = array_sum(array_keys($links));
1428 if (!$values[$rid]['is_active']) {
1429 $mask -= CRM_Core_Action::DISABLE;
1430 }
1431 else {
1432 $mask -= CRM_Core_Action::ENABLE;
1433 $mask -= CRM_Core_Action::DISABLE;
1434 }
cd056f13 1435 $mask = $mask & $permissionMask;
6a488035
TO
1436 }
1437
1438 // Give access to manage case link by copying to MAX_ACTION index temporarily, depending on case permission of user.
1439 if ($values[$rid]['case_id']) {
1440 // Borrowed logic from CRM_Case_Page_Tab
1441 $hasCaseAccess = FALSE;
1442 if (CRM_Core_Permission::check('access all cases and activities')) {
1443 $hasCaseAccess = TRUE;
1444 }
1445 else {
1446 $userCases = CRM_Case_BAO_Case::getCases(FALSE);
1447 if (array_key_exists($values[$rid]['case_id'], $userCases)) {
1448 $hasCaseAccess = TRUE;
1449 }
1450 }
1451
1452 if ($hasCaseAccess) {
1453 // give access by copying to MAX_ACTION temporarily, otherwise leave at NONE which won't display
1454 $links[CRM_Core_Action::MAX_ACTION] = $links[CRM_Core_Action::NONE];
52335bb5 1455 $links[CRM_Core_Action::MAX_ACTION]['name'] = ts('Manage Case #%1', [1 => $values[$rid]['case_id']]);
f89f2102 1456 $links[CRM_Core_Action::MAX_ACTION]['class'] = 'no-popup';
6a488035
TO
1457
1458 // Also make sure we have the right client cid since can get here from multiple relationship tabs.
1459 if ($values[$rid]['rtype'] == 'b_a') {
1460 $replace['clientid'] = $values[$rid]['cid'];
1461 }
13a3d214 1462 $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
1463 }
1464 }
1465
87dab4a4 1466 $values[$rid]['action'] = CRM_Core_Action::formLink(
1cfa04c4
EM
1467 $links,
1468 $mask,
87dab4a4
AH
1469 $replace,
1470 ts('more'),
1471 FALSE,
1472 'relationship.selector.row',
1473 'Relationship',
1474 $rid);
6a488035
TO
1475 unset($links[CRM_Core_Action::MAX_ACTION]);
1476 }
1477 }
1478
6a488035
TO
1479 return $values;
1480 }
1481 }
1482
1483 /**
7cf463d9
M
1484 * Get list of relationship type based on the target contact type.
1485 * Both directions of relationships are included if their labels are not the same.
6a488035 1486 *
77c5b619 1487 * @param string $targetContactType
7cf463d9 1488 * A valid contact type (may be Individual, Organization, Household).
6a488035 1489 *
a6c01b45 1490 * @return array
7cf463d9 1491 * array reference of all relationship types with context to current contact type.
6a488035 1492 */
69078420 1493 public static function getRelationType($targetContactType) {
52335bb5 1494 $relationshipType = [];
6a488035
TO
1495 $allRelationshipType = CRM_Core_PseudoConstant::relationshipType();
1496
1497 foreach ($allRelationshipType as $key => $type) {
7b1ed533 1498 if ($type['contact_type_b'] == $targetContactType || empty($type['contact_type_b'])) {
6a488035
TO
1499 $relationshipType[$key . '_a_b'] = $type['label_a_b'];
1500 }
7cf463d9
M
1501 if (($type['contact_type_a'] == $targetContactType || empty($type['contact_type_a']))
1502 && $type['label_a_b'] != $type['label_b_a']
1503 ) {
1504 $relationshipType[$key . '_b_a'] = $type['label_b_a'];
1505 }
6a488035
TO
1506 }
1507
1508 return $relationshipType;
1509 }
1510
1511 /**
100fef9d 1512 * Create / update / delete membership for related contacts.
6a488035
TO
1513 *
1514 * This function will create/update/delete membership for related
1515 * contact based on 1) contact have active membership 2) that
1516 * membership is is extedned by the same relationship type to that
1517 * of the existing relationship.
1518 *
5a4f6742
CW
1519 * @param int $contactId
1520 * contact id.
1521 * @param array $params
1522 * array of values submitted by POST.
1523 * @param array $ids
1524 * array of ids.
bfa4da96 1525 * @param \const|int $action which action called this function
6a488035 1526 *
dd244018 1527 * @param bool $active
6a488035 1528 *
bfa4da96 1529 * @throws \CRM_Core_Exception
0a2663fd 1530 * @throws \CiviCRM_API3_Exception
6a488035 1531 */
00be9182 1532 public static function relatedMemberships($contactId, &$params, $ids, $action = CRM_Core_Action::ADD, $active = TRUE) {
6a488035 1533 // Check the end date and set the status of the relationship
decc60a0 1534 // accordingly.
6a488035 1535 $status = self::CURRENT;
52335bb5 1536 $targetContact = $targetContact = CRM_Utils_Array::value('contact_check', $params, []);
45089d88
CW
1537 $today = date('Ymd');
1538
1539 // If a relationship hasn't yet started, just return for now
1540 // TODO: handle edge-case of updating start_date of an existing relationship
1541 if (!empty($params['start_date'])) {
1542 $startDate = substr(CRM_Utils_Date::format($params['start_date']), 0, 8);
1543 if ($today < $startDate) {
1544 return;
1545 }
1546 }
6a488035
TO
1547
1548 if (!empty($params['end_date'])) {
45089d88 1549 $endDate = substr(CRM_Utils_Date::format($params['end_date']), 0, 8);
6a488035
TO
1550 if ($today > $endDate) {
1551 $status = self::PAST;
1552 }
1553 }
1554
45089d88
CW
1555 if (($action & CRM_Core_Action::ADD) && ($status & self::PAST)) {
1556 // If relationship is PAST and action is ADD, do nothing.
6a488035
TO
1557 return;
1558 }
1559
1560 $rel = explode('_', $params['relationship_type_id']);
1561
7f3647bc 1562 $relTypeId = $rel[0];
decc60a0
EM
1563 if (!empty($rel[1])) {
1564 $relDirection = "_{$rel[1]}_{$rel[2]}";
1565 }
1566 else {
1567 // this call is coming from somewhere where the direction was resolved early on (e.g an api call)
1568 // so we can assume _a_b
1569 $relDirection = "_a_b";
52335bb5 1570 $targetContact = [$params['contact_id_b'] => 1];
decc60a0 1571 }
04ad3598 1572
6a488035
TO
1573 if (($action & CRM_Core_Action::ADD) ||
1574 ($action & CRM_Core_Action::DELETE)
1575 ) {
1576 $contact = $contactId;
6a488035
TO
1577 }
1578 elseif ($action & CRM_Core_Action::UPDATE) {
6345c936 1579 $contact = (int) $ids['contact'];
52335bb5 1580 $targetContact = [$ids['contactTarget'] => 1];
6a488035
TO
1581 }
1582
1583 // Build the 'values' array for
1584 // 1. ContactA
1585 // 2. ContactB
1586 // This will allow us to check if either of the contacts in
1587 // relationship have active memberships.
1588
52335bb5 1589 $values = [];
6a488035
TO
1590
1591 // 1. ContactA
52335bb5 1592 $values[$contact] = [
6a488035
TO
1593 'relatedContacts' => $targetContact,
1594 'relationshipTypeId' => $relTypeId,
1595 'relationshipTypeDirection' => $relDirection,
52335bb5 1596 ];
6a488035
TO
1597 // 2. ContactB
1598 if (!empty($targetContact)) {
1599 foreach ($targetContact as $cid => $donCare) {
52335bb5 1600 $values[$cid] = [
1601 'relatedContacts' => [$contact => 1],
6a488035 1602 'relationshipTypeId' => $relTypeId,
52335bb5 1603 ];
6a488035 1604
52335bb5 1605 $relTypeParams = ['id' => $relTypeId];
1606 $relTypeValues = [];
6a488035
TO
1607 CRM_Contact_BAO_RelationshipType::retrieve($relTypeParams, $relTypeValues);
1608
1609 if (CRM_Utils_Array::value('name_a_b', $relTypeValues) == CRM_Utils_Array::value('name_b_a', $relTypeValues)) {
1610 $values[$cid]['relationshipTypeDirection'] = '_a_b';
1611 }
1612 else {
1613 $values[$cid]['relationshipTypeDirection'] = ($relDirection == '_a_b') ? '_b_a' : '_a_b';
1614 }
1615 }
1616 }
1617
73a949e4 1618 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant::membershipStatus());
bd655ee6 1619
6345c936 1620 $relationshipProcessor = new CRM_Member_Utils_RelationshipProcessor(array_keys($values), $active);
6a488035 1621 foreach ($values as $cid => $details) {
52335bb5 1622 $relatedContacts = array_keys(CRM_Utils_Array::value('relatedContacts', $details, []));
ee17a760 1623 $mainRelatedContactId = reset($relatedContacts);
6a488035 1624
6345c936 1625 foreach ($relationshipProcessor->getRelationshipMembershipsForContact((int) $cid) as $membershipId => $membershipValues) {
0a2663fd 1626 $membershipInherittedFromContactID = NULL;
1627 if (!empty($membershipValues['owner_membership_id'])) {
6345c936 1628 // @todo - $membership already has this now.
0a2663fd 1629 // Use get not getsingle so that we get e-notice noise but not a fatal is the membership has already been deleted.
1630 $inheritedFromMembership = civicrm_api3('Membership', 'get', ['id' => $membershipValues['owner_membership_id'], 'sequential' => 1])['values'][0];
1631 $membershipInherittedFromContactID = (int) $inheritedFromMembership['contact_id'];
1632 }
52335bb5 1633 $relTypeIds = [];
6a488035 1634 if ($action & CRM_Core_Action::DELETE) {
98fd6fc8 1635 // @todo don't return relTypeId here - but it seems to be used later in a cryptic way (hint cryptic is not a complement).
310c2031 1636 list($relTypeId, $isDeletable) = self::isInheritedMembershipInvalidated($membershipValues, $values, $cid);
98fd6fc8 1637 if ($isDeletable) {
73a949e4 1638 CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipValues['owner_membership_id'], $membershipValues['contact_id']);
6a488035
TO
1639 }
1640 continue;
1641 }
1642 if (($action & CRM_Core_Action::UPDATE) &&
1643 ($status & self::PAST) &&
1644 ($membershipValues['owner_membership_id'])
1645 ) {
1646 // If relationship is PAST and action is UPDATE
1647 // then delete the RELATED membership
1648 CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipValues['owner_membership_id'],
73a949e4 1649 $membershipValues['contact_id']
6a488035
TO
1650 );
1651 continue;
1652 }
1653
1654 // add / edit the memberships for related
1655 // contacts.
1656
6345c936 1657 // @todo - all these lines get 'relTypeDirs' - but it's already a key in the $membership array.
6a488035 1658 // Get the Membership Type Details.
563f6487 1659 $membershipType = CRM_Member_BAO_MembershipType::getMembershipType($membershipValues['membership_type_id']);
6a488035 1660 // Check if contact's relationship type exists in membership type
52335bb5 1661 $relTypeDirs = [];
a7488080 1662 if (!empty($membershipType['relationship_type_id'])) {
563f6487 1663 $relTypeIds = (array) $membershipType['relationship_type_id'];
6a488035 1664 }
a7488080 1665 if (!empty($membershipType['relationship_direction'])) {
563f6487 1666 $relDirections = (array) $membershipType['relationship_direction'];
6a488035
TO
1667 }
1668 foreach ($relTypeIds as $key => $value) {
1669 $relTypeDirs[] = $value . '_' . $relDirections[$key];
1670 }
1671 $relTypeDir = $details['relationshipTypeId'] . $details['relationshipTypeDirection'];
1672 if (in_array($relTypeDir, $relTypeDirs)) {
1673 // Check if relationship being created/updated is
1674 // similar to that of membership type's
1675 // relationship.
1676
1677 $membershipValues['owner_membership_id'] = $membershipId;
1678 unset($membershipValues['id']);
6a488035
TO
1679 unset($membershipValues['contact_id']);
1680 unset($membershipValues['membership_id']);
1681 foreach ($details['relatedContacts'] as $relatedContactId => $donCare) {
1682 $membershipValues['contact_id'] = $relatedContactId;
1683 if ($deceasedStatusId &&
1684 CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $relatedContactId, 'is_deceased')
1685 ) {
1686 $membershipValues['status_id'] = $deceasedStatusId;
1687 $membershipValues['skipStatusCal'] = TRUE;
1688 }
6a488035 1689
6345c936 1690 if (in_array($action, [CRM_Core_Action::UPDATE, CRM_Core_Action::ADD, CRM_Core_Action::ENABLE])) {
e72dea83 1691 //if updated relationship is already related to contact don't delete existing inherited membership
6345c936 1692 if (in_array((int) $relatedContactId, $membershipValues['inheriting_contact_ids'], TRUE)
1693 || $relatedContactId === $membershipValues['owner_contact_id']
1694 ) {
e72dea83 1695 continue;
1696 }
1697
1698 //delete the membership record for related
1699 //contact before creating new membership record.
1700 CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipId, $relatedContactId);
1701 }
00538ec6 1702 //skip status calculation for pay later memberships.
6345c936 1703 if ('Pending' === CRM_Core_PseudoConstant::getName('CRM_Member_BAO_Membership', 'status_id', $membershipValues['status_id'])) {
00538ec6
JP
1704 $membershipValues['skipStatusCal'] = TRUE;
1705 }
0a2663fd 1706 // As long as the membership itself was not created by inheritance from the same contact
1707 // that stands to inherit the membership we add an inherited membership.
1708 if ($membershipInherittedFromContactID !== (int) $membershipValues['contact_id']) {
1709 $membershipValues = self::addInheritedMembership($membershipValues);
1710 }
6a488035
TO
1711 }
1712 }
1713 elseif ($action & CRM_Core_Action::UPDATE) {
1714 // if action is update and updated relationship do
1715 // not match with the existing
1716 // membership=>relationship then we need to
e62adec9 1717 // change the status of the membership record to expired for
1718 // previous relationship -- CRM-12078.
1719 // CRM-16087 we need to pass ownerMembershipId to isRelatedMembershipExpired function
690c56c3 1720 if (empty($params['relationship_ids']) && !empty($params['id'])) {
52335bb5 1721 $relIds = [$params['id']];
690c56c3 1722 }
1723 else {
9c1bc317 1724 $relIds = $params['relationship_ids'] ?? NULL;
690c56c3 1725 }
e62adec9 1726 if (self::isRelatedMembershipExpired($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId,
52335bb5 1727 $relIds) && !empty($membershipValues['owner_membership_id']
1728 ) && !empty($values[$mainRelatedContactId]['memberships'][$membershipValues['owner_membership_id']])) {
e62adec9 1729 $membershipValues['status_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', 'Expired', 'id', 'label');
1730 $type = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $membershipValues['membership_type_id'], 'name', 'id');
1731 CRM_Member_BAO_Membership::add($membershipValues);
1836ab9e 1732 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
1733 }
1734 }
1735 }
1736 }
1737 }
1738
1739 /**
e62adec9 1740 * Helper function to check whether the membership is expired or not.
6616f7c1
EM
1741 *
1742 * Function takes a list of related membership types and if it is not also passed a
e62adec9 1743 * relationship ID of that types evaluates whether the membership status should be changed to expired.
6616f7c1
EM
1744 *
1745 * @param array $membershipTypeRelationshipTypeIDs
1746 * Relation type IDs related to the given membership type.
1747 * @param int $contactId
1748 * @param int $mainRelatedContactId
1749 * @param int $relTypeId
1750 * @param array $relIds
1751 *
1752 * @return bool
6a488035 1753 */
e62adec9 1754 public static function isRelatedMembershipExpired($membershipTypeRelationshipTypeIDs, $contactId, $mainRelatedContactId, $relTypeId, $relIds) {
6616f7c1 1755 if (empty($membershipTypeRelationshipTypeIDs) || in_array($relTypeId, $membershipTypeRelationshipTypeIDs)) {
eec8d770 1756 return FALSE;
6a488035
TO
1757 }
1758
1759 if (empty($relIds)) {
1760 return FALSE;
1761 }
1762
52335bb5 1763 $relParamas = [
1764 1 => [$contactId, 'Integer'],
1765 2 => [$mainRelatedContactId, 'Integer'],
1766 ];
6a488035
TO
1767
1768 if ($contactId == $mainRelatedContactId) {
6616f7c1
EM
1769 $recordsFound = (int) CRM_Core_DAO::singleValueQuery("SELECT COUNT(*) FROM civicrm_relationship WHERE relationship_type_id IN ( " . implode(',', $membershipTypeRelationshipTypeIDs) . " ) AND
1770contact_id_a IN ( %1 ) OR contact_id_b IN ( %1 ) AND id IN (" . implode(',', $relIds) . ")", $relParamas);
6a488035
TO
1771 if ($recordsFound) {
1772 return FALSE;
1773 }
1774 return TRUE;
1775 }
1776
6616f7c1 1777 $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
1778
1779 if ($recordsFound) {
1780 return FALSE;
1781 }
1782
1783 return TRUE;
1784 }
1785
1786 /**
fe482240 1787 * Get Current Employer for Contact.
6a488035 1788 *
77c5b619
TO
1789 * @param $contactIds
1790 * Contact Ids.
6a488035 1791 *
a6c01b45
CW
1792 * @return array
1793 * array of the current employer
6a488035 1794 */
00be9182 1795 public static function getCurrentEmployer($contactIds) {
6a488035
TO
1796 $contacts = implode(',', $contactIds);
1797
1798 $query = "
1799SELECT organization_name, id, employer_id
1800FROM civicrm_contact
1801WHERE id IN ( {$contacts} )
1802";
1803
33621c4f 1804 $dao = CRM_Core_DAO::executeQuery($query);
52335bb5 1805 $currentEmployer = [];
6a488035
TO
1806 while ($dao->fetch()) {
1807 $currentEmployer[$dao->id]['org_id'] = $dao->employer_id;
1808 $currentEmployer[$dao->id]['org_name'] = $dao->organization_name;
1809 }
1810
1811 return $currentEmployer;
1812 }
1813
7f3647bc 1814 /**
fe482240 1815 * Function to return list of permissioned contacts for a given contact and relationship type.
7f3647bc 1816 *
5a4f6742
CW
1817 * @param int $contactID
1818 * contact id whose permissioned contacts are to be found.
b0076fe6 1819 * @param int $relTypeId
5a4f6742
CW
1820 * one or more relationship type id's.
1821 * @param string $name
33260076 1822 * @param string $contactType
7f3647bc 1823 *
a6c01b45 1824 * @return array
16b10e64 1825 * Array of contacts
7f3647bc 1826 */
33260076 1827 public static function getPermissionedContacts($contactID, $relTypeId = NULL, $name = NULL, $contactType = NULL) {
52335bb5 1828 $contacts = [];
1829 $args = [1 => [$contactID, 'Integer']];
33260076 1830 $relationshipTypeClause = $contactTypeClause = '';
51e89def 1831
6a488035 1832 if ($relTypeId) {
b0076fe6
EM
1833 // @todo relTypeId is only ever passed in as an int. Change this to reflect that -
1834 // probably being overly conservative by not doing so but working on stable release.
1835 $relationshipTypeClause = 'AND cr.relationship_type_id IN (%2) ';
52335bb5 1836 $args[2] = [$relTypeId, 'String'];
b0076fe6 1837 }
33260076 1838
1839 if ($contactType) {
1840 $contactTypeClause = ' AND cr.relationship_type_id = crt.id AND crt.contact_type_b = %3 ';
52335bb5 1841 $args[3] = [$contactType, 'String'];
33260076 1842 }
1843
4779abb3 1844 $query = "
6a488035 1845SELECT cc.id as id, cc.sort_name as name
33260076 1846FROM civicrm_relationship cr, civicrm_contact cc, civicrm_relationship_type crt
49f8272d 1847WHERE
51e89def 1848cr.contact_id_a = %1 AND
51e89def 1849cr.is_permission_a_b = 1 AND
6a488035
TO
1850IF(cr.end_date IS NULL, 1, (DATEDIFF( CURDATE( ), cr.end_date ) <= 0)) AND
1851cr.is_active = 1 AND
7ecf6275 1852cc.id = cr.contact_id_b AND
b0076fe6
EM
1853cc.is_deleted = 0
1854$relationshipTypeClause
33260076 1855$contactTypeClause
b0076fe6 1856";
51e89def 1857
4779abb3 1858 if (!empty($name)) {
1859 $name = CRM_Utils_Type::escape($name, 'String');
1860 $query .= "
49f8272d 1861AND cc.sort_name LIKE '%$name%'";
4779abb3 1862 }
6a488035 1863
4779abb3 1864 $dao = CRM_Core_DAO::executeQuery($query, $args);
1865 while ($dao->fetch()) {
52335bb5 1866 $contacts[$dao->id] = [
4779abb3 1867 'name' => $dao->name,
1868 'value' => $dao->id,
52335bb5 1869 ];
4779abb3 1870 }
b0076fe6 1871
51e89def 1872 return $contacts;
6a488035
TO
1873 }
1874
6a488035 1875 /**
fe482240 1876 * Merge relationships from otherContact to mainContact.
bfa4da96 1877 *
6a488035
TO
1878 * Called during contact merge operation
1879 *
77c5b619
TO
1880 * @param int $mainId
1881 * Contact id of main contact record.
1882 * @param int $otherId
1883 * Contact id of record which is going to merge.
1884 * @param array $sqls
1885 * (reference) array of sql statements to append to.
6a488035
TO
1886 *
1887 * @see CRM_Dedupe_Merger::cpTables()
6a488035 1888 */
00be9182 1889 public static function mergeRelationships($mainId, $otherId, &$sqls) {
6a488035
TO
1890 // Delete circular relationships
1891 $sqls[] = "DELETE FROM civicrm_relationship
6ce3ea65
JJ
1892 WHERE (contact_id_a = $mainId AND contact_id_b = $otherId AND case_id IS NULL)
1893 OR (contact_id_b = $mainId AND contact_id_a = $otherId AND case_id IS NULL)";
6a488035
TO
1894
1895 // Delete relationship from other contact if main contact already has that relationship
1896 $sqls[] = "DELETE r2
1897 FROM civicrm_relationship r1, civicrm_relationship r2
1898 WHERE r1.relationship_type_id = r2.relationship_type_id
1899 AND r1.id <> r2.id
6ce3ea65 1900 AND r1.case_id IS NULL AND r2.case_id IS NULL
6a488035
TO
1901 AND (
1902 r1.contact_id_a = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_b = r2.contact_id_b
1903 OR r1.contact_id_b = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_a = r2.contact_id_a
1904 OR (
1905 (r1.contact_id_a = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_b = r2.contact_id_a
1906 OR r1.contact_id_b = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_a = r2.contact_id_b)
1907 AND r1.relationship_type_id IN (SELECT id FROM civicrm_relationship_type WHERE name_b_a = name_a_b)
1908 )
1909 )";
1910
1911 // Move relationships
1912 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_a = $mainId WHERE contact_id_a = $otherId";
1913 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_b = $mainId WHERE contact_id_b = $otherId";
1914
1915 // Move current employer id (name will get updated later)
1916 $sqls[] = "UPDATE civicrm_contact SET employer_id = $mainId WHERE employer_id = $otherId";
1917 }
1918
1919 /**
1920 * Set 'is_valid' field to false for all relationships whose end date is in the past, ie. are expired.
1921 *
72b3a70c
CW
1922 * @return bool
1923 * True on success, false if error is encountered.
f42bcfb1 1924 * @throws \CiviCRM_API3_Exception
6a488035 1925 */
00be9182 1926 public static function disableExpiredRelationships() {
6a488035
TO
1927 $query = "SELECT id FROM civicrm_relationship WHERE is_active = 1 AND end_date < CURDATE()";
1928
1929 $dao = CRM_Core_DAO::executeQuery($query);
1930 while ($dao->fetch()) {
1931 $result = CRM_Contact_BAO_Relationship::setIsActive($dao->id, FALSE);
1932 // Result will be NULL if error occurred. We abort early if error detected.
1933 if ($result == NULL) {
1934 return FALSE;
1935 }
1936 }
1937 return TRUE;
1938 }
c9c41397 1939
1940 /**
fe482240 1941 * Function filters the query by possible relationships for the membership type.
98a06ae0 1942 *
c9c41397 1943 * It is intended to be called when constructing queries for the api (reciprocal & non-reciprocal)
1944 * and to add clauses to limit the return to those relationships which COULD inherit a membership type
1945 * (as opposed to those who inherit a particular membership
1946 *
77c5b619
TO
1947 * @param array $params
1948 * Api input array.
77b97be7
EM
1949 * @param null $direction
1950 *
c301f76e 1951 * @return array|void
52335bb5 1952 * @throws \CiviCRM_API3_Exception
c9c41397 1953 */
00be9182 1954 public static function membershipTypeToRelationshipTypes(&$params, $direction = NULL) {
52335bb5 1955 $membershipType = civicrm_api3('membership_type', 'getsingle', [
353ffa53
TO
1956 'id' => $params['membership_type_id'],
1957 'return' => 'relationship_type_id, relationship_direction',
52335bb5 1958 ]);
c9c41397 1959 $relationshipTypes = $membershipType['relationship_type_id'];
22e263ad 1960 if (empty($relationshipTypes)) {
c301f76e 1961 return NULL;
f201289d 1962 }
c9c41397 1963 // if we don't have any contact data we can only filter on type
22e263ad 1964 if (empty($params['contact_id']) && empty($params['contact_id_a']) && empty($params['contact_id_a'])) {
52335bb5 1965 $params['relationship_type_id'] = ['IN' => $relationshipTypes];
c301f76e 1966 return NULL;
c9c41397 1967 }
1968 else {
1a9b2ee8 1969 $relationshipDirections = (array) $membershipType['relationship_direction'];
c9c41397 1970 // if we have contact_id_a OR contact_id_b we can make a call here
1971 // if we have contact??
1972 foreach ($relationshipDirections as $index => $mtdirection) {
7f3647bc 1973 if (isset($params['contact_id_a']) && $mtdirection == 'a_b' || $direction == 'a_b') {
c9c41397 1974 $types[] = $relationshipTypes[$index];
1975 }
7f3647bc 1976 if (isset($params['contact_id_b']) && $mtdirection == 'b_a' || $direction == 'b_a') {
c9c41397 1977 $types[] = $relationshipTypes[$index];
1978 }
1979 }
22e263ad 1980 if (!empty($types)) {
52335bb5 1981 $params['relationship_type_id'] = ['IN' => $types];
c9c41397 1982 }
7f3647bc 1983 elseif (!empty($clauses)) {
c9c41397 1984 return explode(' OR ', $clauses);
1985 }
92e4c2a5 1986 else {
c9c41397 1987 // effectively setting it to return no results
1988 $params['relationship_type_id'] = 0;
1989 }
1990 }
1991 }
40458f6c 1992
40458f6c 1993 /**
98a06ae0 1994 * Wrapper for contact relationship selector.
40458f6c 1995 *
77c5b619
TO
1996 * @param array $params
1997 * Associated array for params record id.
40458f6c 1998 *
a6c01b45
CW
1999 * @return array
2000 * associated array of contact relationships
52335bb5 2001 * @throws \Exception
40458f6c 2002 */
2003 public static function getContactRelationshipSelector(&$params) {
2004 // format the params
7f3647bc 2005 $params['offset'] = ($params['page'] - 1) * $params['rp'];
9c1bc317 2006 $params['sort'] = $params['sortBy'] ?? NULL;
40458f6c 2007
2008 if ($params['context'] == 'past') {
2009 $relationshipStatus = CRM_Contact_BAO_Relationship::INACTIVE;
2010 }
62e6afce 2011 elseif ($params['context'] == 'all') {
6c292184
TM
2012 $relationshipStatus = CRM_Contact_BAO_Relationship::ALL;
2013 }
40458f6c 2014 else {
2015 $relationshipStatus = CRM_Contact_BAO_Relationship::CURRENT;
2016 }
2017
2018 // check logged in user for permission
2019 $page = new CRM_Core_Page();
2020 CRM_Contact_Page_View::checkUserPermission($page, $params['contact_id']);
52335bb5 2021 $permissions = [$page->_permission];
40458f6c 2022 if ($page->_permission == CRM_Core_Permission::EDIT) {
2023 $permissions[] = CRM_Core_Permission::DELETE;
2024 }
2025 $mask = CRM_Core_Action::mask($permissions);
2026
a93664c8 2027 $permissionedContacts = TRUE;
d0592c3d 2028 if ($params['context'] != 'user') {
2029 $links = CRM_Contact_Page_View_Relationship::links();
d0592c3d 2030 }
2031 else {
2032 $links = CRM_Contact_Page_View_UserDashBoard::links();
d0592c3d 2033 $mask = NULL;
2034 }
40458f6c 2035 // get contact relationships
2036 $relationships = CRM_Contact_BAO_Relationship::getRelationship($params['contact_id'],
2037 $relationshipStatus,
2038 $params['rp'], 0, 0,
d0592c3d 2039 $links, $mask,
2040 $permissionedContacts,
644587aa 2041 $params, TRUE
40458f6c 2042 );
2043
52335bb5 2044 $contactRelationships = [];
644587aa
SL
2045 $params['total'] = $relationships['total_relationships'];
2046 unset($relationships['total_relationships']);
40458f6c 2047 if (!empty($relationships)) {
40458f6c 2048
1250f3d8
AH
2049 $displayName = CRM_Contact_BAO_Contact::displayName($params['contact_id']);
2050
40458f6c 2051 // format params
2052 foreach ($relationships as $relationshipId => $values) {
52335bb5 2053 $relationship = [];
7d12de7f 2054
febb6506 2055 $relationship['DT_RowId'] = $values['id'];
7d12de7f
JL
2056 $relationship['DT_RowClass'] = 'crm-entity';
2057 if ($values['is_active'] == 0) {
2058 $relationship['DT_RowClass'] .= ' disabled';
2059 }
2060
52335bb5 2061 $relationship['DT_RowAttr'] = [];
febb6506
JL
2062 $relationship['DT_RowAttr']['data-entity'] = 'relationship';
2063 $relationship['DT_RowAttr']['data-id'] = $values['id'];
7d12de7f 2064
20be4ac3
BS
2065 //Add image icon for related contacts: CRM-14919; CRM-19668
2066 $contactType = (!empty($values['contact_sub_type'])) ? $values['contact_sub_type'] : $values['contact_type'];
2067 $icon = CRM_Contact_BAO_Contact_Utils::getImage($contactType,
67e4fb51
N
2068 FALSE,
2069 $values['cid']
2070 );
7d12de7f 2071 $relationship['sort_name'] = $icon . ' ' . CRM_Utils_System::href(
7f3647bc
TO
2072 $values['name'],
2073 'civicrm/contact/view',
2074 "reset=1&cid={$values['cid']}");
40458f6c 2075
0a61e567 2076 $relationship['relation'] = CRM_Utils_Array::value('case', $values, '') . CRM_Utils_System::href(
52335bb5 2077 $values['relation'],
2078 'civicrm/contact/view/rel',
2079 "action=view&reset=1&cid={$values['cid']}&id={$values['id']}&rtype={$values['rtype']}");
40458f6c 2080
66229fd5
AS
2081 if (!empty($values['description'])) {
2082 $relationship['relation'] .= "<p class='description'>{$values['description']}</p>";
2083 }
2084
d0592c3d 2085 if ($params['context'] == 'current') {
fee0416f
AH
2086 $smarty = CRM_Core_Smarty::singleton();
2087
2088 $contactCombos = [
2089 [
2090 'permContact' => $params['contact_id'],
2091 'permDisplayName' => $displayName,
2092 'otherContact' => $values['cid'],
2093 'otherDisplayName' => $values['display_name'],
2094 'columnKey' => 'sort_name',
2095 ],
2096 [
2097 'permContact' => $values['cid'],
2098 'permDisplayName' => $values['display_name'],
2099 'otherContact' => $params['contact_id'],
2100 'otherDisplayName' => $displayName,
2101 'columnKey' => 'relation',
2102 ],
2103 ];
2104
2105 foreach ($contactCombos as $combo) {
2106 foreach ([CRM_Contact_BAO_Relationship::EDIT, CRM_Contact_BAO_Relationship::VIEW] as $permType) {
2107 $smarty->assign('permType', $permType);
2108 if (($combo['permContact'] == $values['contact_id_a'] and $values['is_permission_a_b'] == $permType)
2109 || ($combo['permContact'] == $values['contact_id_b'] and $values['is_permission_b_a'] == $permType)
2110 ) {
2111 $smarty->assign('permDisplayName', $combo['permDisplayName']);
2112 $smarty->assign('otherDisplayName', $combo['otherDisplayName']);
2113 $relationship[$combo['columnKey']] .= $smarty->fetch('CRM/Contact/Page/View/RelationshipPerm.tpl');
2114 }
2115 }
f871c3a9 2116 }
40458f6c 2117 }
2118
7d12de7f
JL
2119 $relationship['start_date'] = CRM_Utils_Date::customFormat($values['start_date']);
2120 $relationship['end_date'] = CRM_Utils_Date::customFormat($values['end_date']);
2121 $relationship['city'] = $values['city'];
2122 $relationship['state'] = $values['state'];
2123 $relationship['email'] = $values['email'];
2124 $relationship['phone'] = $values['phone'];
2125 $relationship['links'] = $values['action'];
2126
2127 array_push($contactRelationships, $relationship);
40458f6c 2128 }
2129 }
7d12de7f 2130
16b745b0
MWMC
2131 $columnHeaders = self::getColumnHeaders();
2132 $selector = NULL;
2133 CRM_Utils_Hook::searchColumns('relationship.rows', $columnHeaders, $contactRelationships, $selector);
2134
52335bb5 2135 $relationshipsDT = [];
7d12de7f
JL
2136 $relationshipsDT['data'] = $contactRelationships;
2137 $relationshipsDT['recordsTotal'] = $params['total'];
2138 $relationshipsDT['recordsFiltered'] = $params['total'];
2139
2140 return $relationshipsDT;
40458f6c 2141 }
2142
16b745b0
MWMC
2143 /**
2144 * @return array
2145 */
2146 public static function getColumnHeaders() {
2147 return [
2148 'relation' => [
2149 'name' => ts('Relationship'),
2150 'sort' => 'relation',
2151 'direction' => CRM_Utils_Sort::ASCENDING,
2152 ],
2153 'sort_name' => [
2154 'name' => '',
2155 'sort' => 'sort_name',
2156 'direction' => CRM_Utils_Sort::ASCENDING,
2157 ],
2158 'start_date' => [
2159 'name' => ts('Start'),
2160 'sort' => 'start_date',
2161 'direction' => CRM_Utils_Sort::DONTCARE,
2162 ],
2163 'end_date' => [
2164 'name' => ts('End'),
2165 'sort' => 'end_date',
2166 'direction' => CRM_Utils_Sort::DONTCARE,
2167 ],
2168 'city' => [
2169 'name' => ts('City'),
2170 'sort' => 'city',
2171 'direction' => CRM_Utils_Sort::DONTCARE,
2172 ],
2173 'state' => [
2174 'name' => ts('State/Prov'),
2175 'sort' => 'state',
2176 'direction' => CRM_Utils_Sort::DONTCARE,
2177 ],
2178 'email' => [
2179 'name' => ts('Email'),
2180 'sort' => 'email',
2181 'direction' => CRM_Utils_Sort::DONTCARE,
2182 ],
2183 'phone' => [
2184 'name' => ts('Phone'),
2185 'sort' => 'phone',
2186 'direction' => CRM_Utils_Sort::DONTCARE,
2187 ],
2188 'links' => [
2189 'name' => '',
2190 'sort' => 'links',
2191 'direction' => CRM_Utils_Sort::DONTCARE,
2192 ],
2193 ];
2194 }
2195
89e45979
MD
2196 /**
2197 * @inheritdoc
2198 */
52335bb5 2199 public static function buildOptions($fieldName, $context = NULL, $props = []) {
1ac9bb56
CW
2200 // Quickform-specific format, for use when editing relationship type options in a popup from the contact relationship form
2201 if ($fieldName === 'relationship_type_id' && !empty($props['is_form'])) {
2202 return self::getContactRelationshipType(
2203 $props['contact_id'] ?? NULL,
2204 $props['relationship_direction'] ?? 'a_b',
2205 $props['relationship_id'] ?? NULL,
2206 $props['contact_type'] ?? NULL
2207 );
89e45979
MD
2208 }
2209
2210 return parent::buildOptions($fieldName, $context, $props);
2211 }
2212
df0c42cc
JP
2213 /**
2214 * Process the params from api, form and check if current
2215 * employer should be set or unset.
2216 *
2217 * @param array $params
2218 * @param int $relationshipId
e97c66ff 2219 * @param int|null $updatedRelTypeID
df0c42cc
JP
2220 *
2221 * @return bool
2222 * TRUE if current employer needs to be cleared.
f42bcfb1 2223 * @throws \CiviCRM_API3_Exception
df0c42cc
JP
2224 */
2225 public static function isCurrentEmployerNeedingToBeCleared($params, $relationshipId, $updatedRelTypeID = NULL) {
f42bcfb1 2226 $existingTypeID = (int) CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Relationship', $relationshipId, 'relationship_type_id');
df0c42cc 2227 $updatedRelTypeID = $updatedRelTypeID ? $updatedRelTypeID : $existingTypeID;
0c578c02 2228 $currentEmployerID = (int) civicrm_api3('Contact', 'getvalue', ['return' => 'current_employer_id', 'id' => $params['contact_id_a']]);
df0c42cc 2229
0c578c02 2230 if ($currentEmployerID !== (int) $params['contact_id_b'] || !self::isRelationshipTypeCurrentEmployer($existingTypeID)) {
df0c42cc
JP
2231 return FALSE;
2232 }
2233 //Clear employer if relationship is expired.
2234 if (!empty($params['end_date']) && strtotime($params['end_date']) < time()) {
2235 return TRUE;
2236 }
2237 //current employer checkbox is disabled on the form.
2238 //inactive or relationship type(employer of) is updated.
2239 if ((isset($params['is_current_employer']) && empty($params['is_current_employer']))
2240 || ((isset($params['is_active']) && empty($params['is_active'])))
2241 || $existingTypeID != $updatedRelTypeID) {
0c578c02
MD
2242 // If there are no other active employer relationships between the same 2 contacts...
2243 if (!civicrm_api3('Relationship', 'getcount', [
2244 'is_active' => 1,
2245 'relationship_type_id' => $existingTypeID,
2246 'id' => ['<>' => $params['id']],
2247 'contact_id_a' => $params['contact_id_a'],
2248 'contact_id_b' => $params['contact_id_b'],
2249 ])) {
2250 return TRUE;
2251 }
df0c42cc
JP
2252 }
2253
2254 return FALSE;
2255 }
2256
f42bcfb1
MD
2257 /**
2258 * Is this a current employer relationship type.
2259 *
2260 * @todo - this could use cached pseudoconstant lookups.
2261 *
2262 * @param int $existingTypeID
2263 *
2264 * @return bool
2265 */
2266 private static function isRelationshipTypeCurrentEmployer(int $existingTypeID): bool {
2267 $isCurrentEmployerRelationshipType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', $existingTypeID, 'name_b_a') === 'Employer of';
2268 return $isCurrentEmployerRelationshipType;
2269 }
2270
98fd6fc8 2271 /**
2272 * Is the inherited relationship invalidated by this relationship change.
2273 *
2274 * @param $membershipValues
2275 * @param array $values
2276 * @param int $cid
98fd6fc8 2277 *
2278 * @return array
eb151aab 2279 * @throws \CiviCRM_API3_Exception
98fd6fc8 2280 */
310c2031 2281 private static function isInheritedMembershipInvalidated($membershipValues, array $values, $cid): array {
2282 // @todo most of this can go - it's just the weird historical returning of $relTypeId that it does.
2283 // now we have caching the parent fn can just call CRM_Member_BAO_MembershipType::getMembershipType
eb151aab 2284 $membershipType = CRM_Member_BAO_MembershipType::getMembershipType($membershipValues['membership_type_id']);
2285 $relTypeIds = $membershipType['relationship_type_id'];
310c2031 2286 $membershipInheritedFrom = $membershipValues['owner_membership_id'] ?? NULL;
2287 if (!$membershipInheritedFrom || !in_array($values[$cid]['relationshipTypeId'], $relTypeIds)) {
eb151aab 2288 return [implode(',', $relTypeIds), FALSE];
2289 }
2290 //CRM-16300 check if owner membership exist for related membership
310c2031 2291 return [implode(',', $relTypeIds), !self::isContactHasValidRelationshipToInheritMembershipType((int) $cid, (int) $membershipValues['membership_type_id'], (int) $membershipValues['owner_membership_id'])];
2292 }
2293
2294 /**
2295 * Is there a valid relationship confering this membership type on this contact.
2296 *
2297 * @param int $contactID
2298 * @param int $membershipTypeID
2299 * @param int $parentMembershipID
2300 * Id of the membership being inherited.
2301 *
2302 * @return bool
2303 *
2304 * @throws \CiviCRM_API3_Exception
2305 */
2306 private static function isContactHasValidRelationshipToInheritMembershipType(int $contactID, int $membershipTypeID, int $parentMembershipID): bool {
2307 $membershipType = CRM_Member_BAO_MembershipType::getMembershipType($membershipTypeID);
2308 $existingRelationships = civicrm_api3('Relationship', 'get', [
2309 'contact_id_a' => $contactID,
2310 'contact_id_b' => $contactID,
2311 'relationship_type_id' => ['IN' => $membershipType['relationship_type_id']],
2312 'options' => ['or' => [['contact_id_a', 'contact_id_b']], 'limit' => 0],
2313 'is_active' => 1,
2314 ])['values'];
2315
2316 if (empty($existingRelationships)) {
2317 return FALSE;
2318 }
2319
2320 $membershipInheritedFromContactID = (int) civicrm_api3('Membership', 'getvalue', ['return' => 'contact_id', 'id' => $parentMembershipID]);
2321 // I don't think the api can correctly filter by start & end because of handling for NULL
2322 // so we filter them out here.
2323 foreach ($existingRelationships as $index => $existingRelationship) {
2324 $otherContactID = (int) (($contactID === (int) $existingRelationship['contact_id_a']) ? $existingRelationship['contact_id_b'] : $existingRelationship['contact_id_a']);
2325 if (!empty($existingRelationship['start_date'])
2326 && strtotime($existingRelationship['start_date']) > time()
2327 ) {
2328 unset($existingRelationships[$index]);
2329 continue;
2330 }
2331 if (!empty($existingRelationship['end_date'])
2332 && strtotime($existingRelationship['end_date']) < time()
2333 ) {
2334 unset($existingRelationships[$index]);
2335 continue;
2336 }
2337 if ($membershipInheritedFromContactID !== $otherContactID
2338 ) {
2339 // This is a weird scenario - they have been inheriting the membership
2340 // just not from this relationship - and some max_related calcs etc would be required
2341 // - ie because they are no longer inheriting from this relationship's 'allowance'
2342 // and now are inheriting from the other relationships 'allowance', if it has not
2343 // already hit 'max_related'
2344 // For now ignore here & hope it's handled elsewhere - at least that's consistent with
2345 // before this function was added.
2346 unset($existingRelationships[$index]);
2347 continue;
2348 }
2349 if (!civicrm_api3('Contact', 'getcount', ['id' => $otherContactID, 'is_deleted' => 0])) {
2350 // Can't inherit from a deleted contact.
2351 unset($existingRelationships[$index]);
2352 continue;
2353 }
2354 }
2355 return !empty($existingRelationships);
98fd6fc8 2356 }
2357
52494648 2358 /**
2359 * Add an inherited membership, provided max related not exceeded.
2360 *
2361 * @param array $membershipValues
2362 *
2363 * @return array
2364 * @throws \CRM_Core_Exception
2365 */
2366 protected static function addInheritedMembership($membershipValues) {
2367 $query = "
2368SELECT count(*)
2369 FROM civicrm_membership
2370 LEFT JOIN civicrm_membership_status ON (civicrm_membership_status.id = civicrm_membership.status_id)
2371 WHERE membership_type_id = {$membershipValues['membership_type_id']}
2372 AND owner_membership_id = {$membershipValues['owner_membership_id']}
2373 AND is_current_member = 1";
2374 $result = CRM_Core_DAO::singleValueQuery($query);
2375 if ($result < CRM_Utils_Array::value('max_related', $membershipValues, PHP_INT_MAX)) {
3566c1c3
JJ
2376 // Convert custom_xx_id fields to custom_xx
2377 // See https://lab.civicrm.org/dev/membership/-/issues/37
2378 // This makes sure the value is copied and not the looked up value.
2379 // Which is the case when the custom field is a contact reference field.
2380 // The custom_xx contains the display name of the contact, instead of the contact id.
2381 // The contact id is then available in custom_xx_id.
2382 foreach ($membershipValues as $field => $value) {
2383 if (stripos($field, 'custom_') !== 0) {
2384 // No a custom field
2385 continue;
2386 }
2387 $custom_id = substr($field, 7);
2388 if (substr($custom_id, -3) === '_id') {
2389 $custom_id = substr($custom_id, 0, -3);
2390 unset($membershipValues[$field]);
2391 $membershipValues['custom_' . $custom_id] = $value;
2392 }
2393 }
2394
058180bb 2395 civicrm_api3('Membership', 'create', $membershipValues);
52494648 2396 }
2397 return $membershipValues;
2398 }
2399
6a488035 2400}