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