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
51 * @return object CRM_Contact_BAO_Relationship object
55 static function create(&$params, &$ids) {
56 $valid = $invalid = $duplicate = $saved = 0;
57 $relationshipId = CRM_Utils_Array
::value('relationship', $ids);
58 //CRM-9015 - the hooks are called here & in add (since add doesn't call create)
59 // but in future should be tidied per ticket
60 if (CRM_Utils_Array
::value('relationship', $ids)) {
61 CRM_Utils_Hook
::pre('edit', 'Relationship', $ids['relationship'], $params);
64 CRM_Utils_Hook
::pre('create', 'Relationship', NULL, $params);
66 if (!$relationshipId) {
67 // creating a new relationship
68 $dataExists = self
::dataExists($params);
70 return array(FALSE, TRUE, FALSE, FALSE, NULL);
72 $relationshipIds = array();
73 foreach ($params['contact_check'] as $key => $value) {
75 // check if the relationship is valid between contacts.
76 // step 1: check if the relationship is valid if not valid skip and keep the count
77 // step 2: check the if two contacts already have a relationship if yes skip and keep the count
78 // step 3: if valid relationship then add the relation and keep the count
81 $errors = self
::checkValidRelationship($params, $ids, $key);
88 self
::checkDuplicateRelationship(
90 CRM_Utils_Array
::value('contact', $ids),
99 $relationship = self
::add($params, $ids, $key);
100 $relationshipIds[] = $relationship->id
;
103 // editing the relationship
106 // check for duplicate relationship
109 self
::checkDuplicateRelationship(
111 CRM_Utils_Array
::value('contact', $ids),
112 $ids['contactTarget'],
117 return array($valid, $invalid, $duplicate, $saved, NULL);
120 $validContacts = TRUE;
121 //validate contacts in update mode also.
122 if (CRM_Utils_Array
::value('contact', $ids) &&
123 CRM_Utils_Array
::value('contactTarget', $ids)
125 if (self
::checkValidRelationship($params, $ids, $ids['contactTarget'])) {
126 $validContacts = FALSE;
130 if ($validContacts) {
131 // editing an existing relationship
132 $relationship = self
::add($params, $ids, $ids['contactTarget']);
133 $relationshipIds[] = $relationship->id
;
138 // do not add to recent items for import, CRM-4399
139 if (!(CRM_Utils_Array
::value('skipRecentView', $params) ||
$invalid ||
$duplicate)) {
140 $url = CRM_Utils_System
::url('civicrm/contact/view/rel',
141 "action=view&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&context=home"
145 $session = CRM_Core_Session
::singleton();
146 $recentOther = array();
147 if (($session->get('userID') == $relationship->contact_id_a
) ||
148 CRM_Contact_BAO_Contact_Permission
::allow($relationship->contact_id_a
, CRM_Core_Permission
::EDIT
)
150 $rType = substr(CRM_Utils_Array
::value('relationship_type_id', $params), -3);
151 $recentOther = array(
152 'editUrl' => CRM_Utils_System
::url('civicrm/contact/view/rel',
153 "action=update&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
155 'deleteUrl' => CRM_Utils_System
::url('civicrm/contact/view/rel',
156 "action=delete&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
161 $title = CRM_Contact_BAO_Contact
::displayName($relationship->contact_id_a
) . ' (' . CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType',
162 $relationship->relationship_type_id
, 'label_a_b'
163 ) . ' ' . CRM_Contact_BAO_Contact
::displayName($relationship->contact_id_b
) . ')';
165 // add the recently created Relationship
166 CRM_Utils_Recent
::add($title,
170 $relationship->contact_id_a
,
176 return array($valid, $invalid, $duplicate, $saved, $relationshipIds);
180 * This is the function that check/add if the relationship created is valid
182 * @param array $params (reference ) an assoc array of name/value pairs
183 * @param integer $contactId this is contact id for adding relationship
184 * @param array $ids the array that holds all the db ids
186 * @return object CRM_Contact_BAO_Relationship
190 static function add(&$params, &$ids, $contactId) {
191 if (CRM_Utils_Array
::value('relationship', $ids)) {
192 CRM_Utils_Hook
::pre('edit', 'Relationship', $ids['relationship'], $params);
195 CRM_Utils_Hook
::pre('create', 'Relationship', NULL, $params);
198 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
200 // expolode the string with _ to get the relationship type id and to know which contact has to be inserted in
201 // contact_id_a and which one in contact_id_b
202 list($type, $first, $second) = explode('_', $relationshipTypes);
204 $
{'contact_' . $first} = CRM_Utils_Array
::value('contact', $ids);
205 $
{'contact_' . $second} = $contactId;
207 //check if the relationship type is Head of Household then update the household's primary contact with this contact.
209 CRM_Contact_BAO_Household
::updatePrimaryContact($contact_b, $contact_a);
212 $relationship = new CRM_Contact_BAO_Relationship();
213 $relationship->contact_id_b
= $contact_b;
214 $relationship->contact_id_a
= $contact_a;
215 $relationship->relationship_type_id
= $type;
216 $relationship->id
= CRM_Utils_Array
::value('relationship', $ids);
218 $dateFields = array('end_date', 'start_date');
220 foreach (self
::getdefaults() as $defaultField => $defaultValue){
221 if(isset($params[$defaultField])){
222 if(in_array($defaultField, $dateFields)){
223 $relationship->$defaultField = CRM_Utils_Date
::format(CRM_Utils_Array
::value($defaultField, $params));
224 if(!$relationship->$defaultField){
225 $relationship->$defaultField = 'NULL';
229 $relationship->$defaultField = $params[$defaultField];
232 elseif(empty($relationship->id
)){
233 $relationship->$defaultField = $defaultValue;
237 $relationship->save();
239 // add custom field values
240 if (CRM_Utils_Array
::value('custom', $params)) {
241 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_relationship', $relationship->id
);
244 $relationship->free();
246 if (CRM_Utils_Array
::value('relationship', $ids)) {
247 CRM_Utils_Hook
::post('edit', 'Relationship', $relationship->id
, $relationship);
250 CRM_Utils_Hook
::post('create', 'Relationship', $relationship->id
, $relationship);
253 return $relationship;
256 * Specifiy defaults for creating a relationship
258 * @return array $defaults array of defaults for creating relationship
262 static function getdefaults() {
265 'is_permission_a_b' => 0,
266 'is_permission_b_a' => 0,
268 'start_date' => 'NULL',
270 'end_date' => 'NULL',
276 * Check if there is data to create the object
278 * @param array $params (reference ) an assoc array of name/value pairs
284 static function dataExists(&$params) {
285 // return if no data present
286 if (!is_array(CRM_Utils_Array
::value('contact_check', $params))) {
293 * Function to get get list of relationship type based on the contact type.
295 * @param int $contactId this is the contact id of the current contact.
296 * @param string $strContact this value is currently ignored, keeping it there for legacy reasons
297 * @param string $relationshipId the id of the existing relationship if any
298 * @param string $contactType contact type
299 * @param boolean $all if true returns relationship types in both the direction
300 * @param string $column name/label that going to retrieve from db.
303 * @param string $contactSubType includes relationshiptypes between this subtype
305 * @param boolean $onlySubTypeRelationTypes if set only subtype which is passed by $contactSubType
306 * related relationshiptypes get return
310 * @return array - array reference of all relationship types with context to current contact.
312 static function getContactRelationshipType($contactId = NULL,
313 $contactSuffix = NULL,
314 $relationshipId = NULL,
318 $biDirectional = TRUE,
319 $contactSubType = NULL,
320 $onlySubTypeRelationTypes = FALSE
322 $allRelationshipType = array();
323 $relationshipType = array();
324 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType($column);
326 $otherContactType = NULL;
327 if ($relationshipId) {
328 $relationship = new CRM_Contact_DAO_Relationship();
329 $relationship->id
= $relationshipId;
330 if ($relationship->find(TRUE)) {
331 $contact = new CRM_Contact_DAO_Contact();
332 $contact->id
= ($relationship->contact_id_a
=== $contactId) ?
$relationship->contact_id_b
: $relationship->contact_id_a
;
334 if ($contact->find(TRUE)) {
335 $otherContactType = $contact->contact_type
;
336 //CRM-5125 for contact subtype specific relationshiptypes
337 if ($contact->contact_sub_type
) {
338 $otherContactSubType = $contact->contact_sub_type
;
344 $contactSubType = array();
346 $contactType = CRM_Contact_BAO_Contact
::getContactType($contactId);
347 $contactSubType = CRM_Contact_BAO_Contact
::getContactSubType($contactId);
350 foreach ($allRelationshipType as $key => $value) {
351 // the contact type is required or matches
352 if (((!$value['contact_type_a']) ||
353 $value['contact_type_a'] == $contactType
355 // the other contact type is required or present or matches
356 ((!$value['contact_type_b']) ||
357 (!$otherContactType) ||
358 $value['contact_type_b'] == $otherContactType
361 (in_array($value['contact_sub_type_a'], $contactSubType) ||
362 ((!$value['contact_sub_type_b'] &&
363 !$value['contact_sub_type_a']
365 !$onlySubTypeRelationTypes
370 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
372 elseif (empty($value['contact_type_b'])) {
373 // case contact_type_b is "all contacts", CRM-9877
374 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
377 if (((!$value['contact_type_b']) ||
378 $value['contact_type_b'] == $contactType
380 ((!$value['contact_type_a']) ||
381 (!$otherContactType) ||
382 $value['contact_type_a'] == $otherContactType
385 (in_array($value['contact_sub_type_b'], $contactSubType) ||
386 ((!$value['contact_sub_type_a'] &&
387 !$value['contact_sub_type_b']
389 !$onlySubTypeRelationTypes
394 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
396 elseif (empty($value['contact_type_a'])) {
397 // case contact_type_a is "all contacts", CRM-9877
398 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
402 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
403 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
407 if ($biDirectional) {
408 // lets clean up the data and eliminate all duplicate values
409 // (i.e. the relationship is bi-directional)
410 $relationshipType = array_unique($relationshipType);
413 // sort the relationshipType in ascending order CRM-7736
414 asort($relationshipType);
415 return $relationshipType;
418 static function clearCurrentEmployer($id, $action) {
419 $relationship = new CRM_Contact_DAO_Relationship();
420 $relationship->id
= $id;
421 $relationship->find(TRUE);
423 //to delete relationship between household and individual \
424 //or between individual and orgnization
425 if (($action & CRM_Core_Action
::DISABLE
) ||
($action & CRM_Core_Action
::DELETE
)) {
426 $relTypes = CRM_Utils_Array
::index(array('name_a_b'), CRM_Core_PseudoConstant
::relationshipType('name'));
427 if ($relationship->relationship_type_id
== $relTypes['Employee of']['id'] ||
428 $relationship->relationship_type_id
== $relTypes['Household Member of']['id']) {
429 $sharedContact = new CRM_Contact_DAO_Contact();
430 $sharedContact->id
= $relationship->contact_id_a
;
431 $sharedContact->find(TRUE);
433 if ($relationship->relationship_type_id
== 4 && $relationship->contact_id_b
== $sharedContact->employer_id
) {
434 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($relationship->contact_id_a
);
438 return $relationship;
442 * Function to delete the relationship
444 * @param int $id relationship id
451 static function del($id) {
452 // delete from relationship table
453 CRM_Utils_Hook
::pre('delete', 'Relationship', $id, CRM_Core_DAO
::$_nullArray);
455 $relationship = self
::clearCurrentEmployer($id, CRM_Core_Action
::DELETE
);
456 if (CRM_Core_Permission
::access('CiviMember')) {
457 // create $params array which isrequired to delete memberships
458 // of the related contacts.
460 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
461 'contact_check' => array($relationship->contact_id_b
=> 1),
465 // calling relatedMemberships to delete the memberships of
467 self
::relatedMemberships($relationship->contact_id_a
,
470 CRM_Core_Action
::DELETE
,
475 $relationship->delete();
476 CRM_Core_Session
::setStatus(ts('Selected relationship has been deleted successfully.'), ts('Record Deleted'), 'success');
478 CRM_Utils_Hook
::post('delete', 'Relationship', $relationship->id
, $relationship);
480 // delete the recently created Relationship
481 $relationshipRecent = array(
483 'type' => 'Relationship',
485 CRM_Utils_Recent
::del($relationshipRecent);
487 return $relationship;
491 * Function to disable/enable the relationship
493 * @param int $id relationship id
500 static function disableEnableRelationship($id, $action) {
501 $relationship = self
::clearCurrentEmployer($id, $action);
502 if (CRM_Core_Permission
::access('CiviMember')) {
503 // create $params array which isrequired to delete memberships
504 // of the related contacts.
506 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
507 'contact_check' => array($relationship->contact_id_b
=> 1),
511 // calling relatedMemberships to delete/add the memberships of
513 if ($action & CRM_Core_Action
::DISABLE
) {
514 CRM_Contact_BAO_Relationship
::relatedMemberships($relationship->contact_id_a
,
517 CRM_Core_Action
::DELETE
,
521 elseif ($action & CRM_Core_Action
::ENABLE
) {
522 $ids['contact'] = $relationship->contact_id_a
;
523 CRM_Contact_BAO_Relationship
::relatedMemberships($relationship->contact_id_a
,
526 CRM_Core_Action
::ADD
,
534 * Delete the object records that are associated with this contact
536 * @param int $contactId id of the contact to delete
542 static function deleteContact($contactId) {
543 $relationship = new CRM_Contact_DAO_Relationship();
544 $relationship->contact_id_a
= $contactId;
545 $relationship->delete();
547 $relationship = new CRM_Contact_DAO_Relationship();
548 $relationship->contact_id_b
= $contactId;
549 $relationship->delete();
551 CRM_Contact_BAO_Household
::updatePrimaryContact(NULL, $contactId);
555 * Function to get the other contact in a relationship
557 * @param int $id relationship id
559 * $returns returns the contact ids in the realtionship
563 static function getContactIds($id) {
564 $relationship = new CRM_Contact_DAO_Relationship();
566 $relationship->id
= $id;
567 $relationship->selectAdd();
568 $relationship->selectAdd('contact_id_a, contact_id_b');
569 $relationship->find(TRUE);
571 return $relationship;
575 * Function to check if the relationship type selected between two contacts is correct
577 * @param int $contact_a 1st contact id
578 * @param int $contact_b 2nd contact id
579 * @param int $relationshipTypeId relationship type id
581 * @return boolean true if it is valid relationship else false
585 static function checkRelationshipType($contact_a, $contact_b, $relationshipTypeId) {
586 $relationshipType = new CRM_Contact_DAO_RelationshipType();
587 $relationshipType->id
= $relationshipTypeId;
588 $relationshipType->selectAdd();
589 $relationshipType->selectAdd('contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b');
590 if ($relationshipType->find(TRUE)) {
591 $contact_type_a = CRM_Contact_BAO_Contact
::getContactType($contact_a);
592 $contact_type_b = CRM_Contact_BAO_Contact
::getContactType($contact_b);
594 $contact_sub_type_a = CRM_Contact_BAO_Contact
::getContactSubType($contact_a);
595 $contact_sub_type_b = CRM_Contact_BAO_Contact
::getContactSubType($contact_b);
597 if (((!$relationshipType->contact_type_a
) ||
($relationshipType->contact_type_a
== $contact_type_a)) &&
598 ((!$relationshipType->contact_type_b
) ||
($relationshipType->contact_type_b
== $contact_type_b)) &&
599 ((!$relationshipType->contact_sub_type_a
) ||
(in_array($relationshipType->contact_sub_type_a
,
602 ((!$relationshipType->contact_sub_type_b
) ||
(in_array($relationshipType->contact_sub_type_b
,
616 * this function does the validtion for valid relationship
618 * @param array $params this array contains the values there are subitted by the form
619 * @param array $ids the array that holds all the db ids
620 * @param integer $contactId this is contact id for adding relationship
626 static function checkValidRelationship(&$params, &$ids, $contactId) {
629 // get the string of relationship type
630 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
631 list($type, $first, $second) = explode('_', $relationshipTypes);
632 $
{'contact_' . $first} = CRM_Utils_Array
::value('contact', $ids);
633 $
{'contact_' . $second} = $contactId;
634 // function to check if the relationship selected is correct
635 // i.e. employer relationship can exit between Individual and Organization (not between Individual and Individual)
636 if (!CRM_Contact_BAO_Relationship
::checkRelationshipType($contact_a, $contact_b, $type)) {
637 $errors = 'Please select valid relationship between these two contacts.';
643 * this function checks for duplicate relationship
645 * @param array $params (reference ) an assoc array of name/value pairs
646 * @param integer $id this the id of the contact whom we are adding relationship
647 * @param integer $contactId this is contact id for adding relationship
648 * @param integer $relationshipId this is relationship id for the contact
650 * @return boolean true if record exists else false
654 static function checkDuplicateRelationship(&$params, $id, $contactId = 0, $relationshipId = 0) {
655 $relationshipTypeId = CRM_Utils_Array
::value('relationship_type_id', $params);
656 list($type, $first, $second) = explode('_', $relationshipTypeId);
658 $queryString = " SELECT id
659 FROM civicrm_relationship
660 WHERE relationship_type_id = " . CRM_Utils_Type
::escape($type, 'Integer');
663 * CRM-11792 - date fields from API are in ISO format, but this function supports date arrays
664 * BAO has increasingly standardised to ISO format so I believe this function should support
665 * ISO rather than make API format it - however, need to support array format for now to avoid breakage
666 * @ time of writing this function is called from Relationship::create (twice)
667 * CRM_BAO_Contact_Utils::clearCurrentEmployer (seemingly without dates)
668 * CRM_Contact_Form_Task_AddToOrganization::postProcess &
669 * CRM_Contact_Form_Task_AddToHousehold::postProcess
670 * (I don't think the last 2 support dates but not sure
673 $dateFields = array('end_date', 'start_date');
674 foreach ($dateFields as $dateField){
675 if(array_key_exists($dateField, $params)) {
676 if (empty($params[$dateField]) ||
$params[$dateField] == 'null'){
677 //this is most likely coming from an api call & probably loaded from the DB to deal with some of the
678 //other myriad of excessive checks still in place both in the api & the create functions
679 $queryString .= " AND $dateField IS NULL";
682 elseif (is_array($params[$dateField])){
683 $queryString .= " AND $dateField = " . CRM_Utils_Type
::escape(CRM_Utils_Date
::format($params[$dateField]), 'Date');
686 $queryString .= " AND $dateField = " . CRM_Utils_Type
::escape($params[$dateField], 'Date');
692 " AND ( ( contact_id_a = " . CRM_Utils_Type
::escape($id, 'Integer') .
693 " AND contact_id_b = " . CRM_Utils_Type
::escape($contactId, 'Integer') .
694 " ) OR ( contact_id_a = " . CRM_Utils_Type
::escape($contactId, 'Integer') .
695 " AND contact_id_b = " . CRM_Utils_Type
::escape($id, 'Integer') . " ) ) ";
697 //if caseId is provided, include it duplicate checking.
698 if ($caseId = CRM_Utils_Array
::value('case_id', $params)) {
699 $queryString .= " AND case_id = " . CRM_Utils_Type
::escape($caseId, 'Integer');
702 if ($relationshipId) {
703 $queryString .= " AND id !=" . CRM_Utils_Type
::escape($relationshipId, 'Integer');
706 $relationship = new CRM_Contact_BAO_Relationship();
707 $relationship->query($queryString);
708 $relationship->fetch();
709 $relationship->free();
710 return ($relationship->id
) ?
TRUE : FALSE;
714 * update the is_active flag in the db
716 * @param int $id id of the database record
717 * @param boolean $is_active value we want to set the is_active field
719 * @return Object DAO object on success, null otherwise
722 static function setIsActive($id, $is_active) {
723 CRM_Core_DAO
::setFieldValue('CRM_Contact_DAO_Relationship', $id, 'is_active', $is_active);
726 CRM_Utils_Hook
::enableDisable('CRM_Contact_BAO_Relationship', $id, $is_active);
732 * Given the list of params in the params array, fetch the object
733 * and store the values in the values array
735 * @param array $params input parameters to find object
736 * @param array $values output values of the object
737 * @param array $ids the array that holds all the db ids
739 * @return array (reference) the values that could be potentially assigned to smarty
743 static function &getValues(&$params, &$values) {
744 if (empty($params)) {
749 // get the specific number of relationship or all relationships.
750 if (CRM_Utils_Array
::value('numRelationship', $params)) {
751 $v['data'] = &CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'], NULL, $params['numRelationship']);
754 $v['data'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id']);
757 // get the total count of relationships
758 $v['totalCount'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'], NULL, NULL, TRUE);
760 $values['relationship']['data'] = &$v['data'];
761 $values['relationship']['totalCount'] = &$v['totalCount'];
767 * helper function to form the sql for relationship retrieval
769 * @param int $contactId contact id
770 * @param int $status (check const at top of file)
771 * @param int $numRelationship no of relationships to display (limit)
772 * @param int $count get the no of relationships
773 * $param int $relationshipId relationship id
774 * @param string $direction the direction we are interested in a_b or b_a
776 * return string the query for this diretion
780 static function makeURLClause($contactId, $status, $numRelationship, $count, $relationshipId, $direction) {
781 $select = $from = $where = '';
785 if ($direction == 'a_b') {
786 $select .= ' SELECT count(DISTINCT civicrm_relationship.id) as cnt1, 0 as cnt2 ';
789 $select .= ' SELECT 0 as cnt1, count(DISTINCT civicrm_relationship.id) as cnt2 ';
793 $select .= ' SELECT civicrm_relationship.id as civicrm_relationship_id,
794 civicrm_contact.sort_name as sort_name,
795 civicrm_contact.display_name as display_name,
796 civicrm_contact.job_title as job_title,
797 civicrm_contact.employer_id as employer_id,
798 civicrm_contact.organization_name as organization_name,
799 civicrm_address.street_address as street_address,
800 civicrm_address.city as city,
801 civicrm_address.postal_code as postal_code,
802 civicrm_state_province.abbreviation as state,
803 civicrm_country.name as country,
804 civicrm_email.email as email,
805 civicrm_phone.phone as phone,
806 civicrm_contact.id as civicrm_contact_id,
807 civicrm_contact.contact_type as contact_type,
808 civicrm_relationship.contact_id_b as contact_id_b,
809 civicrm_relationship.contact_id_a as contact_id_a,
810 civicrm_relationship_type.id as civicrm_relationship_type_id,
811 civicrm_relationship.start_date as start_date,
812 civicrm_relationship.end_date as end_date,
813 civicrm_relationship.description as description,
814 civicrm_relationship.is_active as is_active,
815 civicrm_relationship.is_permission_a_b as is_permission_a_b,
816 civicrm_relationship.is_permission_b_a as is_permission_b_a,
817 civicrm_relationship.case_id as case_id';
819 if ($direction == 'a_b') {
820 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
821 civicrm_relationship_type.label_b_a as relation ';
824 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
825 civicrm_relationship_type.label_a_b as relation ';
830 FROM civicrm_relationship
831 INNER JOIN civicrm_relationship_type ON ( civicrm_relationship.relationship_type_id = civicrm_relationship_type.id )
832 INNER JOIN civicrm_contact ";
833 if ($direction == 'a_b') {
834 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_a ) ';
837 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_b ) ';
840 LEFT JOIN civicrm_address ON (civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1)
841 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
842 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id AND civicrm_email.is_primary = 1)
843 LEFT JOIN civicrm_state_province ON (civicrm_address.state_province_id = civicrm_state_province.id)
844 LEFT JOIN civicrm_country ON (civicrm_address.country_id = civicrm_country.id)
846 $where = 'WHERE ( 1 )';
848 if ($direction == 'a_b') {
849 $where .= ' AND civicrm_relationship.contact_id_b = ' . CRM_Utils_Type
::escape($contactId, 'Positive');
852 $where .= ' AND civicrm_relationship.contact_id_a = ' . CRM_Utils_Type
::escape($contactId, 'Positive');
855 if ($relationshipId) {
856 $where .= ' AND civicrm_relationship.id = ' . CRM_Utils_Type
::escape($relationshipId, 'Positive');
859 $date = date('Y-m-d');
860 if ($status == self
::PAST
) {
861 //this case for showing past relationship
862 $where .= ' AND civicrm_relationship.is_active = 1 ';
863 $where .= " AND civicrm_relationship.end_date < '" . $date . "'";
865 elseif ($status == self
::DISABLED
) {
866 // this case for showing disabled relationship
867 $where .= ' AND civicrm_relationship.is_active = 0 ';
869 elseif ($status == self
::CURRENT
) {
870 //this case for showing current relationship
871 $where .= ' AND civicrm_relationship.is_active = 1 ';
872 $where .= " AND (civicrm_relationship.end_date >= '" . $date . "' OR civicrm_relationship.end_date IS NULL) ";
874 elseif ($status == self
::INACTIVE
) {
875 //this case for showing inactive relationships
876 $where .= " AND (civicrm_relationship.end_date < '" . $date . "'";
877 $where .= ' OR civicrm_relationship.is_active = 0 )';
881 $where .= ' AND civicrm_contact.is_deleted = 0';
883 if ($direction == 'a_b') {
884 $where .= ' ) UNION ';
890 return array($select, $from, $where);
894 * This is the function to get the list of relationships
896 * @param int $contactId contact id
897 * @param int $status 1: Past 2: Disabled 3: Current
898 * @param int $numRelationship no of relationships to display (limit)
899 * @param int $count get the no of relationships
900 * $param int $relationshipId relationship id
901 * $param array $links the list of links to display
902 * $param int $permissionMask the permission mask to be applied for the actions
903 * $param boolean $permissionedContact to return only permissioned Contact
905 * return array $values relationship records
909 static function getRelationship($contactId = NULL,
910 $status = 0, $numRelationship = 0,
911 $count = 0, $relationshipId = 0,
912 $links = NULL, $permissionMask = NULL,
913 $permissionedContact = FALSE
916 if (!$contactId && !$relationshipId) {
920 list($select1, $from1, $where1) = self
::makeURLClause($contactId, $status, $numRelationship,
921 $count, $relationshipId, 'a_b'
923 list($select2, $from2, $where2) = self
::makeURLClause($contactId, $status, $numRelationship,
924 $count, $relationshipId, 'b_a'
927 $order = $limit = '';
929 $order = ' ORDER BY civicrm_relationship_type_id, sort_name ';
931 if ($numRelationship) {
932 $limit = " LIMIT 0, $numRelationship";
936 // building the query string
938 $queryString = $select1 . $from1 . $where1 . $select2 . $from2 . $where2 . $order . $limit;
940 $relationship = new CRM_Contact_DAO_Relationship();
942 $relationship->query($queryString);
945 $relationshipCount = 0;
946 while ($relationship->fetch()) {
947 $relationshipCount +
= $relationship->cnt1 +
$relationship->cnt2
;
949 return $relationshipCount;
954 if ($status != self
::INACTIVE
) {
956 $mask = array_sum(array_keys($links));
957 if ($mask & CRM_Core_Action
::DISABLE
) {
958 $mask -= CRM_Core_Action
::DISABLE
;
960 if ($mask & CRM_Core_Action
::ENABLE
) {
961 $mask -= CRM_Core_Action
::ENABLE
;
964 if ($status == self
::CURRENT
) {
965 $mask |
= CRM_Core_Action
::DISABLE
;
967 elseif ($status == self
::DISABLED
) {
968 $mask |
= CRM_Core_Action
::ENABLE
;
970 $mask = $mask & $permissionMask;
973 while ($relationship->fetch()) {
974 $rid = $relationship->civicrm_relationship_id
;
975 $cid = $relationship->civicrm_contact_id
;
976 if (($permissionedContact) &&
977 (!CRM_Contact_BAO_Contact_Permission
::relationship($cid, $contactId))
981 $values[$rid]['id'] = $rid;
982 $values[$rid]['cid'] = $cid;
983 $values[$rid]['contact_id_a'] = $relationship->contact_id_a
;
984 $values[$rid]['contact_id_b'] = $relationship->contact_id_b
;
985 $values[$rid]['relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
986 $values[$rid]['relation'] = $relationship->relation
;
987 $values[$rid]['name'] = $relationship->sort_name
;
988 $values[$rid]['display_name'] = $relationship->display_name
;
989 $values[$rid]['job_title'] = $relationship->job_title
;
990 $values[$rid]['email'] = $relationship->email
;
991 $values[$rid]['phone'] = $relationship->phone
;
992 $values[$rid]['employer_id'] = $relationship->employer_id
;
993 $values[$rid]['organization_name'] = $relationship->organization_name
;
994 $values[$rid]['country'] = $relationship->country
;
995 $values[$rid]['city'] = $relationship->city
;
996 $values[$rid]['state'] = $relationship->state
;
997 $values[$rid]['start_date'] = $relationship->start_date
;
998 $values[$rid]['end_date'] = $relationship->end_date
;
999 $values[$rid]['description'] = $relationship->description
;
1000 $values[$rid]['is_active'] = $relationship->is_active
;
1001 $values[$rid]['is_permission_a_b'] = $relationship->is_permission_a_b
;
1002 $values[$rid]['is_permission_b_a'] = $relationship->is_permission_b_a
;
1003 $values[$rid]['case_id'] = $relationship->case_id
;
1006 $values[$rid]['status'] = $status;
1009 $values[$rid]['civicrm_relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1011 if ($relationship->contact_id_a
== $contactId) {
1012 $values[$rid]['rtype'] = 'a_b';
1015 $values[$rid]['rtype'] = 'b_a';
1021 'rtype' => $values[$rid]['rtype'],
1022 'cid' => $contactId,
1023 'cbid' => $values[$rid]['cid'],
1024 'caseid' => $values[$rid]['case_id'],
1025 'clientid' => $contactId,
1028 if ($status == self
::INACTIVE
) {
1029 // setting links for inactive relationships
1030 $mask = array_sum(array_keys($links));
1031 if (!$values[$rid]['is_active']) {
1032 $mask -= CRM_Core_Action
::DISABLE
;
1035 $mask -= CRM_Core_Action
::ENABLE
;
1036 $mask -= CRM_Core_Action
::DISABLE
;
1040 // Give access to manage case link by copying to MAX_ACTION index temporarily, depending on case permission of user.
1041 if ($values[$rid]['case_id']) {
1042 // Borrowed logic from CRM_Case_Page_Tab
1043 $hasCaseAccess = FALSE;
1044 if (CRM_Core_Permission
::check('access all cases and activities')) {
1045 $hasCaseAccess = TRUE;
1048 $userCases = CRM_Case_BAO_Case
::getCases(FALSE);
1049 if (array_key_exists($values[$rid]['case_id'], $userCases)) {
1050 $hasCaseAccess = TRUE;
1054 if ($hasCaseAccess) {
1055 // give access by copying to MAX_ACTION temporarily, otherwise leave at NONE which won't display
1056 $links[CRM_Core_Action
::MAX_ACTION
] = $links[CRM_Core_Action
::NONE
];
1057 $links[CRM_Core_Action
::MAX_ACTION
]['name'] = ts('Manage Case #%1', array(1 => $values[$rid]['case_id']));
1059 // Also make sure we have the right client cid since can get here from multiple relationship tabs.
1060 if ($values[$rid]['rtype'] == 'b_a') {
1061 $replace['clientid'] = $values[$rid]['cid'];
1066 $values[$rid]['action'] = CRM_Core_Action
::formLink($links, $mask, $replace);
1067 unset($links[CRM_Core_Action
::MAX_ACTION
]);
1071 $relationship->free();
1077 * Function to get get list of relationship type based on the target contact type.
1079 * @param string $targetContactType it's valid contact tpye(may be Individual , Organization , Household)
1081 * @return array - array reference of all relationship types with context to current contact type .
1084 function getRelationType($targetContactType) {
1085 $relationshipType = array();
1086 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType();
1088 foreach ($allRelationshipType as $key => $type) {
1089 if ($type['contact_type_b'] == $targetContactType) {
1090 $relationshipType[$key . '_a_b'] = $type['label_a_b'];
1094 return $relationshipType;
1098 * Function to create / update / delete membership for related contacts.
1100 * This function will create/update/delete membership for related
1101 * contact based on 1) contact have active membership 2) that
1102 * membership is is extedned by the same relationship type to that
1103 * of the existing relationship.
1105 * @param $contactId Int contact id
1106 * @param $params array array of values submitted by POST
1107 * @param $ids array array of ids
1108 * @param $action which action called this function
1113 static function relatedMemberships($contactId, &$params, $ids, $action = CRM_Core_Action
::ADD
, $active = TRUE) {
1114 // Check the end date and set the status of the relationship
1116 $status = self
::CURRENT
;
1118 if (!empty($params['end_date'])) {
1119 $endDate = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Date
::format($params['end_date']), NULL, 'Ymd');
1120 $today = date('Ymd');
1122 if ($today > $endDate) {
1123 $status = self
::PAST
;
1127 if (($action & CRM_Core_Action
::ADD
) &&
1128 ($status & self
::PAST
)
1130 // if relationship is PAST and action is ADD, no qustion
1131 // of creating RELATED membership and return back to
1136 $rel = explode('_', $params['relationship_type_id']);
1138 $relTypeId = $rel[0];
1139 $relDirection = "_{$rel[1]}_{$rel[2]}";
1140 $targetContact = array();
1141 if (($action & CRM_Core_Action
::ADD
) ||
1142 ($action & CRM_Core_Action
::DELETE
)
1144 $contact = $contactId;
1145 $targetContact = CRM_Utils_Array
::value('contact_check', $params);
1147 elseif ($action & CRM_Core_Action
::UPDATE
) {
1148 $contact = $ids['contact'];
1149 $targetContact = array($ids['contactTarget'] => 1);
1152 // Build the 'values' array for
1155 // This will allow us to check if either of the contacts in
1156 // relationship have active memberships.
1161 $values[$contact] = array(
1162 'relatedContacts' => $targetContact,
1163 'relationshipTypeId' => $relTypeId,
1164 'relationshipTypeDirection' => $relDirection,
1167 if (!empty($targetContact)) {
1168 foreach ($targetContact as $cid => $donCare) {
1169 $values[$cid] = array(
1170 'relatedContacts' => array($contact => 1),
1171 'relationshipTypeId' => $relTypeId,
1174 $relTypeParams = array('id' => $relTypeId);
1175 $relTypeValues = array();
1176 CRM_Contact_BAO_RelationshipType
::retrieve($relTypeParams, $relTypeValues);
1178 if (CRM_Utils_Array
::value('name_a_b', $relTypeValues) == CRM_Utils_Array
::value('name_b_a', $relTypeValues)) {
1179 $values[$cid]['relationshipTypeDirection'] = '_a_b';
1182 $values[$cid]['relationshipTypeDirection'] = ($relDirection == '_a_b') ?
'_b_a' : '_a_b';
1187 // Now get the active memberships for all the contacts.
1188 // If contact have any valid membership(s), then add it to
1190 foreach ($values as $cid => $subValues) {
1191 $memParams = array('contact_id' => $cid);
1192 $memberships = array();
1194 CRM_Member_BAO_Membership
::getValues($memParams, $memberships, $active);
1196 if (empty($memberships)) {
1200 $values[$cid]['memberships'] = $memberships;
1202 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1204 // done with 'values' array.
1205 // Finally add / edit / delete memberships for the related contacts
1206 foreach ($values as $cid => $details) {
1207 if (!array_key_exists('memberships', $details)) {
1211 $mainRelatedContactId = key(CRM_Utils_Array
::value('relatedContacts', $details, array()));
1213 foreach ($details['memberships'] as $membershipId => $membershipValues) {
1214 $relTypeIds = array();
1215 if ($action & CRM_Core_Action
::DELETE
) {
1216 // Delete memberships of the related contacts only if relationship type exists for membership type
1218 SELECT relationship_type_id, relationship_direction
1219 FROM civicrm_membership_type
1220 WHERE id = {$membershipValues['membership_type_id']}";
1221 $dao = CRM_Core_DAO
::executeQuery($query);
1222 $relTypeDirs = array();
1223 while ($dao->fetch()) {
1224 $relTypeId = $dao->relationship_type_id
;
1225 $relDirection = $dao->relationship_direction
;
1227 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $relTypeId);
1228 if (in_array($values[$cid]['relationshipTypeId'], $relTypeIds)) {
1229 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $mainRelatedContactId);
1233 if (($action & CRM_Core_Action
::UPDATE
) &&
1234 ($status & self
::PAST
) &&
1235 ($membershipValues['owner_membership_id'])
1237 // If relationship is PAST and action is UPDATE
1238 // then delete the RELATED membership
1239 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipValues['owner_membership_id'],
1240 $membershipValues['membership_contact_id']
1245 // add / edit the memberships for related
1248 // Get the Membership Type Details.
1249 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipValues['membership_type_id']);
1250 // Check if contact's relationship type exists in membership type
1251 $relTypeDirs = array();
1252 if (CRM_Utils_Array
::value('relationship_type_id', $membershipType)) {
1253 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_type_id']);
1255 if (CRM_Utils_Array
::value('relationship_direction', $membershipType)) {
1256 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_direction']);
1258 foreach ($relTypeIds as $key => $value) {
1259 $relTypeDirs[] = $value . '_' . $relDirections[$key];
1261 $relTypeDir = $details['relationshipTypeId'] . $details['relationshipTypeDirection'];
1262 if (in_array($relTypeDir, $relTypeDirs)) {
1263 // Check if relationship being created/updated is
1264 // similar to that of membership type's
1267 $membershipValues['owner_membership_id'] = $membershipId;
1268 unset($membershipValues['id']);
1269 unset($membershipValues['membership_contact_id']);
1270 unset($membershipValues['contact_id']);
1271 unset($membershipValues['membership_id']);
1272 foreach ($details['relatedContacts'] as $relatedContactId => $donCare) {
1273 $membershipValues['contact_id'] = $relatedContactId;
1274 if ($deceasedStatusId &&
1275 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $relatedContactId, 'is_deceased')
1277 $membershipValues['status_id'] = $deceasedStatusId;
1278 $membershipValues['skipStatusCal'] = TRUE;
1281 'join_date', 'start_date', 'end_date') as $dateField) {
1282 if (CRM_Utils_Array
::value($dateField, $membershipValues)) {
1283 $membershipValues[$dateField] = CRM_Utils_Date
::processDate($membershipValues[$dateField]);
1287 if ($action & CRM_Core_Action
::UPDATE
) {
1288 //delete the membership record for related
1289 //contact before creating new membership record.
1290 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $relatedContactId);
1293 // check whether we have some related memberships still available
1296 FROM civicrm_membership
1297 LEFT JOIN civicrm_membership_status ON (civicrm_membership_status.id = civicrm_membership.status_id)
1298 WHERE membership_type_id = {$membershipValues['membership_type_id']} AND owner_membership_id = {$membershipValues['owner_membership_id']}
1299 AND is_current_member = 1";
1300 $result = CRM_Core_DAO
::singleValueQuery($query);
1301 if ($result < CRM_Utils_Array
::value('max_related', $membershipValues, PHP_INT_MAX
)) {
1302 CRM_Member_BAO_Membership
::create($membershipValues, CRM_Core_DAO
::$_nullArray);
1306 elseif ($action & CRM_Core_Action
::UPDATE
) {
1307 // if action is update and updated relationship do
1308 // not match with the existing
1309 // membership=>relationship then we need to
1310 // delete the membership record created for
1311 // previous relationship.
1313 if (self
::isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, CRM_Utils_Array
::value('relationship_ids', $params))) {
1314 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $mainRelatedContactId);
1322 * Helper function to check whether to delete the membership or
1326 function isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, $relIds) {
1327 if (in_array($relTypeId, $relTypeIds)) {
1331 if (empty($relIds)) {
1335 $relParamas = array(1 => array($contactId, 'Integer'),
1336 2 => array($mainRelatedContactId, 'Integer'),
1339 if ($contactId == $mainRelatedContactId) {
1340 $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);
1341 if ($recordsFound) {
1347 $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);
1349 if ($recordsFound) {
1357 * Function to get Current Employer for Contact
1359 * @param $contactIds Contact Ids
1361 * @return $currentEmployer array of the current employer
1366 static function getCurrentEmployer($contactIds) {
1367 $contacts = implode(',', $contactIds);
1370 SELECT organization_name, id, employer_id
1371 FROM civicrm_contact
1372 WHERE id IN ( {$contacts} )
1375 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1376 $currentEmployer = array();
1377 while ($dao->fetch()) {
1378 $currentEmployer[$dao->id
]['org_id'] = $dao->employer_id
;
1379 $currentEmployer[$dao->id
]['org_name'] = $dao->organization_name
;
1382 return $currentEmployer;
1386 * Function to return list of permissioned employer for a given contact.
1388 * @param $contactID int contact id whose employers
1390 * @param $name string employers sort name
1394 * @return array array of employers.
1397 static function getPermissionedEmployer($contactID, $name = '%') {
1398 $employers = array();
1400 //get the relationship id
1401 $relTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType',
1402 'Employee of', 'id', 'name_a_b'
1407 SELECT cc.id as id, cc.sort_name as name
1408 FROM civicrm_relationship cr, civicrm_contact cc
1409 WHERE cr.contact_id_a = $contactID AND
1410 cr.relationship_type_id = $relTypeId AND
1411 cr.is_permission_a_b = 1 AND
1412 IF(cr.end_date IS NULL, 1, (DATEDIFF( CURDATE( ), cr.end_date ) <= 0)) AND
1413 cr.is_active = 1 AND
1414 cc.id = cr.contact_id_b AND
1415 cc.sort_name LIKE '%$name%'";
1417 $nullArray = array();
1418 $dao = CRM_Core_DAO
::executeQuery($query, $nullArray);
1420 while ($dao->fetch()) {
1421 $employers[$dao->id
] = array(
1422 'name' => $dao->name
,
1423 'value' => $dao->id
,
1431 static function getValidContactTypeList($relType) {
1432 // string looks like 4_a_b
1433 $rel_parts = explode('_', $relType);
1434 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType('label');
1435 $contactProfiles = CRM_Core_BAO_UFGroup
::getReservedProfiles('Contact', NULL);
1437 if ($rel_parts[1] == 'a') {
1438 $leftType = $allRelationshipType[$rel_parts[0]]['contact_type_b'];
1441 $leftType = $allRelationshipType[$rel_parts[0]]['contact_type_a'];
1444 // Handle 'All Contacts' contact type for left side of relationship ($leftType is empty in this case)
1445 // In this case all reserved profiles are available
1446 if ($leftType == '') {
1447 $contactTypes = $contactProfiles;
1449 $contactTypes = array();
1450 foreach ($contactProfiles as $key => $value) {
1451 if (strpos($value, $leftType) !== FALSE) {
1452 $contactTypes = array($key => $value);
1457 return $contactTypes;
1461 * Merge relationships from otherContact to mainContact
1462 * Called during contact merge operation
1464 * @param int $mainId contact id of main contact record.
1465 * @param int $otherId contact id of record which is going to merge.
1466 * @param array $sqls (reference) array of sql statements to append to.
1468 * @see CRM_Dedupe_Merger::cpTables()
1472 static function mergeRelationships($mainId, $otherId, &$sqls) {
1473 // Delete circular relationships
1474 $sqls[] = "DELETE FROM civicrm_relationship
1475 WHERE (contact_id_a = $mainId AND contact_id_b = $otherId)
1476 OR (contact_id_b = $mainId AND contact_id_a = $otherId)";
1478 // Delete relationship from other contact if main contact already has that relationship
1479 $sqls[] = "DELETE r2
1480 FROM civicrm_relationship r1, civicrm_relationship r2
1481 WHERE r1.relationship_type_id = r2.relationship_type_id
1484 r1.contact_id_a = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_b = r2.contact_id_b
1485 OR r1.contact_id_b = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_a = r2.contact_id_a
1487 (r1.contact_id_a = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_b = r2.contact_id_a
1488 OR r1.contact_id_b = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_a = r2.contact_id_b)
1489 AND r1.relationship_type_id IN (SELECT id FROM civicrm_relationship_type WHERE name_b_a = name_a_b)
1493 // Move relationships
1494 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_a = $mainId WHERE contact_id_a = $otherId";
1495 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_b = $mainId WHERE contact_id_b = $otherId";
1497 // Move current employer id (name will get updated later)
1498 $sqls[] = "UPDATE civicrm_contact SET employer_id = $mainId WHERE employer_id = $otherId";
1502 * Set 'is_valid' field to false for all relationships whose end date is in the past, ie. are expired.
1504 * @return True on success, false if error is encountered.
1506 static function disableExpiredRelationships() {
1507 $query = "SELECT id FROM civicrm_relationship WHERE is_active = 1 AND end_date < CURDATE()";
1509 $dao = CRM_Core_DAO
::executeQuery($query);
1510 while ($dao->fetch()) {
1511 $result = CRM_Contact_BAO_Relationship
::setIsActive($dao->id
, FALSE);
1512 // Result will be NULL if error occurred. We abort early if error detected.
1513 if ($result == NULL) {