3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
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
116 // @todo this code doesn't cope well with updates - causes e-Notices.
117 // API has a lot of code to work around
118 // this but should review this code & remove the extra handling from the api
119 // it seems doubtful any of this is relevant if the contact fields & relationship
120 // type fields are not set
122 self
::checkDuplicateRelationship(
124 CRM_Utils_Array
::value('contact', $ids),
125 $ids['contactTarget'],
130 return array($valid, $invalid, $duplicate, $saved, NULL);
133 $validContacts = TRUE;
134 //validate contacts in update mode also.
135 if (CRM_Utils_Array
::value('contact', $ids) &&
136 CRM_Utils_Array
::value('contactTarget', $ids)
138 if (self
::checkValidRelationship($params, $ids, $ids['contactTarget'])) {
139 $validContacts = FALSE;
143 if ($validContacts) {
144 // editing an existing relationship
145 $relationship = self
::add($params, $ids, $ids['contactTarget']);
146 $relationshipIds[] = $relationship->id
;
147 $relationships[$relationship->id
] = $relationship;
152 // do not add to recent items for import, CRM-4399
153 if (!(CRM_Utils_Array
::value('skipRecentView', $params) ||
$invalid ||
$duplicate)) {
154 $url = CRM_Utils_System
::url('civicrm/contact/view/rel',
155 "action=view&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&context=home"
159 $session = CRM_Core_Session
::singleton();
160 $recentOther = array();
161 if (($session->get('userID') == $relationship->contact_id_a
) ||
162 CRM_Contact_BAO_Contact_Permission
::allow($relationship->contact_id_a
, CRM_Core_Permission
::EDIT
)
164 $rType = substr(CRM_Utils_Array
::value('relationship_type_id', $params), -3);
165 $recentOther = array(
166 'editUrl' => CRM_Utils_System
::url('civicrm/contact/view/rel',
167 "action=update&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
169 'deleteUrl' => CRM_Utils_System
::url('civicrm/contact/view/rel',
170 "action=delete&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
175 $title = CRM_Contact_BAO_Contact
::displayName($relationship->contact_id_a
) . ' (' . CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType',
176 $relationship->relationship_type_id
, 'label_a_b'
177 ) . ' ' . CRM_Contact_BAO_Contact
::displayName($relationship->contact_id_b
) . ')';
178 // add the recently created Relationship
179 CRM_Utils_Recent
::add($title,
183 $relationship->contact_id_a
,
189 return array($valid, $invalid, $duplicate, $saved, $relationshipIds, $relationships);
193 * This is the function that check/add if the relationship created is valid
195 * @param array $params (reference ) an assoc array of name/value pairs
196 * @param integer $contactId this is contact id for adding relationship
197 * @param array $ids the array that holds all the db ids
199 * @return object CRM_Contact_BAO_Relationship
203 static function add(&$params, $ids = array(), $contactId = NULL) {
205 CRM_Utils_Array
::value('relationship', $ids, CRM_Utils_Array
::value('id', $params));
208 if($relationshipId) {
211 //@todo hook are called from create and add - remove one
212 CRM_Utils_Hook
::pre($hook , 'Relationship', $relationshipId, $params);
214 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
216 // explode the string with _ to get the relationship type id
217 // and to know which contact has to be inserted in
218 // contact_id_a and which one in contact_id_b
219 list($type, $first, $second) = explode('_', $relationshipTypes);
221 $
{'contact_' . $first} = CRM_Utils_Array
::value('contact', $ids);
222 $
{'contact_' . $second} = $contactId;
224 // check if the relationship type is Head of Household then update the
225 // household's primary contact with this contact.
227 CRM_Contact_BAO_Household
::updatePrimaryContact($contact_b, $contact_a);
230 $relationship = new CRM_Contact_BAO_Relationship();
231 //@todo this code needs to be updated for the possibility that not all fields are set
233 $relationship->contact_id_b
= $contact_b;
234 $relationship->contact_id_a
= $contact_a;
235 $relationship->relationship_type_id
= $type;
236 $relationship->id
= $relationshipId;
238 $dateFields = array('end_date', 'start_date');
240 foreach (self
::getdefaults() as $defaultField => $defaultValue){
241 if(isset($params[$defaultField])){
242 if(in_array($defaultField, $dateFields)){
243 $relationship->$defaultField = CRM_Utils_Date
::format(CRM_Utils_Array
::value($defaultField, $params));
244 if(!$relationship->$defaultField){
245 $relationship->$defaultField = 'NULL';
249 $relationship->$defaultField = $params[$defaultField];
252 elseif(!$relationshipId){
253 $relationship->$defaultField = $defaultValue;
257 $relationship->save();
259 // add custom field values
260 if (CRM_Utils_Array
::value('custom', $params)) {
261 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_relationship', $relationship->id
);
264 $relationship->free();
266 CRM_Utils_Hook
::post($hook, 'Relationship', $relationshipId, $relationship);
268 return $relationship;
271 * Specifiy defaults for creating a relationship
273 * @return array $defaults array of defaults for creating relationship
277 static function getdefaults() {
280 'is_permission_a_b' => 0,
281 'is_permission_b_a' => 0,
283 'start_date' => 'NULL',
285 'end_date' => 'NULL',
291 * Check if there is data to create the object
293 * @param array $params (reference ) an assoc array of name/value pairs
299 static function dataExists(&$params) {
300 // return if no data present
301 if (!is_array(CRM_Utils_Array
::value('contact_check', $params))) {
308 * Function to get get list of relationship type based on the contact type.
310 * @param int $contactId this is the contact id of the current contact.
311 * @param string $strContact this value is currently ignored, keeping it there for legacy reasons
312 * @param string $relationshipId the id of the existing relationship if any
313 * @param string $contactType contact type
314 * @param boolean $all if true returns relationship types in both the direction
315 * @param string $column name/label that going to retrieve from db.
318 * @param string $contactSubType includes relationshiptypes between this subtype
320 * @param boolean $onlySubTypeRelationTypes if set only subtype which is passed by $contactSubType
321 * related relationshiptypes get return
325 * @return array - array reference of all relationship types with context to current contact.
327 static function getContactRelationshipType($contactId = NULL,
328 $contactSuffix = NULL,
329 $relationshipId = NULL,
333 $biDirectional = TRUE,
334 $contactSubType = NULL,
335 $onlySubTypeRelationTypes = FALSE
337 $allRelationshipType = array();
338 $relationshipType = array();
339 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType($column);
341 $otherContactType = NULL;
342 if ($relationshipId) {
343 $relationship = new CRM_Contact_DAO_Relationship();
344 $relationship->id
= $relationshipId;
345 if ($relationship->find(TRUE)) {
346 $contact = new CRM_Contact_DAO_Contact();
347 $contact->id
= ($relationship->contact_id_a
=== $contactId) ?
$relationship->contact_id_b
: $relationship->contact_id_a
;
349 if ($contact->find(TRUE)) {
350 $otherContactType = $contact->contact_type
;
351 //CRM-5125 for contact subtype specific relationshiptypes
352 if ($contact->contact_sub_type
) {
353 $otherContactSubType = $contact->contact_sub_type
;
359 $contactSubType = array();
361 $contactType = CRM_Contact_BAO_Contact
::getContactType($contactId);
362 $contactSubType = CRM_Contact_BAO_Contact
::getContactSubType($contactId);
365 foreach ($allRelationshipType as $key => $value) {
366 // the contact type is required or matches
367 if (((!$value['contact_type_a']) ||
368 $value['contact_type_a'] == $contactType
370 // the other contact type is required or present or matches
371 ((!$value['contact_type_b']) ||
372 (!$otherContactType) ||
373 $value['contact_type_b'] == $otherContactType
376 (in_array($value['contact_sub_type_a'], $contactSubType) ||
377 ((!$value['contact_sub_type_b'] &&
378 !$value['contact_sub_type_a']
380 !$onlySubTypeRelationTypes
385 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
387 elseif (empty($value['contact_type_b'])) {
388 // case contact_type_b is "all contacts", CRM-9877
389 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
392 if (((!$value['contact_type_b']) ||
393 $value['contact_type_b'] == $contactType
395 ((!$value['contact_type_a']) ||
396 (!$otherContactType) ||
397 $value['contact_type_a'] == $otherContactType
400 (in_array($value['contact_sub_type_b'], $contactSubType) ||
401 ((!$value['contact_sub_type_a'] &&
402 !$value['contact_sub_type_b']
404 !$onlySubTypeRelationTypes
409 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
411 elseif (empty($value['contact_type_a'])) {
412 // case contact_type_a is "all contacts", CRM-9877
413 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
417 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
418 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
422 if ($biDirectional) {
423 // lets clean up the data and eliminate all duplicate values
424 // (i.e. the relationship is bi-directional)
425 $relationshipType = array_unique($relationshipType);
428 // sort the relationshipType in ascending order CRM-7736
429 asort($relationshipType);
430 return $relationshipType;
433 static function clearCurrentEmployer($id, $action) {
434 $relationship = new CRM_Contact_DAO_Relationship();
435 $relationship->id
= $id;
436 $relationship->find(TRUE);
438 //to delete relationship between household and individual \
439 //or between individual and orgnization
440 if (($action & CRM_Core_Action
::DISABLE
) ||
($action & CRM_Core_Action
::DELETE
)) {
441 $relTypes = CRM_Utils_Array
::index(array('name_a_b'), CRM_Core_PseudoConstant
::relationshipType('name'));
442 if ($relationship->relationship_type_id
== $relTypes['Employee of']['id'] ||
443 $relationship->relationship_type_id
== $relTypes['Household Member of']['id']) {
444 $sharedContact = new CRM_Contact_DAO_Contact();
445 $sharedContact->id
= $relationship->contact_id_a
;
446 $sharedContact->find(TRUE);
448 if ($relationship->relationship_type_id
== 4 && $relationship->contact_id_b
== $sharedContact->employer_id
) {
449 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($relationship->contact_id_a
);
453 return $relationship;
457 * Function to delete the relationship
459 * @param int $id relationship id
466 static function del($id) {
467 // delete from relationship table
468 CRM_Utils_Hook
::pre('delete', 'Relationship', $id, CRM_Core_DAO
::$_nullArray);
470 $relationship = self
::clearCurrentEmployer($id, CRM_Core_Action
::DELETE
);
471 if (CRM_Core_Permission
::access('CiviMember')) {
472 // create $params array which isrequired to delete memberships
473 // of the related contacts.
475 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
476 'contact_check' => array($relationship->contact_id_b
=> 1),
480 // calling relatedMemberships to delete the memberships of
482 self
::relatedMemberships($relationship->contact_id_a
,
485 CRM_Core_Action
::DELETE
,
490 $relationship->delete();
491 CRM_Core_Session
::setStatus(ts('Selected relationship has been deleted successfully.'), ts('Record Deleted'), 'success');
493 CRM_Utils_Hook
::post('delete', 'Relationship', $relationship->id
, $relationship);
495 // delete the recently created Relationship
496 $relationshipRecent = array(
498 'type' => 'Relationship',
500 CRM_Utils_Recent
::del($relationshipRecent);
502 return $relationship;
506 * Function to disable/enable the relationship
508 * @param int $id relationship id
515 static function disableEnableRelationship($id, $action) {
516 $relationship = self
::clearCurrentEmployer($id, $action);
517 if (CRM_Core_Permission
::access('CiviMember')) {
518 // create $params array which isrequired to delete memberships
519 // of the related contacts.
521 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
522 'contact_check' => array($relationship->contact_id_b
=> 1),
526 // calling relatedMemberships to delete/add the memberships of
528 if ($action & CRM_Core_Action
::DISABLE
) {
529 CRM_Contact_BAO_Relationship
::relatedMemberships($relationship->contact_id_a
,
532 CRM_Core_Action
::DELETE
,
536 elseif ($action & CRM_Core_Action
::ENABLE
) {
537 $ids['contact'] = $relationship->contact_id_a
;
538 CRM_Contact_BAO_Relationship
::relatedMemberships($relationship->contact_id_a
,
541 CRM_Core_Action
::ADD
,
549 * Delete the object records that are associated with this contact
551 * @param int $contactId id of the contact to delete
557 static function deleteContact($contactId) {
558 $relationship = new CRM_Contact_DAO_Relationship();
559 $relationship->contact_id_a
= $contactId;
560 $relationship->delete();
562 $relationship = new CRM_Contact_DAO_Relationship();
563 $relationship->contact_id_b
= $contactId;
564 $relationship->delete();
566 CRM_Contact_BAO_Household
::updatePrimaryContact(NULL, $contactId);
570 * Function to get the other contact in a relationship
572 * @param int $id relationship id
574 * $returns returns the contact ids in the realtionship
578 static function getContactIds($id) {
579 $relationship = new CRM_Contact_DAO_Relationship();
581 $relationship->id
= $id;
582 $relationship->selectAdd();
583 $relationship->selectAdd('contact_id_a, contact_id_b');
584 $relationship->find(TRUE);
586 return $relationship;
590 * Function to check if the relationship type selected between two contacts is correct
592 * @param int $contact_a 1st contact id
593 * @param int $contact_b 2nd contact id
594 * @param int $relationshipTypeId relationship type id
596 * @return boolean true if it is valid relationship else false
600 static function checkRelationshipType($contact_a, $contact_b, $relationshipTypeId) {
601 $relationshipType = new CRM_Contact_DAO_RelationshipType();
602 $relationshipType->id
= $relationshipTypeId;
603 $relationshipType->selectAdd();
604 $relationshipType->selectAdd('contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b');
605 if ($relationshipType->find(TRUE)) {
606 $contact_type_a = CRM_Contact_BAO_Contact
::getContactType($contact_a);
607 $contact_type_b = CRM_Contact_BAO_Contact
::getContactType($contact_b);
609 $contact_sub_type_a = CRM_Contact_BAO_Contact
::getContactSubType($contact_a);
610 $contact_sub_type_b = CRM_Contact_BAO_Contact
::getContactSubType($contact_b);
612 if (((!$relationshipType->contact_type_a
) ||
($relationshipType->contact_type_a
== $contact_type_a)) &&
613 ((!$relationshipType->contact_type_b
) ||
($relationshipType->contact_type_b
== $contact_type_b)) &&
614 ((!$relationshipType->contact_sub_type_a
) ||
(in_array($relationshipType->contact_sub_type_a
,
617 ((!$relationshipType->contact_sub_type_b
) ||
(in_array($relationshipType->contact_sub_type_b
,
631 * this function does the validtion for valid relationship
633 * @param array $params this array contains the values there are subitted by the form
634 * @param array $ids the array that holds all the db ids
635 * @param integer $contactId this is contact id for adding relationship
641 static function checkValidRelationship(&$params, &$ids, $contactId) {
644 // get the string of relationship type
645 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
646 list($type, $first, $second) = explode('_', $relationshipTypes);
647 $
{'contact_' . $first} = CRM_Utils_Array
::value('contact', $ids);
648 $
{'contact_' . $second} = $contactId;
649 // function to check if the relationship selected is correct
650 // i.e. employer relationship can exit between Individual and Organization (not between Individual and Individual)
651 if (!CRM_Contact_BAO_Relationship
::checkRelationshipType($contact_a, $contact_b, $type)) {
652 $errors = 'Please select valid relationship between these two contacts.';
658 * this function checks for duplicate relationship
660 * @param array $params (reference ) an assoc array of name/value pairs
661 * @param integer $id this the id of the contact whom we are adding relationship
662 * @param integer $contactId this is contact id for adding relationship
663 * @param integer $relationshipId this is relationship id for the contact
665 * @return boolean true if record exists else false
669 static function checkDuplicateRelationship(&$params, $id, $contactId = 0, $relationshipId = 0) {
670 $relationshipTypeId = CRM_Utils_Array
::value('relationship_type_id', $params);
671 list($type, $first, $second) = explode('_', $relationshipTypeId);
675 FROM civicrm_relationship
676 WHERE relationship_type_id = " . CRM_Utils_Type
::escape($type, 'Integer');
679 * CRM-11792 - date fields from API are in ISO format, but this function
680 * supports date arrays BAO has increasingly standardised to ISO format
681 * so I believe this function should support ISO rather than make API
682 * format it - however, need to support array format for now to avoid breakage
683 * @ time of writing this function is called from Relationship::create (twice)
684 * CRM_BAO_Contact_Utils::clearCurrentEmployer (seemingly without dates)
685 * CRM_Contact_Form_Task_AddToOrganization::postProcess &
686 * CRM_Contact_Form_Task_AddToHousehold::postProcess
687 * (I don't think the last 2 support dates but not sure
690 $dateFields = array('end_date', 'start_date');
691 foreach ($dateFields as $dateField){
692 if(array_key_exists($dateField, $params)) {
693 if (empty($params[$dateField]) ||
$params[$dateField] == 'null'){
694 //this is most likely coming from an api call & probably loaded
695 // from the DB to deal with some of the
696 // other myriad of excessive checks still in place both in
697 // the api & the create functions
698 $queryString .= " AND $dateField IS NULL";
701 elseif (is_array($params[$dateField])){
702 $queryString .= " AND $dateField = " .
703 CRM_Utils_Type
::escape(CRM_Utils_Date
::format($params[$dateField]), 'Date');
706 $queryString .= " AND $dateField = " .
707 CRM_Utils_Type
::escape($params[$dateField], 'Date');
713 " AND ( ( contact_id_a = " . CRM_Utils_Type
::escape($id, 'Integer') .
714 " AND contact_id_b = " . CRM_Utils_Type
::escape($contactId, 'Integer') .
715 " ) OR ( contact_id_a = " . CRM_Utils_Type
::escape($contactId, 'Integer') .
716 " AND contact_id_b = " . CRM_Utils_Type
::escape($id, 'Integer') . " ) ) ";
718 //if caseId is provided, include it duplicate checking.
719 if ($caseId = CRM_Utils_Array
::value('case_id', $params)) {
720 $queryString .= " AND case_id = " . CRM_Utils_Type
::escape($caseId, 'Integer');
723 if ($relationshipId) {
724 $queryString .= " AND id !=" . CRM_Utils_Type
::escape($relationshipId, 'Integer');
727 $relationship = new CRM_Contact_BAO_Relationship();
728 $relationship->query($queryString);
729 $relationship->fetch();
730 $relationship->free();
731 return ($relationship->id
) ?
TRUE : FALSE;
735 * update the is_active flag in the db
737 * @param int $id id of the database record
738 * @param boolean $is_active value we want to set the is_active field
740 * @return Object DAO object on success, null otherwise
743 static function setIsActive($id, $is_active) {
744 // as both the create & add functions have a bunch of logic in them that
745 // doesn't seem to cope with a normal update we will call the api which
746 // has tested handling for this
747 // however, a longer term solution would be to simplify the add, create & api functions
748 // to be more standard. It is debatable @ that point whether it's better to call the BAO
749 // direct as the api is more tested.
750 civicrm_api3('relationship', 'create', array('id' => $id, 'is_active' => $is_active));
752 // call (undocumented possibly deprecated) hook
753 CRM_Utils_Hook
::enableDisable('CRM_Contact_BAO_Relationship', $id, $is_active);
759 * Given the list of params in the params array, fetch the object
760 * and store the values in the values array
762 * @param array $params input parameters to find object
763 * @param array $values output values of the object
764 * @param array $ids the array that holds all the db ids
766 * @return array (reference) the values that could be potentially assigned to smarty
770 static function &getValues(&$params, &$values) {
771 if (empty($params)) {
776 // get the specific number of relationship or all relationships.
777 if (CRM_Utils_Array
::value('numRelationship', $params)) {
778 $v['data'] = &CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'], NULL, $params['numRelationship']);
781 $v['data'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id']);
784 // get the total count of relationships
785 $v['totalCount'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'], NULL, NULL, TRUE);
787 $values['relationship']['data'] = &$v['data'];
788 $values['relationship']['totalCount'] = &$v['totalCount'];
794 * helper function to form the sql for relationship retrieval
796 * @param int $contactId contact id
797 * @param int $status (check const at top of file)
798 * @param int $numRelationship no of relationships to display (limit)
799 * @param int $count get the no of relationships
800 * $param int $relationshipId relationship id
801 * @param string $direction the direction we are interested in a_b or b_a
802 * @param array $params array of extra values including relationship_type_id per api spec
804 * return string the query for this diretion
808 static function makeURLClause($contactId, $status, $numRelationship, $count, $relationshipId, $direction, $params = array()) {
809 $select = $from = $where = '';
813 if ($direction == 'a_b') {
814 $select .= ' SELECT count(DISTINCT civicrm_relationship.id) as cnt1, 0 as cnt2 ';
817 $select .= ' SELECT 0 as cnt1, count(DISTINCT civicrm_relationship.id) as cnt2 ';
821 $select .= ' SELECT civicrm_relationship.id as civicrm_relationship_id,
822 civicrm_contact.sort_name as sort_name,
823 civicrm_contact.display_name as display_name,
824 civicrm_contact.job_title as job_title,
825 civicrm_contact.employer_id as employer_id,
826 civicrm_contact.organization_name as organization_name,
827 civicrm_address.street_address as street_address,
828 civicrm_address.city as city,
829 civicrm_address.postal_code as postal_code,
830 civicrm_state_province.abbreviation as state,
831 civicrm_country.name as country,
832 civicrm_email.email as email,
833 civicrm_phone.phone as phone,
834 civicrm_contact.id as civicrm_contact_id,
835 civicrm_contact.contact_type as contact_type,
836 civicrm_relationship.contact_id_b as contact_id_b,
837 civicrm_relationship.contact_id_a as contact_id_a,
838 civicrm_relationship_type.id as civicrm_relationship_type_id,
839 civicrm_relationship.start_date as start_date,
840 civicrm_relationship.end_date as end_date,
841 civicrm_relationship.description as description,
842 civicrm_relationship.is_active as is_active,
843 civicrm_relationship.is_permission_a_b as is_permission_a_b,
844 civicrm_relationship.is_permission_b_a as is_permission_b_a,
845 civicrm_relationship.case_id as case_id';
847 if ($direction == 'a_b') {
848 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
849 civicrm_relationship_type.label_b_a as relation ';
852 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
853 civicrm_relationship_type.label_a_b as relation ';
858 FROM civicrm_relationship
859 INNER JOIN civicrm_relationship_type ON ( civicrm_relationship.relationship_type_id = civicrm_relationship_type.id )
860 INNER JOIN civicrm_contact ";
861 if ($direction == 'a_b') {
862 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_a ) ';
865 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_b ) ';
868 LEFT JOIN civicrm_address ON (civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1)
869 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
870 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id AND civicrm_email.is_primary = 1)
871 LEFT JOIN civicrm_state_province ON (civicrm_address.state_province_id = civicrm_state_province.id)
872 LEFT JOIN civicrm_country ON (civicrm_address.country_id = civicrm_country.id)
874 $where = 'WHERE ( 1 )';
876 if ($direction == 'a_b') {
877 $where .= ' AND civicrm_relationship.contact_id_b = ' . CRM_Utils_Type
::escape($contactId, 'Positive');
880 $where .= ' AND civicrm_relationship.contact_id_a = ' . CRM_Utils_Type
::escape($contactId, 'Positive');
883 if ($relationshipId) {
884 $where .= ' AND civicrm_relationship.id = ' . CRM_Utils_Type
::escape($relationshipId, 'Positive');
887 $date = date('Y-m-d');
888 if ($status == self
::PAST
) {
889 //this case for showing past relationship
890 $where .= ' AND civicrm_relationship.is_active = 1 ';
891 $where .= " AND civicrm_relationship.end_date < '" . $date . "'";
893 elseif ($status == self
::DISABLED
) {
894 // this case for showing disabled relationship
895 $where .= ' AND civicrm_relationship.is_active = 0 ';
897 elseif ($status == self
::CURRENT
) {
898 //this case for showing current relationship
899 $where .= ' AND civicrm_relationship.is_active = 1 ';
900 $where .= " AND (civicrm_relationship.end_date >= '" . $date . "' OR civicrm_relationship.end_date IS NULL) ";
902 elseif ($status == self
::INACTIVE
) {
903 //this case for showing inactive relationships
904 $where .= " AND (civicrm_relationship.end_date < '" . $date . "'";
905 $where .= ' OR civicrm_relationship.is_active = 0 )';
909 $where .= ' AND civicrm_contact.is_deleted = 0';
910 if(!empty($params['membership_type_id']) && empty($params['relationship_type_id'])) {
911 $where .= self
::membershipTypeToRelationshipTypes($params, $direction);
913 if(!empty($params['relationship_type_id'])) {
914 if(is_array($params['relationship_type_id'])) {
915 $where .= " AND " . CRM_Core_DAO
::createSQLFilter('relationship_type_id', $params['relationship_type_id'], 'Integer');
918 $where .= ' AND relationship_type_id = ' . CRM_Utils_Type
::escape($params['relationship_type_id'], 'Positive');
921 if ($direction == 'a_b') {
922 $where .= ' ) UNION ';
928 return array($select, $from, $where);
932 * This is the function to get the list of relationships
934 * @param int $contactId contact id
935 * @param int $status 1: Past 2: Disabled 3: Current
936 * @param int $numRelationship no of relationships to display (limit)
937 * @param int $count get the no of relationships
938 * $param int $relationshipId relationship id
939 * $param array $links the list of links to display
940 * $param int $permissionMask the permission mask to be applied for the actions
941 * $param boolean $permissionedContact to return only permissioned Contact
942 * $param array $params array of variables consistent with filters supported by the api
943 * return array $values relationship records
947 static function getRelationship($contactId = NULL,
948 $status = 0, $numRelationship = 0,
949 $count = 0, $relationshipId = 0,
950 $links = NULL, $permissionMask = NULL,
951 $permissionedContact = FALSE,
955 if (!$contactId && !$relationshipId) {
959 list($select1, $from1, $where1) = self
::makeURLClause($contactId, $status, $numRelationship,
960 $count, $relationshipId, 'a_b', $params
962 list($select2, $from2, $where2) = self
::makeURLClause($contactId, $status, $numRelationship,
963 $count, $relationshipId, 'b_a', $params
966 $order = $limit = '';
968 $order = ' ORDER BY civicrm_relationship_type_id, sort_name ';
970 if ($numRelationship) {
971 $limit = " LIMIT 0, $numRelationship";
975 // building the query string
977 $queryString = $select1 . $from1 . $where1 . $select2 . $from2 . $where2 . $order . $limit;
979 $relationship = new CRM_Contact_DAO_Relationship();
981 $relationship->query($queryString);
984 $relationshipCount = 0;
985 while ($relationship->fetch()) {
986 $relationshipCount +
= $relationship->cnt1 +
$relationship->cnt2
;
988 return $relationshipCount;
993 if ($status != self
::INACTIVE
) {
995 $mask = array_sum(array_keys($links));
996 if ($mask & CRM_Core_Action
::DISABLE
) {
997 $mask -= CRM_Core_Action
::DISABLE
;
999 if ($mask & CRM_Core_Action
::ENABLE
) {
1000 $mask -= CRM_Core_Action
::ENABLE
;
1003 if ($status == self
::CURRENT
) {
1004 $mask |
= CRM_Core_Action
::DISABLE
;
1006 elseif ($status == self
::DISABLED
) {
1007 $mask |
= CRM_Core_Action
::ENABLE
;
1009 $mask = $mask & $permissionMask;
1012 while ($relationship->fetch()) {
1013 $rid = $relationship->civicrm_relationship_id
;
1014 $cid = $relationship->civicrm_contact_id
;
1015 if (($permissionedContact) &&
1016 (!CRM_Contact_BAO_Contact_Permission
::relationship($cid, $contactId))
1020 $values[$rid]['id'] = $rid;
1021 $values[$rid]['cid'] = $cid;
1022 $values[$rid]['contact_id_a'] = $relationship->contact_id_a
;
1023 $values[$rid]['contact_id_b'] = $relationship->contact_id_b
;
1024 $values[$rid]['relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1025 $values[$rid]['relation'] = $relationship->relation
;
1026 $values[$rid]['name'] = $relationship->sort_name
;
1027 $values[$rid]['display_name'] = $relationship->display_name
;
1028 $values[$rid]['job_title'] = $relationship->job_title
;
1029 $values[$rid]['email'] = $relationship->email
;
1030 $values[$rid]['phone'] = $relationship->phone
;
1031 $values[$rid]['employer_id'] = $relationship->employer_id
;
1032 $values[$rid]['organization_name'] = $relationship->organization_name
;
1033 $values[$rid]['country'] = $relationship->country
;
1034 $values[$rid]['city'] = $relationship->city
;
1035 $values[$rid]['state'] = $relationship->state
;
1036 $values[$rid]['start_date'] = $relationship->start_date
;
1037 $values[$rid]['end_date'] = $relationship->end_date
;
1038 $values[$rid]['description'] = $relationship->description
;
1039 $values[$rid]['is_active'] = $relationship->is_active
;
1040 $values[$rid]['is_permission_a_b'] = $relationship->is_permission_a_b
;
1041 $values[$rid]['is_permission_b_a'] = $relationship->is_permission_b_a
;
1042 $values[$rid]['case_id'] = $relationship->case_id
;
1045 $values[$rid]['status'] = $status;
1048 $values[$rid]['civicrm_relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1050 if ($relationship->contact_id_a
== $contactId) {
1051 $values[$rid]['rtype'] = 'a_b';
1054 $values[$rid]['rtype'] = 'b_a';
1060 'rtype' => $values[$rid]['rtype'],
1061 'cid' => $contactId,
1062 'cbid' => $values[$rid]['cid'],
1063 'caseid' => $values[$rid]['case_id'],
1064 'clientid' => $contactId,
1067 if ($status == self
::INACTIVE
) {
1068 // setting links for inactive relationships
1069 $mask = array_sum(array_keys($links));
1070 if (!$values[$rid]['is_active']) {
1071 $mask -= CRM_Core_Action
::DISABLE
;
1074 $mask -= CRM_Core_Action
::ENABLE
;
1075 $mask -= CRM_Core_Action
::DISABLE
;
1079 // Give access to manage case link by copying to MAX_ACTION index temporarily, depending on case permission of user.
1080 if ($values[$rid]['case_id']) {
1081 // Borrowed logic from CRM_Case_Page_Tab
1082 $hasCaseAccess = FALSE;
1083 if (CRM_Core_Permission
::check('access all cases and activities')) {
1084 $hasCaseAccess = TRUE;
1087 $userCases = CRM_Case_BAO_Case
::getCases(FALSE);
1088 if (array_key_exists($values[$rid]['case_id'], $userCases)) {
1089 $hasCaseAccess = TRUE;
1093 if ($hasCaseAccess) {
1094 // give access by copying to MAX_ACTION temporarily, otherwise leave at NONE which won't display
1095 $links[CRM_Core_Action
::MAX_ACTION
] = $links[CRM_Core_Action
::NONE
];
1096 $links[CRM_Core_Action
::MAX_ACTION
]['name'] = ts('Manage Case #%1', array(1 => $values[$rid]['case_id']));
1098 // Also make sure we have the right client cid since can get here from multiple relationship tabs.
1099 if ($values[$rid]['rtype'] == 'b_a') {
1100 $replace['clientid'] = $values[$rid]['cid'];
1105 $values[$rid]['action'] = CRM_Core_Action
::formLink($links, $mask, $replace);
1106 unset($links[CRM_Core_Action
::MAX_ACTION
]);
1110 $relationship->free();
1116 * Function to get get list of relationship type based on the target contact type.
1118 * @param string $targetContactType it's valid contact tpye(may be Individual , Organization , Household)
1120 * @return array - array reference of all relationship types with context to current contact type .
1123 function getRelationType($targetContactType) {
1124 $relationshipType = array();
1125 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType();
1127 foreach ($allRelationshipType as $key => $type) {
1128 if ($type['contact_type_b'] == $targetContactType) {
1129 $relationshipType[$key . '_a_b'] = $type['label_a_b'];
1133 return $relationshipType;
1137 * Function to create / update / delete membership for related contacts.
1139 * This function will create/update/delete membership for related
1140 * contact based on 1) contact have active membership 2) that
1141 * membership is is extedned by the same relationship type to that
1142 * of the existing relationship.
1144 * @param $contactId Int contact id
1145 * @param $params array array of values submitted by POST
1146 * @param $ids array array of ids
1147 * @param $action which action called this function
1152 static function relatedMemberships($contactId, &$params, $ids, $action = CRM_Core_Action
::ADD
, $active = TRUE) {
1153 // Check the end date and set the status of the relationship
1155 $status = self
::CURRENT
;
1157 if (!empty($params['end_date'])) {
1158 $endDate = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Date
::format($params['end_date']), NULL, 'Ymd');
1159 $today = date('Ymd');
1161 if ($today > $endDate) {
1162 $status = self
::PAST
;
1166 if (($action & CRM_Core_Action
::ADD
) &&
1167 ($status & self
::PAST
)
1169 // if relationship is PAST and action is ADD, no qustion
1170 // of creating RELATED membership and return back to
1175 $rel = explode('_', $params['relationship_type_id']);
1177 $relTypeId = $rel[0];
1178 $relDirection = "_{$rel[1]}_{$rel[2]}";
1179 $targetContact = array();
1180 if (($action & CRM_Core_Action
::ADD
) ||
1181 ($action & CRM_Core_Action
::DELETE
)
1183 $contact = $contactId;
1184 $targetContact = CRM_Utils_Array
::value('contact_check', $params);
1186 elseif ($action & CRM_Core_Action
::UPDATE
) {
1187 $contact = $ids['contact'];
1188 $targetContact = array($ids['contactTarget'] => 1);
1191 // Build the 'values' array for
1194 // This will allow us to check if either of the contacts in
1195 // relationship have active memberships.
1200 $values[$contact] = array(
1201 'relatedContacts' => $targetContact,
1202 'relationshipTypeId' => $relTypeId,
1203 'relationshipTypeDirection' => $relDirection,
1206 if (!empty($targetContact)) {
1207 foreach ($targetContact as $cid => $donCare) {
1208 $values[$cid] = array(
1209 'relatedContacts' => array($contact => 1),
1210 'relationshipTypeId' => $relTypeId,
1213 $relTypeParams = array('id' => $relTypeId);
1214 $relTypeValues = array();
1215 CRM_Contact_BAO_RelationshipType
::retrieve($relTypeParams, $relTypeValues);
1217 if (CRM_Utils_Array
::value('name_a_b', $relTypeValues) == CRM_Utils_Array
::value('name_b_a', $relTypeValues)) {
1218 $values[$cid]['relationshipTypeDirection'] = '_a_b';
1221 $values[$cid]['relationshipTypeDirection'] = ($relDirection == '_a_b') ?
'_b_a' : '_a_b';
1226 // Now get the active memberships for all the contacts.
1227 // If contact have any valid membership(s), then add it to
1229 foreach ($values as $cid => $subValues) {
1230 $memParams = array('contact_id' => $cid);
1231 $memberships = array();
1233 CRM_Member_BAO_Membership
::getValues($memParams, $memberships, $active);
1235 if (empty($memberships)) {
1239 $values[$cid]['memberships'] = $memberships;
1241 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1243 // done with 'values' array.
1244 // Finally add / edit / delete memberships for the related contacts
1245 foreach ($values as $cid => $details) {
1246 if (!array_key_exists('memberships', $details)) {
1250 $mainRelatedContactId = key(CRM_Utils_Array
::value('relatedContacts', $details, array()));
1252 foreach ($details['memberships'] as $membershipId => $membershipValues) {
1253 $relTypeIds = array();
1254 if ($action & CRM_Core_Action
::DELETE
) {
1255 // Delete memberships of the related contacts only if relationship type exists for membership type
1257 SELECT relationship_type_id, relationship_direction
1258 FROM civicrm_membership_type
1259 WHERE id = {$membershipValues['membership_type_id']}";
1260 $dao = CRM_Core_DAO
::executeQuery($query);
1261 $relTypeDirs = array();
1262 while ($dao->fetch()) {
1263 $relTypeId = $dao->relationship_type_id
;
1264 $relDirection = $dao->relationship_direction
;
1266 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $relTypeId);
1267 if (in_array($values[$cid]['relationshipTypeId'], $relTypeIds)) {
1268 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $mainRelatedContactId);
1272 if (($action & CRM_Core_Action
::UPDATE
) &&
1273 ($status & self
::PAST
) &&
1274 ($membershipValues['owner_membership_id'])
1276 // If relationship is PAST and action is UPDATE
1277 // then delete the RELATED membership
1278 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipValues['owner_membership_id'],
1279 $membershipValues['membership_contact_id']
1284 // add / edit the memberships for related
1287 // Get the Membership Type Details.
1288 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipValues['membership_type_id']);
1289 // Check if contact's relationship type exists in membership type
1290 $relTypeDirs = array();
1291 if (CRM_Utils_Array
::value('relationship_type_id', $membershipType)) {
1292 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_type_id']);
1294 if (CRM_Utils_Array
::value('relationship_direction', $membershipType)) {
1295 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_direction']);
1297 foreach ($relTypeIds as $key => $value) {
1298 $relTypeDirs[] = $value . '_' . $relDirections[$key];
1300 $relTypeDir = $details['relationshipTypeId'] . $details['relationshipTypeDirection'];
1301 if (in_array($relTypeDir, $relTypeDirs)) {
1302 // Check if relationship being created/updated is
1303 // similar to that of membership type's
1306 $membershipValues['owner_membership_id'] = $membershipId;
1307 unset($membershipValues['id']);
1308 unset($membershipValues['membership_contact_id']);
1309 unset($membershipValues['contact_id']);
1310 unset($membershipValues['membership_id']);
1311 foreach ($details['relatedContacts'] as $relatedContactId => $donCare) {
1312 $membershipValues['contact_id'] = $relatedContactId;
1313 if ($deceasedStatusId &&
1314 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $relatedContactId, 'is_deceased')
1316 $membershipValues['status_id'] = $deceasedStatusId;
1317 $membershipValues['skipStatusCal'] = TRUE;
1320 'join_date', 'start_date', 'end_date') as $dateField) {
1321 if (CRM_Utils_Array
::value($dateField, $membershipValues)) {
1322 $membershipValues[$dateField] = CRM_Utils_Date
::processDate($membershipValues[$dateField]);
1326 if ($action & CRM_Core_Action
::UPDATE
) {
1327 //delete the membership record for related
1328 //contact before creating new membership record.
1329 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $relatedContactId);
1332 // check whether we have some related memberships still available
1335 FROM civicrm_membership
1336 LEFT JOIN civicrm_membership_status ON (civicrm_membership_status.id = civicrm_membership.status_id)
1337 WHERE membership_type_id = {$membershipValues['membership_type_id']} AND owner_membership_id = {$membershipValues['owner_membership_id']}
1338 AND is_current_member = 1";
1339 $result = CRM_Core_DAO
::singleValueQuery($query);
1340 if ($result < CRM_Utils_Array
::value('max_related', $membershipValues, PHP_INT_MAX
)) {
1341 CRM_Member_BAO_Membership
::create($membershipValues, CRM_Core_DAO
::$_nullArray);
1345 elseif ($action & CRM_Core_Action
::UPDATE
) {
1346 // if action is update and updated relationship do
1347 // not match with the existing
1348 // membership=>relationship then we need to
1349 // delete the membership record created for
1350 // previous relationship.
1352 if (self
::isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, CRM_Utils_Array
::value('relationship_ids', $params))) {
1353 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $mainRelatedContactId);
1361 * Helper function to check whether to delete the membership or
1367 static function isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, $relIds) {
1368 if (in_array($relTypeId, $relTypeIds)) {
1372 if (empty($relIds)) {
1376 $relParamas = array(1 => array($contactId, 'Integer'),
1377 2 => array($mainRelatedContactId, 'Integer'),
1380 if ($contactId == $mainRelatedContactId) {
1381 $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);
1382 if ($recordsFound) {
1388 $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);
1390 if ($recordsFound) {
1398 * Function to get Current Employer for Contact
1400 * @param $contactIds Contact Ids
1402 * @return $currentEmployer array of the current employer
1407 static function getCurrentEmployer($contactIds) {
1408 $contacts = implode(',', $contactIds);
1411 SELECT organization_name, id, employer_id
1412 FROM civicrm_contact
1413 WHERE id IN ( {$contacts} )
1416 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1417 $currentEmployer = array();
1418 while ($dao->fetch()) {
1419 $currentEmployer[$dao->id
]['org_id'] = $dao->employer_id
;
1420 $currentEmployer[$dao->id
]['org_name'] = $dao->organization_name
;
1423 return $currentEmployer;
1427 * Function to return list of permissioned employer for a given contact.
1429 * @param $contactID int contact id whose employers
1431 * @param $name string employers sort name
1435 * @return array array of employers.
1438 static function getPermissionedEmployer($contactID, $name = NULL) {
1439 //get the relationship id
1440 $relTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType',
1441 'Employee of', 'id', 'name_a_b'
1444 return self
::getPermissionedContacts($contactID, $relTypeId, $name);
1449 * Function to return list of permissioned contacts for a given contact and relationship type
1451 * @param $contactID int contact id whose permissioned contacts are to be found.
1452 * @param $relTypeId relationship type id
1453 * @param $name string
1457 * @return array of contacts
1459 static function getPermissionedContacts($contactID, $relTypeId, $name = NULL) {
1460 $contacts = array();
1464 SELECT cc.id as id, cc.sort_name as name
1465 FROM civicrm_relationship cr, civicrm_contact cc
1467 cr.contact_id_a = %1 AND
1468 cr.relationship_type_id = %2 AND
1469 cr.is_permission_a_b = 1 AND
1470 IF(cr.end_date IS NULL, 1, (DATEDIFF( CURDATE( ), cr.end_date ) <= 0)) AND
1471 cr.is_active = 1 AND
1472 cc.id = cr.contact_id_b";
1474 if (!empty($name)) {
1475 $name = CRM_Utils_Type
::escape($name, 'String');
1477 AND cc.sort_name LIKE '%$name%'";
1480 $args = array(1 => array($contactID, 'Integer'), 2 => array($relTypeId, 'Integer'));
1481 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1483 while ($dao->fetch()) {
1484 $contacts[$dao->id
] = array(
1485 'name' => $dao->name
,
1486 'value' => $dao->id
,
1493 static function getValidContactTypeList($relType) {
1494 // string looks like 4_a_b
1495 $rel_parts = explode('_', $relType);
1496 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType('label');
1497 $contactProfiles = CRM_Core_BAO_UFGroup
::getReservedProfiles('Contact', NULL);
1499 if ($rel_parts[1] == 'a') {
1500 $leftType = $allRelationshipType[$rel_parts[0]]['contact_type_b'];
1503 $leftType = $allRelationshipType[$rel_parts[0]]['contact_type_a'];
1506 // Handle 'All Contacts' contact type for left side of relationship ($leftType is empty in this case)
1507 // In this case all reserved profiles are available
1508 if ($leftType == '') {
1509 $contactTypes = $contactProfiles;
1511 $contactTypes = array();
1512 foreach ($contactProfiles as $key => $value) {
1513 if (strpos($value, $leftType) !== FALSE) {
1514 $contactTypes = array($key => $value);
1519 return $contactTypes;
1523 * Merge relationships from otherContact to mainContact
1524 * Called during contact merge operation
1526 * @param int $mainId contact id of main contact record.
1527 * @param int $otherId contact id of record which is going to merge.
1528 * @param array $sqls (reference) array of sql statements to append to.
1530 * @see CRM_Dedupe_Merger::cpTables()
1534 static function mergeRelationships($mainId, $otherId, &$sqls) {
1535 // Delete circular relationships
1536 $sqls[] = "DELETE FROM civicrm_relationship
1537 WHERE (contact_id_a = $mainId AND contact_id_b = $otherId)
1538 OR (contact_id_b = $mainId AND contact_id_a = $otherId)";
1540 // Delete relationship from other contact if main contact already has that relationship
1541 $sqls[] = "DELETE r2
1542 FROM civicrm_relationship r1, civicrm_relationship r2
1543 WHERE r1.relationship_type_id = r2.relationship_type_id
1546 r1.contact_id_a = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_b = r2.contact_id_b
1547 OR r1.contact_id_b = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_a = r2.contact_id_a
1549 (r1.contact_id_a = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_b = r2.contact_id_a
1550 OR r1.contact_id_b = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_a = r2.contact_id_b)
1551 AND r1.relationship_type_id IN (SELECT id FROM civicrm_relationship_type WHERE name_b_a = name_a_b)
1555 // Move relationships
1556 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_a = $mainId WHERE contact_id_a = $otherId";
1557 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_b = $mainId WHERE contact_id_b = $otherId";
1559 // Move current employer id (name will get updated later)
1560 $sqls[] = "UPDATE civicrm_contact SET employer_id = $mainId WHERE employer_id = $otherId";
1564 * Set 'is_valid' field to false for all relationships whose end date is in the past, ie. are expired.
1566 * @return True on success, false if error is encountered.
1568 static function disableExpiredRelationships() {
1569 $query = "SELECT id FROM civicrm_relationship WHERE is_active = 1 AND end_date < CURDATE()";
1571 $dao = CRM_Core_DAO
::executeQuery($query);
1572 while ($dao->fetch()) {
1573 $result = CRM_Contact_BAO_Relationship
::setIsActive($dao->id
, FALSE);
1574 // Result will be NULL if error occurred. We abort early if error detected.
1575 if ($result == NULL) {
1583 * Function filters the query by possible relationships for the membership type
1584 * It is intended to be called when constructing queries for the api (reciprocal & non-reciprocal)
1585 * and to add clauses to limit the return to those relationships which COULD inherit a membership type
1586 * (as opposed to those who inherit a particular membership
1588 * @param array $params api input array
1590 static function membershipTypeToRelationshipTypes(&$params, $direction = NULL) {
1591 $membershipType = civicrm_api3('membership_type', 'getsingle', array('id' => $params['membership_type_id'], 'return' => 'relationship_type_id, relationship_direction'));
1592 $relationshipTypes = $membershipType['relationship_type_id'];
1593 if(empty($relationshipTypes)) {
1596 // if we don't have any contact data we can only filter on type
1597 if(empty($params['contact_id']) && empty($params['contact_id_a']) && empty($params['contact_id_a'])) {
1598 $params['relationship_type_id'] = array('IN' => $relationshipTypes);
1602 $relationshipDirections = (array) $membershipType['relationship_direction'];
1603 // if we have contact_id_a OR contact_id_b we can make a call here
1604 // if we have contact??
1605 foreach ($relationshipDirections as $index => $mtdirection) {
1606 if(isset($params['contact_id_a']) && $mtdirection == 'a_b' ||
$direction == 'a_b') {
1607 $types[] = $relationshipTypes[$index];
1609 if(isset($params['contact_id_b']) && $mtdirection == 'b_a' ||
$direction == 'b_a') {
1610 $types[] = $relationshipTypes[$index];
1613 if(!empty($types)) {
1614 $params['relationship_type_id'] = array('IN' => $types);
1616 elseif(!empty($clauses)) {
1617 return explode(' OR ', $clauses);
1620 // effectively setting it to return no results
1621 $params['relationship_type_id'] = 0;