3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
35 class CRM_Contact_BAO_Relationship
extends CRM_Contact_DAO_Relationship
{
38 * Various constants to indicate different type of relationships
42 const PAST
= 1, DISABLED
= 2, CURRENT
= 4, INACTIVE
= 8;
45 * Create function. (Use the API instead)
46 * Note that the previous create function has been renamed 'createMultiple'
47 * and this is new in 4.6
48 * All existing calls have been changed to createMultiple except the api call - however, it is recommended
49 * that you call that as the end to end testing here is based on the api & refactoring may still be done
51 * @return \CRM_Contact_BAO_Relationship
52 * @throws \CRM_Core_Exception
54 public static function create(&$params) {
55 self
::setContactABFromIDs($params);
56 if (self
::checkDuplicateRelationship($params, $params['contact_id_a'], $params['contact_id_b'], CRM_Utils_Array
::value('id', $params, 0))) {
57 throw new CRM_Core_Exception('Duplicate Relationship');
59 if (self
::checkValidRelationship($params, $params, 0)) {
60 throw new CRM_Core_Exception('Invalid Relationship');
62 $relationship = self
::add($params);
63 if (!empty($params['contact_id_a'])) {
64 $ids = array('contactTarget' => $relationship->contact_id_b
, 'contact' => $params['contact_id_a']);
65 CRM_Contact_BAO_Relationship
::relatedMemberships($params['contact_id_a'], $values, $ids, (empty($params['id']) ? CRM_Core_Action
::ADD
: CRM_Core_Action
::UPDATE
));
67 self
::addRecent($params, $relationship);
72 * Takes an associative array and creates a relationship object
73 * @deprecated For single creates use the api instead (it's tested).
74 * For multiple a new variant of this function needs to be written and migrated to as this is a bit
77 * @param array $params
78 * (reference ) an assoc array of name/value pairs.
80 * The array that holds all the db ids.
81 * per http://wiki.civicrm.org/confluence/display/CRM/Database+layer
82 * "we are moving away from the $ids param "
84 * @return CRM_Contact_BAO_Relationship object
87 public static function createMultiple(&$params, $ids = array()) {
88 $valid = $invalid = $duplicate = $saved = 0;
89 $relationships = $relationshipIds = array();
90 $relationshipId = CRM_Utils_Array
::value('relationship', $ids, CRM_Utils_Array
::value('id', $params));
91 //CRM-9015 - the hooks are called here & in add (since add doesn't call create)
92 // but in future should be tidied per ticket
93 if (empty($relationshipId)) {
95 $action = CRM_Core_Action
::ADD
;
99 $action = CRM_Core_Action
::UPDATE
;
102 CRM_Utils_Hook
::pre($hook, 'Relationship', $relationshipId, $params);
104 if (!$relationshipId) {
105 // creating a new relationship
106 $dataExists = self
::dataExists($params);
108 return array(FALSE, TRUE, FALSE, FALSE, NULL);
110 $relationshipIds = array();
111 foreach ($params['contact_check'] as $key => $value) {
113 // check if the relationship is valid between contacts.
114 // step 1: check if the relationship is valid if not valid skip and keep the count
115 // step 2: check the if two contacts already have a relationship if yes skip and keep the count
116 // step 3: if valid relationship then add the relation and keep the count
119 $errors = self
::checkValidRelationship($params, $ids, $key);
126 self
::checkDuplicateRelationship(
128 CRM_Utils_Array
::value('contact', $ids),
136 self
::setContactABFromIDs($params, $ids, $key);
137 $relationship = self
::add($params);
138 $relationshipIds[] = $relationship->id
;
139 $relationships[$relationship->id
] = $relationship;
142 // editing the relationship
145 // check for duplicate relationship
146 // @todo this code doesn't cope well with updates - causes e-Notices.
147 // API has a lot of code to work around
148 // this but should review this code & remove the extra handling from the api
149 // it seems doubtful any of this is relevant if the contact fields & relationship
150 // type fields are not set
152 self
::checkDuplicateRelationship(
154 CRM_Utils_Array
::value('contact', $ids),
155 $ids['contactTarget'],
160 return array($valid, $invalid, $duplicate, $saved, NULL);
163 $validContacts = TRUE;
164 //validate contacts in update mode also.
165 if (!empty($ids['contact']) && !empty($ids['contactTarget'])) {
166 if (self
::checkValidRelationship($params, $ids, $ids['contactTarget'])) {
167 $validContacts = FALSE;
171 if ($validContacts) {
172 // editing an existing relationship
173 $relationship = self
::add($params, $ids, $ids['contactTarget']);
174 $relationshipIds[] = $relationship->id
;
175 $relationships[$relationship->id
] = $relationship;
180 // do not add to recent items for import, CRM-4399
181 if (!(!empty($params['skipRecentView']) ||
$invalid ||
$duplicate)) {
182 self
::addRecent($params, $relationship);
185 return array($valid, $invalid, $duplicate, $saved, $relationshipIds, $relationships);
189 * This is the function that check/add if the relationship created is valid
191 * @param array $params
192 * (reference ) an assoc array of name/value pairs.
193 * @param int $contactId
194 * This is contact id for adding relationship.
196 * The array that holds all the db ids.
198 * @return CRM_Contact_BAO_Relationship
201 public static function add(&$params, $ids = array(), $contactId = NULL) {
203 CRM_Utils_Array
::value('relationship', $ids, CRM_Utils_Array
::value('id', $params));
206 if ($relationshipId) {
209 //@todo hook are called from create and add - remove one
210 CRM_Utils_Hook
::pre($hook, 'Relationship', $relationshipId, $params);
212 self
::setContactABFromIDs($params);
213 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
215 // explode the string with _ to get the relationship type id
216 // and to know which contact has to be inserted in
217 // contact_id_a and which one in contact_id_b
218 list($type) = explode('_', $relationshipTypes);
220 // check if the relationship type is Head of Household then update the
221 // household's primary contact with this contact.
223 CRM_Contact_BAO_Household
::updatePrimaryContact($params['contact_id_b'], $params['contact_id_a']);
226 $relationship = new CRM_Contact_BAO_Relationship();
227 //@todo this code needs to be updated for the possibility that not all fields are set
229 $relationship->contact_id_b
= $params['contact_id_b'];
230 $relationship->contact_id_a
= $params['contact_id_a'];
231 $relationship->relationship_type_id
= $type;
232 $relationship->id
= $relationshipId;
234 $dateFields = array('end_date', 'start_date');
236 foreach (self
::getdefaults() as $defaultField => $defaultValue) {
237 if (isset($params[$defaultField])) {
238 if (in_array($defaultField, $dateFields)) {
239 $relationship->$defaultField = CRM_Utils_Date
::format(CRM_Utils_Array
::value($defaultField, $params));
240 if (!$relationship->$defaultField) {
241 $relationship->$defaultField = 'NULL';
245 $relationship->$defaultField = $params[$defaultField];
248 elseif (!$relationshipId) {
249 $relationship->$defaultField = $defaultValue;
253 $relationship->save();
255 // add custom field values
256 if (!empty($params['custom'])) {
257 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_relationship', $relationship->id
);
260 $relationship->free();
262 CRM_Utils_Hook
::post($hook, 'Relationship', $relationship->id
, $relationship);
264 return $relationship;
268 * Add relationship to recent links
269 * @param array $params
270 * @param CRM_Contact_DAO_Relationship $relationship
272 public static function addRecent($params, $relationship) {
273 $url = CRM_Utils_System
::url('civicrm/contact/view/rel',
274 "action=view&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&context=home"
276 $session = CRM_Core_Session
::singleton();
277 $recentOther = array();
278 if (($session->get('userID') == $relationship->contact_id_a
) ||
279 CRM_Contact_BAO_Contact_Permission
::allow($relationship->contact_id_a
, CRM_Core_Permission
::EDIT
)
281 $rType = substr(CRM_Utils_Array
::value('relationship_type_id', $params), -3);
282 $recentOther = array(
283 'editUrl' => CRM_Utils_System
::url('civicrm/contact/view/rel',
284 "action=update&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
286 'deleteUrl' => CRM_Utils_System
::url('civicrm/contact/view/rel',
287 "action=delete&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
291 $title = CRM_Contact_BAO_Contact
::displayName($relationship->contact_id_a
) . ' (' . CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType',
292 $relationship->relationship_type_id
, 'label_a_b'
293 ) . ' ' . CRM_Contact_BAO_Contact
::displayName($relationship->contact_id_b
) . ')';
295 CRM_Utils_Recent
::add($title,
299 $relationship->contact_id_a
,
306 * Resolve passed in contact IDs to contact_id_a & contact_id_b
309 * @param null $contactID
310 * @throws \CRM_Core_Exception
312 public static function setContactABFromIDs(&$params, $ids = array(), $contactID = NULL) {
313 if (!empty($params['contact_id_a']) && !empty($params['contact_id_b'])) {
316 if (empty($ids['contact'])) {
317 if (!empty($params['id'])) {
318 //let's load the missing ids here since other things tend to rely on them.
319 $fieldsToFill = array('contact_id_a', 'contact_id_b', 'relationship_type_id');
320 $result = CRM_Core_DAO
::executeQuery("SELECT " . implode(',', $fieldsToFill) . " FROM civicrm_relationship WHERE id = %1", array(
326 while ($result->fetch()) {
327 foreach ($fieldsToFill as $field) {
328 $params[$field] = !empty($params[$field]) ?
$params[$field] : $result->$field;
333 throw new CRM_Core_Exception('Cannot create relationship, insufficient contact IDs provided');
335 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
336 list($relationshipTypeID, $first, $second) = explode('_', $relationshipTypes);
337 if (empty($params['relationship_type_id'])) {
338 $params['relationship_type_id'] = $relationshipTypeID;
340 foreach (array('a', 'b') as $contactLetter) {
341 if (empty($params['contact_' . $contactLetter])) {
342 if ($first == $contactLetter) {
343 $params['contact_id_' . $contactLetter] = CRM_Utils_Array
::value('contact', $ids);
346 $params['contact_id_' . $contactLetter] = $contactID;
353 * Specifiy defaults for creating a relationship
355 * @return array $defaults array of defaults for creating relationship
358 public static function getdefaults() {
361 'is_permission_a_b' => 0,
362 'is_permission_b_a' => 0,
364 'start_date' => 'NULL',
366 'end_date' => 'NULL',
372 * Check if there is data to create the object
374 * @param array $params
375 * (reference ) an assoc array of name/value pairs.
380 public static function dataExists(&$params) {
381 // return if no data present
382 if (!is_array(CRM_Utils_Array
::value('contact_check', $params))) {
389 * Get get list of relationship type based on the contact type.
391 * @param int $contactId
392 * This is the contact id of the current contact.
393 * @param null $contactSuffix
394 * @param string $relationshipId
395 * The id of the existing relationship if any.
396 * @param string $contactType
399 * If true returns relationship types in both the direction.
400 * @param string $column
401 * Name/label that going to retrieve from db.
402 * @param bool $biDirectional
403 * @param string $contactSubType
404 * Includes relationshiptypes between this subtype.
405 * @param bool $onlySubTypeRelationTypes
406 * If set only subtype which is passed by $contactSubType.
407 * related relationshiptypes get return
411 * @return array - array reference of all relationship types with context to current contact.
413 static function getContactRelationshipType(
415 $contactSuffix = NULL,
416 $relationshipId = NULL,
420 $biDirectional = TRUE,
421 $contactSubType = NULL,
422 $onlySubTypeRelationTypes = FALSE
424 $allRelationshipType = array();
425 $relationshipType = array();
426 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType($column);
428 $otherContactType = NULL;
429 if ($relationshipId) {
430 $relationship = new CRM_Contact_DAO_Relationship();
431 $relationship->id
= $relationshipId;
432 if ($relationship->find(TRUE)) {
433 $contact = new CRM_Contact_DAO_Contact();
434 $contact->id
= ($relationship->contact_id_a
=== $contactId) ?
$relationship->contact_id_b
: $relationship->contact_id_a
;
436 if ($contact->find(TRUE)) {
437 $otherContactType = $contact->contact_type
;
438 //CRM-5125 for contact subtype specific relationshiptypes
439 if ($contact->contact_sub_type
) {
440 $otherContactSubType = $contact->contact_sub_type
;
446 $contactSubType = array();
448 $contactType = CRM_Contact_BAO_Contact
::getContactType($contactId);
449 $contactSubType = CRM_Contact_BAO_Contact
::getContactSubType($contactId);
452 foreach ($allRelationshipType as $key => $value) {
453 // the contact type is required or matches
454 if (((!$value['contact_type_a']) ||
455 $value['contact_type_a'] == $contactType
457 // the other contact type is required or present or matches
458 ((!$value['contact_type_b']) ||
459 (!$otherContactType) ||
460 $value['contact_type_b'] == $otherContactType
462 (in_array($value['contact_sub_type_a'], $contactSubType) ||
463 in_array($value['contact_sub_type_b'], $contactSubType) ||
464 (!$value['contact_sub_type_a'] && !$onlySubTypeRelationTypes)
467 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
470 if (((!$value['contact_type_b']) ||
471 $value['contact_type_b'] == $contactType
473 ((!$value['contact_type_a']) ||
474 (!$otherContactType) ||
475 $value['contact_type_a'] == $otherContactType
477 (in_array($value['contact_sub_type_b'], $contactSubType) ||
478 in_array($value['contact_sub_type_a'], $contactSubType) ||
479 (!$value['contact_sub_type_b'] && !$onlySubTypeRelationTypes)
482 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
486 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
487 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
491 if ($biDirectional) {
492 // lets clean up the data and eliminate all duplicate values
493 // (i.e. the relationship is bi-directional)
494 $relationshipType = array_unique($relationshipType);
497 // sort the relationshipType in ascending order CRM-7736
498 asort($relationshipType);
499 return $relationshipType;
506 * @return CRM_Contact_DAO_Relationship
508 public static function clearCurrentEmployer($id, $action) {
509 $relationship = new CRM_Contact_DAO_Relationship();
510 $relationship->id
= $id;
511 $relationship->find(TRUE);
513 //to delete relationship between household and individual \
514 //or between individual and orgnization
515 if (($action & CRM_Core_Action
::DISABLE
) ||
($action & CRM_Core_Action
::DELETE
)) {
516 $relTypes = CRM_Utils_Array
::index(array('name_a_b'), CRM_Core_PseudoConstant
::relationshipType('name'));
517 if ($relationship->relationship_type_id
== $relTypes['Employee of']['id'] ||
518 $relationship->relationship_type_id
== $relTypes['Household Member of']['id']
520 $sharedContact = new CRM_Contact_DAO_Contact();
521 $sharedContact->id
= $relationship->contact_id_a
;
522 $sharedContact->find(TRUE);
524 if ($relationship->relationship_type_id
== 4 && $relationship->contact_id_b
== $sharedContact->employer_id
) {
525 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($relationship->contact_id_a
);
529 return $relationship;
533 * Delete the relationship
542 public static function del($id) {
543 // delete from relationship table
544 CRM_Utils_Hook
::pre('delete', 'Relationship', $id, CRM_Core_DAO
::$_nullArray);
546 $relationship = self
::clearCurrentEmployer($id, CRM_Core_Action
::DELETE
);
547 if (CRM_Core_Permission
::access('CiviMember')) {
548 // create $params array which isrequired to delete memberships
549 // of the related contacts.
551 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
552 'contact_check' => array($relationship->contact_id_b
=> 1),
556 // calling relatedMemberships to delete the memberships of
558 self
::relatedMemberships($relationship->contact_id_a
,
561 CRM_Core_Action
::DELETE
,
566 $relationship->delete();
567 CRM_Core_Session
::setStatus(ts('Selected relationship has been deleted successfully.'), ts('Record Deleted'), 'success');
569 CRM_Utils_Hook
::post('delete', 'Relationship', $id, $relationship);
571 // delete the recently created Relationship
572 $relationshipRecent = array(
574 'type' => 'Relationship',
576 CRM_Utils_Recent
::del($relationshipRecent);
578 return $relationship;
582 * Disable/enable the relationship
592 public static function disableEnableRelationship($id, $action) {
593 $relationship = self
::clearCurrentEmployer($id, $action);
594 if (CRM_Core_Permission
::access('CiviMember')) {
595 // create $params array which isrequired to delete memberships
596 // of the related contacts.
598 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
599 'contact_check' => array($relationship->contact_id_b
=> 1),
603 // calling relatedMemberships to delete/add the memberships of
605 if ($action & CRM_Core_Action
::DISABLE
) {
606 CRM_Contact_BAO_Relationship
::relatedMemberships($relationship->contact_id_a
,
609 CRM_Core_Action
::DELETE
,
613 elseif ($action & CRM_Core_Action
::ENABLE
) {
614 $ids['contact'] = $relationship->contact_id_a
;
615 CRM_Contact_BAO_Relationship
::relatedMemberships($relationship->contact_id_a
,
618 CRM_Core_Action
::ADD
,
626 * Delete the object records that are associated with this contact
628 * @param int $contactId
629 * Id of the contact to delete.
634 public static function deleteContact($contactId) {
635 $relationship = new CRM_Contact_DAO_Relationship();
636 $relationship->contact_id_a
= $contactId;
637 $relationship->delete();
639 $relationship = new CRM_Contact_DAO_Relationship();
640 $relationship->contact_id_b
= $contactId;
641 $relationship->delete();
643 CRM_Contact_BAO_Household
::updatePrimaryContact(NULL, $contactId);
647 * Get the other contact in a relationship
652 * $returns returns the contact ids in the realtionship
654 * @return \CRM_Contact_DAO_Relationship
657 public static function getContactIds($id) {
658 $relationship = new CRM_Contact_DAO_Relationship();
660 $relationship->id
= $id;
661 $relationship->selectAdd();
662 $relationship->selectAdd('contact_id_a, contact_id_b');
663 $relationship->find(TRUE);
665 return $relationship;
669 * Check if the relationship type selected between two contacts is correct
671 * @param int $contact_a
673 * @param int $contact_b
675 * @param int $relationshipTypeId
676 * Relationship type id.
678 * @return boolean true if it is valid relationship else false
681 public static function checkRelationshipType($contact_a, $contact_b, $relationshipTypeId) {
682 $relationshipType = new CRM_Contact_DAO_RelationshipType();
683 $relationshipType->id
= $relationshipTypeId;
684 $relationshipType->selectAdd();
685 $relationshipType->selectAdd('contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b');
686 if ($relationshipType->find(TRUE)) {
687 $contact_type_a = CRM_Contact_BAO_Contact
::getContactType($contact_a);
688 $contact_type_b = CRM_Contact_BAO_Contact
::getContactType($contact_b);
690 $contact_sub_type_a = CRM_Contact_BAO_Contact
::getContactSubType($contact_a);
691 $contact_sub_type_b = CRM_Contact_BAO_Contact
::getContactSubType($contact_b);
693 if (((!$relationshipType->contact_type_a
) ||
($relationshipType->contact_type_a
== $contact_type_a)) &&
694 ((!$relationshipType->contact_type_b
) ||
($relationshipType->contact_type_b
== $contact_type_b)) &&
695 ((!$relationshipType->contact_sub_type_a
) ||
(in_array($relationshipType->contact_sub_type_a
,
698 ((!$relationshipType->contact_sub_type_b
) ||
(in_array($relationshipType->contact_sub_type_b
,
712 * This function does the validtion for valid relationship
714 * @param array $params
715 * This array contains the values there are subitted by the form.
717 * The array that holds all the db ids.
718 * @param int $contactId
719 * This is contact id for adding relationship.
725 public static function checkValidRelationship($params, $ids, $contactId) {
727 self
::setContactABFromIDs($params, $ids, $contactId);
728 // get the string of relationship type
729 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
730 list($type) = explode('_', $relationshipTypes);
731 // function to check if the relationship selected is correct
732 // i.e. employer relationship can exit between Individual and Organization (not between Individual and Individual)
733 if (!CRM_Contact_BAO_Relationship
::checkRelationshipType($params['contact_id_a'], $params['contact_id_b'], $type)) {
734 $errors = 'Please select valid relationship between these two contacts.';
740 * This function checks for duplicate relationship
742 * @param array $params
743 * (reference ) an assoc array of name/value pairs.
745 * This the id of the contact whom we are adding relationship.
746 * @param int $contactId
747 * This is contact id for adding relationship.
748 * @param int $relationshipId
749 * This is relationship id for the contact.
751 * @return boolean true if record exists else false
754 public static function checkDuplicateRelationship(&$params, $id, $contactId = 0, $relationshipId = 0) {
755 $relationshipTypeId = CRM_Utils_Array
::value('relationship_type_id', $params);
756 list($type) = explode('_', $relationshipTypeId);
760 FROM civicrm_relationship
761 WHERE relationship_type_id = " . CRM_Utils_Type
::escape($type, 'Integer');
764 * CRM-11792 - date fields from API are in ISO format, but this function
765 * supports date arrays BAO has increasingly standardised to ISO format
766 * so I believe this function should support ISO rather than make API
767 * format it - however, need to support array format for now to avoid breakage
768 * @ time of writing this function is called from Relationship::createMultiple (twice)
769 * CRM_BAO_Contact_Utils::clearCurrentEmployer (seemingly without dates)
770 * CRM_Contact_Form_Task_AddToOrganization::postProcess &
771 * CRM_Contact_Form_Task_AddToHousehold::postProcess
772 * (I don't think the last 2 support dates but not sure
775 $dateFields = array('end_date', 'start_date');
776 foreach ($dateFields as $dateField) {
777 if (array_key_exists($dateField, $params)) {
778 if (empty($params[$dateField]) ||
$params[$dateField] == 'null') {
779 //this is most likely coming from an api call & probably loaded
780 // from the DB to deal with some of the
781 // other myriad of excessive checks still in place both in
782 // the api & the create functions
783 $queryString .= " AND $dateField IS NULL";
786 elseif (is_array($params[$dateField])) {
787 $queryString .= " AND $dateField = " .
788 CRM_Utils_Type
::escape(CRM_Utils_Date
::format($params[$dateField]), 'Date');
791 $queryString .= " AND $dateField = " .
792 CRM_Utils_Type
::escape($params[$dateField], 'Date');
798 " AND ( ( contact_id_a = " . CRM_Utils_Type
::escape($id, 'Integer') .
799 " AND contact_id_b = " . CRM_Utils_Type
::escape($contactId, 'Integer') .
800 " ) OR ( contact_id_a = " . CRM_Utils_Type
::escape($contactId, 'Integer') .
801 " AND contact_id_b = " . CRM_Utils_Type
::escape($id, 'Integer') . " ) ) ";
803 //if caseId is provided, include it duplicate checking.
804 if ($caseId = CRM_Utils_Array
::value('case_id', $params)) {
805 $queryString .= " AND case_id = " . CRM_Utils_Type
::escape($caseId, 'Integer');
808 if ($relationshipId) {
809 $queryString .= " AND id !=" . CRM_Utils_Type
::escape($relationshipId, 'Integer');
812 $relationship = new CRM_Contact_BAO_Relationship();
813 $relationship->query($queryString);
814 $relationship->fetch();
815 $relationship->free();
816 return ($relationship->id
) ?
TRUE : FALSE;
820 * Update the is_active flag in the db
823 * Id of the database record.
824 * @param bool $is_active
825 * Value we want to set the is_active field.
827 * @throws CiviCRM_API3_Exception
828 * @return Object DAO object on success, null otherwise
831 public static function setIsActive($id, $is_active) {
832 // as both the create & add functions have a bunch of logic in them that
833 // doesn't seem to cope with a normal update we will call the api which
834 // has tested handling for this
835 // however, a longer term solution would be to simplify the add, create & api functions
836 // to be more standard. It is debatable @ that point whether it's better to call the BAO
837 // direct as the api is more tested.
838 $result = civicrm_api('relationship', 'create', array(
840 'is_active' => $is_active,
844 if (is_array($result) && !empty($result['is_error']) && $result['error_message'] != 'Relationship already exists') {
845 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array
::value('error_code', $result, 'undefined'), $result);
848 // call (undocumented possibly deprecated) hook
849 CRM_Utils_Hook
::enableDisable('CRM_Contact_BAO_Relationship', $id, $is_active);
855 * Given the list of params in the params array, fetch the object
856 * and store the values in the values array
858 * @param array $params
859 * Input parameters to find object.
860 * @param array $values
861 * Output values of the object.
863 * @return array (reference) the values that could be potentially assigned to smarty
866 public static function &getValues(&$params, &$values) {
867 if (empty($params)) {
872 // get the specific number of relationship or all relationships.
873 if (!empty($params['numRelationship'])) {
874 $v['data'] = &CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'], NULL, $params['numRelationship']);
877 $v['data'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id']);
880 // get the total count of relationships
881 $v['totalCount'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'], NULL, NULL, TRUE);
883 $values['relationship']['data'] = &$v['data'];
884 $values['relationship']['totalCount'] = &$v['totalCount'];
890 * Helper function to form the sql for relationship retrieval
892 * @param int $contactId
895 * (check const at top of file).
896 * @param int $numRelationship
897 * No of relationships to display (limit).
899 * Get the no of relationships.
900 * $param int $relationshipId relationship id
901 * @param int $relationshipId
902 * @param string $direction
903 * The direction we are interested in a_b or b_a.
904 * @param array $params
905 * Array of extra values including relationship_type_id per api spec.
907 * return string the query for this diretion
912 public static function makeURLClause($contactId, $status, $numRelationship, $count, $relationshipId, $direction, $params = array()) {
913 $select = $from = $where = '';
917 if ($direction == 'a_b') {
918 $select .= ' SELECT count(DISTINCT civicrm_relationship.id) as cnt1, 0 as cnt2 ';
921 $select .= ' SELECT 0 as cnt1, count(DISTINCT civicrm_relationship.id) as cnt2 ';
925 $select .= ' SELECT civicrm_relationship.id as civicrm_relationship_id,
926 civicrm_contact.sort_name as sort_name,
927 civicrm_contact.display_name as display_name,
928 civicrm_contact.job_title as job_title,
929 civicrm_contact.employer_id as employer_id,
930 civicrm_contact.organization_name as organization_name,
931 civicrm_address.street_address as street_address,
932 civicrm_address.city as city,
933 civicrm_address.postal_code as postal_code,
934 civicrm_state_province.abbreviation as state,
935 civicrm_country.name as country,
936 civicrm_email.email as email,
937 civicrm_contact.contact_type as contact_type,
938 civicrm_phone.phone as phone,
939 civicrm_contact.id as civicrm_contact_id,
940 civicrm_relationship.contact_id_b as contact_id_b,
941 civicrm_relationship.contact_id_a as contact_id_a,
942 civicrm_relationship_type.id as civicrm_relationship_type_id,
943 civicrm_relationship.start_date as start_date,
944 civicrm_relationship.end_date as end_date,
945 civicrm_relationship.description as description,
946 civicrm_relationship.is_active as is_active,
947 civicrm_relationship.is_permission_a_b as is_permission_a_b,
948 civicrm_relationship.is_permission_b_a as is_permission_b_a,
949 civicrm_relationship.case_id as case_id';
951 if ($direction == 'a_b') {
952 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
953 civicrm_relationship_type.label_b_a as relation ';
956 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
957 civicrm_relationship_type.label_a_b as relation ';
962 FROM civicrm_relationship
963 INNER JOIN civicrm_relationship_type ON ( civicrm_relationship.relationship_type_id = civicrm_relationship_type.id )
964 INNER JOIN civicrm_contact ";
965 if ($direction == 'a_b') {
966 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_a ) ';
969 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_b ) ';
972 LEFT JOIN civicrm_address ON (civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1)
973 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
974 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id AND civicrm_email.is_primary = 1)
975 LEFT JOIN civicrm_state_province ON (civicrm_address.state_province_id = civicrm_state_province.id)
976 LEFT JOIN civicrm_country ON (civicrm_address.country_id = civicrm_country.id)
978 $where = 'WHERE ( 1 )';
980 if ($direction == 'a_b') {
981 $where .= ' AND civicrm_relationship.contact_id_b = ' . CRM_Utils_Type
::escape($contactId, 'Positive');
984 $where .= ' AND civicrm_relationship.contact_id_a = ' . CRM_Utils_Type
::escape($contactId, 'Positive') . '
985 AND civicrm_relationship.contact_id_a != civicrm_relationship.contact_id_b ';
988 if ($relationshipId) {
989 $where .= ' AND civicrm_relationship.id = ' . CRM_Utils_Type
::escape($relationshipId, 'Positive');
992 $date = date('Y-m-d');
993 if ($status == self
::PAST
) {
994 //this case for showing past relationship
995 $where .= ' AND civicrm_relationship.is_active = 1 ';
996 $where .= " AND civicrm_relationship.end_date < '" . $date . "'";
998 elseif ($status == self
::DISABLED
) {
999 // this case for showing disabled relationship
1000 $where .= ' AND civicrm_relationship.is_active = 0 ';
1002 elseif ($status == self
::CURRENT
) {
1003 //this case for showing current relationship
1004 $where .= ' AND civicrm_relationship.is_active = 1 ';
1005 $where .= " AND (civicrm_relationship.end_date >= '" . $date . "' OR civicrm_relationship.end_date IS NULL) ";
1007 elseif ($status == self
::INACTIVE
) {
1008 //this case for showing inactive relationships
1009 $where .= " AND (civicrm_relationship.end_date < '" . $date . "'";
1010 $where .= ' OR civicrm_relationship.is_active = 0 )';
1014 $where .= ' AND civicrm_contact.is_deleted = 0';
1015 if (!empty($params['membership_type_id']) && empty($params['relationship_type_id'])) {
1016 $where .= self
::membershipTypeToRelationshipTypes($params, $direction);
1018 if (!empty($params['relationship_type_id'])) {
1019 if (is_array($params['relationship_type_id'])) {
1020 $where .= " AND " . CRM_Core_DAO
::createSQLFilter('relationship_type_id', $params['relationship_type_id'], 'Integer');
1023 $where .= ' AND relationship_type_id = ' . CRM_Utils_Type
::escape($params['relationship_type_id'], 'Positive');
1026 if ($direction == 'a_b') {
1027 $where .= ' ) UNION ';
1033 return array($select, $from, $where);
1037 * This is the function to get the list of relationships
1039 * @param int $contactId
1041 * @param int $status
1042 * 1: Past 2: Disabled 3: Current.
1043 * @param int $numRelationship
1044 * No of relationships to display (limit).
1046 * Get the no of relationships.
1047 * $param int $relationshipId relationship id
1048 * $param array $links the list of links to display
1049 * $param int $permissionMask the permission mask to be applied for the actions
1050 * $param boolean $permissionedContact to return only permissioned Contact
1051 * $param array $params array of variables consistent with filters supported by the api
1052 * return array $values relationship records
1053 * @param int $relationshipId
1054 * @param null $links
1055 * @param null $permissionMask
1056 * @param bool $permissionedContact
1057 * @param array $params
1062 static function getRelationship(
1064 $status = 0, $numRelationship = 0,
1065 $count = 0, $relationshipId = 0,
1066 $links = NULL, $permissionMask = NULL,
1067 $permissionedContact = FALSE,
1071 if (!$contactId && !$relationshipId) {
1075 list($select1, $from1, $where1) = self
::makeURLClause($contactId, $status, $numRelationship,
1076 $count, $relationshipId, 'a_b', $params
1078 list($select2, $from2, $where2) = self
::makeURLClause($contactId, $status, $numRelationship,
1079 $count, $relationshipId, 'b_a', $params
1082 $order = $limit = '';
1084 if (empty($params['sort'])) {
1085 $order = ' ORDER BY civicrm_relationship_type_id, sort_name ';
1088 $order = " ORDER BY {$params['sort']} ";
1092 if (!empty($params['offset']) && $params['offset'] > 0) {
1093 $offset = $params['offset'];
1096 if ($numRelationship) {
1097 $limit = " LIMIT {$offset}, $numRelationship";
1101 // building the query string
1102 $queryString = $select1 . $from1 . $where1 . $select2 . $from2 . $where2 . $order . $limit;
1104 $relationship = new CRM_Contact_DAO_Relationship();
1106 $relationship->query($queryString);
1109 $relationshipCount = 0;
1110 while ($relationship->fetch()) {
1111 $relationshipCount +
= $relationship->cnt1 +
$relationship->cnt2
;
1113 return $relationshipCount;
1118 if ($status != self
::INACTIVE
) {
1120 $mask = array_sum(array_keys($links));
1121 if ($mask & CRM_Core_Action
::DISABLE
) {
1122 $mask -= CRM_Core_Action
::DISABLE
;
1124 if ($mask & CRM_Core_Action
::ENABLE
) {
1125 $mask -= CRM_Core_Action
::ENABLE
;
1128 if ($status == self
::CURRENT
) {
1129 $mask |
= CRM_Core_Action
::DISABLE
;
1131 elseif ($status == self
::DISABLED
) {
1132 $mask |
= CRM_Core_Action
::ENABLE
;
1134 $mask = $mask & $permissionMask;
1137 while ($relationship->fetch()) {
1138 $rid = $relationship->civicrm_relationship_id
;
1139 $cid = $relationship->civicrm_contact_id
;
1140 if (($permissionedContact) &&
1141 (!CRM_Contact_BAO_Contact_Permission
::relationship($cid, $contactId))
1145 $values[$rid]['id'] = $rid;
1146 $values[$rid]['cid'] = $cid;
1147 $values[$rid]['contact_id_a'] = $relationship->contact_id_a
;
1148 $values[$rid]['contact_id_b'] = $relationship->contact_id_b
;
1149 $values[$rid]['contact_type'] = $relationship->contact_type
;
1150 $values[$rid]['relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1151 $values[$rid]['relation'] = $relationship->relation
;
1152 $values[$rid]['name'] = $relationship->sort_name
;
1153 $values[$rid]['display_name'] = $relationship->display_name
;
1154 $values[$rid]['job_title'] = $relationship->job_title
;
1155 $values[$rid]['email'] = $relationship->email
;
1156 $values[$rid]['phone'] = $relationship->phone
;
1157 $values[$rid]['employer_id'] = $relationship->employer_id
;
1158 $values[$rid]['organization_name'] = $relationship->organization_name
;
1159 $values[$rid]['country'] = $relationship->country
;
1160 $values[$rid]['city'] = $relationship->city
;
1161 $values[$rid]['state'] = $relationship->state
;
1162 $values[$rid]['start_date'] = $relationship->start_date
;
1163 $values[$rid]['end_date'] = $relationship->end_date
;
1164 $values[$rid]['description'] = $relationship->description
;
1165 $values[$rid]['is_active'] = $relationship->is_active
;
1166 $values[$rid]['is_permission_a_b'] = $relationship->is_permission_a_b
;
1167 $values[$rid]['is_permission_b_a'] = $relationship->is_permission_b_a
;
1168 $values[$rid]['case_id'] = $relationship->case_id
;
1171 $values[$rid]['status'] = $status;
1174 $values[$rid]['civicrm_relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1176 if ($relationship->contact_id_a
== $contactId) {
1177 $values[$rid]['rtype'] = 'a_b';
1180 $values[$rid]['rtype'] = 'b_a';
1186 'rtype' => $values[$rid]['rtype'],
1187 'cid' => $contactId,
1188 'cbid' => $values[$rid]['cid'],
1189 'caseid' => $values[$rid]['case_id'],
1190 'clientid' => $contactId,
1193 if ($status == self
::INACTIVE
) {
1194 // setting links for inactive relationships
1195 $mask = array_sum(array_keys($links));
1196 if (!$values[$rid]['is_active']) {
1197 $mask -= CRM_Core_Action
::DISABLE
;
1200 $mask -= CRM_Core_Action
::ENABLE
;
1201 $mask -= CRM_Core_Action
::DISABLE
;
1205 // Give access to manage case link by copying to MAX_ACTION index temporarily, depending on case permission of user.
1206 if ($values[$rid]['case_id']) {
1207 // Borrowed logic from CRM_Case_Page_Tab
1208 $hasCaseAccess = FALSE;
1209 if (CRM_Core_Permission
::check('access all cases and activities')) {
1210 $hasCaseAccess = TRUE;
1213 $userCases = CRM_Case_BAO_Case
::getCases(FALSE);
1214 if (array_key_exists($values[$rid]['case_id'], $userCases)) {
1215 $hasCaseAccess = TRUE;
1219 if ($hasCaseAccess) {
1220 // give access by copying to MAX_ACTION temporarily, otherwise leave at NONE which won't display
1221 $links[CRM_Core_Action
::MAX_ACTION
] = $links[CRM_Core_Action
::NONE
];
1222 $links[CRM_Core_Action
::MAX_ACTION
]['name'] = ts('Manage Case #%1', array(1 => $values[$rid]['case_id']));
1223 $links[CRM_Core_Action
::MAX_ACTION
]['class'] = 'no-popup';
1225 // Also make sure we have the right client cid since can get here from multiple relationship tabs.
1226 if ($values[$rid]['rtype'] == 'b_a') {
1227 $replace['clientid'] = $values[$rid]['cid'];
1232 $values[$rid]['action'] = CRM_Core_Action
::formLink(
1238 'relationship.selector.row',
1241 unset($links[CRM_Core_Action
::MAX_ACTION
]);
1245 $relationship->free();
1251 * Get get list of relationship type based on the target contact type.
1253 * @param string $targetContactType
1254 * It's valid contact tpye(may be Individual , Organization , Household).
1256 * @return array - array reference of all relationship types with context to current contact type .
1259 public function getRelationType($targetContactType) {
1260 $relationshipType = array();
1261 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType();
1263 foreach ($allRelationshipType as $key => $type) {
1264 if ($type['contact_type_b'] == $targetContactType) {
1265 $relationshipType[$key . '_a_b'] = $type['label_a_b'];
1269 return $relationshipType;
1273 * Create / update / delete membership for related contacts.
1275 * This function will create/update/delete membership for related
1276 * contact based on 1) contact have active membership 2) that
1277 * membership is is extedned by the same relationship type to that
1278 * of the existing relationship.
1283 * Array array of values submitted by POST.
1285 * Array array of ids.
1286 * @param \const|\which $action which action called this function
1288 * @param bool $active
1292 public static function relatedMemberships($contactId, &$params, $ids, $action = CRM_Core_Action
::ADD
, $active = TRUE) {
1293 // Check the end date and set the status of the relationship
1295 $status = self
::CURRENT
;
1297 if (!empty($params['end_date'])) {
1298 $endDate = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Date
::format($params['end_date']), NULL, 'Ymd');
1299 $today = date('Ymd');
1301 if ($today > $endDate) {
1302 $status = self
::PAST
;
1306 if (($action & CRM_Core_Action
::ADD
) &&
1307 ($status & self
::PAST
)
1309 // if relationship is PAST and action is ADD, no qustion
1310 // of creating RELATED membership and return back to
1315 $rel = explode('_', $params['relationship_type_id']);
1317 $relTypeId = $rel[0];
1318 if (!empty($rel[1])) {
1319 $relDirection = "_{$rel[1]}_{$rel[2]}";
1322 // this call is coming from somewhere where the direction was resolved early on (e.g an api call)
1323 // so we can assume _a_b
1324 $relDirection = "_a_b";
1326 $targetContact = array();
1327 if (($action & CRM_Core_Action
::ADD
) ||
1328 ($action & CRM_Core_Action
::DELETE
)
1330 $contact = $contactId;
1331 $targetContact = CRM_Utils_Array
::value('contact_check', $params);
1333 elseif ($action & CRM_Core_Action
::UPDATE
) {
1334 $contact = $ids['contact'];
1335 $targetContact = array($ids['contactTarget'] => 1);
1338 // Build the 'values' array for
1341 // This will allow us to check if either of the contacts in
1342 // relationship have active memberships.
1347 $values[$contact] = array(
1348 'relatedContacts' => $targetContact,
1349 'relationshipTypeId' => $relTypeId,
1350 'relationshipTypeDirection' => $relDirection,
1353 if (!empty($targetContact)) {
1354 foreach ($targetContact as $cid => $donCare) {
1355 $values[$cid] = array(
1356 'relatedContacts' => array($contact => 1),
1357 'relationshipTypeId' => $relTypeId,
1360 $relTypeParams = array('id' => $relTypeId);
1361 $relTypeValues = array();
1362 CRM_Contact_BAO_RelationshipType
::retrieve($relTypeParams, $relTypeValues);
1364 if (CRM_Utils_Array
::value('name_a_b', $relTypeValues) == CRM_Utils_Array
::value('name_b_a', $relTypeValues)) {
1365 $values[$cid]['relationshipTypeDirection'] = '_a_b';
1368 $values[$cid]['relationshipTypeDirection'] = ($relDirection == '_a_b') ?
'_b_a' : '_a_b';
1373 // Now get the active memberships for all the contacts.
1374 // If contact have any valid membership(s), then add it to
1376 foreach ($values as $cid => $subValues) {
1377 $memParams = array('contact_id' => $cid);
1378 $memberships = array();
1380 CRM_Member_BAO_Membership
::getValues($memParams, $memberships, $active);
1382 if (empty($memberships)) {
1386 $values[$cid]['memberships'] = $memberships;
1388 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1390 // done with 'values' array.
1391 // Finally add / edit / delete memberships for the related contacts
1392 foreach ($values as $cid => $details) {
1393 if (!array_key_exists('memberships', $details)) {
1397 $mainRelatedContactId = key(CRM_Utils_Array
::value('relatedContacts', $details, array()));
1399 foreach ($details['memberships'] as $membershipId => $membershipValues) {
1400 $relTypeIds = array();
1401 if ($action & CRM_Core_Action
::DELETE
) {
1402 // Delete memberships of the related contacts only if relationship type exists for membership type
1404 SELECT relationship_type_id, relationship_direction
1405 FROM civicrm_membership_type
1406 WHERE id = {$membershipValues['membership_type_id']}";
1407 $dao = CRM_Core_DAO
::executeQuery($query);
1408 $relTypeDirs = array();
1409 while ($dao->fetch()) {
1410 $relTypeId = $dao->relationship_type_id
;
1411 $relDirection = $dao->relationship_direction
;
1413 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $relTypeId);
1414 if (in_array($values[$cid]['relationshipTypeId'], $relTypeIds)) {
1415 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $mainRelatedContactId);
1419 if (($action & CRM_Core_Action
::UPDATE
) &&
1420 ($status & self
::PAST
) &&
1421 ($membershipValues['owner_membership_id'])
1423 // If relationship is PAST and action is UPDATE
1424 // then delete the RELATED membership
1425 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipValues['owner_membership_id'],
1426 $membershipValues['membership_contact_id']
1431 // add / edit the memberships for related
1434 // Get the Membership Type Details.
1435 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipValues['membership_type_id']);
1436 // Check if contact's relationship type exists in membership type
1437 $relTypeDirs = array();
1438 if (!empty($membershipType['relationship_type_id'])) {
1439 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_type_id']);
1441 if (!empty($membershipType['relationship_direction'])) {
1442 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_direction']);
1444 foreach ($relTypeIds as $key => $value) {
1445 $relTypeDirs[] = $value . '_' . $relDirections[$key];
1447 $relTypeDir = $details['relationshipTypeId'] . $details['relationshipTypeDirection'];
1448 if (in_array($relTypeDir, $relTypeDirs)) {
1449 // Check if relationship being created/updated is
1450 // similar to that of membership type's
1453 $membershipValues['owner_membership_id'] = $membershipId;
1454 unset($membershipValues['id']);
1455 unset($membershipValues['membership_contact_id']);
1456 unset($membershipValues['contact_id']);
1457 unset($membershipValues['membership_id']);
1458 foreach ($details['relatedContacts'] as $relatedContactId => $donCare) {
1459 $membershipValues['contact_id'] = $relatedContactId;
1460 if ($deceasedStatusId &&
1461 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $relatedContactId, 'is_deceased')
1463 $membershipValues['status_id'] = $deceasedStatusId;
1464 $membershipValues['skipStatusCal'] = TRUE;
1471 if (!empty($membershipValues[$dateField])) {
1472 $membershipValues[$dateField] = CRM_Utils_Date
::processDate($membershipValues[$dateField]);
1476 if ($action & CRM_Core_Action
::UPDATE
) {
1477 //delete the membership record for related
1478 //contact before creating new membership record.
1479 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $relatedContactId);
1482 // check whether we have some related memberships still available
1485 FROM civicrm_membership
1486 LEFT JOIN civicrm_membership_status ON (civicrm_membership_status.id = civicrm_membership.status_id)
1487 WHERE membership_type_id = {$membershipValues['membership_type_id']} AND owner_membership_id = {$membershipValues['owner_membership_id']}
1488 AND is_current_member = 1";
1489 $result = CRM_Core_DAO
::singleValueQuery($query);
1490 if ($result < CRM_Utils_Array
::value('max_related', $membershipValues, PHP_INT_MAX
)) {
1491 CRM_Member_BAO_Membership
::create($membershipValues, CRM_Core_DAO
::$_nullArray);
1495 elseif ($action & CRM_Core_Action
::UPDATE
) {
1496 // if action is update and updated relationship do
1497 // not match with the existing
1498 // membership=>relationship then we need to
1499 // delete the membership record created for
1500 // previous relationship.
1502 if (self
::isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, CRM_Utils_Array
::value('relationship_ids', $params))) {
1503 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $mainRelatedContactId);
1511 * Helper function to check whether to delete the membership or
1517 public static function isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, $relIds) {
1518 if (in_array($relTypeId, $relTypeIds)) {
1522 if (empty($relIds)) {
1526 $relParamas = array(
1527 1 => array($contactId, 'Integer'),
1528 2 => array($mainRelatedContactId, 'Integer'),
1531 if ($contactId == $mainRelatedContactId) {
1532 $recordsFound = (int) CRM_Core_DAO
::singleValueQuery("SELECT COUNT(*) FROM civicrm_relationship WHERE relationship_type_id IN ( " . implode(',', $relTypeIds) . " ) AND contact_id_a IN ( %1 ) OR contact_id_b IN ( %1 ) AND id IN (" . implode(',', $relIds) . ")", $relParamas);
1533 if ($recordsFound) {
1539 $recordsFound = (int) CRM_Core_DAO
::singleValueQuery("SELECT COUNT(*) FROM civicrm_relationship WHERE relationship_type_id IN ( " . implode(',', $relTypeIds) . " ) AND contact_id_a IN ( %1, %2 ) AND contact_id_b IN ( %1, %2 ) AND id NOT IN (" . implode(',', $relIds) . ")", $relParamas);
1541 if ($recordsFound) {
1549 * Get Current Employer for Contact
1551 * @param $contactIds
1554 * @return array $currentEmployer array of the current employer@static
1556 public static function getCurrentEmployer($contactIds) {
1557 $contacts = implode(',', $contactIds);
1560 SELECT organization_name, id, employer_id
1561 FROM civicrm_contact
1562 WHERE id IN ( {$contacts} )
1565 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1566 $currentEmployer = array();
1567 while ($dao->fetch()) {
1568 $currentEmployer[$dao->id
]['org_id'] = $dao->employer_id
;
1569 $currentEmployer[$dao->id
]['org_name'] = $dao->organization_name
;
1572 return $currentEmployer;
1576 * Return list of permissioned employer for a given contact.
1579 * Int contact id whose employers.
1582 * String employers sort name.
1586 * @return array array of employers.
1589 public static function getPermissionedEmployer($contactID, $name = NULL) {
1590 //get the relationship id
1591 $relTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType',
1592 'Employee of', 'id', 'name_a_b'
1595 return self
::getPermissionedContacts($contactID, $relTypeId, $name);
1600 * Function to return list of permissioned contacts for a given contact and relationship type
1603 * Int contact id whose permissioned contacts are to be found.
1605 * String one or more relationship type id's.
1611 * @return array of contacts
1613 public static function getPermissionedContacts($contactID, $relTypeId, $name = NULL) {
1614 $contacts = array();
1618 SELECT cc.id as id, cc.sort_name as name
1619 FROM civicrm_relationship cr, civicrm_contact cc
1621 cr.contact_id_a = %1 AND
1622 cr.relationship_type_id IN (%2) AND
1623 cr.is_permission_a_b = 1 AND
1624 IF(cr.end_date IS NULL, 1, (DATEDIFF( CURDATE( ), cr.end_date ) <= 0)) AND
1625 cr.is_active = 1 AND
1626 cc.id = cr.contact_id_b AND
1629 if (!empty($name)) {
1630 $name = CRM_Utils_Type
::escape($name, 'String');
1632 AND cc.sort_name LIKE '%$name%'";
1635 $args = array(1 => array($contactID, 'Integer'), 2 => array($relTypeId, 'String'));
1636 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1638 while ($dao->fetch()) {
1639 $contacts[$dao->id
] = array(
1640 'name' => $dao->name
,
1641 'value' => $dao->id
,
1649 * Merge relationships from otherContact to mainContact
1650 * Called during contact merge operation
1652 * @param int $mainId
1653 * Contact id of main contact record.
1654 * @param int $otherId
1655 * Contact id of record which is going to merge.
1656 * @param array $sqls
1657 * (reference) array of sql statements to append to.
1659 * @see CRM_Dedupe_Merger::cpTables()
1663 public static function mergeRelationships($mainId, $otherId, &$sqls) {
1664 // Delete circular relationships
1665 $sqls[] = "DELETE FROM civicrm_relationship
1666 WHERE (contact_id_a = $mainId AND contact_id_b = $otherId)
1667 OR (contact_id_b = $mainId AND contact_id_a = $otherId)";
1669 // Delete relationship from other contact if main contact already has that relationship
1670 $sqls[] = "DELETE r2
1671 FROM civicrm_relationship r1, civicrm_relationship r2
1672 WHERE r1.relationship_type_id = r2.relationship_type_id
1675 r1.contact_id_a = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_b = r2.contact_id_b
1676 OR r1.contact_id_b = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_a = r2.contact_id_a
1678 (r1.contact_id_a = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_b = r2.contact_id_a
1679 OR r1.contact_id_b = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_a = r2.contact_id_b)
1680 AND r1.relationship_type_id IN (SELECT id FROM civicrm_relationship_type WHERE name_b_a = name_a_b)
1684 // Move relationships
1685 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_a = $mainId WHERE contact_id_a = $otherId";
1686 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_b = $mainId WHERE contact_id_b = $otherId";
1688 // Move current employer id (name will get updated later)
1689 $sqls[] = "UPDATE civicrm_contact SET employer_id = $mainId WHERE employer_id = $otherId";
1693 * Set 'is_valid' field to false for all relationships whose end date is in the past, ie. are expired.
1695 * @return True on success, false if error is encountered.
1697 public static function disableExpiredRelationships() {
1698 $query = "SELECT id FROM civicrm_relationship WHERE is_active = 1 AND end_date < CURDATE()";
1700 $dao = CRM_Core_DAO
::executeQuery($query);
1701 while ($dao->fetch()) {
1702 $result = CRM_Contact_BAO_Relationship
::setIsActive($dao->id
, FALSE);
1703 // Result will be NULL if error occurred. We abort early if error detected.
1704 if ($result == NULL) {
1712 * Function filters the query by possible relationships for the membership type
1713 * It is intended to be called when constructing queries for the api (reciprocal & non-reciprocal)
1714 * and to add clauses to limit the return to those relationships which COULD inherit a membership type
1715 * (as opposed to those who inherit a particular membership
1717 * @param array $params
1719 * @param null $direction
1723 public static function membershipTypeToRelationshipTypes(&$params, $direction = NULL) {
1724 $membershipType = civicrm_api3('membership_type', 'getsingle', array(
1725 'id' => $params['membership_type_id'],
1726 'return' => 'relationship_type_id, relationship_direction'
1728 $relationshipTypes = $membershipType['relationship_type_id'];
1729 if (empty($relationshipTypes)) {
1732 // if we don't have any contact data we can only filter on type
1733 if (empty($params['contact_id']) && empty($params['contact_id_a']) && empty($params['contact_id_a'])) {
1734 $params['relationship_type_id'] = array('IN' => $relationshipTypes);
1738 $relationshipDirections = (array) $membershipType['relationship_direction'];
1739 // if we have contact_id_a OR contact_id_b we can make a call here
1740 // if we have contact??
1741 foreach ($relationshipDirections as $index => $mtdirection) {
1742 if (isset($params['contact_id_a']) && $mtdirection == 'a_b' ||
$direction == 'a_b') {
1743 $types[] = $relationshipTypes[$index];
1745 if (isset($params['contact_id_b']) && $mtdirection == 'b_a' ||
$direction == 'b_a') {
1746 $types[] = $relationshipTypes[$index];
1749 if (!empty($types)) {
1750 $params['relationship_type_id'] = array('IN' => $types);
1752 elseif (!empty($clauses)) {
1753 return explode(' OR ', $clauses);
1756 // effectively setting it to return no results
1757 $params['relationship_type_id'] = 0;
1764 * This function is a wrapper for contact relationship selector
1766 * @param array $params
1767 * Associated array for params record id.
1769 * @return array $contactRelationships associated array of contact relationships
1771 public static function getContactRelationshipSelector(&$params) {
1772 // format the params
1773 $params['offset'] = ($params['page'] - 1) * $params['rp'];
1774 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
1776 if ($params['context'] == 'past') {
1777 $relationshipStatus = CRM_Contact_BAO_Relationship
::INACTIVE
;
1780 $relationshipStatus = CRM_Contact_BAO_Relationship
::CURRENT
;
1783 // check logged in user for permission
1784 $page = new CRM_Core_Page();
1785 CRM_Contact_Page_View
::checkUserPermission($page, $params['contact_id']);
1786 $permissions = array($page->_permission
);
1787 if ($page->_permission
== CRM_Core_Permission
::EDIT
) {
1788 $permissions[] = CRM_Core_Permission
::DELETE
;
1790 $mask = CRM_Core_Action
::mask($permissions);
1792 if ($params['context'] != 'user') {
1793 $links = CRM_Contact_Page_View_Relationship
::links();
1794 $permissionedContacts = FALSE;
1797 $links = CRM_Contact_Page_View_UserDashBoard
::links();
1798 $permissionedContacts = TRUE;
1801 // get contact relationships
1802 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1803 $relationshipStatus,
1804 $params['rp'], 0, 0,
1806 $permissionedContacts,
1810 $contactRelationships = array();
1811 $params['total'] = 0;
1812 if (!empty($relationships)) {
1813 // get the total relationships
1814 if ($params['context'] != 'user') {
1815 $params['total'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1816 $relationshipStatus, 0, 1, 0, NULL, NULL, $permissionedContacts);
1819 // FIX ME: we cannot directly determine total permissioned relationship, hence re-fire query
1820 $permissionedRelationships = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1821 $relationshipStatus,
1825 $params['total'] = count($permissionedRelationships);
1829 foreach ($relationships as $relationshipId => $values) {
1830 //Add image icon for related contacts: CRM-14919
1831 $icon = CRM_Contact_BAO_Contact_Utils
::getImage($values['contact_type'],
1835 $contactRelationships[$relationshipId]['name'] = $icon . ' ' . CRM_Utils_System
::href(
1837 'civicrm/contact/view',
1838 "reset=1&cid={$values['cid']}");
1840 $contactRelationships[$relationshipId]['relation'] = CRM_Utils_System
::href(
1841 $values['relation'],
1842 'civicrm/contact/view/rel',
1843 "action=view&reset=1&cid={$values['cid']}&id={$values['id']}&rtype={$values['rtype']}");
1845 if ($params['context'] == 'current') {
1846 if (($params['contact_id'] == $values['contact_id_a'] AND $values['is_permission_a_b'] == 1) OR
1847 ($params['contact_id'] == $values['contact_id_b'] AND $values['is_permission_b_a'] == 1)
1849 $contactRelationships[$relationshipId]['name'] .= '<span id="permission-a-b" class="crm-marker permission-relationship"> *</span>';
1852 if (($values['cid'] == $values['contact_id_a'] AND $values['is_permission_a_b'] == 1) OR
1853 ($values['cid'] == $values['contact_id_b'] AND $values['is_permission_b_a'] == 1)
1855 $contactRelationships[$relationshipId]['relation'] .= '<span id="permission-b-a" class="crm-marker permission-relationship"> *</span>';
1859 if (!empty($values['description'])) {
1860 $contactRelationships[$relationshipId]['relation'] .= "<p class='description'>{$values['description']}</p>";
1863 $contactRelationships[$relationshipId]['start_date'] = CRM_Utils_Date
::customFormat($values['start_date']);
1864 $contactRelationships[$relationshipId]['end_date'] = CRM_Utils_Date
::customFormat($values['end_date']);
1865 $contactRelationships[$relationshipId]['city'] = $values['city'];
1866 $contactRelationships[$relationshipId]['state'] = $values['state'];
1867 $contactRelationships[$relationshipId]['email'] = $values['email'];
1868 $contactRelationships[$relationshipId]['phone'] = $values['phone'];
1869 $contactRelationships[$relationshipId]['links'] = $values['action'];
1870 $contactRelationships[$relationshipId]['id'] = $values['id'];
1871 $contactRelationships[$relationshipId]['is_active'] = $values['is_active'];
1874 return $contactRelationships;