CRM-16290 fix fatal on relationship edit
[civicrm-core.git] / CRM / Contact / BAO / Relationship.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
e7112fa7 6 | Copyright CiviCRM LLC (c) 2004-2015 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
bfa4da96 29 * Class CRM_Contact_BAO_Relationship.
6a488035
TO
30 */
31class CRM_Contact_BAO_Relationship extends CRM_Contact_DAO_Relationship {
32
33 /**
fe482240 34 * Various constants to indicate different type of relationships.
6a488035
TO
35 *
36 * @var int
37 */
a4dc03f7 38 const ALL = 0, PAST = 1, DISABLED = 2, CURRENT = 4, INACTIVE = 8;
6a488035 39
7ecf6275 40 /**
d49c2966 41 * Create function - use the API instead.
bfa4da96 42 *
2da59b29 43 * Note that the previous create function has been renamed 'legacyCreateMultiple'
7ecf6275 44 * and this is new in 4.6
2da59b29 45 * All existing calls have been changed to legacyCreateMultiple except the api call - however, it is recommended
bfa4da96
EM
46 * that you call that as the end to end testing here is based on the api & refactoring may still be done.
47 *
16b10e64 48 * @param array $params
bfa4da96 49 *
7ecf6275
EM
50 * @return \CRM_Contact_BAO_Relationship
51 * @throws \CRM_Core_Exception
52 */
53 public static function create(&$params) {
d49c2966 54 $params = self::loadExistingRelationshipDetails($params);
7ecf6275
EM
55 if (self::checkDuplicateRelationship($params, $params['contact_id_a'], $params['contact_id_b'], CRM_Utils_Array::value('id', $params, 0))) {
56 throw new CRM_Core_Exception('Duplicate Relationship');
57 }
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'])) {
04ad3598
EM
63 $ids = array(
64 'contactTarget' => $relationship->contact_id_b,
65 'contact' => $params['contact_id_a'],
66 );
6c25ede2 67
690c56c3 68 //CRM-16087 removed additional call to function relatedMemberships which is already called by disableEnableRelationship
69 //resulting in memership 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
7ecf6275
EM
82 self::addRecent($params, $relationship);
83 return $relationship;
84 }
7f3647bc 85
2da59b29 86 /**
d49c2966 87 * Create multiple relationships for one contact.
2da59b29 88 *
d49c2966
EM
89 * The relationship details are the same for each relationship except the secondary contact
90 * id can be an array.
91 *
92 * @param array $params
93 * Parameters for creating multiple relationships.
94 * The parameters are the same as for relationship create function except that the non-primary
95 * end of the relationship should be an array of one or more contact IDs.
96 * @param string $primaryContactLetter
97 * a or b to denote the primary contact for this action. The secondary may be multiple contacts
98 * and should be an array.
2da59b29
EM
99 *
100 * @return array
101 * @throws \CRM_Core_Exception
102 */
103 public static function createMultiple($params, $primaryContactLetter) {
104 $secondaryContactLetter = ($primaryContactLetter == 'a') ? 'b' : 'a';
105 $secondaryContactIDs = $params['contact_id_' . $secondaryContactLetter];
106 $valid = $invalid = $duplicate = $saved = 0;
d49c2966 107 $relationshipIDs = array();
2da59b29
EM
108 foreach ($secondaryContactIDs as $secondaryContactID) {
109 try {
110 $params['contact_id_' . $secondaryContactLetter] = $secondaryContactID;
111 $relationship = civicrm_api3('relationship', 'create', $params);
d49c2966 112 $relationshipIDs[] = $relationship['id'];
bfa4da96 113 $valid++;
2da59b29
EM
114 }
115 catch (CiviCRM_API3_Exception $e) {
116 switch ($e->getMessage()) {
bfa4da96
EM
117 case 'Duplicate Relationship':
118 $duplicate++;
2da59b29
EM
119 break;
120
bfa4da96
EM
121 case 'Invalid Relationship':
122 $invalid++;
2da59b29
EM
123 break;
124
125 default:
126 throw new CRM_Core_Exception('unknown relationship create error ' . $e->getMessage());
127 }
128 }
129 }
130
d49c2966
EM
131 return array(
132 'valid' => $valid,
133 'invalid' => $invalid,
134 'duplicate' => $duplicate,
135 'saved' => $saved,
136 'relationship_ids' => $relationshipIDs,
137 );
2da59b29
EM
138 }
139
6a488035 140 /**
fe482240 141 * Takes an associative array and creates a relationship object.
7ecf6275
EM
142 * @deprecated For single creates use the api instead (it's tested).
143 * For multiple a new variant of this function needs to be written and migrated to as this is a bit
144 * nasty
6a488035 145 *
77c5b619
TO
146 * @param array $params
147 * (reference ) an assoc array of name/value pairs.
148 * @param array $ids
149 * The array that holds all the db ids.
16b10e64 150 * per http://wiki.civicrm.org/confluence/display/CRM/Database+layer
26dcc9eb 151 * "we are moving away from the $ids param "
6a488035 152 *
16b10e64 153 * @return CRM_Contact_BAO_Relationship
6a488035 154 */
2da59b29 155 public static function legacyCreateMultiple(&$params, $ids = array()) {
6a488035 156 $valid = $invalid = $duplicate = $saved = 0;
9af2925b 157 $relationships = $relationshipIds = array();
26dcc9eb 158 $relationshipId = CRM_Utils_Array::value('relationship', $ids, CRM_Utils_Array::value('id', $params));
5ad88e9d 159
6a488035
TO
160 //CRM-9015 - the hooks are called here & in add (since add doesn't call create)
161 // but in future should be tidied per ticket
9b873358 162 if (empty($relationshipId)) {
26dcc9eb 163 $hook = 'create';
6a488035 164 }
92e4c2a5 165 else {
26dcc9eb 166 $hook = 'edit';
6a488035 167 }
26dcc9eb 168
169 CRM_Utils_Hook::pre($hook, 'Relationship', $relationshipId, $params);
170
6a488035
TO
171 if (!$relationshipId) {
172 // creating a new relationship
173 $dataExists = self::dataExists($params);
174 if (!$dataExists) {
43291913 175 return array(FALSE, TRUE, FALSE, FALSE, NULL);
6a488035
TO
176 }
177 $relationshipIds = array();
178 foreach ($params['contact_check'] as $key => $value) {
179 $errors = '';
180 // check if the relationship is valid between contacts.
181 // step 1: check if the relationship is valid if not valid skip and keep the count
182 // step 2: check the if two contacts already have a relationship if yes skip and keep the count
183 // step 3: if valid relationship then add the relation and keep the count
184
185 // step 1
2001204e
EM
186 $contactFields = self::setContactABFromIDs($params, $ids, $key);
187 $errors = self::checkValidRelationship($contactFields, $ids, $key);
6a488035
TO
188 if ($errors) {
189 $invalid++;
190 continue;
191 }
192
193 if (
7f3647bc 194 self::checkDuplicateRelationship(
2001204e 195 $contactFields,
7f3647bc
TO
196 CRM_Utils_Array::value('contact', $ids),
197 // step 2
198 $key
199 )
6a488035
TO
200 ) {
201 $duplicate++;
202 continue;
203 }
2001204e 204
bfa4da96 205 $singleInstanceParams = array_merge($params, $contactFields);
eff45dce 206 $relationship = self::add($singleInstanceParams);
6a488035 207 $relationshipIds[] = $relationship->id;
26dcc9eb 208 $relationships[$relationship->id] = $relationship;
6a488035
TO
209 $valid++;
210 }
211 // editing the relationship
212 }
213 else {
214 // check for duplicate relationship
f0fc26a5
DL
215 // @todo this code doesn't cope well with updates - causes e-Notices.
216 // API has a lot of code to work around
49f8272d 217 // this but should review this code & remove the extra handling from the api
f0fc26a5
DL
218 // it seems doubtful any of this is relevant if the contact fields & relationship
219 // type fields are not set
6a488035 220 if (
7f3647bc
TO
221 self::checkDuplicateRelationship(
222 $params,
223 CRM_Utils_Array::value('contact', $ids),
224 $ids['contactTarget'],
225 $relationshipId
226 )
6a488035
TO
227 ) {
228 $duplicate++;
43291913 229 return array($valid, $invalid, $duplicate, $saved, NULL);
6a488035
TO
230 }
231
232 $validContacts = TRUE;
233 //validate contacts in update mode also.
8cc574cf 234 if (!empty($ids['contact']) && !empty($ids['contactTarget'])) {
6a488035
TO
235 if (self::checkValidRelationship($params, $ids, $ids['contactTarget'])) {
236 $validContacts = FALSE;
237 $invalid++;
238 }
239 }
240 if ($validContacts) {
241 // editing an existing relationship
242 $relationship = self::add($params, $ids, $ids['contactTarget']);
243 $relationshipIds[] = $relationship->id;
26dcc9eb 244 $relationships[$relationship->id] = $relationship;
6a488035
TO
245 $saved++;
246 }
247 }
248
249 // do not add to recent items for import, CRM-4399
8cc574cf 250 if (!(!empty($params['skipRecentView']) || $invalid || $duplicate)) {
7ecf6275 251 self::addRecent($params, $relationship);
6a488035
TO
252 }
253
26dcc9eb 254 return array($valid, $invalid, $duplicate, $saved, $relationshipIds, $relationships);
6a488035
TO
255 }
256
257 /**
bfa4da96 258 * This is the function that check/add if the relationship created is valid.
6a488035 259 *
77c5b619
TO
260 * @param array $params
261 * (reference ) an assoc array of name/value pairs.
77c5b619
TO
262 * @param array $ids
263 * The array that holds all the db ids.
c301f76e 264 * @param int $contactId
265 * This is contact id for adding relationship.
6a488035 266 *
c490a46a 267 * @return CRM_Contact_BAO_Relationship
6a488035 268 */
00be9182 269 public static function add(&$params, $ids = array(), $contactId = NULL) {
c301f76e 270 $relationshipId = CRM_Utils_Array::value('relationship', $ids, CRM_Utils_Array::value('id', $params));
f0fc26a5 271
49f8272d 272 $hook = 'create';
22e263ad 273 if ($relationshipId) {
49f8272d 274 $hook = 'edit';
6a488035 275 }
49f8272d 276 //@todo hook are called from create and add - remove one
7f3647bc 277 CRM_Utils_Hook::pre($hook, 'Relationship', $relationshipId, $params);
6a488035
TO
278
279 $relationshipTypes = CRM_Utils_Array::value('relationship_type_id', $params);
280
f0fc26a5
DL
281 // explode the string with _ to get the relationship type id
282 // and to know which contact has to be inserted in
6a488035 283 // contact_id_a and which one in contact_id_b
7ecf6275 284 list($type) = explode('_', $relationshipTypes);
6a488035 285
f0fc26a5
DL
286 // check if the relationship type is Head of Household then update the
287 // household's primary contact with this contact.
6a488035 288 if ($type == 6) {
7ecf6275 289 CRM_Contact_BAO_Household::updatePrimaryContact($params['contact_id_b'], $params['contact_id_a']);
6a488035
TO
290 }
291
292 $relationship = new CRM_Contact_BAO_Relationship();
49f8272d 293 //@todo this code needs to be updated for the possibility that not all fields are set
eff45dce 294 // by using $relationship->copyValues($params);
49f8272d 295 // (update)
7ecf6275
EM
296 $relationship->contact_id_b = $params['contact_id_b'];
297 $relationship->contact_id_a = $params['contact_id_a'];
6a488035 298 $relationship->relationship_type_id = $type;
49f8272d 299 $relationship->id = $relationshipId;
6a488035
TO
300
301 $dateFields = array('end_date', 'start_date');
302
9b873358
TO
303 foreach (self::getdefaults() as $defaultField => $defaultValue) {
304 if (isset($params[$defaultField])) {
305 if (in_array($defaultField, $dateFields)) {
6a488035 306 $relationship->$defaultField = CRM_Utils_Date::format(CRM_Utils_Array::value($defaultField, $params));
9b873358 307 if (!$relationship->$defaultField) {
6a488035
TO
308 $relationship->$defaultField = 'NULL';
309 }
310 }
92e4c2a5 311 else {
6a488035
TO
312 $relationship->$defaultField = $params[$defaultField];
313 }
314 }
7f3647bc 315 elseif (!$relationshipId) {
6a488035
TO
316 $relationship->$defaultField = $defaultValue;
317 }
318 }
319
320 $relationship->save();
321
322 // add custom field values
a7488080 323 if (!empty($params['custom'])) {
6a488035
TO
324 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_relationship', $relationship->id);
325 }
326
327 $relationship->free();
328
5c208c3f 329 CRM_Utils_Hook::post($hook, 'Relationship', $relationship->id, $relationship);
6a488035
TO
330
331 return $relationship;
332 }
7ecf6275
EM
333
334 /**
fe482240 335 * Add relationship to recent links.
bfa4da96 336 *
7ecf6275
EM
337 * @param array $params
338 * @param CRM_Contact_DAO_Relationship $relationship
339 */
340 public static function addRecent($params, $relationship) {
341 $url = CRM_Utils_System::url('civicrm/contact/view/rel',
342 "action=view&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&context=home"
343 );
344 $session = CRM_Core_Session::singleton();
345 $recentOther = array();
346 if (($session->get('userID') == $relationship->contact_id_a) ||
347 CRM_Contact_BAO_Contact_Permission::allow($relationship->contact_id_a, CRM_Core_Permission::EDIT)
348 ) {
349 $rType = substr(CRM_Utils_Array::value('relationship_type_id', $params), -3);
350 $recentOther = array(
351 'editUrl' => CRM_Utils_System::url('civicrm/contact/view/rel',
352 "action=update&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
353 ),
354 'deleteUrl' => CRM_Utils_System::url('civicrm/contact/view/rel',
355 "action=delete&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
356 ),
357 );
358 }
359 $title = CRM_Contact_BAO_Contact::displayName($relationship->contact_id_a) . ' (' . CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType',
360 $relationship->relationship_type_id, 'label_a_b'
361 ) . ' ' . CRM_Contact_BAO_Contact::displayName($relationship->contact_id_b) . ')';
362
363 CRM_Utils_Recent::add($title,
364 $url,
365 $relationship->id,
366 'Relationship',
367 $relationship->contact_id_a,
368 NULL,
369 $recentOther
370 );
371 }
372
d49c2966
EM
373 /**
374 * Load contact ids and relationship type id when doing a create call if not provided.
375 *
376 * There are are various checks done in create which require this information which is optional
377 * when using id.
378 *
379 * @param array $params
380 * Parameters passed to create call.
381 *
382 * @return array
383 * Parameters with missing fields added if required.
384 */
385 public static function loadExistingRelationshipDetails($params) {
386 if (!empty($params['contact_id_a'])
387 && !empty($params['contact_id_b'])
388 && is_numeric($params['relationship_type_id'])) {
389 return $params;
390 }
391 if (empty($params['id'])) {
392 return $params;
393 }
394
395 $fieldsToFill = array('contact_id_a', 'contact_id_b', 'relationship_type_id');
396 $result = CRM_Core_DAO::executeQuery("SELECT " . implode(',', $fieldsToFill) . " FROM civicrm_relationship WHERE id = %1", array(
397 1 => array(
398 $params['id'],
399 'Integer',
400 ),
401 ));
402 while ($result->fetch()) {
403 foreach ($fieldsToFill as $field) {
404 $params[$field] = !empty($params[$field]) ? $params[$field] : $result->$field;
405 }
406 }
407 return $params;
408 }
409
7ecf6275 410 /**
bfa4da96 411 * Resolve passed in contact IDs to contact_id_a & contact_id_b.
eff45dce 412 *
16b10e64 413 * @param array $params
7ecf6275
EM
414 * @param array $ids
415 * @param null $contactID
eff45dce
EM
416 *
417 * @return array
7ecf6275
EM
418 * @throws \CRM_Core_Exception
419 */
eff45dce
EM
420 public static function setContactABFromIDs($params, $ids = array(), $contactID = NULL) {
421 $returnFields = array();
d49c2966
EM
422
423 // $ids['contact'] is deprecated but comes from legacyCreateMultiple function.
7ecf6275
EM
424 if (empty($ids['contact'])) {
425 if (!empty($params['id'])) {
d49c2966 426 return self::loadExistingRelationshipDetails($params);
7ecf6275
EM
427 }
428 throw new CRM_Core_Exception('Cannot create relationship, insufficient contact IDs provided');
429 }
2001204e 430 if (isset($params['relationship_type_id']) && !is_numeric($params['relationship_type_id'])) {
eff45dce
EM
431 $relationshipTypes = CRM_Utils_Array::value('relationship_type_id', $params);
432 list($relationshipTypeID, $first) = explode('_', $relationshipTypes);
2001204e
EM
433 $returnFields['relationship_type_id'] = $relationshipTypeID;
434
d49c2966
EM
435 foreach (array('a', 'b') as $contactLetter) {
436 if (empty($params['contact_' . $contactLetter])) {
437 if ($first == $contactLetter) {
438 $returnFields['contact_id_' . $contactLetter] = CRM_Utils_Array::value('contact', $ids);
439 }
440 else {
441 $returnFields['contact_id_' . $contactLetter] = $contactID;
442 }
7ecf6275
EM
443 }
444 }
445 }
d49c2966 446
eff45dce 447 return $returnFields;
7ecf6275
EM
448 }
449
6a488035 450 /**
d49c2966 451 * Specify defaults for creating a relationship.
6a488035 452 *
a6c01b45
CW
453 * @return array
454 * array of defaults for creating relationship
6a488035 455 */
00be9182 456 public static function getdefaults() {
6a488035
TO
457 return array(
458 'is_active' => 0,
459 'is_permission_a_b' => 0,
460 'is_permission_b_a' => 0,
461 'description' => '',
462 'start_date' => 'NULL',
463 'case_id' => NULL,
464 'end_date' => 'NULL',
465 );
466 }
467
468
469 /**
fe482240 470 * Check if there is data to create the object.
6a488035 471 *
77c5b619
TO
472 * @param array $params
473 * (reference ) an assoc array of name/value pairs.
6a488035 474 *
c301f76e 475 * @return bool
6a488035 476 */
00be9182 477 public static function dataExists(&$params) {
6a488035
TO
478 // return if no data present
479 if (!is_array(CRM_Utils_Array::value('contact_check', $params))) {
480 return FALSE;
481 }
482 return TRUE;
483 }
484
485 /**
100fef9d 486 * Get get list of relationship type based on the contact type.
6a488035 487 *
77c5b619
TO
488 * @param int $contactId
489 * This is the contact id of the current contact.
fd31fa4c 490 * @param null $contactSuffix
77c5b619
TO
491 * @param string $relationshipId
492 * The id of the existing relationship if any.
493 * @param string $contactType
494 * Contact type.
495 * @param bool $all
496 * If true returns relationship types in both the direction.
497 * @param string $column
498 * Name/label that going to retrieve from db.
fd31fa4c 499 * @param bool $biDirectional
77c5b619 500 * @param string $contactSubType
bfa4da96 501 * Includes relationship types between this subtype.
77c5b619 502 * @param bool $onlySubTypeRelationTypes
bfa4da96
EM
503 * If set only subtype which is passed by $contactSubType
504 * related relationship types get return
6a488035 505 *
a6c01b45
CW
506 * @return array
507 * array reference of all relationship types with context to current contact.
6a488035 508 */
c301f76e 509 public static function getContactRelationshipType(
51ccfbbe 510 $contactId = NULL,
6a488035
TO
511 $contactSuffix = NULL,
512 $relationshipId = NULL,
513 $contactType = NULL,
514 $all = FALSE,
515 $column = 'label',
516 $biDirectional = TRUE,
517 $contactSubType = NULL,
518 $onlySubTypeRelationTypes = FALSE
519 ) {
d49c2966 520
7f3647bc 521 $relationshipType = array();
6a488035
TO
522 $allRelationshipType = CRM_Core_PseudoConstant::relationshipType($column);
523
524 $otherContactType = NULL;
525 if ($relationshipId) {
526 $relationship = new CRM_Contact_DAO_Relationship();
527 $relationship->id = $relationshipId;
528 if ($relationship->find(TRUE)) {
529 $contact = new CRM_Contact_DAO_Contact();
530 $contact->id = ($relationship->contact_id_a === $contactId) ? $relationship->contact_id_b : $relationship->contact_id_a;
531
532 if ($contact->find(TRUE)) {
533 $otherContactType = $contact->contact_type;
534 //CRM-5125 for contact subtype specific relationshiptypes
535 if ($contact->contact_sub_type) {
536 $otherContactSubType = $contact->contact_sub_type;
537 }
538 }
539 }
540 }
541
542 $contactSubType = array();
543 if ($contactId) {
544 $contactType = CRM_Contact_BAO_Contact::getContactType($contactId);
545 $contactSubType = CRM_Contact_BAO_Contact::getContactSubType($contactId);
546 }
547
548 foreach ($allRelationshipType as $key => $value) {
549 // the contact type is required or matches
550 if (((!$value['contact_type_a']) ||
551 $value['contact_type_a'] == $contactType
552 ) &&
553 // the other contact type is required or present or matches
554 ((!$value['contact_type_b']) ||
555 (!$otherContactType) ||
556 $value['contact_type_b'] == $otherContactType
557 ) &&
91c0d0d8 558 (in_array($value['contact_sub_type_a'], $contactSubType) ||
559 in_array($value['contact_sub_type_b'], $contactSubType) ||
560 (!$value['contact_sub_type_a'] && !$onlySubTypeRelationTypes)
6a488035
TO
561 )
562 ) {
563 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
564 }
6a488035
TO
565
566 if (((!$value['contact_type_b']) ||
567 $value['contact_type_b'] == $contactType
568 ) &&
569 ((!$value['contact_type_a']) ||
570 (!$otherContactType) ||
571 $value['contact_type_a'] == $otherContactType
572 ) &&
91c0d0d8 573 (in_array($value['contact_sub_type_b'], $contactSubType) ||
574 in_array($value['contact_sub_type_a'], $contactSubType) ||
575 (!$value['contact_sub_type_b'] && !$onlySubTypeRelationTypes)
6a488035
TO
576 )
577 ) {
578 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
579 }
6a488035
TO
580
581 if ($all) {
582 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
583 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
584 }
585 }
586
587 if ($biDirectional) {
588 // lets clean up the data and eliminate all duplicate values
589 // (i.e. the relationship is bi-directional)
590 $relationshipType = array_unique($relationshipType);
591 }
592
593 // sort the relationshipType in ascending order CRM-7736
594 asort($relationshipType);
595 return $relationshipType;
596 }
597
86538308 598 /**
98a06ae0
EM
599 * Delete current employer relationship.
600 *
100fef9d 601 * @param int $id
98a06ae0 602 * @param int $action
86538308
EM
603 *
604 * @return CRM_Contact_DAO_Relationship
605 */
00be9182 606 public static function clearCurrentEmployer($id, $action) {
6a488035
TO
607 $relationship = new CRM_Contact_DAO_Relationship();
608 $relationship->id = $id;
609 $relationship->find(TRUE);
610
611 //to delete relationship between household and individual \
98a06ae0 612 //or between individual and organization
6a488035 613 if (($action & CRM_Core_Action::DISABLE) || ($action & CRM_Core_Action::DELETE)) {
05802b8e
DG
614 $relTypes = CRM_Utils_Array::index(array('name_a_b'), CRM_Core_PseudoConstant::relationshipType('name'));
615 if ($relationship->relationship_type_id == $relTypes['Employee of']['id'] ||
7f3647bc
TO
616 $relationship->relationship_type_id == $relTypes['Household Member of']['id']
617 ) {
05802b8e
DG
618 $sharedContact = new CRM_Contact_DAO_Contact();
619 $sharedContact->id = $relationship->contact_id_a;
620 $sharedContact->find(TRUE);
621
7f3647bc 622 if ($relationship->relationship_type_id == 4 && $relationship->contact_id_b == $sharedContact->employer_id) {
05802b8e
DG
623 CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($relationship->contact_id_a);
624 }
6a488035
TO
625 }
626 }
7f3647bc 627 return $relationship;
6a488035
TO
628 }
629
630 /**
fe482240 631 * Delete the relationship.
6a488035 632 *
77c5b619
TO
633 * @param int $id
634 * Relationship id.
6a488035
TO
635 *
636 * @return null
6a488035 637 */
00be9182 638 public static function del($id) {
6a488035
TO
639 // delete from relationship table
640 CRM_Utils_Hook::pre('delete', 'Relationship', $id, CRM_Core_DAO::$_nullArray);
641
642 $relationship = self::clearCurrentEmployer($id, CRM_Core_Action::DELETE);
643 if (CRM_Core_Permission::access('CiviMember')) {
644 // create $params array which isrequired to delete memberships
645 // of the related contacts.
646 $params = array(
647 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
648 'contact_check' => array($relationship->contact_id_b => 1),
649 );
650
651 $ids = array();
652 // calling relatedMemberships to delete the memberships of
653 // related contacts.
654 self::relatedMemberships($relationship->contact_id_a,
655 $params,
656 $ids,
657 CRM_Core_Action::DELETE,
658 FALSE
659 );
660 }
661
662 $relationship->delete();
663 CRM_Core_Session::setStatus(ts('Selected relationship has been deleted successfully.'), ts('Record Deleted'), 'success');
664
5c208c3f 665 CRM_Utils_Hook::post('delete', 'Relationship', $id, $relationship);
6a488035
TO
666
667 // delete the recently created Relationship
668 $relationshipRecent = array(
669 'id' => $id,
670 'type' => 'Relationship',
671 );
672 CRM_Utils_Recent::del($relationshipRecent);
673
674 return $relationship;
675 }
676
677 /**
98a06ae0 678 * Disable/enable the relationship.
6a488035 679 *
77c5b619
TO
680 * @param int $id
681 * Relationship id.
6a488035 682 *
2a6da8d7 683 * @param $action
6a488035 684 */
690c56c3 685 public static function disableEnableRelationship($id, $action, $params = array(), $ids = array(), $active = FALSE) {
6a488035 686 $relationship = self::clearCurrentEmployer($id, $action);
25f1372e 687
6a488035 688 if (CRM_Core_Permission::access('CiviMember')) {
25f1372e 689 // create $params array which is required to delete memberships
6a488035 690 // of the related contacts.
690c56c3 691 if (empty($params)) {
692 $params = array(
693 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
694 'contact_check' => array($relationship->contact_id_b => 1),
695 );
696 }
690c56c3 697 $contact_id_a = empty($params['contact_id_a']) ? $relationship->contact_id_a : $params['contact_id_a'];
6a488035
TO
698 // calling relatedMemberships to delete/add the memberships of
699 // related contacts.
700 if ($action & CRM_Core_Action::DISABLE) {
690c56c3 701 CRM_Contact_BAO_Relationship::relatedMemberships($contact_id_a,
6a488035
TO
702 $params,
703 $ids,
704 CRM_Core_Action::DELETE,
690c56c3 705 $active
6a488035
TO
706 );
707 }
708 elseif ($action & CRM_Core_Action::ENABLE) {
91244f1d 709 $ids['contact'] = empty($ids['contact']) ? $contact_id_a : $ids['contact'];
690c56c3 710 CRM_Contact_BAO_Relationship::relatedMemberships($contact_id_a,
6a488035
TO
711 $params,
712 $ids,
690c56c3 713 empty($params['id']) ? CRM_Core_Action::ADD : CRM_Core_Action::UPDATE,
714 $active
6a488035
TO
715 );
716 }
717 }
718 }
719
720 /**
fe482240 721 * Delete the object records that are associated with this contact.
6a488035 722 *
77c5b619
TO
723 * @param int $contactId
724 * Id of the contact to delete.
6a488035 725 */
00be9182 726 public static function deleteContact($contactId) {
6a488035
TO
727 $relationship = new CRM_Contact_DAO_Relationship();
728 $relationship->contact_id_a = $contactId;
729 $relationship->delete();
730
731 $relationship = new CRM_Contact_DAO_Relationship();
732 $relationship->contact_id_b = $contactId;
733 $relationship->delete();
734
735 CRM_Contact_BAO_Household::updatePrimaryContact(NULL, $contactId);
736 }
737
738 /**
fe482240 739 * Get the other contact in a relationship.
6a488035 740 *
77c5b619
TO
741 * @param int $id
742 * Relationship id.
6a488035
TO
743 *
744 * $returns returns the contact ids in the realtionship
77b97be7
EM
745 *
746 * @return \CRM_Contact_DAO_Relationship
6a488035 747 */
eff45dce 748 public static function getRelationshipByID($id) {
6a488035
TO
749 $relationship = new CRM_Contact_DAO_Relationship();
750
751 $relationship->id = $id;
752 $relationship->selectAdd();
753 $relationship->selectAdd('contact_id_a, contact_id_b');
754 $relationship->find(TRUE);
755
756 return $relationship;
757 }
758
759 /**
fe482240 760 * Check if the relationship type selected between two contacts is correct.
6a488035 761 *
77c5b619
TO
762 * @param int $contact_a
763 * 1st contact id.
764 * @param int $contact_b
765 * 2nd contact id.
766 * @param int $relationshipTypeId
767 * Relationship type id.
6a488035 768 *
c301f76e 769 * @return bool
a6c01b45 770 * true if it is valid relationship else false
6a488035 771 */
00be9182 772 public static function checkRelationshipType($contact_a, $contact_b, $relationshipTypeId) {
6a488035
TO
773 $relationshipType = new CRM_Contact_DAO_RelationshipType();
774 $relationshipType->id = $relationshipTypeId;
775 $relationshipType->selectAdd();
776 $relationshipType->selectAdd('contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b');
777 if ($relationshipType->find(TRUE)) {
778 $contact_type_a = CRM_Contact_BAO_Contact::getContactType($contact_a);
779 $contact_type_b = CRM_Contact_BAO_Contact::getContactType($contact_b);
780
781 $contact_sub_type_a = CRM_Contact_BAO_Contact::getContactSubType($contact_a);
782 $contact_sub_type_b = CRM_Contact_BAO_Contact::getContactSubType($contact_b);
783
784 if (((!$relationshipType->contact_type_a) || ($relationshipType->contact_type_a == $contact_type_a)) &&
785 ((!$relationshipType->contact_type_b) || ($relationshipType->contact_type_b == $contact_type_b)) &&
786 ((!$relationshipType->contact_sub_type_a) || (in_array($relationshipType->contact_sub_type_a,
7f3647bc
TO
787 $contact_sub_type_a
788 ))) &&
6a488035 789 ((!$relationshipType->contact_sub_type_b) || (in_array($relationshipType->contact_sub_type_b,
7f3647bc
TO
790 $contact_sub_type_b
791 )))
6a488035
TO
792 ) {
793 return TRUE;
794 }
795 else {
796 return FALSE;
797 }
798 }
799 return FALSE;
800 }
801
802 /**
fe482240 803 * This function does the validtion for valid relationship.
6a488035 804 *
77c5b619
TO
805 * @param array $params
806 * This array contains the values there are subitted by the form.
807 * @param array $ids
808 * The array that holds all the db ids.
809 * @param int $contactId
810 * This is contact id for adding relationship.
6a488035 811 *
2a6da8d7 812 * @return string
6a488035 813 */
7ecf6275 814 public static function checkValidRelationship($params, $ids, $contactId) {
6a488035 815 $errors = '';
6a488035
TO
816 // function to check if the relationship selected is correct
817 // i.e. employer relationship can exit between Individual and Organization (not between Individual and Individual)
c4dcea5b
EM
818 if (!CRM_Contact_BAO_Relationship::checkRelationshipType($params['contact_id_a'], $params['contact_id_b'],
819 $params['relationship_type_id'])) {
6a488035
TO
820 $errors = 'Please select valid relationship between these two contacts.';
821 }
822 return $errors;
823 }
824
825 /**
fe482240 826 * This function checks for duplicate relationship.
6a488035 827 *
77c5b619
TO
828 * @param array $params
829 * (reference ) an assoc array of name/value pairs.
830 * @param int $id
831 * This the id of the contact whom we are adding relationship.
832 * @param int $contactId
833 * This is contact id for adding relationship.
834 * @param int $relationshipId
835 * This is relationship id for the contact.
6a488035 836 *
c301f76e 837 * @return bool
a6c01b45 838 * true if record exists else false
6a488035 839 */
00be9182 840 public static function checkDuplicateRelationship(&$params, $id, $contactId = 0, $relationshipId = 0) {
6a488035 841 $relationshipTypeId = CRM_Utils_Array::value('relationship_type_id', $params);
decc60a0 842 list($type) = explode('_', $relationshipTypeId);
6a488035 843
f0fc26a5
DL
844 $queryString = "
845SELECT id
846FROM civicrm_relationship
847WHERE relationship_type_id = " . CRM_Utils_Type::escape($type, 'Integer');
6a488035
TO
848
849 /*
e70a7fc0
TO
850 * CRM-11792 - date fields from API are in ISO format, but this function
851 * supports date arrays BAO has increasingly standardised to ISO format
852 * so I believe this function should support ISO rather than make API
853 * format it - however, need to support array format for now to avoid breakage
2da59b29 854 * @ time of writing this function is called from Relationship::legacyCreateMultiple (twice)
e70a7fc0
TO
855 * CRM_BAO_Contact_Utils::clearCurrentEmployer (seemingly without dates)
856 * CRM_Contact_Form_Task_AddToOrganization::postProcess &
857 * CRM_Contact_Form_Task_AddToHousehold::postProcess
858 * (I don't think the last 2 support dates but not sure
859 */
6a488035
TO
860
861 $dateFields = array('end_date', 'start_date');
9b873358 862 foreach ($dateFields as $dateField) {
22e263ad 863 if (array_key_exists($dateField, $params)) {
9b873358 864 if (empty($params[$dateField]) || $params[$dateField] == 'null') {
f0fc26a5
DL
865 //this is most likely coming from an api call & probably loaded
866 // from the DB to deal with some of the
867 // other myriad of excessive checks still in place both in
868 // the api & the create functions
6a488035
TO
869 $queryString .= " AND $dateField IS NULL";
870 continue;
871 }
9b873358 872 elseif (is_array($params[$dateField])) {
f0fc26a5
DL
873 $queryString .= " AND $dateField = " .
874 CRM_Utils_Type::escape(CRM_Utils_Date::format($params[$dateField]), 'Date');
6a488035 875 }
f0fc26a5
DL
876 else {
877 $queryString .= " AND $dateField = " .
878 CRM_Utils_Type::escape($params[$dateField], 'Date');
6a488035
TO
879 }
880 }
881 }
882
883 $queryString .=
884 " AND ( ( contact_id_a = " . CRM_Utils_Type::escape($id, 'Integer') .
885 " AND contact_id_b = " . CRM_Utils_Type::escape($contactId, 'Integer') .
886 " ) OR ( contact_id_a = " . CRM_Utils_Type::escape($contactId, 'Integer') .
887 " AND contact_id_b = " . CRM_Utils_Type::escape($id, 'Integer') . " ) ) ";
888
889 //if caseId is provided, include it duplicate checking.
890 if ($caseId = CRM_Utils_Array::value('case_id', $params)) {
891 $queryString .= " AND case_id = " . CRM_Utils_Type::escape($caseId, 'Integer');
892 }
893
894 if ($relationshipId) {
895 $queryString .= " AND id !=" . CRM_Utils_Type::escape($relationshipId, 'Integer');
896 }
897
898 $relationship = new CRM_Contact_BAO_Relationship();
899 $relationship->query($queryString);
900 $relationship->fetch();
901 $relationship->free();
902 return ($relationship->id) ? TRUE : FALSE;
903 }
904
905 /**
fe482240 906 * Update the is_active flag in the db.
6a488035 907 *
77c5b619
TO
908 * @param int $id
909 * Id of the database record.
910 * @param bool $is_active
911 * Value we want to set the is_active field.
6a488035 912 *
77b97be7 913 * @throws CiviCRM_API3_Exception
a6c01b45
CW
914 * @return Object
915 * DAO object on success, null otherwise
6a488035 916 */
00be9182 917 public static function setIsActive($id, $is_active) {
49f8272d
E
918 // as both the create & add functions have a bunch of logic in them that
919 // doesn't seem to cope with a normal update we will call the api which
920 // has tested handling for this
921 // however, a longer term solution would be to simplify the add, create & api functions
922 // to be more standard. It is debatable @ that point whether it's better to call the BAO
923 // direct as the api is more tested.
80109b10 924 $result = civicrm_api('relationship', 'create', array(
925 'id' => $id,
926 'is_active' => $is_active,
927 'version' => 3,
928 ));
929
930 if (is_array($result) && !empty($result['is_error']) && $result['error_message'] != 'Relationship already exists') {
931 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array::value('error_code', $result, 'undefined'), $result);
932 }
49f8272d 933
6a488035
TO
934 return TRUE;
935 }
936
937 /**
98a06ae0 938 * Fetch a relationship object and store the values in the values array.
6a488035 939 *
77c5b619
TO
940 * @param array $params
941 * Input parameters to find object.
942 * @param array $values
943 * Output values of the object.
6a488035 944 *
a6c01b45
CW
945 * @return array
946 * (reference) the values that could be potentially assigned to smarty
6a488035 947 */
00be9182 948 public static function &getValues(&$params, &$values) {
6a488035
TO
949 if (empty($params)) {
950 return NULL;
951 }
952 $v = array();
953
954 // get the specific number of relationship or all relationships.
a7488080 955 if (!empty($params['numRelationship'])) {
6a488035
TO
956 $v['data'] = &CRM_Contact_BAO_Relationship::getRelationship($params['contact_id'], NULL, $params['numRelationship']);
957 }
958 else {
959 $v['data'] = CRM_Contact_BAO_Relationship::getRelationship($params['contact_id']);
960 }
961
962 // get the total count of relationships
963 $v['totalCount'] = CRM_Contact_BAO_Relationship::getRelationship($params['contact_id'], NULL, NULL, TRUE);
964
965 $values['relationship']['data'] = &$v['data'];
966 $values['relationship']['totalCount'] = &$v['totalCount'];
967
968 return $v;
969 }
970
971 /**
fe482240 972 * Helper function to form the sql for relationship retrieval.
6a488035 973 *
77c5b619
TO
974 * @param int $contactId
975 * Contact id.
976 * @param int $status
977 * (check const at top of file).
978 * @param int $numRelationship
979 * No of relationships to display (limit).
980 * @param int $count
981 * Get the no of relationships.
6a488035 982 * $param int $relationshipId relationship id
100fef9d 983 * @param int $relationshipId
77c5b619
TO
984 * @param string $direction
985 * The direction we are interested in a_b or b_a.
986 * @param array $params
987 * Array of extra values including relationship_type_id per api spec.
6a488035 988 *
77b97be7 989 * @return array
76e7a76c 990 * [select, from, where]
6a488035 991 */
00be9182 992 public static function makeURLClause($contactId, $status, $numRelationship, $count, $relationshipId, $direction, $params = array()) {
6a488035
TO
993 $select = $from = $where = '';
994
995 $select = '( ';
996 if ($count) {
997 if ($direction == 'a_b') {
998 $select .= ' SELECT count(DISTINCT civicrm_relationship.id) as cnt1, 0 as cnt2 ';
999 }
1000 else {
1001 $select .= ' SELECT 0 as cnt1, count(DISTINCT civicrm_relationship.id) as cnt2 ';
1002 }
1003 }
1004 else {
1005 $select .= ' SELECT civicrm_relationship.id as civicrm_relationship_id,
1006 civicrm_contact.sort_name as sort_name,
1007 civicrm_contact.display_name as display_name,
1008 civicrm_contact.job_title as job_title,
1009 civicrm_contact.employer_id as employer_id,
1010 civicrm_contact.organization_name as organization_name,
1011 civicrm_address.street_address as street_address,
1012 civicrm_address.city as city,
1013 civicrm_address.postal_code as postal_code,
1014 civicrm_state_province.abbreviation as state,
1015 civicrm_country.name as country,
1016 civicrm_email.email as email,
c6c691a5 1017 civicrm_contact.contact_type as contact_type,
6a488035
TO
1018 civicrm_phone.phone as phone,
1019 civicrm_contact.id as civicrm_contact_id,
6a488035
TO
1020 civicrm_relationship.contact_id_b as contact_id_b,
1021 civicrm_relationship.contact_id_a as contact_id_a,
1022 civicrm_relationship_type.id as civicrm_relationship_type_id,
1023 civicrm_relationship.start_date as start_date,
1024 civicrm_relationship.end_date as end_date,
1025 civicrm_relationship.description as description,
1026 civicrm_relationship.is_active as is_active,
1027 civicrm_relationship.is_permission_a_b as is_permission_a_b,
1028 civicrm_relationship.is_permission_b_a as is_permission_b_a,
1029 civicrm_relationship.case_id as case_id';
1030
1031 if ($direction == 'a_b') {
1032 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
c6c691a5 1033 civicrm_relationship_type.label_b_a as relation ';
6a488035
TO
1034 }
1035 else {
1036 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
c6c691a5 1037 civicrm_relationship_type.label_a_b as relation ';
6a488035
TO
1038 }
1039 }
1040
1041 $from = "
1042 FROM civicrm_relationship
1043INNER JOIN civicrm_relationship_type ON ( civicrm_relationship.relationship_type_id = civicrm_relationship_type.id )
1044INNER JOIN civicrm_contact ";
1045 if ($direction == 'a_b') {
1046 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_a ) ';
1047 }
1048 else {
1049 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_b ) ';
1050 }
1051 $from .= "
1052LEFT JOIN civicrm_address ON (civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1)
1053LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
1054LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id AND civicrm_email.is_primary = 1)
1055LEFT JOIN civicrm_state_province ON (civicrm_address.state_province_id = civicrm_state_province.id)
1056LEFT JOIN civicrm_country ON (civicrm_address.country_id = civicrm_country.id)
1057";
1058 $where = 'WHERE ( 1 )';
1059 if ($contactId) {
1060 if ($direction == 'a_b') {
1061 $where .= ' AND civicrm_relationship.contact_id_b = ' . CRM_Utils_Type::escape($contactId, 'Positive');
1062 }
1063 else {
075fa74e 1064 $where .= ' AND civicrm_relationship.contact_id_a = ' . CRM_Utils_Type::escape($contactId, 'Positive') . '
1065 AND civicrm_relationship.contact_id_a != civicrm_relationship.contact_id_b ';
6a488035
TO
1066 }
1067 }
1068 if ($relationshipId) {
1069 $where .= ' AND civicrm_relationship.id = ' . CRM_Utils_Type::escape($relationshipId, 'Positive');
1070 }
1071
1072 $date = date('Y-m-d');
1073 if ($status == self::PAST) {
1074 //this case for showing past relationship
1075 $where .= ' AND civicrm_relationship.is_active = 1 ';
1076 $where .= " AND civicrm_relationship.end_date < '" . $date . "'";
1077 }
1078 elseif ($status == self::DISABLED) {
1079 // this case for showing disabled relationship
1080 $where .= ' AND civicrm_relationship.is_active = 0 ';
1081 }
1082 elseif ($status == self::CURRENT) {
1083 //this case for showing current relationship
1084 $where .= ' AND civicrm_relationship.is_active = 1 ';
1085 $where .= " AND (civicrm_relationship.end_date >= '" . $date . "' OR civicrm_relationship.end_date IS NULL) ";
1086 }
1087 elseif ($status == self::INACTIVE) {
1088 //this case for showing inactive relationships
1089 $where .= " AND (civicrm_relationship.end_date < '" . $date . "'";
1090 $where .= ' OR civicrm_relationship.is_active = 0 )';
1091 }
1092
1093 // CRM-6181
1094 $where .= ' AND civicrm_contact.is_deleted = 0';
22e263ad 1095 if (!empty($params['membership_type_id']) && empty($params['relationship_type_id'])) {
c9c41397 1096 $where .= self::membershipTypeToRelationshipTypes($params, $direction);
1097 }
22e263ad
TO
1098 if (!empty($params['relationship_type_id'])) {
1099 if (is_array($params['relationship_type_id'])) {
7f3647bc 1100 $where .= " AND " . CRM_Core_DAO::createSQLFilter('relationship_type_id', $params['relationship_type_id'], 'Integer');
75638074 1101 }
1102 else {
1103 $where .= ' AND relationship_type_id = ' . CRM_Utils_Type::escape($params['relationship_type_id'], 'Positive');
1104 }
1105 }
6a488035
TO
1106 if ($direction == 'a_b') {
1107 $where .= ' ) UNION ';
1108 }
1109 else {
1110 $where .= ' ) ';
1111 }
1112
1113 return array($select, $from, $where);
1114 }
1115
1116 /**
fe482240 1117 * Get a list of relationships.
6a488035 1118 *
77c5b619
TO
1119 * @param int $contactId
1120 * Contact id.
1121 * @param int $status
1122 * 1: Past 2: Disabled 3: Current.
1123 * @param int $numRelationship
1124 * No of relationships to display (limit).
1125 * @param int $count
1126 * Get the no of relationships.
77b97be7 1127 * @param int $relationshipId
76e7a76c
CW
1128 * @param array $links
1129 * the list of links to display
1130 * @param int $permissionMask
1131 * the permission mask to be applied for the actions
77b97be7 1132 * @param bool $permissionedContact
76e7a76c 1133 * to return only permissioned Contact
77b97be7
EM
1134 * @param array $params
1135 *
1136 * @return array|int
76e7a76c 1137 * relationship records
6a488035 1138 */
c301f76e 1139 public static function getRelationship(
51ccfbbe 1140 $contactId = NULL,
7f3647bc
TO
1141 $status = 0, $numRelationship = 0,
1142 $count = 0, $relationshipId = 0,
1143 $links = NULL, $permissionMask = NULL,
75638074 1144 $permissionedContact = FALSE,
1145 $params = array()
6a488035
TO
1146 ) {
1147 $values = array();
1148 if (!$contactId && !$relationshipId) {
1149 return $values;
1150 }
1151
1152 list($select1, $from1, $where1) = self::makeURLClause($contactId, $status, $numRelationship,
75638074 1153 $count, $relationshipId, 'a_b', $params
6a488035
TO
1154 );
1155 list($select2, $from2, $where2) = self::makeURLClause($contactId, $status, $numRelationship,
75638074 1156 $count, $relationshipId, 'b_a', $params
6a488035
TO
1157 );
1158
1159 $order = $limit = '';
1160 if (!$count) {
40458f6c 1161 if (empty($params['sort'])) {
1162 $order = ' ORDER BY civicrm_relationship_type_id, sort_name ';
1163 }
1164 else {
1165 $order = " ORDER BY {$params['sort']} ";
1166 }
1167
1168 $offset = 0;
630d1aaa 1169 if (!empty($params['offset']) && $params['offset'] > 0) {
40458f6c 1170 $offset = $params['offset'];
1171 }
6a488035
TO
1172
1173 if ($numRelationship) {
40458f6c 1174 $limit = " LIMIT {$offset}, $numRelationship";
6a488035
TO
1175 }
1176 }
1177
1178 // building the query string
6a488035
TO
1179 $queryString = $select1 . $from1 . $where1 . $select2 . $from2 . $where2 . $order . $limit;
1180
1181 $relationship = new CRM_Contact_DAO_Relationship();
1182
1183 $relationship->query($queryString);
1184 $row = array();
1185 if ($count) {
1186 $relationshipCount = 0;
1187 while ($relationship->fetch()) {
1188 $relationshipCount += $relationship->cnt1 + $relationship->cnt2;
1189 }
1190 return $relationshipCount;
1191 }
1192 else {
1193
1194 $mask = NULL;
1195 if ($status != self::INACTIVE) {
1196 if ($links) {
1197 $mask = array_sum(array_keys($links));
1198 if ($mask & CRM_Core_Action::DISABLE) {
1199 $mask -= CRM_Core_Action::DISABLE;
1200 }
1201 if ($mask & CRM_Core_Action::ENABLE) {
1202 $mask -= CRM_Core_Action::ENABLE;
1203 }
1204
1205 if ($status == self::CURRENT) {
1206 $mask |= CRM_Core_Action::DISABLE;
1207 }
1208 elseif ($status == self::DISABLED) {
1209 $mask |= CRM_Core_Action::ENABLE;
1210 }
1211 $mask = $mask & $permissionMask;
1212 }
1213 }
1214 while ($relationship->fetch()) {
1215 $rid = $relationship->civicrm_relationship_id;
1216 $cid = $relationship->civicrm_contact_id;
1217 if (($permissionedContact) &&
1218 (!CRM_Contact_BAO_Contact_Permission::relationship($cid, $contactId))
1219 ) {
1220 continue;
1221 }
1222 $values[$rid]['id'] = $rid;
1223 $values[$rid]['cid'] = $cid;
1224 $values[$rid]['contact_id_a'] = $relationship->contact_id_a;
1225 $values[$rid]['contact_id_b'] = $relationship->contact_id_b;
c6c691a5 1226 $values[$rid]['contact_type'] = $relationship->contact_type;
6a488035
TO
1227 $values[$rid]['relationship_type_id'] = $relationship->civicrm_relationship_type_id;
1228 $values[$rid]['relation'] = $relationship->relation;
1229 $values[$rid]['name'] = $relationship->sort_name;
1230 $values[$rid]['display_name'] = $relationship->display_name;
1231 $values[$rid]['job_title'] = $relationship->job_title;
1232 $values[$rid]['email'] = $relationship->email;
1233 $values[$rid]['phone'] = $relationship->phone;
1234 $values[$rid]['employer_id'] = $relationship->employer_id;
1235 $values[$rid]['organization_name'] = $relationship->organization_name;
1236 $values[$rid]['country'] = $relationship->country;
1237 $values[$rid]['city'] = $relationship->city;
1238 $values[$rid]['state'] = $relationship->state;
1239 $values[$rid]['start_date'] = $relationship->start_date;
1240 $values[$rid]['end_date'] = $relationship->end_date;
1241 $values[$rid]['description'] = $relationship->description;
1242 $values[$rid]['is_active'] = $relationship->is_active;
1243 $values[$rid]['is_permission_a_b'] = $relationship->is_permission_a_b;
1244 $values[$rid]['is_permission_b_a'] = $relationship->is_permission_b_a;
1245 $values[$rid]['case_id'] = $relationship->case_id;
1246
1247 if ($status) {
1248 $values[$rid]['status'] = $status;
1249 }
1250
1251 $values[$rid]['civicrm_relationship_type_id'] = $relationship->civicrm_relationship_type_id;
1252
1253 if ($relationship->contact_id_a == $contactId) {
1254 $values[$rid]['rtype'] = 'a_b';
1255 }
1256 else {
1257 $values[$rid]['rtype'] = 'b_a';
1258 }
1259
1260 if ($links) {
1261 $replace = array(
1262 'id' => $rid,
1263 'rtype' => $values[$rid]['rtype'],
1264 'cid' => $contactId,
1265 'cbid' => $values[$rid]['cid'],
1266 'caseid' => $values[$rid]['case_id'],
1267 'clientid' => $contactId,
1268 );
1269
1270 if ($status == self::INACTIVE) {
1271 // setting links for inactive relationships
1272 $mask = array_sum(array_keys($links));
1273 if (!$values[$rid]['is_active']) {
1274 $mask -= CRM_Core_Action::DISABLE;
1275 }
1276 else {
1277 $mask -= CRM_Core_Action::ENABLE;
1278 $mask -= CRM_Core_Action::DISABLE;
1279 }
1280 }
1281
1282 // Give access to manage case link by copying to MAX_ACTION index temporarily, depending on case permission of user.
1283 if ($values[$rid]['case_id']) {
1284 // Borrowed logic from CRM_Case_Page_Tab
1285 $hasCaseAccess = FALSE;
1286 if (CRM_Core_Permission::check('access all cases and activities')) {
1287 $hasCaseAccess = TRUE;
1288 }
1289 else {
1290 $userCases = CRM_Case_BAO_Case::getCases(FALSE);
1291 if (array_key_exists($values[$rid]['case_id'], $userCases)) {
1292 $hasCaseAccess = TRUE;
1293 }
1294 }
1295
1296 if ($hasCaseAccess) {
1297 // give access by copying to MAX_ACTION temporarily, otherwise leave at NONE which won't display
1298 $links[CRM_Core_Action::MAX_ACTION] = $links[CRM_Core_Action::NONE];
1299 $links[CRM_Core_Action::MAX_ACTION]['name'] = ts('Manage Case #%1', array(1 => $values[$rid]['case_id']));
f89f2102 1300 $links[CRM_Core_Action::MAX_ACTION]['class'] = 'no-popup';
6a488035
TO
1301
1302 // Also make sure we have the right client cid since can get here from multiple relationship tabs.
1303 if ($values[$rid]['rtype'] == 'b_a') {
1304 $replace['clientid'] = $values[$rid]['cid'];
1305 }
1306 }
1307 }
1308
87dab4a4 1309 $values[$rid]['action'] = CRM_Core_Action::formLink(
1cfa04c4
EM
1310 $links,
1311 $mask,
87dab4a4
AH
1312 $replace,
1313 ts('more'),
1314 FALSE,
1315 'relationship.selector.row',
1316 'Relationship',
1317 $rid);
6a488035
TO
1318 unset($links[CRM_Core_Action::MAX_ACTION]);
1319 }
1320 }
1321
1322 $relationship->free();
1323 return $values;
1324 }
1325 }
1326
1327 /**
100fef9d 1328 * Get get list of relationship type based on the target contact type.
6a488035 1329 *
77c5b619
TO
1330 * @param string $targetContactType
1331 * It's valid contact tpye(may be Individual , Organization , Household).
6a488035 1332 *
a6c01b45
CW
1333 * @return array
1334 * array reference of all relationship types with context to current contact type .
6a488035 1335 */
ee17a760 1336 static public function getRelationType($targetContactType) {
6a488035
TO
1337 $relationshipType = array();
1338 $allRelationshipType = CRM_Core_PseudoConstant::relationshipType();
1339
1340 foreach ($allRelationshipType as $key => $type) {
1341 if ($type['contact_type_b'] == $targetContactType) {
1342 $relationshipType[$key . '_a_b'] = $type['label_a_b'];
1343 }
1344 }
1345
1346 return $relationshipType;
1347 }
1348
1349 /**
100fef9d 1350 * Create / update / delete membership for related contacts.
6a488035
TO
1351 *
1352 * This function will create/update/delete membership for related
1353 * contact based on 1) contact have active membership 2) that
1354 * membership is is extedned by the same relationship type to that
1355 * of the existing relationship.
1356 *
5a4f6742
CW
1357 * @param int $contactId
1358 * contact id.
1359 * @param array $params
1360 * array of values submitted by POST.
1361 * @param array $ids
1362 * array of ids.
bfa4da96 1363 * @param \const|int $action which action called this function
6a488035 1364 *
dd244018 1365 * @param bool $active
6a488035 1366 *
bfa4da96 1367 * @throws \CRM_Core_Exception
6a488035 1368 */
00be9182 1369 public static function relatedMemberships($contactId, &$params, $ids, $action = CRM_Core_Action::ADD, $active = TRUE) {
6a488035 1370 // Check the end date and set the status of the relationship
decc60a0 1371 // accordingly.
6a488035 1372 $status = self::CURRENT;
04ad3598 1373 $targetContact = $targetContact = CRM_Utils_Array::value('contact_check', $params, array());
6a488035
TO
1374
1375 if (!empty($params['end_date'])) {
1376 $endDate = CRM_Utils_Date::setDateDefaults(CRM_Utils_Date::format($params['end_date']), NULL, 'Ymd');
1377 $today = date('Ymd');
1378
1379 if ($today > $endDate) {
1380 $status = self::PAST;
1381 }
1382 }
1383
1384 if (($action & CRM_Core_Action::ADD) &&
1385 ($status & self::PAST)
1386 ) {
1387 // if relationship is PAST and action is ADD, no qustion
1388 // of creating RELATED membership and return back to
1389 // calling method
1390 return;
1391 }
1392
1393 $rel = explode('_', $params['relationship_type_id']);
1394
7f3647bc 1395 $relTypeId = $rel[0];
decc60a0
EM
1396 if (!empty($rel[1])) {
1397 $relDirection = "_{$rel[1]}_{$rel[2]}";
1398 }
1399 else {
1400 // this call is coming from somewhere where the direction was resolved early on (e.g an api call)
1401 // so we can assume _a_b
1402 $relDirection = "_a_b";
04ad3598 1403 $targetContact = array($params['contact_id_b'] => 1);
decc60a0 1404 }
04ad3598 1405
6a488035
TO
1406 if (($action & CRM_Core_Action::ADD) ||
1407 ($action & CRM_Core_Action::DELETE)
1408 ) {
1409 $contact = $contactId;
6a488035
TO
1410 }
1411 elseif ($action & CRM_Core_Action::UPDATE) {
1412 $contact = $ids['contact'];
1413 $targetContact = array($ids['contactTarget'] => 1);
1414 }
1415
1416 // Build the 'values' array for
1417 // 1. ContactA
1418 // 2. ContactB
1419 // This will allow us to check if either of the contacts in
1420 // relationship have active memberships.
1421
1422 $values = array();
1423
1424 // 1. ContactA
1425 $values[$contact] = array(
1426 'relatedContacts' => $targetContact,
1427 'relationshipTypeId' => $relTypeId,
1428 'relationshipTypeDirection' => $relDirection,
1429 );
1430 // 2. ContactB
1431 if (!empty($targetContact)) {
1432 foreach ($targetContact as $cid => $donCare) {
1433 $values[$cid] = array(
1434 'relatedContacts' => array($contact => 1),
1435 'relationshipTypeId' => $relTypeId,
1436 );
1437
1438 $relTypeParams = array('id' => $relTypeId);
1439 $relTypeValues = array();
1440 CRM_Contact_BAO_RelationshipType::retrieve($relTypeParams, $relTypeValues);
1441
1442 if (CRM_Utils_Array::value('name_a_b', $relTypeValues) == CRM_Utils_Array::value('name_b_a', $relTypeValues)) {
1443 $values[$cid]['relationshipTypeDirection'] = '_a_b';
1444 }
1445 else {
1446 $values[$cid]['relationshipTypeDirection'] = ($relDirection == '_a_b') ? '_b_a' : '_a_b';
1447 }
1448 }
1449 }
1450
1451 // Now get the active memberships for all the contacts.
1452 // If contact have any valid membership(s), then add it to
1453 // 'values' array.
1454 foreach ($values as $cid => $subValues) {
1455 $memParams = array('contact_id' => $cid);
1456 $memberships = array();
1457
1458 CRM_Member_BAO_Membership::getValues($memParams, $memberships, $active);
1459
1460 if (empty($memberships)) {
1461 continue;
1462 }
1463
1464 $values[$cid]['memberships'] = $memberships;
1465 }
1466 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant::membershipStatus());
1467
1468 // done with 'values' array.
1469 // Finally add / edit / delete memberships for the related contacts
ee17a760 1470
6a488035
TO
1471 foreach ($values as $cid => $details) {
1472 if (!array_key_exists('memberships', $details)) {
1473 continue;
1474 }
1475
25f1372e 1476 $relatedContacts = array_keys(CRM_Utils_Array::value('relatedContacts', $details, array()));
ee17a760 1477 $mainRelatedContactId = reset($relatedContacts);
6a488035
TO
1478
1479 foreach ($details['memberships'] as $membershipId => $membershipValues) {
1480 $relTypeIds = array();
1481 if ($action & CRM_Core_Action::DELETE) {
1482 // Delete memberships of the related contacts only if relationship type exists for membership type
1483 $query = "
1484SELECT relationship_type_id, relationship_direction
1485 FROM civicrm_membership_type
1486 WHERE id = {$membershipValues['membership_type_id']}";
1487 $dao = CRM_Core_DAO::executeQuery($query);
1488 $relTypeDirs = array();
1489 while ($dao->fetch()) {
1490 $relTypeId = $dao->relationship_type_id;
1491 $relDirection = $dao->relationship_direction;
1492 }
1493 $relTypeIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $relTypeId);
690c56c3 1494 if (in_array($values[$cid]['relationshipTypeId'], $relTypeIds) && !empty($membershipValues['owner_membership_id'])) {
1495 CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipValues['owner_membership_id'], $membershipValues['membership_contact_id']);
6a488035
TO
1496 }
1497 continue;
1498 }
1499 if (($action & CRM_Core_Action::UPDATE) &&
1500 ($status & self::PAST) &&
1501 ($membershipValues['owner_membership_id'])
1502 ) {
1503 // If relationship is PAST and action is UPDATE
1504 // then delete the RELATED membership
1505 CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipValues['owner_membership_id'],
1506 $membershipValues['membership_contact_id']
1507 );
1508 continue;
1509 }
1510
1511 // add / edit the memberships for related
1512 // contacts.
1513
1514 // Get the Membership Type Details.
1515 $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($membershipValues['membership_type_id']);
1516 // Check if contact's relationship type exists in membership type
1517 $relTypeDirs = array();
a7488080 1518 if (!empty($membershipType['relationship_type_id'])) {
6a488035
TO
1519 $relTypeIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_type_id']);
1520 }
a7488080 1521 if (!empty($membershipType['relationship_direction'])) {
6a488035
TO
1522 $relDirections = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_direction']);
1523 }
1524 foreach ($relTypeIds as $key => $value) {
1525 $relTypeDirs[] = $value . '_' . $relDirections[$key];
1526 }
1527 $relTypeDir = $details['relationshipTypeId'] . $details['relationshipTypeDirection'];
1528 if (in_array($relTypeDir, $relTypeDirs)) {
1529 // Check if relationship being created/updated is
1530 // similar to that of membership type's
1531 // relationship.
1532
1533 $membershipValues['owner_membership_id'] = $membershipId;
1534 unset($membershipValues['id']);
1535 unset($membershipValues['membership_contact_id']);
1536 unset($membershipValues['contact_id']);
1537 unset($membershipValues['membership_id']);
1538 foreach ($details['relatedContacts'] as $relatedContactId => $donCare) {
1539 $membershipValues['contact_id'] = $relatedContactId;
1540 if ($deceasedStatusId &&
1541 CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $relatedContactId, 'is_deceased')
1542 ) {
1543 $membershipValues['status_id'] = $deceasedStatusId;
1544 $membershipValues['skipStatusCal'] = TRUE;
1545 }
1546 foreach (array(
7f3647bc
TO
1547 'join_date',
1548 'start_date',
21dfd5f5 1549 'end_date',
7f3647bc 1550 ) as $dateField) {
a7488080 1551 if (!empty($membershipValues[$dateField])) {
6a488035
TO
1552 $membershipValues[$dateField] = CRM_Utils_Date::processDate($membershipValues[$dateField]);
1553 }
1554 }
1555
1556 if ($action & CRM_Core_Action::UPDATE) {
eec8d770 1557 //if updated relationship is already related to contact don't delete existing inherited membership
1558 if (in_array($relTypeId, $relTypeIds) && !empty($values[$relatedContactId]['memberships'])) {
1559 continue;
1560 }
6a488035
TO
1561 //delete the membership record for related
1562 //contact before creating new membership record.
1563 CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipId, $relatedContactId);
1564 }
1565
1566 // check whether we have some related memberships still available
1567 $query = "
1568SELECT count(*)
1569 FROM civicrm_membership
1570 LEFT JOIN civicrm_membership_status ON (civicrm_membership_status.id = civicrm_membership.status_id)
1571 WHERE membership_type_id = {$membershipValues['membership_type_id']} AND owner_membership_id = {$membershipValues['owner_membership_id']}
1572 AND is_current_member = 1";
1573 $result = CRM_Core_DAO::singleValueQuery($query);
1574 if ($result < CRM_Utils_Array::value('max_related', $membershipValues, PHP_INT_MAX)) {
43291913 1575 CRM_Member_BAO_Membership::create($membershipValues, CRM_Core_DAO::$_nullArray);
6a488035
TO
1576 }
1577 }
1578 }
1579 elseif ($action & CRM_Core_Action::UPDATE) {
1580 // if action is update and updated relationship do
1581 // not match with the existing
1582 // membership=>relationship then we need to
1583 // delete the membership record created for
1584 // previous relationship.
690c56c3 1585 // CRM-16087 we need to pass ownerMembershipId to deleteRelatedMemberships function
1586 if (empty($params['relationship_ids']) && !empty($params['id'])) {
1587 $relIds = array($params['id']);
1588 }
1589 else {
1590 $relIds = CRM_Utils_Array::value('relationship_ids', $params);
1591 }
1592 if (self::isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId,
1593 $relIds
1594 ) && !empty($membershipValues['owner_membership_id'])) {
1595 CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipValues['owner_membership_id'], $membershipValues['membership_contact_id']);
6a488035
TO
1596 }
1597 }
1598 }
1599 }
1600 }
1601
1602 /**
98a06ae0 1603 * Helper function to check whether to delete the membership or not.
6616f7c1
EM
1604 *
1605 * Function takes a list of related membership types and if it is not also passed a
1606 * relationship ID of that types evaluates whether the membership should be deleted.
1607 *
1608 * @param array $membershipTypeRelationshipTypeIDs
1609 * Relation type IDs related to the given membership type.
1610 * @param int $contactId
1611 * @param int $mainRelatedContactId
1612 * @param int $relTypeId
1613 * @param array $relIds
1614 *
1615 * @return bool
6a488035 1616 */
6616f7c1
EM
1617 public static function isDeleteRelatedMembership($membershipTypeRelationshipTypeIDs, $contactId, $mainRelatedContactId, $relTypeId, $relIds) {
1618 if (empty($membershipTypeRelationshipTypeIDs) || in_array($relTypeId, $membershipTypeRelationshipTypeIDs)) {
eec8d770 1619 return FALSE;
6a488035
TO
1620 }
1621
1622 if (empty($relIds)) {
1623 return FALSE;
1624 }
1625
7f3647bc
TO
1626 $relParamas = array(
1627 1 => array($contactId, 'Integer'),
6a488035
TO
1628 2 => array($mainRelatedContactId, 'Integer'),
1629 );
1630
1631 if ($contactId == $mainRelatedContactId) {
6616f7c1
EM
1632 $recordsFound = (int) CRM_Core_DAO::singleValueQuery("SELECT COUNT(*) FROM civicrm_relationship WHERE relationship_type_id IN ( " . implode(',', $membershipTypeRelationshipTypeIDs) . " ) AND
1633contact_id_a IN ( %1 ) OR contact_id_b IN ( %1 ) AND id IN (" . implode(',', $relIds) . ")", $relParamas);
6a488035
TO
1634 if ($recordsFound) {
1635 return FALSE;
1636 }
1637 return TRUE;
1638 }
1639
6616f7c1 1640 $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
1641
1642 if ($recordsFound) {
1643 return FALSE;
1644 }
1645
1646 return TRUE;
1647 }
1648
1649 /**
fe482240 1650 * Get Current Employer for Contact.
6a488035 1651 *
77c5b619
TO
1652 * @param $contactIds
1653 * Contact Ids.
6a488035 1654 *
a6c01b45
CW
1655 * @return array
1656 * array of the current employer
6a488035 1657 */
00be9182 1658 public static function getCurrentEmployer($contactIds) {
6a488035
TO
1659 $contacts = implode(',', $contactIds);
1660
1661 $query = "
1662SELECT organization_name, id, employer_id
1663FROM civicrm_contact
1664WHERE id IN ( {$contacts} )
1665";
1666
1667 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
1668 $currentEmployer = array();
1669 while ($dao->fetch()) {
1670 $currentEmployer[$dao->id]['org_id'] = $dao->employer_id;
1671 $currentEmployer[$dao->id]['org_name'] = $dao->organization_name;
1672 }
1673
1674 return $currentEmployer;
1675 }
1676
1677 /**
100fef9d 1678 * Return list of permissioned employer for a given contact.
6a488035 1679 *
5a4f6742
CW
1680 * @param int $contactID
1681 * contact id whose employers.
16b10e64 1682 * are to be found.
5a4f6742
CW
1683 * @param string $name
1684 * employers sort name.
6a488035 1685 *
a6c01b45
CW
1686 * @return array
1687 * array of employers.
6a488035 1688 */
00be9182 1689 public static function getPermissionedEmployer($contactID, $name = NULL) {
6a488035
TO
1690 //get the relationship id
1691 $relTypeId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType',
1692 'Employee of', 'id', 'name_a_b'
1693 );
1694
51e89def
DS
1695 return self::getPermissionedContacts($contactID, $relTypeId, $name);
1696 }
1697
1698
7f3647bc 1699 /**
fe482240 1700 * Function to return list of permissioned contacts for a given contact and relationship type.
7f3647bc 1701 *
5a4f6742
CW
1702 * @param int $contactID
1703 * contact id whose permissioned contacts are to be found.
1704 * @param string $relTypeId
1705 * one or more relationship type id's.
1706 * @param string $name
7f3647bc 1707 *
a6c01b45 1708 * @return array
16b10e64 1709 * Array of contacts
7f3647bc 1710 */
00be9182 1711 public static function getPermissionedContacts($contactID, $relTypeId, $name = NULL) {
51e89def
DS
1712 $contacts = array();
1713
6a488035
TO
1714 if ($relTypeId) {
1715 $query = "
1716SELECT cc.id as id, cc.sort_name as name
1717FROM civicrm_relationship cr, civicrm_contact cc
49f8272d 1718WHERE
51e89def 1719cr.contact_id_a = %1 AND
f9f0eff9 1720cr.relationship_type_id IN (%2) AND
51e89def 1721cr.is_permission_a_b = 1 AND
6a488035
TO
1722IF(cr.end_date IS NULL, 1, (DATEDIFF( CURDATE( ), cr.end_date ) <= 0)) AND
1723cr.is_active = 1 AND
7ecf6275 1724cc.id = cr.contact_id_b AND
4755bcde 1725cc.is_deleted = 0";
51e89def
DS
1726
1727 if (!empty($name)) {
7f3647bc 1728 $name = CRM_Utils_Type::escape($name, 'String');
51e89def 1729 $query .= "
49f8272d 1730AND cc.sort_name LIKE '%$name%'";
51e89def 1731 }
6a488035 1732
f9f0eff9 1733 $args = array(1 => array($contactID, 'Integer'), 2 => array($relTypeId, 'String'));
7f3647bc 1734 $dao = CRM_Core_DAO::executeQuery($query, $args);
6a488035
TO
1735
1736 while ($dao->fetch()) {
51e89def 1737 $contacts[$dao->id] = array(
6a488035
TO
1738 'name' => $dao->name,
1739 'value' => $dao->id,
1740 );
1741 }
1742 }
51e89def 1743 return $contacts;
6a488035
TO
1744 }
1745
6a488035 1746 /**
fe482240 1747 * Merge relationships from otherContact to mainContact.
bfa4da96 1748 *
6a488035
TO
1749 * Called during contact merge operation
1750 *
77c5b619
TO
1751 * @param int $mainId
1752 * Contact id of main contact record.
1753 * @param int $otherId
1754 * Contact id of record which is going to merge.
1755 * @param array $sqls
1756 * (reference) array of sql statements to append to.
6a488035
TO
1757 *
1758 * @see CRM_Dedupe_Merger::cpTables()
6a488035 1759 */
00be9182 1760 public static function mergeRelationships($mainId, $otherId, &$sqls) {
6a488035
TO
1761 // Delete circular relationships
1762 $sqls[] = "DELETE FROM civicrm_relationship
1763 WHERE (contact_id_a = $mainId AND contact_id_b = $otherId)
1764 OR (contact_id_b = $mainId AND contact_id_a = $otherId)";
1765
1766 // Delete relationship from other contact if main contact already has that relationship
1767 $sqls[] = "DELETE r2
1768 FROM civicrm_relationship r1, civicrm_relationship r2
1769 WHERE r1.relationship_type_id = r2.relationship_type_id
1770 AND r1.id <> r2.id
1771 AND (
1772 r1.contact_id_a = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_b = r2.contact_id_b
1773 OR r1.contact_id_b = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_a = r2.contact_id_a
1774 OR (
1775 (r1.contact_id_a = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_b = r2.contact_id_a
1776 OR r1.contact_id_b = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_a = r2.contact_id_b)
1777 AND r1.relationship_type_id IN (SELECT id FROM civicrm_relationship_type WHERE name_b_a = name_a_b)
1778 )
1779 )";
1780
1781 // Move relationships
1782 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_a = $mainId WHERE contact_id_a = $otherId";
1783 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_b = $mainId WHERE contact_id_b = $otherId";
1784
1785 // Move current employer id (name will get updated later)
1786 $sqls[] = "UPDATE civicrm_contact SET employer_id = $mainId WHERE employer_id = $otherId";
1787 }
1788
1789 /**
1790 * Set 'is_valid' field to false for all relationships whose end date is in the past, ie. are expired.
1791 *
72b3a70c
CW
1792 * @return bool
1793 * True on success, false if error is encountered.
6a488035 1794 */
00be9182 1795 public static function disableExpiredRelationships() {
6a488035
TO
1796 $query = "SELECT id FROM civicrm_relationship WHERE is_active = 1 AND end_date < CURDATE()";
1797
1798 $dao = CRM_Core_DAO::executeQuery($query);
1799 while ($dao->fetch()) {
1800 $result = CRM_Contact_BAO_Relationship::setIsActive($dao->id, FALSE);
1801 // Result will be NULL if error occurred. We abort early if error detected.
1802 if ($result == NULL) {
1803 return FALSE;
1804 }
1805 }
1806 return TRUE;
1807 }
c9c41397 1808
1809 /**
fe482240 1810 * Function filters the query by possible relationships for the membership type.
98a06ae0 1811 *
c9c41397 1812 * It is intended to be called when constructing queries for the api (reciprocal & non-reciprocal)
1813 * and to add clauses to limit the return to those relationships which COULD inherit a membership type
1814 * (as opposed to those who inherit a particular membership
1815 *
77c5b619
TO
1816 * @param array $params
1817 * Api input array.
77b97be7
EM
1818 * @param null $direction
1819 *
c301f76e 1820 * @return array|void
c9c41397 1821 */
00be9182 1822 public static function membershipTypeToRelationshipTypes(&$params, $direction = NULL) {
7f3647bc 1823 $membershipType = civicrm_api3('membership_type', 'getsingle', array(
353ffa53
TO
1824 'id' => $params['membership_type_id'],
1825 'return' => 'relationship_type_id, relationship_direction',
1826 ));
c9c41397 1827 $relationshipTypes = $membershipType['relationship_type_id'];
22e263ad 1828 if (empty($relationshipTypes)) {
c301f76e 1829 return NULL;
f201289d 1830 }
c9c41397 1831 // if we don't have any contact data we can only filter on type
22e263ad 1832 if (empty($params['contact_id']) && empty($params['contact_id_a']) && empty($params['contact_id_a'])) {
c9c41397 1833 $params['relationship_type_id'] = array('IN' => $relationshipTypes);
c301f76e 1834 return NULL;
c9c41397 1835 }
1836 else {
1a9b2ee8 1837 $relationshipDirections = (array) $membershipType['relationship_direction'];
c9c41397 1838 // if we have contact_id_a OR contact_id_b we can make a call here
1839 // if we have contact??
1840 foreach ($relationshipDirections as $index => $mtdirection) {
7f3647bc 1841 if (isset($params['contact_id_a']) && $mtdirection == 'a_b' || $direction == 'a_b') {
c9c41397 1842 $types[] = $relationshipTypes[$index];
1843 }
7f3647bc 1844 if (isset($params['contact_id_b']) && $mtdirection == 'b_a' || $direction == 'b_a') {
c9c41397 1845 $types[] = $relationshipTypes[$index];
1846 }
1847 }
22e263ad 1848 if (!empty($types)) {
c9c41397 1849 $params['relationship_type_id'] = array('IN' => $types);
1850 }
7f3647bc 1851 elseif (!empty($clauses)) {
c9c41397 1852 return explode(' OR ', $clauses);
1853 }
92e4c2a5 1854 else {
c9c41397 1855 // effectively setting it to return no results
1856 $params['relationship_type_id'] = 0;
1857 }
1858 }
1859 }
40458f6c 1860
1861
1862 /**
98a06ae0 1863 * Wrapper for contact relationship selector.
40458f6c 1864 *
77c5b619
TO
1865 * @param array $params
1866 * Associated array for params record id.
40458f6c 1867 *
a6c01b45
CW
1868 * @return array
1869 * associated array of contact relationships
40458f6c 1870 */
1871 public static function getContactRelationshipSelector(&$params) {
1872 // format the params
7f3647bc
TO
1873 $params['offset'] = ($params['page'] - 1) * $params['rp'];
1874 $params['sort'] = CRM_Utils_Array::value('sortBy', $params);
40458f6c 1875
1876 if ($params['context'] == 'past') {
1877 $relationshipStatus = CRM_Contact_BAO_Relationship::INACTIVE;
1878 }
62e6afce 1879 elseif ($params['context'] == 'all') {
6c292184
TM
1880 $relationshipStatus = CRM_Contact_BAO_Relationship::ALL;
1881 }
40458f6c 1882 else {
1883 $relationshipStatus = CRM_Contact_BAO_Relationship::CURRENT;
1884 }
1885
1886 // check logged in user for permission
1887 $page = new CRM_Core_Page();
1888 CRM_Contact_Page_View::checkUserPermission($page, $params['contact_id']);
1889 $permissions = array($page->_permission);
1890 if ($page->_permission == CRM_Core_Permission::EDIT) {
1891 $permissions[] = CRM_Core_Permission::DELETE;
1892 }
1893 $mask = CRM_Core_Action::mask($permissions);
1894
d0592c3d 1895 if ($params['context'] != 'user') {
1896 $links = CRM_Contact_Page_View_Relationship::links();
1897 $permissionedContacts = FALSE;
1898 }
1899 else {
1900 $links = CRM_Contact_Page_View_UserDashBoard::links();
1901 $permissionedContacts = TRUE;
1902 $mask = NULL;
1903 }
40458f6c 1904 // get contact relationships
1905 $relationships = CRM_Contact_BAO_Relationship::getRelationship($params['contact_id'],
1906 $relationshipStatus,
1907 $params['rp'], 0, 0,
d0592c3d 1908 $links, $mask,
1909 $permissionedContacts,
40458f6c 1910 $params
1911 );
1912
1913 $contactRelationships = array();
d0592c3d 1914 $params['total'] = 0;
40458f6c 1915 if (!empty($relationships)) {
d0592c3d 1916 // get the total relationships
1917 if ($params['context'] != 'user') {
1918 $params['total'] = CRM_Contact_BAO_Relationship::getRelationship($params['contact_id'],
7f3647bc 1919 $relationshipStatus, 0, 1, 0, NULL, NULL, $permissionedContacts);
d0592c3d 1920 }
1921 else {
1922 // FIX ME: we cannot directly determine total permissioned relationship, hence re-fire query
1923 $permissionedRelationships = CRM_Contact_BAO_Relationship::getRelationship($params['contact_id'],
1924 $relationshipStatus,
1925 0, 0, 0,
1926 NULL, NULL, TRUE
1927 );
1928 $params['total'] = count($permissionedRelationships);
1929 }
40458f6c 1930
1931 // format params
1932 foreach ($relationships as $relationshipId => $values) {
67e4fb51 1933 //Add image icon for related contacts: CRM-14919
c6c691a5 1934 $icon = CRM_Contact_BAO_Contact_Utils::getImage($values['contact_type'],
67e4fb51
N
1935 FALSE,
1936 $values['cid']
1937 );
92fcb95f 1938 $contactRelationships[$relationshipId]['name'] = $icon . ' ' . CRM_Utils_System::href(
7f3647bc
TO
1939 $values['name'],
1940 'civicrm/contact/view',
1941 "reset=1&cid={$values['cid']}");
40458f6c 1942
1943 $contactRelationships[$relationshipId]['relation'] = CRM_Utils_System::href(
1944 $values['relation'],
1945 'civicrm/contact/view/rel',
f1cb718d 1946 "action=view&reset=1&cid={$values['cid']}&id={$values['id']}&rtype={$values['rtype']}");
40458f6c 1947
d0592c3d 1948 if ($params['context'] == 'current') {
40458f6c 1949 if (($params['contact_id'] == $values['contact_id_a'] AND $values['is_permission_a_b'] == 1) OR
1950 ($params['contact_id'] == $values['contact_id_b'] AND $values['is_permission_b_a'] == 1)
1951 ) {
1952 $contactRelationships[$relationshipId]['name'] .= '<span id="permission-a-b" class="crm-marker permission-relationship"> *</span>';
1953 }
1954
1955 if (($values['cid'] == $values['contact_id_a'] AND $values['is_permission_a_b'] == 1) OR
1956 ($values['cid'] == $values['contact_id_b'] AND $values['is_permission_b_a'] == 1)
1957 ) {
1958 $contactRelationships[$relationshipId]['relation'] .= '<span id="permission-b-a" class="crm-marker permission-relationship"> *</span>';
1959 }
1960 }
1961
1962 if (!empty($values['description'])) {
1963 $contactRelationships[$relationshipId]['relation'] .= "<p class='description'>{$values['description']}</p>";
1964 }
1965
1966 $contactRelationships[$relationshipId]['start_date'] = CRM_Utils_Date::customFormat($values['start_date']);
1967 $contactRelationships[$relationshipId]['end_date'] = CRM_Utils_Date::customFormat($values['end_date']);
1968 $contactRelationships[$relationshipId]['city'] = $values['city'];
1969 $contactRelationships[$relationshipId]['state'] = $values['state'];
1970 $contactRelationships[$relationshipId]['email'] = $values['email'];
1971 $contactRelationships[$relationshipId]['phone'] = $values['phone'];
1972 $contactRelationships[$relationshipId]['links'] = $values['action'];
e1cad725 1973 $contactRelationships[$relationshipId]['id'] = $values['id'];
f1321272 1974 $contactRelationships[$relationshipId]['is_active'] = $values['is_active'];
40458f6c 1975 }
1976 }
1977 return $contactRelationships;
1978 }
1979
6a488035 1980}