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
356 * array of defaults for creating relationship
359 public static function getdefaults() {
362 'is_permission_a_b' => 0,
363 'is_permission_b_a' => 0,
365 'start_date' => 'NULL',
367 'end_date' => 'NULL',
373 * Check if there is data to create the object
375 * @param array $params
376 * (reference ) an assoc array of name/value pairs.
381 public static function dataExists(&$params) {
382 // return if no data present
383 if (!is_array(CRM_Utils_Array
::value('contact_check', $params))) {
390 * Get get list of relationship type based on the contact type.
392 * @param int $contactId
393 * This is the contact id of the current contact.
394 * @param null $contactSuffix
395 * @param string $relationshipId
396 * The id of the existing relationship if any.
397 * @param string $contactType
400 * If true returns relationship types in both the direction.
401 * @param string $column
402 * Name/label that going to retrieve from db.
403 * @param bool $biDirectional
404 * @param string $contactSubType
405 * Includes relationshiptypes between this subtype.
406 * @param bool $onlySubTypeRelationTypes
407 * If set only subtype which is passed by $contactSubType.
408 * related relationshiptypes get return
413 * array reference of all relationship types with context to current contact.
415 static function getContactRelationshipType(
417 $contactSuffix = NULL,
418 $relationshipId = NULL,
422 $biDirectional = TRUE,
423 $contactSubType = NULL,
424 $onlySubTypeRelationTypes = FALSE
426 $allRelationshipType = array();
427 $relationshipType = array();
428 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType($column);
430 $otherContactType = NULL;
431 if ($relationshipId) {
432 $relationship = new CRM_Contact_DAO_Relationship();
433 $relationship->id
= $relationshipId;
434 if ($relationship->find(TRUE)) {
435 $contact = new CRM_Contact_DAO_Contact();
436 $contact->id
= ($relationship->contact_id_a
=== $contactId) ?
$relationship->contact_id_b
: $relationship->contact_id_a
;
438 if ($contact->find(TRUE)) {
439 $otherContactType = $contact->contact_type
;
440 //CRM-5125 for contact subtype specific relationshiptypes
441 if ($contact->contact_sub_type
) {
442 $otherContactSubType = $contact->contact_sub_type
;
448 $contactSubType = array();
450 $contactType = CRM_Contact_BAO_Contact
::getContactType($contactId);
451 $contactSubType = CRM_Contact_BAO_Contact
::getContactSubType($contactId);
454 foreach ($allRelationshipType as $key => $value) {
455 // the contact type is required or matches
456 if (((!$value['contact_type_a']) ||
457 $value['contact_type_a'] == $contactType
459 // the other contact type is required or present or matches
460 ((!$value['contact_type_b']) ||
461 (!$otherContactType) ||
462 $value['contact_type_b'] == $otherContactType
464 (in_array($value['contact_sub_type_a'], $contactSubType) ||
465 in_array($value['contact_sub_type_b'], $contactSubType) ||
466 (!$value['contact_sub_type_a'] && !$onlySubTypeRelationTypes)
469 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
472 if (((!$value['contact_type_b']) ||
473 $value['contact_type_b'] == $contactType
475 ((!$value['contact_type_a']) ||
476 (!$otherContactType) ||
477 $value['contact_type_a'] == $otherContactType
479 (in_array($value['contact_sub_type_b'], $contactSubType) ||
480 in_array($value['contact_sub_type_a'], $contactSubType) ||
481 (!$value['contact_sub_type_b'] && !$onlySubTypeRelationTypes)
484 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
488 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
489 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
493 if ($biDirectional) {
494 // lets clean up the data and eliminate all duplicate values
495 // (i.e. the relationship is bi-directional)
496 $relationshipType = array_unique($relationshipType);
499 // sort the relationshipType in ascending order CRM-7736
500 asort($relationshipType);
501 return $relationshipType;
508 * @return CRM_Contact_DAO_Relationship
510 public static function clearCurrentEmployer($id, $action) {
511 $relationship = new CRM_Contact_DAO_Relationship();
512 $relationship->id
= $id;
513 $relationship->find(TRUE);
515 //to delete relationship between household and individual \
516 //or between individual and orgnization
517 if (($action & CRM_Core_Action
::DISABLE
) ||
($action & CRM_Core_Action
::DELETE
)) {
518 $relTypes = CRM_Utils_Array
::index(array('name_a_b'), CRM_Core_PseudoConstant
::relationshipType('name'));
519 if ($relationship->relationship_type_id
== $relTypes['Employee of']['id'] ||
520 $relationship->relationship_type_id
== $relTypes['Household Member of']['id']
522 $sharedContact = new CRM_Contact_DAO_Contact();
523 $sharedContact->id
= $relationship->contact_id_a
;
524 $sharedContact->find(TRUE);
526 if ($relationship->relationship_type_id
== 4 && $relationship->contact_id_b
== $sharedContact->employer_id
) {
527 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($relationship->contact_id_a
);
531 return $relationship;
535 * Delete the relationship
544 public static function del($id) {
545 // delete from relationship table
546 CRM_Utils_Hook
::pre('delete', 'Relationship', $id, CRM_Core_DAO
::$_nullArray);
548 $relationship = self
::clearCurrentEmployer($id, CRM_Core_Action
::DELETE
);
549 if (CRM_Core_Permission
::access('CiviMember')) {
550 // create $params array which isrequired to delete memberships
551 // of the related contacts.
553 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
554 'contact_check' => array($relationship->contact_id_b
=> 1),
558 // calling relatedMemberships to delete the memberships of
560 self
::relatedMemberships($relationship->contact_id_a
,
563 CRM_Core_Action
::DELETE
,
568 $relationship->delete();
569 CRM_Core_Session
::setStatus(ts('Selected relationship has been deleted successfully.'), ts('Record Deleted'), 'success');
571 CRM_Utils_Hook
::post('delete', 'Relationship', $id, $relationship);
573 // delete the recently created Relationship
574 $relationshipRecent = array(
576 'type' => 'Relationship',
578 CRM_Utils_Recent
::del($relationshipRecent);
580 return $relationship;
584 * Disable/enable the relationship
594 public static function disableEnableRelationship($id, $action) {
595 $relationship = self
::clearCurrentEmployer($id, $action);
596 if (CRM_Core_Permission
::access('CiviMember')) {
597 // create $params array which isrequired to delete memberships
598 // of the related contacts.
600 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
601 'contact_check' => array($relationship->contact_id_b
=> 1),
605 // calling relatedMemberships to delete/add the memberships of
607 if ($action & CRM_Core_Action
::DISABLE
) {
608 CRM_Contact_BAO_Relationship
::relatedMemberships($relationship->contact_id_a
,
611 CRM_Core_Action
::DELETE
,
615 elseif ($action & CRM_Core_Action
::ENABLE
) {
616 $ids['contact'] = $relationship->contact_id_a
;
617 CRM_Contact_BAO_Relationship
::relatedMemberships($relationship->contact_id_a
,
620 CRM_Core_Action
::ADD
,
628 * Delete the object records that are associated with this contact
630 * @param int $contactId
631 * Id of the contact to delete.
636 public static function deleteContact($contactId) {
637 $relationship = new CRM_Contact_DAO_Relationship();
638 $relationship->contact_id_a
= $contactId;
639 $relationship->delete();
641 $relationship = new CRM_Contact_DAO_Relationship();
642 $relationship->contact_id_b
= $contactId;
643 $relationship->delete();
645 CRM_Contact_BAO_Household
::updatePrimaryContact(NULL, $contactId);
649 * Get the other contact in a relationship
654 * $returns returns the contact ids in the realtionship
656 * @return \CRM_Contact_DAO_Relationship
659 public static function getContactIds($id) {
660 $relationship = new CRM_Contact_DAO_Relationship();
662 $relationship->id
= $id;
663 $relationship->selectAdd();
664 $relationship->selectAdd('contact_id_a, contact_id_b');
665 $relationship->find(TRUE);
667 return $relationship;
671 * Check if the relationship type selected between two contacts is correct
673 * @param int $contact_a
675 * @param int $contact_b
677 * @param int $relationshipTypeId
678 * Relationship type id.
681 * true if it is valid relationship else false
684 public static function checkRelationshipType($contact_a, $contact_b, $relationshipTypeId) {
685 $relationshipType = new CRM_Contact_DAO_RelationshipType();
686 $relationshipType->id
= $relationshipTypeId;
687 $relationshipType->selectAdd();
688 $relationshipType->selectAdd('contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b');
689 if ($relationshipType->find(TRUE)) {
690 $contact_type_a = CRM_Contact_BAO_Contact
::getContactType($contact_a);
691 $contact_type_b = CRM_Contact_BAO_Contact
::getContactType($contact_b);
693 $contact_sub_type_a = CRM_Contact_BAO_Contact
::getContactSubType($contact_a);
694 $contact_sub_type_b = CRM_Contact_BAO_Contact
::getContactSubType($contact_b);
696 if (((!$relationshipType->contact_type_a
) ||
($relationshipType->contact_type_a
== $contact_type_a)) &&
697 ((!$relationshipType->contact_type_b
) ||
($relationshipType->contact_type_b
== $contact_type_b)) &&
698 ((!$relationshipType->contact_sub_type_a
) ||
(in_array($relationshipType->contact_sub_type_a
,
701 ((!$relationshipType->contact_sub_type_b
) ||
(in_array($relationshipType->contact_sub_type_b
,
715 * This function does the validtion for valid relationship
717 * @param array $params
718 * This array contains the values there are subitted by the form.
720 * The array that holds all the db ids.
721 * @param int $contactId
722 * This is contact id for adding relationship.
728 public static function checkValidRelationship($params, $ids, $contactId) {
730 self
::setContactABFromIDs($params, $ids, $contactId);
731 // get the string of relationship type
732 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
733 list($type) = explode('_', $relationshipTypes);
734 // function to check if the relationship selected is correct
735 // i.e. employer relationship can exit between Individual and Organization (not between Individual and Individual)
736 if (!CRM_Contact_BAO_Relationship
::checkRelationshipType($params['contact_id_a'], $params['contact_id_b'], $type)) {
737 $errors = 'Please select valid relationship between these two contacts.';
743 * This function checks for duplicate relationship
745 * @param array $params
746 * (reference ) an assoc array of name/value pairs.
748 * This the id of the contact whom we are adding relationship.
749 * @param int $contactId
750 * This is contact id for adding relationship.
751 * @param int $relationshipId
752 * This is relationship id for the contact.
755 * true if record exists else false
758 public static function checkDuplicateRelationship(&$params, $id, $contactId = 0, $relationshipId = 0) {
759 $relationshipTypeId = CRM_Utils_Array
::value('relationship_type_id', $params);
760 list($type) = explode('_', $relationshipTypeId);
764 FROM civicrm_relationship
765 WHERE relationship_type_id = " . CRM_Utils_Type
::escape($type, 'Integer');
768 * CRM-11792 - date fields from API are in ISO format, but this function
769 * supports date arrays BAO has increasingly standardised to ISO format
770 * so I believe this function should support ISO rather than make API
771 * format it - however, need to support array format for now to avoid breakage
772 * @ time of writing this function is called from Relationship::createMultiple (twice)
773 * CRM_BAO_Contact_Utils::clearCurrentEmployer (seemingly without dates)
774 * CRM_Contact_Form_Task_AddToOrganization::postProcess &
775 * CRM_Contact_Form_Task_AddToHousehold::postProcess
776 * (I don't think the last 2 support dates but not sure
779 $dateFields = array('end_date', 'start_date');
780 foreach ($dateFields as $dateField) {
781 if (array_key_exists($dateField, $params)) {
782 if (empty($params[$dateField]) ||
$params[$dateField] == 'null') {
783 //this is most likely coming from an api call & probably loaded
784 // from the DB to deal with some of the
785 // other myriad of excessive checks still in place both in
786 // the api & the create functions
787 $queryString .= " AND $dateField IS NULL";
790 elseif (is_array($params[$dateField])) {
791 $queryString .= " AND $dateField = " .
792 CRM_Utils_Type
::escape(CRM_Utils_Date
::format($params[$dateField]), 'Date');
795 $queryString .= " AND $dateField = " .
796 CRM_Utils_Type
::escape($params[$dateField], 'Date');
802 " AND ( ( contact_id_a = " . CRM_Utils_Type
::escape($id, 'Integer') .
803 " AND contact_id_b = " . CRM_Utils_Type
::escape($contactId, 'Integer') .
804 " ) OR ( contact_id_a = " . CRM_Utils_Type
::escape($contactId, 'Integer') .
805 " AND contact_id_b = " . CRM_Utils_Type
::escape($id, 'Integer') . " ) ) ";
807 //if caseId is provided, include it duplicate checking.
808 if ($caseId = CRM_Utils_Array
::value('case_id', $params)) {
809 $queryString .= " AND case_id = " . CRM_Utils_Type
::escape($caseId, 'Integer');
812 if ($relationshipId) {
813 $queryString .= " AND id !=" . CRM_Utils_Type
::escape($relationshipId, 'Integer');
816 $relationship = new CRM_Contact_BAO_Relationship();
817 $relationship->query($queryString);
818 $relationship->fetch();
819 $relationship->free();
820 return ($relationship->id
) ?
TRUE : FALSE;
824 * Update the is_active flag in the db
827 * Id of the database record.
828 * @param bool $is_active
829 * Value we want to set the is_active field.
831 * @throws CiviCRM_API3_Exception
833 * DAO object on success, null otherwise
836 public static function setIsActive($id, $is_active) {
837 // as both the create & add functions have a bunch of logic in them that
838 // doesn't seem to cope with a normal update we will call the api which
839 // has tested handling for this
840 // however, a longer term solution would be to simplify the add, create & api functions
841 // to be more standard. It is debatable @ that point whether it's better to call the BAO
842 // direct as the api is more tested.
843 $result = civicrm_api('relationship', 'create', array(
845 'is_active' => $is_active,
849 if (is_array($result) && !empty($result['is_error']) && $result['error_message'] != 'Relationship already exists') {
850 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array
::value('error_code', $result, 'undefined'), $result);
853 // call (undocumented possibly deprecated) hook
854 CRM_Utils_Hook
::enableDisable('CRM_Contact_BAO_Relationship', $id, $is_active);
860 * Given the list of params in the params array, fetch the object
861 * and store the values in the values array
863 * @param array $params
864 * Input parameters to find object.
865 * @param array $values
866 * Output values of the object.
869 * (reference) the values that could be potentially assigned to smarty
872 public static function &getValues(&$params, &$values) {
873 if (empty($params)) {
878 // get the specific number of relationship or all relationships.
879 if (!empty($params['numRelationship'])) {
880 $v['data'] = &CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'], NULL, $params['numRelationship']);
883 $v['data'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id']);
886 // get the total count of relationships
887 $v['totalCount'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'], NULL, NULL, TRUE);
889 $values['relationship']['data'] = &$v['data'];
890 $values['relationship']['totalCount'] = &$v['totalCount'];
896 * Helper function to form the sql for relationship retrieval
898 * @param int $contactId
901 * (check const at top of file).
902 * @param int $numRelationship
903 * No of relationships to display (limit).
905 * Get the no of relationships.
906 * $param int $relationshipId relationship id
907 * @param int $relationshipId
908 * @param string $direction
909 * The direction we are interested in a_b or b_a.
910 * @param array $params
911 * Array of extra values including relationship_type_id per api spec.
913 * return string the query for this diretion
918 public static function makeURLClause($contactId, $status, $numRelationship, $count, $relationshipId, $direction, $params = array()) {
919 $select = $from = $where = '';
923 if ($direction == 'a_b') {
924 $select .= ' SELECT count(DISTINCT civicrm_relationship.id) as cnt1, 0 as cnt2 ';
927 $select .= ' SELECT 0 as cnt1, count(DISTINCT civicrm_relationship.id) as cnt2 ';
931 $select .= ' SELECT civicrm_relationship.id as civicrm_relationship_id,
932 civicrm_contact.sort_name as sort_name,
933 civicrm_contact.display_name as display_name,
934 civicrm_contact.job_title as job_title,
935 civicrm_contact.employer_id as employer_id,
936 civicrm_contact.organization_name as organization_name,
937 civicrm_address.street_address as street_address,
938 civicrm_address.city as city,
939 civicrm_address.postal_code as postal_code,
940 civicrm_state_province.abbreviation as state,
941 civicrm_country.name as country,
942 civicrm_email.email as email,
943 civicrm_contact.contact_type as contact_type,
944 civicrm_phone.phone as phone,
945 civicrm_contact.id as civicrm_contact_id,
946 civicrm_relationship.contact_id_b as contact_id_b,
947 civicrm_relationship.contact_id_a as contact_id_a,
948 civicrm_relationship_type.id as civicrm_relationship_type_id,
949 civicrm_relationship.start_date as start_date,
950 civicrm_relationship.end_date as end_date,
951 civicrm_relationship.description as description,
952 civicrm_relationship.is_active as is_active,
953 civicrm_relationship.is_permission_a_b as is_permission_a_b,
954 civicrm_relationship.is_permission_b_a as is_permission_b_a,
955 civicrm_relationship.case_id as case_id';
957 if ($direction == 'a_b') {
958 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
959 civicrm_relationship_type.label_b_a as relation ';
962 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
963 civicrm_relationship_type.label_a_b as relation ';
968 FROM civicrm_relationship
969 INNER JOIN civicrm_relationship_type ON ( civicrm_relationship.relationship_type_id = civicrm_relationship_type.id )
970 INNER JOIN civicrm_contact ";
971 if ($direction == 'a_b') {
972 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_a ) ';
975 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_b ) ';
978 LEFT JOIN civicrm_address ON (civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1)
979 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
980 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id AND civicrm_email.is_primary = 1)
981 LEFT JOIN civicrm_state_province ON (civicrm_address.state_province_id = civicrm_state_province.id)
982 LEFT JOIN civicrm_country ON (civicrm_address.country_id = civicrm_country.id)
984 $where = 'WHERE ( 1 )';
986 if ($direction == 'a_b') {
987 $where .= ' AND civicrm_relationship.contact_id_b = ' . CRM_Utils_Type
::escape($contactId, 'Positive');
990 $where .= ' AND civicrm_relationship.contact_id_a = ' . CRM_Utils_Type
::escape($contactId, 'Positive') . '
991 AND civicrm_relationship.contact_id_a != civicrm_relationship.contact_id_b ';
994 if ($relationshipId) {
995 $where .= ' AND civicrm_relationship.id = ' . CRM_Utils_Type
::escape($relationshipId, 'Positive');
998 $date = date('Y-m-d');
999 if ($status == self
::PAST
) {
1000 //this case for showing past relationship
1001 $where .= ' AND civicrm_relationship.is_active = 1 ';
1002 $where .= " AND civicrm_relationship.end_date < '" . $date . "'";
1004 elseif ($status == self
::DISABLED
) {
1005 // this case for showing disabled relationship
1006 $where .= ' AND civicrm_relationship.is_active = 0 ';
1008 elseif ($status == self
::CURRENT
) {
1009 //this case for showing current relationship
1010 $where .= ' AND civicrm_relationship.is_active = 1 ';
1011 $where .= " AND (civicrm_relationship.end_date >= '" . $date . "' OR civicrm_relationship.end_date IS NULL) ";
1013 elseif ($status == self
::INACTIVE
) {
1014 //this case for showing inactive relationships
1015 $where .= " AND (civicrm_relationship.end_date < '" . $date . "'";
1016 $where .= ' OR civicrm_relationship.is_active = 0 )';
1020 $where .= ' AND civicrm_contact.is_deleted = 0';
1021 if (!empty($params['membership_type_id']) && empty($params['relationship_type_id'])) {
1022 $where .= self
::membershipTypeToRelationshipTypes($params, $direction);
1024 if (!empty($params['relationship_type_id'])) {
1025 if (is_array($params['relationship_type_id'])) {
1026 $where .= " AND " . CRM_Core_DAO
::createSQLFilter('relationship_type_id', $params['relationship_type_id'], 'Integer');
1029 $where .= ' AND relationship_type_id = ' . CRM_Utils_Type
::escape($params['relationship_type_id'], 'Positive');
1032 if ($direction == 'a_b') {
1033 $where .= ' ) UNION ';
1039 return array($select, $from, $where);
1043 * This is the function to get the list of relationships
1045 * @param int $contactId
1047 * @param int $status
1048 * 1: Past 2: Disabled 3: Current.
1049 * @param int $numRelationship
1050 * No of relationships to display (limit).
1052 * Get the no of relationships.
1053 * $param int $relationshipId relationship id
1054 * $param array $links the list of links to display
1055 * $param int $permissionMask the permission mask to be applied for the actions
1056 * $param boolean $permissionedContact to return only permissioned Contact
1057 * $param array $params array of variables consistent with filters supported by the api
1058 * return array $values relationship records
1059 * @param int $relationshipId
1060 * @param null $links
1061 * @param null $permissionMask
1062 * @param bool $permissionedContact
1063 * @param array $params
1068 static function getRelationship(
1070 $status = 0, $numRelationship = 0,
1071 $count = 0, $relationshipId = 0,
1072 $links = NULL, $permissionMask = NULL,
1073 $permissionedContact = FALSE,
1077 if (!$contactId && !$relationshipId) {
1081 list($select1, $from1, $where1) = self
::makeURLClause($contactId, $status, $numRelationship,
1082 $count, $relationshipId, 'a_b', $params
1084 list($select2, $from2, $where2) = self
::makeURLClause($contactId, $status, $numRelationship,
1085 $count, $relationshipId, 'b_a', $params
1088 $order = $limit = '';
1090 if (empty($params['sort'])) {
1091 $order = ' ORDER BY civicrm_relationship_type_id, sort_name ';
1094 $order = " ORDER BY {$params['sort']} ";
1098 if (!empty($params['offset']) && $params['offset'] > 0) {
1099 $offset = $params['offset'];
1102 if ($numRelationship) {
1103 $limit = " LIMIT {$offset}, $numRelationship";
1107 // building the query string
1108 $queryString = $select1 . $from1 . $where1 . $select2 . $from2 . $where2 . $order . $limit;
1110 $relationship = new CRM_Contact_DAO_Relationship();
1112 $relationship->query($queryString);
1115 $relationshipCount = 0;
1116 while ($relationship->fetch()) {
1117 $relationshipCount +
= $relationship->cnt1 +
$relationship->cnt2
;
1119 return $relationshipCount;
1124 if ($status != self
::INACTIVE
) {
1126 $mask = array_sum(array_keys($links));
1127 if ($mask & CRM_Core_Action
::DISABLE
) {
1128 $mask -= CRM_Core_Action
::DISABLE
;
1130 if ($mask & CRM_Core_Action
::ENABLE
) {
1131 $mask -= CRM_Core_Action
::ENABLE
;
1134 if ($status == self
::CURRENT
) {
1135 $mask |
= CRM_Core_Action
::DISABLE
;
1137 elseif ($status == self
::DISABLED
) {
1138 $mask |
= CRM_Core_Action
::ENABLE
;
1140 $mask = $mask & $permissionMask;
1143 while ($relationship->fetch()) {
1144 $rid = $relationship->civicrm_relationship_id
;
1145 $cid = $relationship->civicrm_contact_id
;
1146 if (($permissionedContact) &&
1147 (!CRM_Contact_BAO_Contact_Permission
::relationship($cid, $contactId))
1151 $values[$rid]['id'] = $rid;
1152 $values[$rid]['cid'] = $cid;
1153 $values[$rid]['contact_id_a'] = $relationship->contact_id_a
;
1154 $values[$rid]['contact_id_b'] = $relationship->contact_id_b
;
1155 $values[$rid]['contact_type'] = $relationship->contact_type
;
1156 $values[$rid]['relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1157 $values[$rid]['relation'] = $relationship->relation
;
1158 $values[$rid]['name'] = $relationship->sort_name
;
1159 $values[$rid]['display_name'] = $relationship->display_name
;
1160 $values[$rid]['job_title'] = $relationship->job_title
;
1161 $values[$rid]['email'] = $relationship->email
;
1162 $values[$rid]['phone'] = $relationship->phone
;
1163 $values[$rid]['employer_id'] = $relationship->employer_id
;
1164 $values[$rid]['organization_name'] = $relationship->organization_name
;
1165 $values[$rid]['country'] = $relationship->country
;
1166 $values[$rid]['city'] = $relationship->city
;
1167 $values[$rid]['state'] = $relationship->state
;
1168 $values[$rid]['start_date'] = $relationship->start_date
;
1169 $values[$rid]['end_date'] = $relationship->end_date
;
1170 $values[$rid]['description'] = $relationship->description
;
1171 $values[$rid]['is_active'] = $relationship->is_active
;
1172 $values[$rid]['is_permission_a_b'] = $relationship->is_permission_a_b
;
1173 $values[$rid]['is_permission_b_a'] = $relationship->is_permission_b_a
;
1174 $values[$rid]['case_id'] = $relationship->case_id
;
1177 $values[$rid]['status'] = $status;
1180 $values[$rid]['civicrm_relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1182 if ($relationship->contact_id_a
== $contactId) {
1183 $values[$rid]['rtype'] = 'a_b';
1186 $values[$rid]['rtype'] = 'b_a';
1192 'rtype' => $values[$rid]['rtype'],
1193 'cid' => $contactId,
1194 'cbid' => $values[$rid]['cid'],
1195 'caseid' => $values[$rid]['case_id'],
1196 'clientid' => $contactId,
1199 if ($status == self
::INACTIVE
) {
1200 // setting links for inactive relationships
1201 $mask = array_sum(array_keys($links));
1202 if (!$values[$rid]['is_active']) {
1203 $mask -= CRM_Core_Action
::DISABLE
;
1206 $mask -= CRM_Core_Action
::ENABLE
;
1207 $mask -= CRM_Core_Action
::DISABLE
;
1211 // Give access to manage case link by copying to MAX_ACTION index temporarily, depending on case permission of user.
1212 if ($values[$rid]['case_id']) {
1213 // Borrowed logic from CRM_Case_Page_Tab
1214 $hasCaseAccess = FALSE;
1215 if (CRM_Core_Permission
::check('access all cases and activities')) {
1216 $hasCaseAccess = TRUE;
1219 $userCases = CRM_Case_BAO_Case
::getCases(FALSE);
1220 if (array_key_exists($values[$rid]['case_id'], $userCases)) {
1221 $hasCaseAccess = TRUE;
1225 if ($hasCaseAccess) {
1226 // give access by copying to MAX_ACTION temporarily, otherwise leave at NONE which won't display
1227 $links[CRM_Core_Action
::MAX_ACTION
] = $links[CRM_Core_Action
::NONE
];
1228 $links[CRM_Core_Action
::MAX_ACTION
]['name'] = ts('Manage Case #%1', array(1 => $values[$rid]['case_id']));
1229 $links[CRM_Core_Action
::MAX_ACTION
]['class'] = 'no-popup';
1231 // Also make sure we have the right client cid since can get here from multiple relationship tabs.
1232 if ($values[$rid]['rtype'] == 'b_a') {
1233 $replace['clientid'] = $values[$rid]['cid'];
1238 $values[$rid]['action'] = CRM_Core_Action
::formLink(
1244 'relationship.selector.row',
1247 unset($links[CRM_Core_Action
::MAX_ACTION
]);
1251 $relationship->free();
1257 * Get get list of relationship type based on the target contact type.
1259 * @param string $targetContactType
1260 * It's valid contact tpye(may be Individual , Organization , Household).
1263 * array reference of all relationship types with context to current contact type .
1265 public function getRelationType($targetContactType) {
1266 $relationshipType = array();
1267 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType();
1269 foreach ($allRelationshipType as $key => $type) {
1270 if ($type['contact_type_b'] == $targetContactType) {
1271 $relationshipType[$key . '_a_b'] = $type['label_a_b'];
1275 return $relationshipType;
1279 * Create / update / delete membership for related contacts.
1281 * This function will create/update/delete membership for related
1282 * contact based on 1) contact have active membership 2) that
1283 * membership is is extedned by the same relationship type to that
1284 * of the existing relationship.
1286 * @param int $contactId
1288 * @param array $params
1289 * array of values submitted by POST.
1292 * @param \const|\which $action which action called this function
1294 * @param bool $active
1298 public static function relatedMemberships($contactId, &$params, $ids, $action = CRM_Core_Action
::ADD
, $active = TRUE) {
1299 // Check the end date and set the status of the relationship
1301 $status = self
::CURRENT
;
1303 if (!empty($params['end_date'])) {
1304 $endDate = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Date
::format($params['end_date']), NULL, 'Ymd');
1305 $today = date('Ymd');
1307 if ($today > $endDate) {
1308 $status = self
::PAST
;
1312 if (($action & CRM_Core_Action
::ADD
) &&
1313 ($status & self
::PAST
)
1315 // if relationship is PAST and action is ADD, no qustion
1316 // of creating RELATED membership and return back to
1321 $rel = explode('_', $params['relationship_type_id']);
1323 $relTypeId = $rel[0];
1324 if (!empty($rel[1])) {
1325 $relDirection = "_{$rel[1]}_{$rel[2]}";
1328 // this call is coming from somewhere where the direction was resolved early on (e.g an api call)
1329 // so we can assume _a_b
1330 $relDirection = "_a_b";
1332 $targetContact = array();
1333 if (($action & CRM_Core_Action
::ADD
) ||
1334 ($action & CRM_Core_Action
::DELETE
)
1336 $contact = $contactId;
1337 $targetContact = CRM_Utils_Array
::value('contact_check', $params);
1339 elseif ($action & CRM_Core_Action
::UPDATE
) {
1340 $contact = $ids['contact'];
1341 $targetContact = array($ids['contactTarget'] => 1);
1344 // Build the 'values' array for
1347 // This will allow us to check if either of the contacts in
1348 // relationship have active memberships.
1353 $values[$contact] = array(
1354 'relatedContacts' => $targetContact,
1355 'relationshipTypeId' => $relTypeId,
1356 'relationshipTypeDirection' => $relDirection,
1359 if (!empty($targetContact)) {
1360 foreach ($targetContact as $cid => $donCare) {
1361 $values[$cid] = array(
1362 'relatedContacts' => array($contact => 1),
1363 'relationshipTypeId' => $relTypeId,
1366 $relTypeParams = array('id' => $relTypeId);
1367 $relTypeValues = array();
1368 CRM_Contact_BAO_RelationshipType
::retrieve($relTypeParams, $relTypeValues);
1370 if (CRM_Utils_Array
::value('name_a_b', $relTypeValues) == CRM_Utils_Array
::value('name_b_a', $relTypeValues)) {
1371 $values[$cid]['relationshipTypeDirection'] = '_a_b';
1374 $values[$cid]['relationshipTypeDirection'] = ($relDirection == '_a_b') ?
'_b_a' : '_a_b';
1379 // Now get the active memberships for all the contacts.
1380 // If contact have any valid membership(s), then add it to
1382 foreach ($values as $cid => $subValues) {
1383 $memParams = array('contact_id' => $cid);
1384 $memberships = array();
1386 CRM_Member_BAO_Membership
::getValues($memParams, $memberships, $active);
1388 if (empty($memberships)) {
1392 $values[$cid]['memberships'] = $memberships;
1394 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1396 // done with 'values' array.
1397 // Finally add / edit / delete memberships for the related contacts
1398 foreach ($values as $cid => $details) {
1399 if (!array_key_exists('memberships', $details)) {
1403 $mainRelatedContactId = key(CRM_Utils_Array
::value('relatedContacts', $details, array()));
1405 foreach ($details['memberships'] as $membershipId => $membershipValues) {
1406 $relTypeIds = array();
1407 if ($action & CRM_Core_Action
::DELETE
) {
1408 // Delete memberships of the related contacts only if relationship type exists for membership type
1410 SELECT relationship_type_id, relationship_direction
1411 FROM civicrm_membership_type
1412 WHERE id = {$membershipValues['membership_type_id']}";
1413 $dao = CRM_Core_DAO
::executeQuery($query);
1414 $relTypeDirs = array();
1415 while ($dao->fetch()) {
1416 $relTypeId = $dao->relationship_type_id
;
1417 $relDirection = $dao->relationship_direction
;
1419 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $relTypeId);
1420 if (in_array($values[$cid]['relationshipTypeId'], $relTypeIds)) {
1421 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $mainRelatedContactId);
1425 if (($action & CRM_Core_Action
::UPDATE
) &&
1426 ($status & self
::PAST
) &&
1427 ($membershipValues['owner_membership_id'])
1429 // If relationship is PAST and action is UPDATE
1430 // then delete the RELATED membership
1431 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipValues['owner_membership_id'],
1432 $membershipValues['membership_contact_id']
1437 // add / edit the memberships for related
1440 // Get the Membership Type Details.
1441 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipValues['membership_type_id']);
1442 // Check if contact's relationship type exists in membership type
1443 $relTypeDirs = array();
1444 if (!empty($membershipType['relationship_type_id'])) {
1445 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_type_id']);
1447 if (!empty($membershipType['relationship_direction'])) {
1448 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_direction']);
1450 foreach ($relTypeIds as $key => $value) {
1451 $relTypeDirs[] = $value . '_' . $relDirections[$key];
1453 $relTypeDir = $details['relationshipTypeId'] . $details['relationshipTypeDirection'];
1454 if (in_array($relTypeDir, $relTypeDirs)) {
1455 // Check if relationship being created/updated is
1456 // similar to that of membership type's
1459 $membershipValues['owner_membership_id'] = $membershipId;
1460 unset($membershipValues['id']);
1461 unset($membershipValues['membership_contact_id']);
1462 unset($membershipValues['contact_id']);
1463 unset($membershipValues['membership_id']);
1464 foreach ($details['relatedContacts'] as $relatedContactId => $donCare) {
1465 $membershipValues['contact_id'] = $relatedContactId;
1466 if ($deceasedStatusId &&
1467 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $relatedContactId, 'is_deceased')
1469 $membershipValues['status_id'] = $deceasedStatusId;
1470 $membershipValues['skipStatusCal'] = TRUE;
1477 if (!empty($membershipValues[$dateField])) {
1478 $membershipValues[$dateField] = CRM_Utils_Date
::processDate($membershipValues[$dateField]);
1482 if ($action & CRM_Core_Action
::UPDATE
) {
1483 //delete the membership record for related
1484 //contact before creating new membership record.
1485 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $relatedContactId);
1488 // check whether we have some related memberships still available
1491 FROM civicrm_membership
1492 LEFT JOIN civicrm_membership_status ON (civicrm_membership_status.id = civicrm_membership.status_id)
1493 WHERE membership_type_id = {$membershipValues['membership_type_id']} AND owner_membership_id = {$membershipValues['owner_membership_id']}
1494 AND is_current_member = 1";
1495 $result = CRM_Core_DAO
::singleValueQuery($query);
1496 if ($result < CRM_Utils_Array
::value('max_related', $membershipValues, PHP_INT_MAX
)) {
1497 CRM_Member_BAO_Membership
::create($membershipValues, CRM_Core_DAO
::$_nullArray);
1501 elseif ($action & CRM_Core_Action
::UPDATE
) {
1502 // if action is update and updated relationship do
1503 // not match with the existing
1504 // membership=>relationship then we need to
1505 // delete the membership record created for
1506 // previous relationship.
1508 if (self
::isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, CRM_Utils_Array
::value('relationship_ids', $params))) {
1509 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $mainRelatedContactId);
1517 * Helper function to check whether to delete the membership or
1522 public static function isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, $relIds) {
1523 if (in_array($relTypeId, $relTypeIds)) {
1527 if (empty($relIds)) {
1531 $relParamas = array(
1532 1 => array($contactId, 'Integer'),
1533 2 => array($mainRelatedContactId, 'Integer'),
1536 if ($contactId == $mainRelatedContactId) {
1537 $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);
1538 if ($recordsFound) {
1544 $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);
1546 if ($recordsFound) {
1554 * Get Current Employer for Contact
1556 * @param $contactIds
1560 * array of the current employer
1563 public static function getCurrentEmployer($contactIds) {
1564 $contacts = implode(',', $contactIds);
1567 SELECT organization_name, id, employer_id
1568 FROM civicrm_contact
1569 WHERE id IN ( {$contacts} )
1572 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1573 $currentEmployer = array();
1574 while ($dao->fetch()) {
1575 $currentEmployer[$dao->id
]['org_id'] = $dao->employer_id
;
1576 $currentEmployer[$dao->id
]['org_name'] = $dao->organization_name
;
1579 return $currentEmployer;
1583 * Return list of permissioned employer for a given contact.
1585 * @param int $contactID
1586 * contact id whose employers.
1588 * @param string $name
1589 * employers sort name.
1594 * array of employers.
1596 public static function getPermissionedEmployer($contactID, $name = NULL) {
1597 //get the relationship id
1598 $relTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType',
1599 'Employee of', 'id', 'name_a_b'
1602 return self
::getPermissionedContacts($contactID, $relTypeId, $name);
1607 * Function to return list of permissioned contacts for a given contact and relationship type
1609 * @param int $contactID
1610 * contact id whose permissioned contacts are to be found.
1611 * @param string $relTypeId
1612 * one or more relationship type id's.
1613 * @param string $name
1620 public static function getPermissionedContacts($contactID, $relTypeId, $name = NULL) {
1621 $contacts = array();
1625 SELECT cc.id as id, cc.sort_name as name
1626 FROM civicrm_relationship cr, civicrm_contact cc
1628 cr.contact_id_a = %1 AND
1629 cr.relationship_type_id IN (%2) AND
1630 cr.is_permission_a_b = 1 AND
1631 IF(cr.end_date IS NULL, 1, (DATEDIFF( CURDATE( ), cr.end_date ) <= 0)) AND
1632 cr.is_active = 1 AND
1633 cc.id = cr.contact_id_b AND
1636 if (!empty($name)) {
1637 $name = CRM_Utils_Type
::escape($name, 'String');
1639 AND cc.sort_name LIKE '%$name%'";
1642 $args = array(1 => array($contactID, 'Integer'), 2 => array($relTypeId, 'String'));
1643 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1645 while ($dao->fetch()) {
1646 $contacts[$dao->id
] = array(
1647 'name' => $dao->name
,
1648 'value' => $dao->id
,
1656 * Merge relationships from otherContact to mainContact
1657 * Called during contact merge operation
1659 * @param int $mainId
1660 * Contact id of main contact record.
1661 * @param int $otherId
1662 * Contact id of record which is going to merge.
1663 * @param array $sqls
1664 * (reference) array of sql statements to append to.
1666 * @see CRM_Dedupe_Merger::cpTables()
1670 public static function mergeRelationships($mainId, $otherId, &$sqls) {
1671 // Delete circular relationships
1672 $sqls[] = "DELETE FROM civicrm_relationship
1673 WHERE (contact_id_a = $mainId AND contact_id_b = $otherId)
1674 OR (contact_id_b = $mainId AND contact_id_a = $otherId)";
1676 // Delete relationship from other contact if main contact already has that relationship
1677 $sqls[] = "DELETE r2
1678 FROM civicrm_relationship r1, civicrm_relationship r2
1679 WHERE r1.relationship_type_id = r2.relationship_type_id
1682 r1.contact_id_a = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_b = r2.contact_id_b
1683 OR r1.contact_id_b = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_a = r2.contact_id_a
1685 (r1.contact_id_a = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_b = r2.contact_id_a
1686 OR r1.contact_id_b = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_a = r2.contact_id_b)
1687 AND r1.relationship_type_id IN (SELECT id FROM civicrm_relationship_type WHERE name_b_a = name_a_b)
1691 // Move relationships
1692 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_a = $mainId WHERE contact_id_a = $otherId";
1693 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_b = $mainId WHERE contact_id_b = $otherId";
1695 // Move current employer id (name will get updated later)
1696 $sqls[] = "UPDATE civicrm_contact SET employer_id = $mainId WHERE employer_id = $otherId";
1700 * Set 'is_valid' field to false for all relationships whose end date is in the past, ie. are expired.
1702 * @return True on success, false if error is encountered.
1704 public static function disableExpiredRelationships() {
1705 $query = "SELECT id FROM civicrm_relationship WHERE is_active = 1 AND end_date < CURDATE()";
1707 $dao = CRM_Core_DAO
::executeQuery($query);
1708 while ($dao->fetch()) {
1709 $result = CRM_Contact_BAO_Relationship
::setIsActive($dao->id
, FALSE);
1710 // Result will be NULL if error occurred. We abort early if error detected.
1711 if ($result == NULL) {
1719 * Function filters the query by possible relationships for the membership type
1720 * It is intended to be called when constructing queries for the api (reciprocal & non-reciprocal)
1721 * and to add clauses to limit the return to those relationships which COULD inherit a membership type
1722 * (as opposed to those who inherit a particular membership
1724 * @param array $params
1726 * @param null $direction
1730 public static function membershipTypeToRelationshipTypes(&$params, $direction = NULL) {
1731 $membershipType = civicrm_api3('membership_type', 'getsingle', array(
1732 'id' => $params['membership_type_id'],
1733 'return' => 'relationship_type_id, relationship_direction',
1735 $relationshipTypes = $membershipType['relationship_type_id'];
1736 if (empty($relationshipTypes)) {
1739 // if we don't have any contact data we can only filter on type
1740 if (empty($params['contact_id']) && empty($params['contact_id_a']) && empty($params['contact_id_a'])) {
1741 $params['relationship_type_id'] = array('IN' => $relationshipTypes);
1745 $relationshipDirections = (array) $membershipType['relationship_direction'];
1746 // if we have contact_id_a OR contact_id_b we can make a call here
1747 // if we have contact??
1748 foreach ($relationshipDirections as $index => $mtdirection) {
1749 if (isset($params['contact_id_a']) && $mtdirection == 'a_b' ||
$direction == 'a_b') {
1750 $types[] = $relationshipTypes[$index];
1752 if (isset($params['contact_id_b']) && $mtdirection == 'b_a' ||
$direction == 'b_a') {
1753 $types[] = $relationshipTypes[$index];
1756 if (!empty($types)) {
1757 $params['relationship_type_id'] = array('IN' => $types);
1759 elseif (!empty($clauses)) {
1760 return explode(' OR ', $clauses);
1763 // effectively setting it to return no results
1764 $params['relationship_type_id'] = 0;
1771 * wrapper for contact relationship selector
1773 * @param array $params
1774 * Associated array for params record id.
1777 * associated array of contact relationships
1779 public static function getContactRelationshipSelector(&$params) {
1780 // format the params
1781 $params['offset'] = ($params['page'] - 1) * $params['rp'];
1782 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
1784 if ($params['context'] == 'past') {
1785 $relationshipStatus = CRM_Contact_BAO_Relationship
::INACTIVE
;
1788 $relationshipStatus = CRM_Contact_BAO_Relationship
::CURRENT
;
1791 // check logged in user for permission
1792 $page = new CRM_Core_Page();
1793 CRM_Contact_Page_View
::checkUserPermission($page, $params['contact_id']);
1794 $permissions = array($page->_permission
);
1795 if ($page->_permission
== CRM_Core_Permission
::EDIT
) {
1796 $permissions[] = CRM_Core_Permission
::DELETE
;
1798 $mask = CRM_Core_Action
::mask($permissions);
1800 if ($params['context'] != 'user') {
1801 $links = CRM_Contact_Page_View_Relationship
::links();
1802 $permissionedContacts = FALSE;
1805 $links = CRM_Contact_Page_View_UserDashBoard
::links();
1806 $permissionedContacts = TRUE;
1809 // get contact relationships
1810 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1811 $relationshipStatus,
1812 $params['rp'], 0, 0,
1814 $permissionedContacts,
1818 $contactRelationships = array();
1819 $params['total'] = 0;
1820 if (!empty($relationships)) {
1821 // get the total relationships
1822 if ($params['context'] != 'user') {
1823 $params['total'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1824 $relationshipStatus, 0, 1, 0, NULL, NULL, $permissionedContacts);
1827 // FIX ME: we cannot directly determine total permissioned relationship, hence re-fire query
1828 $permissionedRelationships = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1829 $relationshipStatus,
1833 $params['total'] = count($permissionedRelationships);
1837 foreach ($relationships as $relationshipId => $values) {
1838 //Add image icon for related contacts: CRM-14919
1839 $icon = CRM_Contact_BAO_Contact_Utils
::getImage($values['contact_type'],
1843 $contactRelationships[$relationshipId]['name'] = $icon . ' ' . CRM_Utils_System
::href(
1845 'civicrm/contact/view',
1846 "reset=1&cid={$values['cid']}");
1848 $contactRelationships[$relationshipId]['relation'] = CRM_Utils_System
::href(
1849 $values['relation'],
1850 'civicrm/contact/view/rel',
1851 "action=view&reset=1&cid={$values['cid']}&id={$values['id']}&rtype={$values['rtype']}");
1853 if ($params['context'] == 'current') {
1854 if (($params['contact_id'] == $values['contact_id_a'] AND $values['is_permission_a_b'] == 1) OR
1855 ($params['contact_id'] == $values['contact_id_b'] AND $values['is_permission_b_a'] == 1)
1857 $contactRelationships[$relationshipId]['name'] .= '<span id="permission-a-b" class="crm-marker permission-relationship"> *</span>';
1860 if (($values['cid'] == $values['contact_id_a'] AND $values['is_permission_a_b'] == 1) OR
1861 ($values['cid'] == $values['contact_id_b'] AND $values['is_permission_b_a'] == 1)
1863 $contactRelationships[$relationshipId]['relation'] .= '<span id="permission-b-a" class="crm-marker permission-relationship"> *</span>';
1867 if (!empty($values['description'])) {
1868 $contactRelationships[$relationshipId]['relation'] .= "<p class='description'>{$values['description']}</p>";
1871 $contactRelationships[$relationshipId]['start_date'] = CRM_Utils_Date
::customFormat($values['start_date']);
1872 $contactRelationships[$relationshipId]['end_date'] = CRM_Utils_Date
::customFormat($values['end_date']);
1873 $contactRelationships[$relationshipId]['city'] = $values['city'];
1874 $contactRelationships[$relationshipId]['state'] = $values['state'];
1875 $contactRelationships[$relationshipId]['email'] = $values['email'];
1876 $contactRelationships[$relationshipId]['phone'] = $values['phone'];
1877 $contactRelationships[$relationshipId]['links'] = $values['action'];
1878 $contactRelationships[$relationshipId]['id'] = $values['id'];
1879 $contactRelationships[$relationshipId]['is_active'] = $values['is_active'];
1882 return $contactRelationships;