3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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 * takes an associative array and creates a relationship object
48 * @param array $params (reference ) an assoc array of name/value pairs
49 * @param array $ids the array that holds all the db ids
50 * per http://wiki.civicrm.org/confluence/display/CRM/Database+layer
51 * "we are moving away from the $ids param "
53 * @return object CRM_Contact_BAO_Relationship object
57 static function create(&$params, $ids = array()) {
58 $valid = $invalid = $duplicate = $saved = 0;
59 $relationships = array();
60 $relationshipId = CRM_Utils_Array
::value('relationship', $ids, CRM_Utils_Array
::value('id', $params));
61 //CRM-9015 - the hooks are called here & in add (since add doesn't call create)
62 // but in future should be tidied per ticket
63 if(empty($relationshipId)){
65 $action = CRM_Core_Action
::ADD
;
69 $action = CRM_Core_Action
::UPDATE
;
72 CRM_Utils_Hook
::pre($hook, 'Relationship', $relationshipId, $params);
74 if (!$relationshipId) {
75 // creating a new relationship
76 $dataExists = self
::dataExists($params);
78 return array(FALSE, TRUE, FALSE, FALSE, NULL);
80 $relationshipIds = array();
81 foreach ($params['contact_check'] as $key => $value) {
83 // check if the relationship is valid between contacts.
84 // step 1: check if the relationship is valid if not valid skip and keep the count
85 // step 2: check the if two contacts already have a relationship if yes skip and keep the count
86 // step 3: if valid relationship then add the relation and keep the count
89 $errors = self
::checkValidRelationship($params, $ids, $key);
96 self
::checkDuplicateRelationship(
98 CRM_Utils_Array
::value('contact', $ids),
107 $relationship = self
::add($params, $ids, $key);
108 $relationshipIds[] = $relationship->id
;
109 $relationships[$relationship->id
] = $relationship;
112 // editing the relationship
115 // check for duplicate relationship
118 self
::checkDuplicateRelationship(
120 CRM_Utils_Array
::value('contact', $ids),
121 $ids['contactTarget'],
126 return array($valid, $invalid, $duplicate, $saved, NULL);
129 $validContacts = TRUE;
130 //validate contacts in update mode also.
131 if (CRM_Utils_Array
::value('contact', $ids) &&
132 CRM_Utils_Array
::value('contactTarget', $ids)
134 if (self
::checkValidRelationship($params, $ids, $ids['contactTarget'])) {
135 $validContacts = FALSE;
139 if ($validContacts) {
140 // editing an existing relationship
141 $relationship = self
::add($params, $ids, $ids['contactTarget']);
142 $relationshipIds[] = $relationship->id
;
143 $relationships[$relationship->id
] = $relationship;
148 // do not add to recent items for import, CRM-4399
149 if (!(CRM_Utils_Array
::value('skipRecentView', $params) ||
$invalid ||
$duplicate)) {
150 $url = CRM_Utils_System
::url('civicrm/contact/view/rel',
151 "action=view&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&context=home"
155 $session = CRM_Core_Session
::singleton();
156 $recentOther = array();
157 if (($session->get('userID') == $relationship->contact_id_a
) ||
158 CRM_Contact_BAO_Contact_Permission
::allow($relationship->contact_id_a
, CRM_Core_Permission
::EDIT
)
160 $rType = substr(CRM_Utils_Array
::value('relationship_type_id', $params), -3);
161 $recentOther = array(
162 'editUrl' => CRM_Utils_System
::url('civicrm/contact/view/rel',
163 "action=update&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
165 'deleteUrl' => CRM_Utils_System
::url('civicrm/contact/view/rel',
166 "action=delete&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
171 $title = CRM_Contact_BAO_Contact
::displayName($relationship->contact_id_a
) . ' (' . CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType',
172 $relationship->relationship_type_id
, 'label_a_b'
173 ) . ' ' . CRM_Contact_BAO_Contact
::displayName($relationship->contact_id_b
) . ')';
174 // add the recently created Relationship
175 CRM_Utils_Recent
::add($title,
179 $relationship->contact_id_a
,
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 (reference ) an assoc array of name/value pairs
192 * @param integer $contactId this is contact id for adding relationship
193 * @param array $ids the array that holds all the db ids
195 * @return object CRM_Contact_BAO_Relationship
199 static function add(&$params, &$ids, $contactId) {
200 if (CRM_Utils_Array
::value('relationship', $ids)) {
201 CRM_Utils_Hook
::pre('edit', 'Relationship', $ids['relationship'], $params);
204 CRM_Utils_Hook
::pre('create', 'Relationship', NULL, $params);
207 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
209 // expolode the string with _ to get the relationship type id and to know which contact has to be inserted in
210 // contact_id_a and which one in contact_id_b
211 list($type, $first, $second) = explode('_', $relationshipTypes);
213 $
{'contact_' . $first} = CRM_Utils_Array
::value('contact', $ids);
214 $
{'contact_' . $second} = $contactId;
216 //check if the relationship type is Head of Household then update the household's primary contact with this contact.
218 CRM_Contact_BAO_Household
::updatePrimaryContact($contact_b, $contact_a);
221 $relationship = new CRM_Contact_BAO_Relationship();
222 $relationship->contact_id_b
= $contact_b;
223 $relationship->contact_id_a
= $contact_a;
224 $relationship->relationship_type_id
= $type;
225 $relationship->id
= CRM_Utils_Array
::value('relationship', $ids);
227 $dateFields = array('end_date', 'start_date');
229 foreach (self
::getdefaults() as $defaultField => $defaultValue){
230 if(isset($params[$defaultField])){
231 if(in_array($defaultField, $dateFields)){
232 $relationship->$defaultField = CRM_Utils_Date
::format(CRM_Utils_Array
::value($defaultField, $params));
233 if(!$relationship->$defaultField){
234 $relationship->$defaultField = 'NULL';
238 $relationship->$defaultField = $params[$defaultField];
241 elseif(empty($relationship->id
)){
242 $relationship->$defaultField = $defaultValue;
246 $relationship->save();
248 // add custom field values
249 if (CRM_Utils_Array
::value('custom', $params)) {
250 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_relationship', $relationship->id
);
253 $relationship->free();
255 if (CRM_Utils_Array
::value('relationship', $ids)) {
256 CRM_Utils_Hook
::post('edit', 'Relationship', $relationship->id
, $relationship);
259 CRM_Utils_Hook
::post('create', 'Relationship', $relationship->id
, $relationship);
262 return $relationship;
265 * Specifiy defaults for creating a relationship
267 * @return array $defaults array of defaults for creating relationship
271 static function getdefaults() {
274 'is_permission_a_b' => 0,
275 'is_permission_b_a' => 0,
277 'start_date' => 'NULL',
279 'end_date' => 'NULL',
285 * Check if there is data to create the object
287 * @param array $params (reference ) an assoc array of name/value pairs
293 static function dataExists(&$params) {
294 // return if no data present
295 if (!is_array(CRM_Utils_Array
::value('contact_check', $params))) {
302 * Function to get get list of relationship type based on the contact type.
304 * @param int $contactId this is the contact id of the current contact.
305 * @param string $strContact this value is currently ignored, keeping it there for legacy reasons
306 * @param string $relationshipId the id of the existing relationship if any
307 * @param string $contactType contact type
308 * @param boolean $all if true returns relationship types in both the direction
309 * @param string $column name/label that going to retrieve from db.
312 * @param string $contactSubType includes relationshiptypes between this subtype
314 * @param boolean $onlySubTypeRelationTypes if set only subtype which is passed by $contactSubType
315 * related relationshiptypes get return
319 * @return array - array reference of all relationship types with context to current contact.
321 static function getContactRelationshipType($contactId = NULL,
322 $contactSuffix = NULL,
323 $relationshipId = NULL,
327 $biDirectional = TRUE,
328 $contactSubType = NULL,
329 $onlySubTypeRelationTypes = FALSE
331 $allRelationshipType = array();
332 $relationshipType = array();
333 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType($column);
335 $otherContactType = NULL;
336 if ($relationshipId) {
337 $relationship = new CRM_Contact_DAO_Relationship();
338 $relationship->id
= $relationshipId;
339 if ($relationship->find(TRUE)) {
340 $contact = new CRM_Contact_DAO_Contact();
341 $contact->id
= ($relationship->contact_id_a
=== $contactId) ?
$relationship->contact_id_b
: $relationship->contact_id_a
;
343 if ($contact->find(TRUE)) {
344 $otherContactType = $contact->contact_type
;
345 //CRM-5125 for contact subtype specific relationshiptypes
346 if ($contact->contact_sub_type
) {
347 $otherContactSubType = $contact->contact_sub_type
;
353 $contactSubType = array();
355 $contactType = CRM_Contact_BAO_Contact
::getContactType($contactId);
356 $contactSubType = CRM_Contact_BAO_Contact
::getContactSubType($contactId);
359 foreach ($allRelationshipType as $key => $value) {
360 // the contact type is required or matches
361 if (((!$value['contact_type_a']) ||
362 $value['contact_type_a'] == $contactType
364 // the other contact type is required or present or matches
365 ((!$value['contact_type_b']) ||
366 (!$otherContactType) ||
367 $value['contact_type_b'] == $otherContactType
370 (in_array($value['contact_sub_type_a'], $contactSubType) ||
371 ((!$value['contact_sub_type_b'] &&
372 !$value['contact_sub_type_a']
374 !$onlySubTypeRelationTypes
379 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
381 elseif (empty($value['contact_type_b'])) {
382 // case contact_type_b is "all contacts", CRM-9877
383 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
386 if (((!$value['contact_type_b']) ||
387 $value['contact_type_b'] == $contactType
389 ((!$value['contact_type_a']) ||
390 (!$otherContactType) ||
391 $value['contact_type_a'] == $otherContactType
394 (in_array($value['contact_sub_type_b'], $contactSubType) ||
395 ((!$value['contact_sub_type_a'] &&
396 !$value['contact_sub_type_b']
398 !$onlySubTypeRelationTypes
403 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
405 elseif (empty($value['contact_type_a'])) {
406 // case contact_type_a is "all contacts", CRM-9877
407 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
411 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
412 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
416 if ($biDirectional) {
417 // lets clean up the data and eliminate all duplicate values
418 // (i.e. the relationship is bi-directional)
419 $relationshipType = array_unique($relationshipType);
422 // sort the relationshipType in ascending order CRM-7736
423 asort($relationshipType);
424 return $relationshipType;
427 static function clearCurrentEmployer($id, $action) {
428 $relationship = new CRM_Contact_DAO_Relationship();
429 $relationship->id
= $id;
430 $relationship->find(TRUE);
432 //to delete relationship between household and individual \
433 //or between individual and orgnization
434 if (($action & CRM_Core_Action
::DISABLE
) ||
($action & CRM_Core_Action
::DELETE
)) {
435 if ($relationship->relationship_type_id
== 4 ||
$relationship->relationship_type_id
== 7) {
436 $sharedContact = new CRM_Contact_DAO_Contact();
437 $sharedContact->id
= $relationship->contact_id_a
;
438 $sharedContact->find(TRUE);
440 if ($relationship->relationship_type_id
== 4 && $relationship->contact_id_b
== $sharedContact->employer_id
) {
441 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($relationship->contact_id_a
);
445 return $relationship;
449 * Function to delete the relationship
451 * @param int $id relationship id
458 static function del($id) {
459 // delete from relationship table
460 CRM_Utils_Hook
::pre('delete', 'Relationship', $id, CRM_Core_DAO
::$_nullArray);
462 $relationship = self
::clearCurrentEmployer($id, CRM_Core_Action
::DELETE
);
463 if (CRM_Core_Permission
::access('CiviMember')) {
464 // create $params array which isrequired to delete memberships
465 // of the related contacts.
467 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
468 'contact_check' => array($relationship->contact_id_b
=> 1),
472 // calling relatedMemberships to delete the memberships of
474 self
::relatedMemberships($relationship->contact_id_a
,
477 CRM_Core_Action
::DELETE
,
482 $relationship->delete();
483 CRM_Core_Session
::setStatus(ts('Selected relationship has been deleted successfully.'), ts('Record Deleted'), 'success');
485 CRM_Utils_Hook
::post('delete', 'Relationship', $relationship->id
, $relationship);
487 // delete the recently created Relationship
488 $relationshipRecent = array(
490 'type' => 'Relationship',
492 CRM_Utils_Recent
::del($relationshipRecent);
494 return $relationship;
498 * Function to disable/enable the relationship
500 * @param int $id relationship id
507 static function disableEnableRelationship($id, $action) {
508 $relationship = self
::clearCurrentEmployer($id, $action);
509 if (CRM_Core_Permission
::access('CiviMember')) {
510 // create $params array which isrequired to delete memberships
511 // of the related contacts.
513 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
514 'contact_check' => array($relationship->contact_id_b
=> 1),
518 // calling relatedMemberships to delete/add the memberships of
520 if ($action & CRM_Core_Action
::DISABLE
) {
521 CRM_Contact_BAO_Relationship
::relatedMemberships($relationship->contact_id_a
,
524 CRM_Core_Action
::DELETE
,
528 elseif ($action & CRM_Core_Action
::ENABLE
) {
529 $ids['contact'] = $relationship->contact_id_a
;
530 CRM_Contact_BAO_Relationship
::relatedMemberships($relationship->contact_id_a
,
533 CRM_Core_Action
::ADD
,
541 * Delete the object records that are associated with this contact
543 * @param int $contactId id of the contact to delete
549 static function deleteContact($contactId) {
550 $relationship = new CRM_Contact_DAO_Relationship();
551 $relationship->contact_id_a
= $contactId;
552 $relationship->delete();
554 $relationship = new CRM_Contact_DAO_Relationship();
555 $relationship->contact_id_b
= $contactId;
556 $relationship->delete();
558 CRM_Contact_BAO_Household
::updatePrimaryContact(NULL, $contactId);
562 * Function to get the other contact in a relationship
564 * @param int $id relationship id
566 * $returns returns the contact ids in the realtionship
570 static function getContactIds($id) {
571 $relationship = new CRM_Contact_DAO_Relationship();
573 $relationship->id
= $id;
574 $relationship->selectAdd();
575 $relationship->selectAdd('contact_id_a, contact_id_b');
576 $relationship->find(TRUE);
578 return $relationship;
582 * Function to check if the relationship type selected between two contacts is correct
584 * @param int $contact_a 1st contact id
585 * @param int $contact_b 2nd contact id
586 * @param int $relationshipTypeId relationship type id
588 * @return boolean true if it is valid relationship else false
592 static function checkRelationshipType($contact_a, $contact_b, $relationshipTypeId) {
593 $relationshipType = new CRM_Contact_DAO_RelationshipType();
594 $relationshipType->id
= $relationshipTypeId;
595 $relationshipType->selectAdd();
596 $relationshipType->selectAdd('contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b');
597 if ($relationshipType->find(TRUE)) {
598 $contact_type_a = CRM_Contact_BAO_Contact
::getContactType($contact_a);
599 $contact_type_b = CRM_Contact_BAO_Contact
::getContactType($contact_b);
601 $contact_sub_type_a = CRM_Contact_BAO_Contact
::getContactSubType($contact_a);
602 $contact_sub_type_b = CRM_Contact_BAO_Contact
::getContactSubType($contact_b);
604 if (((!$relationshipType->contact_type_a
) ||
($relationshipType->contact_type_a
== $contact_type_a)) &&
605 ((!$relationshipType->contact_type_b
) ||
($relationshipType->contact_type_b
== $contact_type_b)) &&
606 ((!$relationshipType->contact_sub_type_a
) ||
(in_array($relationshipType->contact_sub_type_a
,
609 ((!$relationshipType->contact_sub_type_b
) ||
(in_array($relationshipType->contact_sub_type_b
,
623 * this function does the validtion for valid relationship
625 * @param array $params this array contains the values there are subitted by the form
626 * @param array $ids the array that holds all the db ids
627 * @param integer $contactId this is contact id for adding relationship
633 static function checkValidRelationship(&$params, &$ids, $contactId) {
636 // get the string of relationship type
637 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
638 list($type, $first, $second) = explode('_', $relationshipTypes);
639 $
{'contact_' . $first} = CRM_Utils_Array
::value('contact', $ids);
640 $
{'contact_' . $second} = $contactId;
641 // function to check if the relationship selected is correct
642 // i.e. employer relationship can exit between Individual and Organization (not between Individual and Individual)
643 if (!CRM_Contact_BAO_Relationship
::checkRelationshipType($contact_a, $contact_b, $type)) {
644 $errors = 'Please select valid relationship between these two contacts.';
650 * this function checks for duplicate relationship
652 * @param array $params (reference ) an assoc array of name/value pairs
653 * @param integer $id this the id of the contact whom we are adding relationship
654 * @param integer $contactId this is contact id for adding relationship
655 * @param integer $relationshipId this is relationship id for the contact
657 * @return boolean true if record exists else false
661 static function checkDuplicateRelationship(&$params, $id, $contactId = 0, $relationshipId = 0) {
662 $relationshipTypeId = CRM_Utils_Array
::value('relationship_type_id', $params);
663 list($type, $first, $second) = explode('_', $relationshipTypeId);
665 $queryString = " SELECT id
666 FROM civicrm_relationship
667 WHERE relationship_type_id = " . CRM_Utils_Type
::escape($type, 'Integer');
670 * CRM-11792 - date fields from API are in ISO format, but this function supports date arrays
671 * BAO has increasingly standardised to ISO format so I believe this function should support
672 * ISO rather than make API format it - however, need to support array format for now to avoid breakage
673 * @ time of writing this function is called from Relationship::create (twice)
674 * CRM_BAO_Contact_Utils::clearCurrentEmployer (seemingly without dates)
675 * CRM_Contact_Form_Task_AddToOrganization::postProcess &
676 * CRM_Contact_Form_Task_AddToHousehold::postProcess
677 * (I don't think the last 2 support dates but not sure
680 $dateFields = array('end_date', 'start_date');
681 foreach ($dateFields as $dateField){
682 if(array_key_exists($dateField, $params)) {
683 if (empty($params[$dateField]) ||
$params[$dateField] == 'null'){
684 //this is most likely coming from an api call & probably loaded from the DB to deal with some of the
685 //other myriad of excessive checks still in place both in the api & the create functions
686 $queryString .= " AND $dateField IS NULL";
689 elseif (is_array($params[$dateField])){
690 $queryString .= " AND $dateField = " . CRM_Utils_Type
::escape(CRM_Utils_Date
::format($params[$dateField]), 'Date');
693 $queryString .= " AND $dateField = " . CRM_Utils_Type
::escape($params[$dateField], 'Date');
699 " AND ( ( contact_id_a = " . CRM_Utils_Type
::escape($id, 'Integer') .
700 " AND contact_id_b = " . CRM_Utils_Type
::escape($contactId, 'Integer') .
701 " ) OR ( contact_id_a = " . CRM_Utils_Type
::escape($contactId, 'Integer') .
702 " AND contact_id_b = " . CRM_Utils_Type
::escape($id, 'Integer') . " ) ) ";
704 //if caseId is provided, include it duplicate checking.
705 if ($caseId = CRM_Utils_Array
::value('case_id', $params)) {
706 $queryString .= " AND case_id = " . CRM_Utils_Type
::escape($caseId, 'Integer');
709 if ($relationshipId) {
710 $queryString .= " AND id !=" . CRM_Utils_Type
::escape($relationshipId, 'Integer');
713 $relationship = new CRM_Contact_BAO_Relationship();
714 $relationship->query($queryString);
715 $relationship->fetch();
716 $relationship->free();
717 return ($relationship->id
) ?
TRUE : FALSE;
721 * update the is_active flag in the db
723 * @param int $id id of the database record
724 * @param boolean $is_active value we want to set the is_active field
726 * @return Object DAO object on success, null otherwise
729 static function setIsActive($id, $is_active) {
730 CRM_Core_DAO
::setFieldValue('CRM_Contact_DAO_Relationship', $id, 'is_active', $is_active);
733 CRM_Utils_Hook
::enableDisable('CRM_Contact_BAO_Relationship', $id, $is_active);
739 * Given the list of params in the params array, fetch the object
740 * and store the values in the values array
742 * @param array $params input parameters to find object
743 * @param array $values output values of the object
744 * @param array $ids the array that holds all the db ids
746 * @return array (reference) the values that could be potentially assigned to smarty
750 static function &getValues(&$params, &$values) {
751 if (empty($params)) {
756 // get the specific number of relationship or all relationships.
757 if (CRM_Utils_Array
::value('numRelationship', $params)) {
758 $v['data'] = &CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'], NULL, $params['numRelationship']);
761 $v['data'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id']);
764 // get the total count of relationships
765 $v['totalCount'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'], NULL, NULL, TRUE);
767 $values['relationship']['data'] = &$v['data'];
768 $values['relationship']['totalCount'] = &$v['totalCount'];
774 * helper function to form the sql for relationship retrieval
776 * @param int $contactId contact id
777 * @param int $status (check const at top of file)
778 * @param int $numRelationship no of relationships to display (limit)
779 * @param int $count get the no of relationships
780 * $param int $relationshipId relationship id
781 * @param string $direction the direction we are interested in a_b or b_a
782 * @param array $params array of extra values including relationship_type_id per api spec
784 * return string the query for this diretion
788 static function makeURLClause($contactId, $status, $numRelationship, $count, $relationshipId, $direction, $params = array()) {
789 $select = $from = $where = '';
793 if ($direction == 'a_b') {
794 $select .= ' SELECT count(DISTINCT civicrm_relationship.id) as cnt1, 0 as cnt2 ';
797 $select .= ' SELECT 0 as cnt1, count(DISTINCT civicrm_relationship.id) as cnt2 ';
801 $select .= ' SELECT civicrm_relationship.id as civicrm_relationship_id,
802 civicrm_contact.sort_name as sort_name,
803 civicrm_contact.display_name as display_name,
804 civicrm_contact.job_title as job_title,
805 civicrm_contact.employer_id as employer_id,
806 civicrm_contact.organization_name as organization_name,
807 civicrm_address.street_address as street_address,
808 civicrm_address.city as city,
809 civicrm_address.postal_code as postal_code,
810 civicrm_state_province.abbreviation as state,
811 civicrm_country.name as country,
812 civicrm_email.email as email,
813 civicrm_phone.phone as phone,
814 civicrm_contact.id as civicrm_contact_id,
815 civicrm_contact.contact_type as contact_type,
816 civicrm_relationship.contact_id_b as contact_id_b,
817 civicrm_relationship.contact_id_a as contact_id_a,
818 civicrm_relationship_type.id as civicrm_relationship_type_id,
819 civicrm_relationship.start_date as start_date,
820 civicrm_relationship.end_date as end_date,
821 civicrm_relationship.description as description,
822 civicrm_relationship.is_active as is_active,
823 civicrm_relationship.is_permission_a_b as is_permission_a_b,
824 civicrm_relationship.is_permission_b_a as is_permission_b_a,
825 civicrm_relationship.case_id as case_id';
827 if ($direction == 'a_b') {
828 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
829 civicrm_relationship_type.label_b_a as relation ';
832 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
833 civicrm_relationship_type.label_a_b as relation ';
838 FROM civicrm_relationship
839 INNER JOIN civicrm_relationship_type ON ( civicrm_relationship.relationship_type_id = civicrm_relationship_type.id )
840 INNER JOIN civicrm_contact ";
841 if ($direction == 'a_b') {
842 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_a ) ';
845 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_b ) ';
848 LEFT JOIN civicrm_address ON (civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1)
849 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
850 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id AND civicrm_email.is_primary = 1)
851 LEFT JOIN civicrm_state_province ON (civicrm_address.state_province_id = civicrm_state_province.id)
852 LEFT JOIN civicrm_country ON (civicrm_address.country_id = civicrm_country.id)
854 $where = 'WHERE ( 1 )';
856 if ($direction == 'a_b') {
857 $where .= ' AND civicrm_relationship.contact_id_b = ' . CRM_Utils_Type
::escape($contactId, 'Positive');
860 $where .= ' AND civicrm_relationship.contact_id_a = ' . CRM_Utils_Type
::escape($contactId, 'Positive');
863 if ($relationshipId) {
864 $where .= ' AND civicrm_relationship.id = ' . CRM_Utils_Type
::escape($relationshipId, 'Positive');
867 $date = date('Y-m-d');
868 if ($status == self
::PAST
) {
869 //this case for showing past relationship
870 $where .= ' AND civicrm_relationship.is_active = 1 ';
871 $where .= " AND civicrm_relationship.end_date < '" . $date . "'";
873 elseif ($status == self
::DISABLED
) {
874 // this case for showing disabled relationship
875 $where .= ' AND civicrm_relationship.is_active = 0 ';
877 elseif ($status == self
::CURRENT
) {
878 //this case for showing current relationship
879 $where .= ' AND civicrm_relationship.is_active = 1 ';
880 $where .= " AND (civicrm_relationship.end_date >= '" . $date . "' OR civicrm_relationship.end_date IS NULL) ";
882 elseif ($status == self
::INACTIVE
) {
883 //this case for showing inactive relationships
884 $where .= " AND (civicrm_relationship.end_date < '" . $date . "'";
885 $where .= ' OR civicrm_relationship.is_active = 0 )';
889 $where .= ' AND civicrm_contact.is_deleted = 0';
890 if(!empty($params['membership_type_id']) && empty($params['relationship_type_id'])) {
891 $where .= self
::membershipTypeToRelationshipTypes($params, $direction);
893 if(!empty($params['relationship_type_id'])) {
894 if(is_array($params['relationship_type_id'])) {
895 $where .= " AND " . CRM_Core_DAO
::createSQLFilter('relationship_type_id', $params['relationship_type_id'], 'Integer');
898 $where .= ' AND relationship_type_id = ' . CRM_Utils_Type
::escape($params['relationship_type_id'], 'Positive');
901 if ($direction == 'a_b') {
902 $where .= ' ) UNION ';
908 return array($select, $from, $where);
912 * This is the function to get the list of relationships
914 * @param int $contactId contact id
915 * @param int $status 1: Past 2: Disabled 3: Current
916 * @param int $numRelationship no of relationships to display (limit)
917 * @param int $count get the no of relationships
918 * $param int $relationshipId relationship id
919 * $param array $links the list of links to display
920 * $param int $permissionMask the permission mask to be applied for the actions
921 * $param boolean $permissionedContact to return only permissioned Contact
922 * $param array $params array of variables consistent with filters supported by the api
923 * return array $values relationship records
927 static function getRelationship($contactId = NULL,
928 $status = 0, $numRelationship = 0,
929 $count = 0, $relationshipId = 0,
930 $links = NULL, $permissionMask = NULL,
931 $permissionedContact = FALSE,
935 if (!$contactId && !$relationshipId) {
939 list($select1, $from1, $where1) = self
::makeURLClause($contactId, $status, $numRelationship,
940 $count, $relationshipId, 'a_b', $params
942 list($select2, $from2, $where2) = self
::makeURLClause($contactId, $status, $numRelationship,
943 $count, $relationshipId, 'b_a', $params
946 $order = $limit = '';
948 $order = ' ORDER BY civicrm_relationship_type_id, sort_name ';
950 if ($numRelationship) {
951 $limit = " LIMIT 0, $numRelationship";
955 // building the query string
957 $queryString = $select1 . $from1 . $where1 . $select2 . $from2 . $where2 . $order . $limit;
959 $relationship = new CRM_Contact_DAO_Relationship();
961 $relationship->query($queryString);
964 $relationshipCount = 0;
965 while ($relationship->fetch()) {
966 $relationshipCount +
= $relationship->cnt1 +
$relationship->cnt2
;
968 return $relationshipCount;
973 if ($status != self
::INACTIVE
) {
975 $mask = array_sum(array_keys($links));
976 if ($mask & CRM_Core_Action
::DISABLE
) {
977 $mask -= CRM_Core_Action
::DISABLE
;
979 if ($mask & CRM_Core_Action
::ENABLE
) {
980 $mask -= CRM_Core_Action
::ENABLE
;
983 if ($status == self
::CURRENT
) {
984 $mask |
= CRM_Core_Action
::DISABLE
;
986 elseif ($status == self
::DISABLED
) {
987 $mask |
= CRM_Core_Action
::ENABLE
;
989 $mask = $mask & $permissionMask;
992 while ($relationship->fetch()) {
993 $rid = $relationship->civicrm_relationship_id
;
994 $cid = $relationship->civicrm_contact_id
;
995 if (($permissionedContact) &&
996 (!CRM_Contact_BAO_Contact_Permission
::relationship($cid, $contactId))
1000 $values[$rid]['id'] = $rid;
1001 $values[$rid]['cid'] = $cid;
1002 $values[$rid]['contact_id_a'] = $relationship->contact_id_a
;
1003 $values[$rid]['contact_id_b'] = $relationship->contact_id_b
;
1004 $values[$rid]['relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1005 $values[$rid]['relation'] = $relationship->relation
;
1006 $values[$rid]['name'] = $relationship->sort_name
;
1007 $values[$rid]['display_name'] = $relationship->display_name
;
1008 $values[$rid]['job_title'] = $relationship->job_title
;
1009 $values[$rid]['email'] = $relationship->email
;
1010 $values[$rid]['phone'] = $relationship->phone
;
1011 $values[$rid]['employer_id'] = $relationship->employer_id
;
1012 $values[$rid]['organization_name'] = $relationship->organization_name
;
1013 $values[$rid]['country'] = $relationship->country
;
1014 $values[$rid]['city'] = $relationship->city
;
1015 $values[$rid]['state'] = $relationship->state
;
1016 $values[$rid]['start_date'] = $relationship->start_date
;
1017 $values[$rid]['end_date'] = $relationship->end_date
;
1018 $values[$rid]['description'] = $relationship->description
;
1019 $values[$rid]['is_active'] = $relationship->is_active
;
1020 $values[$rid]['is_permission_a_b'] = $relationship->is_permission_a_b
;
1021 $values[$rid]['is_permission_b_a'] = $relationship->is_permission_b_a
;
1022 $values[$rid]['case_id'] = $relationship->case_id
;
1025 $values[$rid]['status'] = $status;
1028 $values[$rid]['civicrm_relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1030 if ($relationship->contact_id_a
== $contactId) {
1031 $values[$rid]['rtype'] = 'a_b';
1034 $values[$rid]['rtype'] = 'b_a';
1040 'rtype' => $values[$rid]['rtype'],
1041 'cid' => $contactId,
1042 'cbid' => $values[$rid]['cid'],
1043 'caseid' => $values[$rid]['case_id'],
1044 'clientid' => $contactId,
1047 if ($status == self
::INACTIVE
) {
1048 // setting links for inactive relationships
1049 $mask = array_sum(array_keys($links));
1050 if (!$values[$rid]['is_active']) {
1051 $mask -= CRM_Core_Action
::DISABLE
;
1054 $mask -= CRM_Core_Action
::ENABLE
;
1055 $mask -= CRM_Core_Action
::DISABLE
;
1059 // Give access to manage case link by copying to MAX_ACTION index temporarily, depending on case permission of user.
1060 if ($values[$rid]['case_id']) {
1061 // Borrowed logic from CRM_Case_Page_Tab
1062 $hasCaseAccess = FALSE;
1063 if (CRM_Core_Permission
::check('access all cases and activities')) {
1064 $hasCaseAccess = TRUE;
1067 $userCases = CRM_Case_BAO_Case
::getCases(FALSE);
1068 if (array_key_exists($values[$rid]['case_id'], $userCases)) {
1069 $hasCaseAccess = TRUE;
1073 if ($hasCaseAccess) {
1074 // give access by copying to MAX_ACTION temporarily, otherwise leave at NONE which won't display
1075 $links[CRM_Core_Action
::MAX_ACTION
] = $links[CRM_Core_Action
::NONE
];
1076 $links[CRM_Core_Action
::MAX_ACTION
]['name'] = ts('Manage Case #%1', array(1 => $values[$rid]['case_id']));
1078 // Also make sure we have the right client cid since can get here from multiple relationship tabs.
1079 if ($values[$rid]['rtype'] == 'b_a') {
1080 $replace['clientid'] = $values[$rid]['cid'];
1085 $values[$rid]['action'] = CRM_Core_Action
::formLink($links, $mask, $replace);
1086 unset($links[CRM_Core_Action
::MAX_ACTION
]);
1090 $relationship->free();
1096 * Function to get get list of relationship type based on the target contact type.
1098 * @param string $targetContactType it's valid contact tpye(may be Individual , Organization , Household)
1100 * @return array - array reference of all relationship types with context to current contact type .
1103 function getRelationType($targetContactType) {
1104 $relationshipType = array();
1105 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType();
1107 foreach ($allRelationshipType as $key => $type) {
1108 if ($type['contact_type_b'] == $targetContactType) {
1109 $relationshipType[$key . '_a_b'] = $type['label_a_b'];
1113 return $relationshipType;
1117 * Function to create / update / delete membership for related contacts.
1119 * This function will create/update/delete membership for related
1120 * contact based on 1) contact have active membership 2) that
1121 * membership is is extedned by the same relationship type to that
1122 * of the existing relationship.
1124 * @param $contactId Int contact id
1125 * @param $params array array of values submitted by POST
1126 * @param $ids array array of ids
1127 * @param $action which action called this function
1132 static function relatedMemberships($contactId, &$params, $ids, $action = CRM_Core_Action
::ADD
, $active = TRUE) {
1133 // Check the end date and set the status of the relationship
1135 $status = self
::CURRENT
;
1137 if (!empty($params['end_date'])) {
1138 $endDate = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Date
::format($params['end_date']), NULL, 'Ymd');
1139 $today = date('Ymd');
1141 if ($today > $endDate) {
1142 $status = self
::PAST
;
1146 if (($action & CRM_Core_Action
::ADD
) &&
1147 ($status & self
::PAST
)
1149 // if relationship is PAST and action is ADD, no qustion
1150 // of creating RELATED membership and return back to
1155 $rel = explode('_', $params['relationship_type_id']);
1157 $relTypeId = $rel[0];
1158 $relDirection = "_{$rel[1]}_{$rel[2]}";
1159 $targetContact = array();
1160 if (($action & CRM_Core_Action
::ADD
) ||
1161 ($action & CRM_Core_Action
::DELETE
)
1163 $contact = $contactId;
1164 $targetContact = CRM_Utils_Array
::value('contact_check', $params);
1166 elseif ($action & CRM_Core_Action
::UPDATE
) {
1167 $contact = $ids['contact'];
1168 $targetContact = array($ids['contactTarget'] => 1);
1171 // Build the 'values' array for
1174 // This will allow us to check if either of the contacts in
1175 // relationship have active memberships.
1180 $values[$contact] = array(
1181 'relatedContacts' => $targetContact,
1182 'relationshipTypeId' => $relTypeId,
1183 'relationshipTypeDirection' => $relDirection,
1186 if (!empty($targetContact)) {
1187 foreach ($targetContact as $cid => $donCare) {
1188 $values[$cid] = array(
1189 'relatedContacts' => array($contact => 1),
1190 'relationshipTypeId' => $relTypeId,
1193 $relTypeParams = array('id' => $relTypeId);
1194 $relTypeValues = array();
1195 CRM_Contact_BAO_RelationshipType
::retrieve($relTypeParams, $relTypeValues);
1197 if (CRM_Utils_Array
::value('name_a_b', $relTypeValues) == CRM_Utils_Array
::value('name_b_a', $relTypeValues)) {
1198 $values[$cid]['relationshipTypeDirection'] = '_a_b';
1201 $values[$cid]['relationshipTypeDirection'] = ($relDirection == '_a_b') ?
'_b_a' : '_a_b';
1206 // Now get the active memberships for all the contacts.
1207 // If contact have any valid membership(s), then add it to
1209 foreach ($values as $cid => $subValues) {
1210 $memParams = array('contact_id' => $cid);
1211 $memberships = array();
1213 CRM_Member_BAO_Membership
::getValues($memParams, $memberships, $active);
1215 if (empty($memberships)) {
1219 $values[$cid]['memberships'] = $memberships;
1221 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1223 // done with 'values' array.
1224 // Finally add / edit / delete memberships for the related contacts
1225 foreach ($values as $cid => $details) {
1226 if (!array_key_exists('memberships', $details)) {
1230 $mainRelatedContactId = key(CRM_Utils_Array
::value('relatedContacts', $details, array()));
1232 foreach ($details['memberships'] as $membershipId => $membershipValues) {
1233 $relTypeIds = array();
1234 if ($action & CRM_Core_Action
::DELETE
) {
1235 // Delete memberships of the related contacts only if relationship type exists for membership type
1237 SELECT relationship_type_id, relationship_direction
1238 FROM civicrm_membership_type
1239 WHERE id = {$membershipValues['membership_type_id']}";
1240 $dao = CRM_Core_DAO
::executeQuery($query);
1241 $relTypeDirs = array();
1242 while ($dao->fetch()) {
1243 $relTypeId = $dao->relationship_type_id
;
1244 $relDirection = $dao->relationship_direction
;
1246 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $relTypeId);
1247 if (in_array($values[$cid]['relationshipTypeId'], $relTypeIds)) {
1248 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $mainRelatedContactId);
1252 if (($action & CRM_Core_Action
::UPDATE
) &&
1253 ($status & self
::PAST
) &&
1254 ($membershipValues['owner_membership_id'])
1256 // If relationship is PAST and action is UPDATE
1257 // then delete the RELATED membership
1258 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipValues['owner_membership_id'],
1259 $membershipValues['membership_contact_id']
1264 // add / edit the memberships for related
1267 // Get the Membership Type Details.
1268 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipValues['membership_type_id']);
1269 // Check if contact's relationship type exists in membership type
1270 $relTypeDirs = array();
1271 if (CRM_Utils_Array
::value('relationship_type_id', $membershipType)) {
1272 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_type_id']);
1274 if (CRM_Utils_Array
::value('relationship_direction', $membershipType)) {
1275 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_direction']);
1277 foreach ($relTypeIds as $key => $value) {
1278 $relTypeDirs[] = $value . '_' . $relDirections[$key];
1280 $relTypeDir = $details['relationshipTypeId'] . $details['relationshipTypeDirection'];
1281 if (in_array($relTypeDir, $relTypeDirs)) {
1282 // Check if relationship being created/updated is
1283 // similar to that of membership type's
1286 $membershipValues['owner_membership_id'] = $membershipId;
1287 unset($membershipValues['id']);
1288 unset($membershipValues['membership_contact_id']);
1289 unset($membershipValues['contact_id']);
1290 unset($membershipValues['membership_id']);
1291 foreach ($details['relatedContacts'] as $relatedContactId => $donCare) {
1292 $membershipValues['contact_id'] = $relatedContactId;
1293 if ($deceasedStatusId &&
1294 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $relatedContactId, 'is_deceased')
1296 $membershipValues['status_id'] = $deceasedStatusId;
1297 $membershipValues['skipStatusCal'] = TRUE;
1300 'join_date', 'start_date', 'end_date') as $dateField) {
1301 if (CRM_Utils_Array
::value($dateField, $membershipValues)) {
1302 $membershipValues[$dateField] = CRM_Utils_Date
::processDate($membershipValues[$dateField]);
1306 if ($action & CRM_Core_Action
::UPDATE
) {
1307 //delete the membership record for related
1308 //contact before creating new membership record.
1309 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $relatedContactId);
1312 // check whether we have some related memberships still available
1315 FROM civicrm_membership
1316 LEFT JOIN civicrm_membership_status ON (civicrm_membership_status.id = civicrm_membership.status_id)
1317 WHERE membership_type_id = {$membershipValues['membership_type_id']} AND owner_membership_id = {$membershipValues['owner_membership_id']}
1318 AND is_current_member = 1";
1319 $result = CRM_Core_DAO
::singleValueQuery($query);
1320 if ($result < CRM_Utils_Array
::value('max_related', $membershipValues, PHP_INT_MAX
)) {
1321 CRM_Member_BAO_Membership
::create($membershipValues, CRM_Core_DAO
::$_nullArray);
1325 elseif ($action & CRM_Core_Action
::UPDATE
) {
1326 // if action is update and updated relationship do
1327 // not match with the existing
1328 // membership=>relationship then we need to
1329 // delete the membership record created for
1330 // previous relationship.
1332 if (self
::isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, CRM_Utils_Array
::value('relationship_ids', $params))) {
1333 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $mainRelatedContactId);
1341 * Helper function to check whether to delete the membership or
1347 static function isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, $relIds) {
1348 if (in_array($relTypeId, $relTypeIds)) {
1352 if (empty($relIds)) {
1356 $relParamas = array(1 => array($contactId, 'Integer'),
1357 2 => array($mainRelatedContactId, 'Integer'),
1360 if ($contactId == $mainRelatedContactId) {
1361 $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);
1362 if ($recordsFound) {
1368 $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);
1370 if ($recordsFound) {
1378 * Function to get Current Employer for Contact
1380 * @param $contactIds Contact Ids
1382 * @return $currentEmployer array of the current employer
1387 static function getCurrentEmployer($contactIds) {
1388 $contacts = implode(',', $contactIds);
1391 SELECT organization_name, id, employer_id
1392 FROM civicrm_contact
1393 WHERE id IN ( {$contacts} )
1396 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1397 $currentEmployer = array();
1398 while ($dao->fetch()) {
1399 $currentEmployer[$dao->id
]['org_id'] = $dao->employer_id
;
1400 $currentEmployer[$dao->id
]['org_name'] = $dao->organization_name
;
1403 return $currentEmployer;
1407 * Function to return list of permissioned employer for a given contact.
1409 * @param $contactID int contact id whose employers
1411 * @param $name string employers sort name
1415 * @return array array of employers.
1418 static function getPermissionedEmployer($contactID, $name = '%') {
1419 $employers = array();
1421 //get the relationship id
1422 $relTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType',
1423 'Employee of', 'id', 'name_a_b'
1428 SELECT cc.id as id, cc.sort_name as name
1429 FROM civicrm_relationship cr, civicrm_contact cc
1430 WHERE cr.contact_id_a = $contactID AND
1431 cr.relationship_type_id = $relTypeId AND
1432 cr.is_permission_a_b = 1 AND
1433 IF(cr.end_date IS NULL, 1, (DATEDIFF( CURDATE( ), cr.end_date ) <= 0)) AND
1434 cr.is_active = 1 AND
1435 cc.id = cr.contact_id_b AND
1436 cc.sort_name LIKE '%$name%'";
1438 $nullArray = array();
1439 $dao = CRM_Core_DAO
::executeQuery($query, $nullArray);
1441 while ($dao->fetch()) {
1442 $employers[$dao->id
] = array(
1443 'name' => $dao->name
,
1444 'value' => $dao->id
,
1452 static function getValidContactTypeList($relType) {
1453 // string looks like 4_a_b
1454 $rel_parts = explode('_', $relType);
1455 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType('label');
1456 $contactProfiles = CRM_Core_BAO_UFGroup
::getReservedProfiles('Contact', NULL);
1458 if ($rel_parts[1] == 'a') {
1459 $leftType = $allRelationshipType[$rel_parts[0]]['contact_type_b'];
1462 $leftType = $allRelationshipType[$rel_parts[0]]['contact_type_a'];
1465 // Handle 'All Contacts' contact type for left side of relationship ($leftType is empty in this case)
1466 // In this case all reserved profiles are available
1467 if ($leftType == '') {
1468 $contactTypes = $contactProfiles;
1470 $contactTypes = array();
1471 foreach ($contactProfiles as $key => $value) {
1472 if (strpos($value, $leftType) !== FALSE) {
1473 $contactTypes = array($key => $value);
1478 return $contactTypes;
1482 * Merge relationships from otherContact to mainContact
1483 * Called during contact merge operation
1485 * @param int $mainId contact id of main contact record.
1486 * @param int $otherId contact id of record which is going to merge.
1487 * @param array $sqls (reference) array of sql statements to append to.
1489 * @see CRM_Dedupe_Merger::cpTables()
1493 static function mergeRelationships($mainId, $otherId, &$sqls) {
1494 // Delete circular relationships
1495 $sqls[] = "DELETE FROM civicrm_relationship
1496 WHERE (contact_id_a = $mainId AND contact_id_b = $otherId)
1497 OR (contact_id_b = $mainId AND contact_id_a = $otherId)";
1499 // Delete relationship from other contact if main contact already has that relationship
1500 $sqls[] = "DELETE r2
1501 FROM civicrm_relationship r1, civicrm_relationship r2
1502 WHERE r1.relationship_type_id = r2.relationship_type_id
1505 r1.contact_id_a = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_b = r2.contact_id_b
1506 OR r1.contact_id_b = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_a = r2.contact_id_a
1508 (r1.contact_id_a = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_b = r2.contact_id_a
1509 OR r1.contact_id_b = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_a = r2.contact_id_b)
1510 AND r1.relationship_type_id IN (SELECT id FROM civicrm_relationship_type WHERE name_b_a = name_a_b)
1514 // Move relationships
1515 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_a = $mainId WHERE contact_id_a = $otherId";
1516 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_b = $mainId WHERE contact_id_b = $otherId";
1518 // Move current employer id (name will get updated later)
1519 $sqls[] = "UPDATE civicrm_contact SET employer_id = $mainId WHERE employer_id = $otherId";
1523 * Set 'is_valid' field to false for all relationships whose end date is in the past, ie. are expired.
1525 * @return True on success, false if error is encountered.
1527 static function disableExpiredRelationships() {
1528 $query = "SELECT id FROM civicrm_relationship WHERE is_active = 1 AND end_date < CURDATE()";
1530 $dao = CRM_Core_DAO
::executeQuery($query);
1531 while ($dao->fetch()) {
1532 $result = CRM_Contact_BAO_Relationship
::setIsActive($dao->id
, FALSE);
1533 // Result will be NULL if error occurred. We abort early if error detected.
1534 if ($result == NULL) {
1542 * Function filters the query by possible relationships for the membership type
1543 * It is intended to be called when constructing queries for the api (reciprocal & non-reciprocal)
1544 * and to add clauses to limit the return to those relationships which COULD inherit a membership type
1545 * (as opposed to those who inherit a particular membership
1547 * @param array $params api input array
1549 static function membershipTypeToRelationshipTypes(&$params, $direction = NULL) {
1550 $membershipType = civicrm_api3('membership_type', 'getsingle', array('id' => $params['membership_type_id'], 'return' => 'relationship_type_id, relationship_direction'));
1551 $relationshipTypes = $membershipType['relationship_type_id'];
1552 if(empty($relationshipTypes)) {
1555 // if we don't have any contact data we can only filter on type
1556 if(empty($params['contact_id']) && empty($params['contact_id_a']) && empty($params['contact_id_a'])) {
1557 $params['relationship_type_id'] = array('IN' => $relationshipTypes);
1561 $relationshipDirections = $membershipType['relationship_direction'];
1562 // if we have contact_id_a OR contact_id_b we can make a call here
1563 // if we have contact??
1564 foreach ($relationshipDirections as $index => $mtdirection) {
1565 if(isset($params['contact_id_a']) && $mtdirection == 'a_b' ||
$direction == 'a_b') {
1566 $types[] = $relationshipTypes[$index];
1568 if(isset($params['contact_id_b']) && $mtdirection == 'b_a' ||
$direction == 'b_a') {
1569 $types[] = $relationshipTypes[$index];
1572 if(!empty($types)) {
1573 $params['relationship_type_id'] = array('IN' => $types);
1575 elseif(!empty($clauses)) {
1576 return explode(' OR ', $clauses);
1579 // effectively setting it to return no results
1580 $params['relationship_type_id'] = 0;