3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
29 * Class CRM_Contact_BAO_Relationship.
31 class CRM_Contact_BAO_Relationship
extends CRM_Contact_DAO_Relationship
{
34 * Various constants to indicate different type of relationships.
38 const ALL
= 0, PAST
= 1, DISABLED
= 2, CURRENT
= 4, INACTIVE
= 8;
41 * Create function - use the API instead.
43 * Note that the previous create function has been renamed 'legacyCreateMultiple'
44 * and this is new in 4.6
45 * All existing calls have been changed to legacyCreateMultiple except the api call - however, it is recommended
46 * that you call that as the end to end testing here is based on the api & refactoring may still be done.
48 * @param array $params
50 * @return \CRM_Contact_BAO_Relationship
51 * @throws \CRM_Core_Exception
53 public static function create(&$params) {
54 $params = self
::loadExistingRelationshipDetails($params);
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');
58 if (self
::checkValidRelationship($params, $params, 0)) {
59 throw new CRM_Core_Exception('Invalid Relationship');
61 $relationship = self
::add($params);
62 if (!empty($params['contact_id_a'])) {
64 'contactTarget' => $relationship->contact_id_b
,
65 'contact' => $params['contact_id_a'],
68 //CRM-16087 removed additional call to function relatedMemberships which is already called by disableEnableRelationship
69 //resulting in memership being created twice
70 if (array_key_exists('is_active', $params) && empty($params['is_active'])) {
71 $action = CRM_Core_Action
::DISABLE
;
75 $action = CRM_Core_Action
::ENABLE
;
78 $id = empty($params['id']) ?
$relationship->id
: $params['id'];
79 self
::disableEnableRelationship($id, $action, $params, $ids, $active);
82 self
::addRecent($params, $relationship);
87 * Create multiple relationships for one contact.
89 * The relationship details are the same for each relationship except the secondary contact
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.
101 * @throws \CRM_Core_Exception
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;
107 $relationshipIDs = array();
108 foreach ($secondaryContactIDs as $secondaryContactID) {
110 $params['contact_id_' . $secondaryContactLetter] = $secondaryContactID;
111 $relationship = civicrm_api3('relationship', 'create', $params);
112 $relationshipIDs[] = $relationship['id'];
115 catch (CiviCRM_API3_Exception
$e) {
116 switch ($e->getMessage()) {
117 case 'Duplicate Relationship':
121 case 'Invalid Relationship':
126 throw new CRM_Core_Exception('unknown relationship create error ' . $e->getMessage());
133 'invalid' => $invalid,
134 'duplicate' => $duplicate,
136 'relationship_ids' => $relationshipIDs,
141 * Takes an associative array and creates a relationship object.
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
146 * @param array $params
147 * (reference ) an assoc array of name/value pairs.
149 * The array that holds all the db ids.
150 * per http://wiki.civicrm.org/confluence/display/CRM/Database+layer
151 * "we are moving away from the $ids param "
153 * @return CRM_Contact_BAO_Relationship
155 public static function legacyCreateMultiple(&$params, $ids = array()) {
156 $valid = $invalid = $duplicate = $saved = 0;
157 $relationships = $relationshipIds = array();
158 $relationshipId = CRM_Utils_Array
::value('relationship', $ids, CRM_Utils_Array
::value('id', $params));
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
162 if (empty($relationshipId)) {
169 CRM_Utils_Hook
::pre($hook, 'Relationship', $relationshipId, $params);
171 if (!$relationshipId) {
172 // creating a new relationship
173 $dataExists = self
::dataExists($params);
175 return array(FALSE, TRUE, FALSE, FALSE, NULL);
177 $relationshipIds = array();
178 foreach ($params['contact_check'] as $key => $value) {
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
186 $contactFields = self
::setContactABFromIDs($params, $ids, $key);
187 $errors = self
::checkValidRelationship($contactFields, $ids, $key);
194 self
::checkDuplicateRelationship(
196 CRM_Utils_Array
::value('contact', $ids),
205 $singleInstanceParams = array_merge($params, $contactFields);
206 $relationship = self
::add($singleInstanceParams);
207 $relationshipIds[] = $relationship->id
;
208 $relationships[$relationship->id
] = $relationship;
211 // editing the relationship
214 // check for duplicate relationship
215 // @todo this code doesn't cope well with updates - causes e-Notices.
216 // API has a lot of code to work around
217 // this but should review this code & remove the extra handling from the api
218 // it seems doubtful any of this is relevant if the contact fields & relationship
219 // type fields are not set
221 self
::checkDuplicateRelationship(
223 CRM_Utils_Array
::value('contact', $ids),
224 $ids['contactTarget'],
229 return array($valid, $invalid, $duplicate, $saved, NULL);
232 $validContacts = TRUE;
233 //validate contacts in update mode also.
234 if (!empty($ids['contact']) && !empty($ids['contactTarget'])) {
235 if (self
::checkValidRelationship($params, $ids, $ids['contactTarget'])) {
236 $validContacts = FALSE;
240 if ($validContacts) {
241 // editing an existing relationship
242 $relationship = self
::add($params, $ids, $ids['contactTarget']);
243 $relationshipIds[] = $relationship->id
;
244 $relationships[$relationship->id
] = $relationship;
249 // do not add to recent items for import, CRM-4399
250 if (!(!empty($params['skipRecentView']) ||
$invalid ||
$duplicate)) {
251 self
::addRecent($params, $relationship);
254 return array($valid, $invalid, $duplicate, $saved, $relationshipIds, $relationships);
258 * This is the function that check/add if the relationship created is valid.
260 * @param array $params
261 * (reference ) an assoc array of name/value pairs.
263 * The array that holds all the db ids.
264 * @param int $contactId
265 * This is contact id for adding relationship.
267 * @return CRM_Contact_BAO_Relationship
269 public static function add(&$params, $ids = array(), $contactId = NULL) {
270 $relationshipId = CRM_Utils_Array
::value('relationship', $ids, CRM_Utils_Array
::value('id', $params));
273 if ($relationshipId) {
276 //@todo hook are called from create and add - remove one
277 CRM_Utils_Hook
::pre($hook, 'Relationship', $relationshipId, $params);
279 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
281 // explode the string with _ to get the relationship type id
282 // and to know which contact has to be inserted in
283 // contact_id_a and which one in contact_id_b
284 list($type) = explode('_', $relationshipTypes);
286 // check if the relationship type is Head of Household then update the
287 // household's primary contact with this contact.
289 CRM_Contact_BAO_Household
::updatePrimaryContact($params['contact_id_b'], $params['contact_id_a']);
292 $relationship = new CRM_Contact_BAO_Relationship();
293 //@todo this code needs to be updated for the possibility that not all fields are set
294 // by using $relationship->copyValues($params);
296 $relationship->contact_id_b
= $params['contact_id_b'];
297 $relationship->contact_id_a
= $params['contact_id_a'];
298 $relationship->relationship_type_id
= $type;
299 $relationship->id
= $relationshipId;
301 $dateFields = array('end_date', 'start_date');
303 foreach (self
::getdefaults() as $defaultField => $defaultValue) {
304 if (isset($params[$defaultField])) {
305 if (in_array($defaultField, $dateFields)) {
306 $relationship->$defaultField = CRM_Utils_Date
::format(CRM_Utils_Array
::value($defaultField, $params));
307 if (!$relationship->$defaultField) {
308 $relationship->$defaultField = 'NULL';
312 $relationship->$defaultField = $params[$defaultField];
315 elseif (!$relationshipId) {
316 $relationship->$defaultField = $defaultValue;
320 $relationship->save();
322 // add custom field values
323 if (!empty($params['custom'])) {
324 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_relationship', $relationship->id
);
327 $relationship->free();
329 CRM_Utils_Hook
::post($hook, 'Relationship', $relationship->id
, $relationship);
331 return $relationship;
335 * Add relationship to recent links.
337 * @param array $params
338 * @param CRM_Contact_DAO_Relationship $relationship
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"
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
)
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"
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"
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
) . ')';
363 CRM_Utils_Recent
::add($title,
367 $relationship->contact_id_a
,
374 * Load contact ids and relationship type id when doing a create call if not provided.
376 * There are are various checks done in create which require this information which is optional
379 * @param array $params
380 * Parameters passed to create call.
383 * Parameters with missing fields added if required.
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'])) {
391 if (empty($params['id'])) {
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(
402 while ($result->fetch()) {
403 foreach ($fieldsToFill as $field) {
404 $params[$field] = !empty($params[$field]) ?
$params[$field] : $result->$field;
411 * Resolve passed in contact IDs to contact_id_a & contact_id_b.
413 * @param array $params
415 * @param null $contactID
418 * @throws \CRM_Core_Exception
420 public static function setContactABFromIDs($params, $ids = array(), $contactID = NULL) {
421 $returnFields = array();
423 // $ids['contact'] is deprecated but comes from legacyCreateMultiple function.
424 if (empty($ids['contact'])) {
425 if (!empty($params['id'])) {
426 return self
::loadExistingRelationshipDetails($params);
428 throw new CRM_Core_Exception('Cannot create relationship, insufficient contact IDs provided');
430 if (isset($params['relationship_type_id']) && !is_numeric($params['relationship_type_id'])) {
431 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
432 list($relationshipTypeID, $first) = explode('_', $relationshipTypes);
433 $returnFields['relationship_type_id'] = $relationshipTypeID;
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);
441 $returnFields['contact_id_' . $contactLetter] = $contactID;
447 return $returnFields;
451 * Specify defaults for creating a relationship.
454 * array of defaults for creating relationship
456 public static function getdefaults() {
459 'is_permission_a_b' => 0,
460 'is_permission_b_a' => 0,
462 'start_date' => 'NULL',
464 'end_date' => 'NULL',
470 * Check if there is data to create the object.
472 * @param array $params
473 * (reference ) an assoc array of name/value pairs.
477 public static function dataExists(&$params) {
478 // return if no data present
479 if (!is_array(CRM_Utils_Array
::value('contact_check', $params))) {
486 * Get get list of relationship type based on the contact type.
488 * @param int $contactId
489 * This is the contact id of the current contact.
490 * @param null $contactSuffix
491 * @param string $relationshipId
492 * The id of the existing relationship if any.
493 * @param string $contactType
496 * If true returns relationship types in both the direction.
497 * @param string $column
498 * Name/label that going to retrieve from db.
499 * @param bool $biDirectional
500 * @param string $contactSubType
501 * Includes relationship types between this subtype.
502 * @param bool $onlySubTypeRelationTypes
503 * If set only subtype which is passed by $contactSubType
504 * related relationship types get return
507 * array reference of all relationship types with context to current contact.
509 public static function getContactRelationshipType(
511 $contactSuffix = NULL,
512 $relationshipId = NULL,
516 $biDirectional = TRUE,
517 $contactSubType = NULL,
518 $onlySubTypeRelationTypes = FALSE
521 $relationshipType = array();
522 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType($column);
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
;
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
;
542 $contactSubType = array();
544 $contactType = CRM_Contact_BAO_Contact
::getContactType($contactId);
545 $contactSubType = CRM_Contact_BAO_Contact
::getContactSubType($contactId);
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
553 // the other contact type is required or present or matches
554 ((!$value['contact_type_b']) ||
555 (!$otherContactType) ||
556 $value['contact_type_b'] == $otherContactType
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)
563 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
566 if (((!$value['contact_type_b']) ||
567 $value['contact_type_b'] == $contactType
569 ((!$value['contact_type_a']) ||
570 (!$otherContactType) ||
571 $value['contact_type_a'] == $otherContactType
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)
578 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
582 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
583 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
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);
593 // sort the relationshipType in ascending order CRM-7736
594 asort($relationshipType);
595 return $relationshipType;
599 * Delete current employer relationship.
604 * @return CRM_Contact_DAO_Relationship
606 public static function clearCurrentEmployer($id, $action) {
607 $relationship = new CRM_Contact_DAO_Relationship();
608 $relationship->id
= $id;
609 $relationship->find(TRUE);
611 //to delete relationship between household and individual \
612 //or between individual and organization
613 if (($action & CRM_Core_Action
::DISABLE
) ||
($action & CRM_Core_Action
::DELETE
)) {
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'] ||
616 $relationship->relationship_type_id
== $relTypes['Household Member of']['id']
618 $sharedContact = new CRM_Contact_DAO_Contact();
619 $sharedContact->id
= $relationship->contact_id_a
;
620 $sharedContact->find(TRUE);
622 if ($relationship->relationship_type_id
== 4 && $relationship->contact_id_b
== $sharedContact->employer_id
) {
623 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($relationship->contact_id_a
);
627 return $relationship;
631 * Delete the relationship.
638 public static function del($id) {
639 // delete from relationship table
640 CRM_Utils_Hook
::pre('delete', 'Relationship', $id, CRM_Core_DAO
::$_nullArray);
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.
647 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
648 'contact_check' => array($relationship->contact_id_b
=> 1),
652 // calling relatedMemberships to delete the memberships of
654 self
::relatedMemberships($relationship->contact_id_a
,
657 CRM_Core_Action
::DELETE
,
662 $relationship->delete();
663 CRM_Core_Session
::setStatus(ts('Selected relationship has been deleted successfully.'), ts('Record Deleted'), 'success');
665 CRM_Utils_Hook
::post('delete', 'Relationship', $id, $relationship);
667 // delete the recently created Relationship
668 $relationshipRecent = array(
670 'type' => 'Relationship',
672 CRM_Utils_Recent
::del($relationshipRecent);
674 return $relationship;
678 * Disable/enable the relationship.
685 public static function disableEnableRelationship($id, $action, $params = array(), $ids = array(), $active = FALSE) {
686 $relationship = self
::clearCurrentEmployer($id, $action);
688 if (CRM_Core_Permission
::access('CiviMember')) {
689 // create $params array which is required to delete memberships
690 // of the related contacts.
691 if (empty($params)) {
693 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
694 'contact_check' => array($relationship->contact_id_b
=> 1),
697 $contact_id_a = empty($params['contact_id_a']) ?
$relationship->contact_id_a
: $params['contact_id_a'];
698 // calling relatedMemberships to delete/add the memberships of
700 if ($action & CRM_Core_Action
::DISABLE
) {
701 CRM_Contact_BAO_Relationship
::relatedMemberships($contact_id_a,
704 CRM_Core_Action
::DELETE
,
708 elseif ($action & CRM_Core_Action
::ENABLE
) {
709 $ids['contact'] = empty($ids['contact']) ?
$contact_id_a : $ids['contact'];
710 CRM_Contact_BAO_Relationship
::relatedMemberships($contact_id_a,
713 empty($params['id']) ? CRM_Core_Action
::ADD
: CRM_Core_Action
::UPDATE
,
721 * Delete the object records that are associated with this contact.
723 * @param int $contactId
724 * Id of the contact to delete.
726 public static function deleteContact($contactId) {
727 $relationship = new CRM_Contact_DAO_Relationship();
728 $relationship->contact_id_a
= $contactId;
729 $relationship->delete();
731 $relationship = new CRM_Contact_DAO_Relationship();
732 $relationship->contact_id_b
= $contactId;
733 $relationship->delete();
735 CRM_Contact_BAO_Household
::updatePrimaryContact(NULL, $contactId);
739 * Get the other contact in a relationship.
744 * $returns returns the contact ids in the realtionship
746 * @return \CRM_Contact_DAO_Relationship
748 public static function getRelationshipByID($id) {
749 $relationship = new CRM_Contact_DAO_Relationship();
751 $relationship->id
= $id;
752 $relationship->selectAdd();
753 $relationship->selectAdd('contact_id_a, contact_id_b');
754 $relationship->find(TRUE);
756 return $relationship;
760 * Check if the relationship type selected between two contacts is correct.
762 * @param int $contact_a
764 * @param int $contact_b
766 * @param int $relationshipTypeId
767 * Relationship type id.
770 * true if it is valid relationship else false
772 public static function checkRelationshipType($contact_a, $contact_b, $relationshipTypeId) {
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);
781 $contact_sub_type_a = CRM_Contact_BAO_Contact
::getContactSubType($contact_a);
782 $contact_sub_type_b = CRM_Contact_BAO_Contact
::getContactSubType($contact_b);
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
,
789 ((!$relationshipType->contact_sub_type_b
) ||
(in_array($relationshipType->contact_sub_type_b
,
803 * This function does the validtion for valid relationship.
805 * @param array $params
806 * This array contains the values there are subitted by the form.
808 * The array that holds all the db ids.
809 * @param int $contactId
810 * This is contact id for adding relationship.
814 public static function checkValidRelationship($params, $ids, $contactId) {
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)
818 if (!CRM_Contact_BAO_Relationship
::checkRelationshipType($params['contact_id_a'], $params['contact_id_b'],
819 $params['relationship_type_id'])) {
820 $errors = 'Please select valid relationship between these two contacts.';
826 * This function checks for duplicate relationship.
828 * @param array $params
829 * (reference ) an assoc array of name/value pairs.
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.
838 * true if record exists else false
840 public static function checkDuplicateRelationship(&$params, $id, $contactId = 0, $relationshipId = 0) {
841 $relationshipTypeId = CRM_Utils_Array
::value('relationship_type_id', $params);
842 list($type) = explode('_', $relationshipTypeId);
846 FROM civicrm_relationship
847 WHERE relationship_type_id = " . CRM_Utils_Type
::escape($type, 'Integer');
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
854 * @ time of writing this function is called from Relationship::legacyCreateMultiple (twice)
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
861 $dateFields = array('end_date', 'start_date');
862 foreach ($dateFields as $dateField) {
863 if (array_key_exists($dateField, $params)) {
864 if (empty($params[$dateField]) ||
$params[$dateField] == 'null') {
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
869 $queryString .= " AND $dateField IS NULL";
872 elseif (is_array($params[$dateField])) {
873 $queryString .= " AND $dateField = " .
874 CRM_Utils_Type
::escape(CRM_Utils_Date
::format($params[$dateField]), 'Date');
877 $queryString .= " AND $dateField = " .
878 CRM_Utils_Type
::escape($params[$dateField], 'Date');
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') . " ) ) ";
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');
894 if ($relationshipId) {
895 $queryString .= " AND id !=" . CRM_Utils_Type
::escape($relationshipId, 'Integer');
898 $relationship = new CRM_Contact_BAO_Relationship();
899 $relationship->query($queryString);
900 $relationship->fetch();
901 $relationship->free();
902 return ($relationship->id
) ?
TRUE : FALSE;
906 * Update the is_active flag in the db.
909 * Id of the database record.
910 * @param bool $is_active
911 * Value we want to set the is_active field.
913 * @throws CiviCRM_API3_Exception
915 * DAO object on success, null otherwise
917 public static function setIsActive($id, $is_active) {
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.
924 $result = civicrm_api('relationship', 'create', array(
926 'is_active' => $is_active,
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);
938 * Fetch a relationship object and store the values in the values array.
940 * @param array $params
941 * Input parameters to find object.
942 * @param array $values
943 * Output values of the object.
946 * (reference) the values that could be potentially assigned to smarty
948 public static function &getValues(&$params, &$values) {
949 if (empty($params)) {
954 // get the specific number of relationship or all relationships.
955 if (!empty($params['numRelationship'])) {
956 $v['data'] = &CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'], NULL, $params['numRelationship']);
959 $v['data'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id']);
962 // get the total count of relationships
963 $v['totalCount'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'], NULL, NULL, TRUE);
965 $values['relationship']['data'] = &$v['data'];
966 $values['relationship']['totalCount'] = &$v['totalCount'];
972 * Helper function to form the sql for relationship retrieval.
974 * @param int $contactId
977 * (check const at top of file).
978 * @param int $numRelationship
979 * No of relationships to display (limit).
981 * Get the no of relationships.
982 * $param int $relationshipId relationship id
983 * @param int $relationshipId
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.
990 * [select, from, where]
992 public static function makeURLClause($contactId, $status, $numRelationship, $count, $relationshipId, $direction, $params = array()) {
993 $select = $from = $where = '';
997 if ($direction == 'a_b') {
998 $select .= ' SELECT count(DISTINCT civicrm_relationship.id) as cnt1, 0 as cnt2 ';
1001 $select .= ' SELECT 0 as cnt1, count(DISTINCT civicrm_relationship.id) as cnt2 ';
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,
1017 civicrm_contact.contact_type as contact_type,
1018 civicrm_phone.phone as phone,
1019 civicrm_contact.id as civicrm_contact_id,
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';
1031 if ($direction == 'a_b') {
1032 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
1033 civicrm_relationship_type.label_b_a as relation ';
1036 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
1037 civicrm_relationship_type.label_a_b as relation ';
1042 FROM civicrm_relationship
1043 INNER JOIN civicrm_relationship_type ON ( civicrm_relationship.relationship_type_id = civicrm_relationship_type.id )
1044 INNER JOIN civicrm_contact ";
1045 if ($direction == 'a_b') {
1046 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_a ) ';
1049 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_b ) ';
1052 LEFT JOIN civicrm_address ON (civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1)
1053 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
1054 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id AND civicrm_email.is_primary = 1)
1055 LEFT JOIN civicrm_state_province ON (civicrm_address.state_province_id = civicrm_state_province.id)
1056 LEFT JOIN civicrm_country ON (civicrm_address.country_id = civicrm_country.id)
1058 $where = 'WHERE ( 1 )';
1060 if ($direction == 'a_b') {
1061 $where .= ' AND civicrm_relationship.contact_id_b = ' . CRM_Utils_Type
::escape($contactId, 'Positive');
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 ';
1068 if ($relationshipId) {
1069 $where .= ' AND civicrm_relationship.id = ' . CRM_Utils_Type
::escape($relationshipId, 'Positive');
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 . "'";
1078 elseif ($status == self
::DISABLED
) {
1079 // this case for showing disabled relationship
1080 $where .= ' AND civicrm_relationship.is_active = 0 ';
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) ";
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 )';
1094 $where .= ' AND civicrm_contact.is_deleted = 0';
1095 if (!empty($params['membership_type_id']) && empty($params['relationship_type_id'])) {
1096 $where .= self
::membershipTypeToRelationshipTypes($params, $direction);
1098 if (!empty($params['relationship_type_id'])) {
1099 if (is_array($params['relationship_type_id'])) {
1100 $where .= " AND " . CRM_Core_DAO
::createSQLFilter('relationship_type_id', $params['relationship_type_id'], 'Integer');
1103 $where .= ' AND relationship_type_id = ' . CRM_Utils_Type
::escape($params['relationship_type_id'], 'Positive');
1106 if ($direction == 'a_b') {
1107 $where .= ' ) UNION ';
1113 return array($select, $from, $where);
1117 * Get a list of relationships.
1119 * @param int $contactId
1121 * @param int $status
1122 * 1: Past 2: Disabled 3: Current.
1123 * @param int $numRelationship
1124 * No of relationships to display (limit).
1126 * Get the no of relationships.
1127 * @param int $relationshipId
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
1132 * @param bool $permissionedContact
1133 * to return only permissioned Contact
1134 * @param array $params
1137 * relationship records
1139 public static function getRelationship(
1141 $status = 0, $numRelationship = 0,
1142 $count = 0, $relationshipId = 0,
1143 $links = NULL, $permissionMask = NULL,
1144 $permissionedContact = FALSE,
1148 if (!$contactId && !$relationshipId) {
1152 list($select1, $from1, $where1) = self
::makeURLClause($contactId, $status, $numRelationship,
1153 $count, $relationshipId, 'a_b', $params
1155 list($select2, $from2, $where2) = self
::makeURLClause($contactId, $status, $numRelationship,
1156 $count, $relationshipId, 'b_a', $params
1159 $order = $limit = '';
1161 if (empty($params['sort'])) {
1162 $order = ' ORDER BY civicrm_relationship_type_id, sort_name ';
1165 $order = " ORDER BY {$params['sort']} ";
1169 if (!empty($params['offset']) && $params['offset'] > 0) {
1170 $offset = $params['offset'];
1173 if ($numRelationship) {
1174 $limit = " LIMIT {$offset}, $numRelationship";
1178 // building the query string
1179 $queryString = $select1 . $from1 . $where1 . $select2 . $from2 . $where2 . $order . $limit;
1181 $relationship = new CRM_Contact_DAO_Relationship();
1183 $relationship->query($queryString);
1186 $relationshipCount = 0;
1187 while ($relationship->fetch()) {
1188 $relationshipCount +
= $relationship->cnt1 +
$relationship->cnt2
;
1190 return $relationshipCount;
1195 if ($status != self
::INACTIVE
) {
1197 $mask = array_sum(array_keys($links));
1198 if ($mask & CRM_Core_Action
::DISABLE
) {
1199 $mask -= CRM_Core_Action
::DISABLE
;
1201 if ($mask & CRM_Core_Action
::ENABLE
) {
1202 $mask -= CRM_Core_Action
::ENABLE
;
1205 if ($status == self
::CURRENT
) {
1206 $mask |
= CRM_Core_Action
::DISABLE
;
1208 elseif ($status == self
::DISABLED
) {
1209 $mask |
= CRM_Core_Action
::ENABLE
;
1211 $mask = $mask & $permissionMask;
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))
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
;
1226 $values[$rid]['contact_type'] = $relationship->contact_type
;
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
;
1248 $values[$rid]['status'] = $status;
1251 $values[$rid]['civicrm_relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1253 if ($relationship->contact_id_a
== $contactId) {
1254 $values[$rid]['rtype'] = 'a_b';
1257 $values[$rid]['rtype'] = 'b_a';
1263 'rtype' => $values[$rid]['rtype'],
1264 'cid' => $contactId,
1265 'cbid' => $values[$rid]['cid'],
1266 'caseid' => $values[$rid]['case_id'],
1267 'clientid' => $contactId,
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
;
1277 $mask -= CRM_Core_Action
::ENABLE
;
1278 $mask -= CRM_Core_Action
::DISABLE
;
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;
1290 $userCases = CRM_Case_BAO_Case
::getCases(FALSE);
1291 if (array_key_exists($values[$rid]['case_id'], $userCases)) {
1292 $hasCaseAccess = TRUE;
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']));
1300 $links[CRM_Core_Action
::MAX_ACTION
]['class'] = 'no-popup';
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'];
1309 $values[$rid]['action'] = CRM_Core_Action
::formLink(
1315 'relationship.selector.row',
1318 unset($links[CRM_Core_Action
::MAX_ACTION
]);
1322 $relationship->free();
1328 * Get get list of relationship type based on the target contact type.
1330 * @param string $targetContactType
1331 * It's valid contact tpye(may be Individual , Organization , Household).
1334 * array reference of all relationship types with context to current contact type .
1336 static public function getRelationType($targetContactType) {
1337 $relationshipType = array();
1338 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType();
1340 foreach ($allRelationshipType as $key => $type) {
1341 if ($type['contact_type_b'] == $targetContactType) {
1342 $relationshipType[$key . '_a_b'] = $type['label_a_b'];
1346 return $relationshipType;
1350 * Create / update / delete membership for related contacts.
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.
1357 * @param int $contactId
1359 * @param array $params
1360 * array of values submitted by POST.
1363 * @param \const|int $action which action called this function
1365 * @param bool $active
1367 * @throws \CRM_Core_Exception
1369 public static function relatedMemberships($contactId, &$params, $ids, $action = CRM_Core_Action
::ADD
, $active = TRUE) {
1370 // Check the end date and set the status of the relationship
1372 $status = self
::CURRENT
;
1373 $targetContact = $targetContact = CRM_Utils_Array
::value('contact_check', $params, array());
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');
1379 if ($today > $endDate) {
1380 $status = self
::PAST
;
1384 if (($action & CRM_Core_Action
::ADD
) &&
1385 ($status & self
::PAST
)
1387 // if relationship is PAST and action is ADD, no qustion
1388 // of creating RELATED membership and return back to
1393 $rel = explode('_', $params['relationship_type_id']);
1395 $relTypeId = $rel[0];
1396 if (!empty($rel[1])) {
1397 $relDirection = "_{$rel[1]}_{$rel[2]}";
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";
1403 $targetContact = array($params['contact_id_b'] => 1);
1406 if (($action & CRM_Core_Action
::ADD
) ||
1407 ($action & CRM_Core_Action
::DELETE
)
1409 $contact = $contactId;
1411 elseif ($action & CRM_Core_Action
::UPDATE
) {
1412 $contact = $ids['contact'];
1413 $targetContact = array($ids['contactTarget'] => 1);
1416 // Build the 'values' array for
1419 // This will allow us to check if either of the contacts in
1420 // relationship have active memberships.
1425 $values[$contact] = array(
1426 'relatedContacts' => $targetContact,
1427 'relationshipTypeId' => $relTypeId,
1428 'relationshipTypeDirection' => $relDirection,
1431 if (!empty($targetContact)) {
1432 foreach ($targetContact as $cid => $donCare) {
1433 $values[$cid] = array(
1434 'relatedContacts' => array($contact => 1),
1435 'relationshipTypeId' => $relTypeId,
1438 $relTypeParams = array('id' => $relTypeId);
1439 $relTypeValues = array();
1440 CRM_Contact_BAO_RelationshipType
::retrieve($relTypeParams, $relTypeValues);
1442 if (CRM_Utils_Array
::value('name_a_b', $relTypeValues) == CRM_Utils_Array
::value('name_b_a', $relTypeValues)) {
1443 $values[$cid]['relationshipTypeDirection'] = '_a_b';
1446 $values[$cid]['relationshipTypeDirection'] = ($relDirection == '_a_b') ?
'_b_a' : '_a_b';
1451 // Now get the active memberships for all the contacts.
1452 // If contact have any valid membership(s), then add it to
1454 foreach ($values as $cid => $subValues) {
1455 $memParams = array('contact_id' => $cid);
1456 $memberships = array();
1458 CRM_Member_BAO_Membership
::getValues($memParams, $memberships, $active);
1460 if (empty($memberships)) {
1464 $values[$cid]['memberships'] = $memberships;
1466 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1468 // done with 'values' array.
1469 // Finally add / edit / delete memberships for the related contacts
1471 foreach ($values as $cid => $details) {
1472 if (!array_key_exists('memberships', $details)) {
1476 $relatedContacts = array_keys(CRM_Utils_Array
::value('relatedContacts', $details, array()));
1477 $mainRelatedContactId = reset($relatedContacts);
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
1484 SELECT 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
;
1493 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $relTypeId);
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']);
1499 if (($action & CRM_Core_Action
::UPDATE
) &&
1500 ($status & self
::PAST
) &&
1501 ($membershipValues['owner_membership_id'])
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']
1511 // add / edit the memberships for related
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();
1518 if (!empty($membershipType['relationship_type_id'])) {
1519 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_type_id']);
1521 if (!empty($membershipType['relationship_direction'])) {
1522 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_direction']);
1524 foreach ($relTypeIds as $key => $value) {
1525 $relTypeDirs[] = $value . '_' . $relDirections[$key];
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
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')
1543 $membershipValues['status_id'] = $deceasedStatusId;
1544 $membershipValues['skipStatusCal'] = TRUE;
1551 if (!empty($membershipValues[$dateField])) {
1552 $membershipValues[$dateField] = CRM_Utils_Date
::processDate($membershipValues[$dateField]);
1556 if ($action & CRM_Core_Action
::UPDATE
) {
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'])) {
1561 //delete the membership record for related
1562 //contact before creating new membership record.
1563 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $relatedContactId);
1566 // check whether we have some related memberships still available
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
)) {
1575 CRM_Member_BAO_Membership
::create($membershipValues, CRM_Core_DAO
::$_nullArray);
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.
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']);
1590 $relIds = CRM_Utils_Array
::value('relationship_ids', $params);
1592 if (self
::isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId,
1594 ) && !empty($membershipValues['owner_membership_id'])) {
1595 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipValues['owner_membership_id'], $membershipValues['membership_contact_id']);
1603 * Helper function to check whether to delete the membership or not.
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.
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
1617 public static function isDeleteRelatedMembership($membershipTypeRelationshipTypeIDs, $contactId, $mainRelatedContactId, $relTypeId, $relIds) {
1618 if (empty($membershipTypeRelationshipTypeIDs) ||
in_array($relTypeId, $membershipTypeRelationshipTypeIDs)) {
1622 if (empty($relIds)) {
1626 $relParamas = array(
1627 1 => array($contactId, 'Integer'),
1628 2 => array($mainRelatedContactId, 'Integer'),
1631 if ($contactId == $mainRelatedContactId) {
1632 $recordsFound = (int) CRM_Core_DAO
::singleValueQuery("SELECT COUNT(*) FROM civicrm_relationship WHERE relationship_type_id IN ( " . implode(',', $membershipTypeRelationshipTypeIDs) . " ) AND
1633 contact_id_a IN ( %1 ) OR contact_id_b IN ( %1 ) AND id IN (" . implode(',', $relIds) . ")", $relParamas);
1634 if ($recordsFound) {
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);
1642 if ($recordsFound) {
1650 * Get Current Employer for Contact.
1652 * @param $contactIds
1656 * array of the current employer
1658 public static function getCurrentEmployer($contactIds) {
1659 $contacts = implode(',', $contactIds);
1662 SELECT organization_name, id, employer_id
1663 FROM civicrm_contact
1664 WHERE id IN ( {$contacts} )
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
;
1674 return $currentEmployer;
1678 * Return list of permissioned employer for a given contact.
1680 * @param int $contactID
1681 * contact id whose employers.
1683 * @param string $name
1684 * employers sort name.
1687 * array of employers.
1689 public static function getPermissionedEmployer($contactID, $name = NULL) {
1690 //get the relationship id
1691 $relTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType',
1692 'Employee of', 'id', 'name_a_b'
1695 return self
::getPermissionedContacts($contactID, $relTypeId, $name);
1700 * Function to return list of permissioned contacts for a given contact and relationship type.
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
1711 public static function getPermissionedContacts($contactID, $relTypeId, $name = NULL) {
1712 $contacts = array();
1716 SELECT cc.id as id, cc.sort_name as name
1717 FROM civicrm_relationship cr, civicrm_contact cc
1719 cr.contact_id_a = %1 AND
1720 cr.relationship_type_id IN (%2) AND
1721 cr.is_permission_a_b = 1 AND
1722 IF(cr.end_date IS NULL, 1, (DATEDIFF( CURDATE( ), cr.end_date ) <= 0)) AND
1723 cr.is_active = 1 AND
1724 cc.id = cr.contact_id_b AND
1727 if (!empty($name)) {
1728 $name = CRM_Utils_Type
::escape($name, 'String');
1730 AND cc.sort_name LIKE '%$name%'";
1733 $args = array(1 => array($contactID, 'Integer'), 2 => array($relTypeId, 'String'));
1734 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1736 while ($dao->fetch()) {
1737 $contacts[$dao->id
] = array(
1738 'name' => $dao->name
,
1739 'value' => $dao->id
,
1747 * Merge relationships from otherContact to mainContact.
1749 * Called during contact merge operation
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.
1758 * @see CRM_Dedupe_Merger::cpTables()
1760 public static function mergeRelationships($mainId, $otherId, &$sqls) {
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)";
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
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
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)
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";
1785 // Move current employer id (name will get updated later)
1786 $sqls[] = "UPDATE civicrm_contact SET employer_id = $mainId WHERE employer_id = $otherId";
1790 * Set 'is_valid' field to false for all relationships whose end date is in the past, ie. are expired.
1793 * True on success, false if error is encountered.
1795 public static function disableExpiredRelationships() {
1796 $query = "SELECT id FROM civicrm_relationship WHERE is_active = 1 AND end_date < CURDATE()";
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) {
1810 * Function filters the query by possible relationships for the membership type.
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
1816 * @param array $params
1818 * @param null $direction
1820 * @return array|void
1822 public static function membershipTypeToRelationshipTypes(&$params, $direction = NULL) {
1823 $membershipType = civicrm_api3('membership_type', 'getsingle', array(
1824 'id' => $params['membership_type_id'],
1825 'return' => 'relationship_type_id, relationship_direction',
1827 $relationshipTypes = $membershipType['relationship_type_id'];
1828 if (empty($relationshipTypes)) {
1831 // if we don't have any contact data we can only filter on type
1832 if (empty($params['contact_id']) && empty($params['contact_id_a']) && empty($params['contact_id_a'])) {
1833 $params['relationship_type_id'] = array('IN' => $relationshipTypes);
1837 $relationshipDirections = (array) $membershipType['relationship_direction'];
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) {
1841 if (isset($params['contact_id_a']) && $mtdirection == 'a_b' ||
$direction == 'a_b') {
1842 $types[] = $relationshipTypes[$index];
1844 if (isset($params['contact_id_b']) && $mtdirection == 'b_a' ||
$direction == 'b_a') {
1845 $types[] = $relationshipTypes[$index];
1848 if (!empty($types)) {
1849 $params['relationship_type_id'] = array('IN' => $types);
1851 elseif (!empty($clauses)) {
1852 return explode(' OR ', $clauses);
1855 // effectively setting it to return no results
1856 $params['relationship_type_id'] = 0;
1863 * Wrapper for contact relationship selector.
1865 * @param array $params
1866 * Associated array for params record id.
1869 * associated array of contact relationships
1871 public static function getContactRelationshipSelector(&$params) {
1872 // format the params
1873 $params['offset'] = ($params['page'] - 1) * $params['rp'];
1874 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
1876 if ($params['context'] == 'past') {
1877 $relationshipStatus = CRM_Contact_BAO_Relationship
::INACTIVE
;
1879 elseif ($params['context'] == 'all') {
1880 $relationshipStatus = CRM_Contact_BAO_Relationship
::ALL
;
1883 $relationshipStatus = CRM_Contact_BAO_Relationship
::CURRENT
;
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
;
1893 $mask = CRM_Core_Action
::mask($permissions);
1895 if ($params['context'] != 'user') {
1896 $links = CRM_Contact_Page_View_Relationship
::links();
1897 $permissionedContacts = FALSE;
1900 $links = CRM_Contact_Page_View_UserDashBoard
::links();
1901 $permissionedContacts = TRUE;
1904 // get contact relationships
1905 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1906 $relationshipStatus,
1907 $params['rp'], 0, 0,
1909 $permissionedContacts,
1913 $contactRelationships = array();
1914 $params['total'] = 0;
1915 if (!empty($relationships)) {
1916 // get the total relationships
1917 if ($params['context'] != 'user') {
1918 $params['total'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1919 $relationshipStatus, 0, 1, 0, NULL, NULL, $permissionedContacts);
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,
1928 $params['total'] = count($permissionedRelationships);
1932 foreach ($relationships as $relationshipId => $values) {
1933 //Add image icon for related contacts: CRM-14919
1934 $icon = CRM_Contact_BAO_Contact_Utils
::getImage($values['contact_type'],
1938 $contactRelationships[$relationshipId]['name'] = $icon . ' ' . CRM_Utils_System
::href(
1940 'civicrm/contact/view',
1941 "reset=1&cid={$values['cid']}");
1943 $contactRelationships[$relationshipId]['relation'] = CRM_Utils_System
::href(
1944 $values['relation'],
1945 'civicrm/contact/view/rel',
1946 "action=view&reset=1&cid={$values['cid']}&id={$values['id']}&rtype={$values['rtype']}");
1948 if ($params['context'] == 'current') {
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)
1952 $contactRelationships[$relationshipId]['name'] .= '<span id="permission-a-b" class="crm-marker permission-relationship"> *</span>';
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)
1958 $contactRelationships[$relationshipId]['relation'] .= '<span id="permission-b-a" class="crm-marker permission-relationship"> *</span>';
1962 if (!empty($values['description'])) {
1963 $contactRelationships[$relationshipId]['relation'] .= "<p class='description'>{$values['description']}</p>";
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'];
1973 $contactRelationships[$relationshipId]['id'] = $values['id'];
1974 $contactRelationships[$relationshipId]['is_active'] = $values['is_active'];
1977 return $contactRelationships;