3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
35 class CRM_Contact_BAO_Relationship
extends CRM_Contact_DAO_Relationship
{
38 * Various constants to indicate different type of relationships
42 const PAST
= 1, DISABLED
= 2, CURRENT
= 4, INACTIVE
= 8;
45 * 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 CRM_Contact_BAO_Relationship object
56 public static function create(&$params, $ids = array()) {
57 $valid = $invalid = $duplicate = $saved = 0;
58 $relationships = $relationshipIds = array();
59 $relationshipId = CRM_Utils_Array
::value('relationship', $ids, CRM_Utils_Array
::value('id', $params));
60 //CRM-9015 - the hooks are called here & in add (since add doesn't call create)
61 // but in future should be tidied per ticket
62 if(empty($relationshipId)){
64 $action = CRM_Core_Action
::ADD
;
68 $action = CRM_Core_Action
::UPDATE
;
71 CRM_Utils_Hook
::pre($hook, 'Relationship', $relationshipId, $params);
73 if (!$relationshipId) {
74 // creating a new relationship
75 $dataExists = self
::dataExists($params);
77 return array(FALSE, TRUE, FALSE, FALSE, NULL);
79 $relationshipIds = array();
80 foreach ($params['contact_check'] as $key => $value) {
82 // check if the relationship is valid between contacts.
83 // step 1: check if the relationship is valid if not valid skip and keep the count
84 // step 2: check the if two contacts already have a relationship if yes skip and keep the count
85 // step 3: if valid relationship then add the relation and keep the count
88 $errors = self
::checkValidRelationship($params, $ids, $key);
95 self
::checkDuplicateRelationship(
97 CRM_Utils_Array
::value('contact', $ids),
106 $relationship = self
::add($params, $ids, $key);
107 $relationshipIds[] = $relationship->id
;
108 $relationships[$relationship->id
] = $relationship;
111 // editing the relationship
114 // check for duplicate relationship
115 // @todo this code doesn't cope well with updates - causes e-Notices.
116 // API has a lot of code to work around
117 // this but should review this code & remove the extra handling from the api
118 // it seems doubtful any of this is relevant if the contact fields & relationship
119 // type fields are not set
121 self
::checkDuplicateRelationship(
123 CRM_Utils_Array
::value('contact', $ids),
124 $ids['contactTarget'],
129 return array($valid, $invalid, $duplicate, $saved, NULL);
132 $validContacts = TRUE;
133 //validate contacts in update mode also.
134 if (!empty($ids['contact']) && !empty($ids['contactTarget'])) {
135 if (self
::checkValidRelationship($params, $ids, $ids['contactTarget'])) {
136 $validContacts = FALSE;
140 if ($validContacts) {
141 // editing an existing relationship
142 $relationship = self
::add($params, $ids, $ids['contactTarget']);
143 $relationshipIds[] = $relationship->id
;
144 $relationships[$relationship->id
] = $relationship;
149 // do not add to recent items for import, CRM-4399
150 if (!(!empty($params['skipRecentView']) ||
$invalid ||
$duplicate)) {
151 $url = CRM_Utils_System
::url('civicrm/contact/view/rel',
152 "action=view&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&context=home"
156 $session = CRM_Core_Session
::singleton();
157 $recentOther = array();
158 if (($session->get('userID') == $relationship->contact_id_a
) ||
159 CRM_Contact_BAO_Contact_Permission
::allow($relationship->contact_id_a
, CRM_Core_Permission
::EDIT
)
161 $rType = substr(CRM_Utils_Array
::value('relationship_type_id', $params), -3);
162 $recentOther = array(
163 'editUrl' => CRM_Utils_System
::url('civicrm/contact/view/rel',
164 "action=update&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
166 'deleteUrl' => CRM_Utils_System
::url('civicrm/contact/view/rel',
167 "action=delete&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
172 $title = CRM_Contact_BAO_Contact
::displayName($relationship->contact_id_a
) . ' (' . CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType',
173 $relationship->relationship_type_id
, 'label_a_b'
174 ) . ' ' . CRM_Contact_BAO_Contact
::displayName($relationship->contact_id_b
) . ')';
175 // add the recently created Relationship
176 CRM_Utils_Recent
::add($title,
180 $relationship->contact_id_a
,
186 return array($valid, $invalid, $duplicate, $saved, $relationshipIds, $relationships);
190 * This is the function that check/add if the relationship created is valid
192 * @param array $params (reference ) an assoc array of name/value pairs
193 * @param integer $contactId this is contact id for adding relationship
194 * @param array $ids the array that holds all the db ids
196 * @return CRM_Contact_BAO_Relationship
199 public static function add(&$params, $ids = array(), $contactId = NULL) {
201 CRM_Utils_Array
::value('relationship', $ids, CRM_Utils_Array
::value('id', $params));
204 if($relationshipId) {
207 //@todo hook are called from create and add - remove one
208 CRM_Utils_Hook
::pre($hook , 'Relationship', $relationshipId, $params);
210 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
212 // explode the string with _ to get the relationship type id
213 // and to know which contact has to be inserted in
214 // contact_id_a and which one in contact_id_b
215 list($type, $first, $second) = explode('_', $relationshipTypes);
217 $
{'contact_' . $first} = CRM_Utils_Array
::value('contact', $ids);
218 $
{'contact_' . $second} = $contactId;
220 // check if the relationship type is Head of Household then update the
221 // household's primary contact with this contact.
223 CRM_Contact_BAO_Household
::updatePrimaryContact($contact_b, $contact_a);
226 $relationship = new CRM_Contact_BAO_Relationship();
227 //@todo this code needs to be updated for the possibility that not all fields are set
229 $relationship->contact_id_b
= $contact_b;
230 $relationship->contact_id_a
= $contact_a;
231 $relationship->relationship_type_id
= $type;
232 $relationship->id
= $relationshipId;
234 $dateFields = array('end_date', 'start_date');
236 foreach (self
::getdefaults() as $defaultField => $defaultValue){
237 if(isset($params[$defaultField])){
238 if(in_array($defaultField, $dateFields)){
239 $relationship->$defaultField = CRM_Utils_Date
::format(CRM_Utils_Array
::value($defaultField, $params));
240 if(!$relationship->$defaultField){
241 $relationship->$defaultField = 'NULL';
245 $relationship->$defaultField = $params[$defaultField];
248 elseif(!$relationshipId){
249 $relationship->$defaultField = $defaultValue;
253 $relationship->save();
255 // add custom field values
256 if (!empty($params['custom'])) {
257 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_relationship', $relationship->id
);
260 $relationship->free();
262 CRM_Utils_Hook
::post($hook, 'Relationship', $relationship->id
, $relationship);
264 return $relationship;
267 * Specifiy defaults for creating a relationship
269 * @return array $defaults array of defaults for creating relationship
272 public static function getdefaults() {
275 'is_permission_a_b' => 0,
276 'is_permission_b_a' => 0,
278 'start_date' => 'NULL',
280 'end_date' => 'NULL',
286 * Check if there is data to create the object
288 * @param array $params (reference ) an assoc array of name/value pairs
293 public static function dataExists(&$params) {
294 // return if no data present
295 if (!is_array(CRM_Utils_Array
::value('contact_check', $params))) {
302 * Get get list of relationship type based on the contact type.
304 * @param int $contactId this is the contact id of the current contact.
305 * @param null $contactSuffix
306 * @param string $relationshipId the id of the existing relationship if any
307 * @param string $contactType contact type
308 * @param boolean $all if true returns relationship types in both the direction
309 * @param string $column name/label that going to retrieve from db.
310 * @param bool $biDirectional
311 * @param string $contactSubType includes relationshiptypes between this subtype
312 * @param boolean $onlySubTypeRelationTypes if set only subtype which is passed by $contactSubType
313 * related relationshiptypes get return
317 * @return array - array reference of all relationship types with context to current contact.
319 static function getContactRelationshipType($contactId = NULL,
320 $contactSuffix = NULL,
321 $relationshipId = NULL,
325 $biDirectional = TRUE,
326 $contactSubType = NULL,
327 $onlySubTypeRelationTypes = FALSE
329 $allRelationshipType = array();
330 $relationshipType = array();
331 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType($column);
333 $otherContactType = NULL;
334 if ($relationshipId) {
335 $relationship = new CRM_Contact_DAO_Relationship();
336 $relationship->id
= $relationshipId;
337 if ($relationship->find(TRUE)) {
338 $contact = new CRM_Contact_DAO_Contact();
339 $contact->id
= ($relationship->contact_id_a
=== $contactId) ?
$relationship->contact_id_b
: $relationship->contact_id_a
;
341 if ($contact->find(TRUE)) {
342 $otherContactType = $contact->contact_type
;
343 //CRM-5125 for contact subtype specific relationshiptypes
344 if ($contact->contact_sub_type
) {
345 $otherContactSubType = $contact->contact_sub_type
;
351 $contactSubType = array();
353 $contactType = CRM_Contact_BAO_Contact
::getContactType($contactId);
354 $contactSubType = CRM_Contact_BAO_Contact
::getContactSubType($contactId);
357 foreach ($allRelationshipType as $key => $value) {
358 // the contact type is required or matches
359 if (((!$value['contact_type_a']) ||
360 $value['contact_type_a'] == $contactType
362 // the other contact type is required or present or matches
363 ((!$value['contact_type_b']) ||
364 (!$otherContactType) ||
365 $value['contact_type_b'] == $otherContactType
367 (in_array($value['contact_sub_type_a'], $contactSubType) ||
368 in_array($value['contact_sub_type_b'], $contactSubType) ||
369 (!$value['contact_sub_type_a'] && !$onlySubTypeRelationTypes)
372 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
375 if (((!$value['contact_type_b']) ||
376 $value['contact_type_b'] == $contactType
378 ((!$value['contact_type_a']) ||
379 (!$otherContactType) ||
380 $value['contact_type_a'] == $otherContactType
382 (in_array($value['contact_sub_type_b'], $contactSubType) ||
383 in_array($value['contact_sub_type_a'], $contactSubType) ||
384 (!$value['contact_sub_type_b'] && !$onlySubTypeRelationTypes)
387 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
391 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
392 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
396 if ($biDirectional) {
397 // lets clean up the data and eliminate all duplicate values
398 // (i.e. the relationship is bi-directional)
399 $relationshipType = array_unique($relationshipType);
402 // sort the relationshipType in ascending order CRM-7736
403 asort($relationshipType);
404 return $relationshipType;
411 * @return CRM_Contact_DAO_Relationship
413 public static function clearCurrentEmployer($id, $action) {
414 $relationship = new CRM_Contact_DAO_Relationship();
415 $relationship->id
= $id;
416 $relationship->find(TRUE);
418 //to delete relationship between household and individual \
419 //or between individual and orgnization
420 if (($action & CRM_Core_Action
::DISABLE
) ||
($action & CRM_Core_Action
::DELETE
)) {
421 $relTypes = CRM_Utils_Array
::index(array('name_a_b'), CRM_Core_PseudoConstant
::relationshipType('name'));
422 if ($relationship->relationship_type_id
== $relTypes['Employee of']['id'] ||
423 $relationship->relationship_type_id
== $relTypes['Household Member of']['id']) {
424 $sharedContact = new CRM_Contact_DAO_Contact();
425 $sharedContact->id
= $relationship->contact_id_a
;
426 $sharedContact->find(TRUE);
428 if ($relationship->relationship_type_id
== 4 && $relationship->contact_id_b
== $sharedContact->employer_id
) {
429 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($relationship->contact_id_a
);
433 return $relationship;
437 * Delete the relationship
439 * @param int $id relationship id
445 public static function del($id) {
446 // delete from relationship table
447 CRM_Utils_Hook
::pre('delete', 'Relationship', $id, CRM_Core_DAO
::$_nullArray);
449 $relationship = self
::clearCurrentEmployer($id, CRM_Core_Action
::DELETE
);
450 if (CRM_Core_Permission
::access('CiviMember')) {
451 // create $params array which isrequired to delete memberships
452 // of the related contacts.
454 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
455 'contact_check' => array($relationship->contact_id_b
=> 1),
459 // calling relatedMemberships to delete the memberships of
461 self
::relatedMemberships($relationship->contact_id_a
,
464 CRM_Core_Action
::DELETE
,
469 $relationship->delete();
470 CRM_Core_Session
::setStatus(ts('Selected relationship has been deleted successfully.'), ts('Record Deleted'), 'success');
472 CRM_Utils_Hook
::post('delete', 'Relationship', $id, $relationship);
474 // delete the recently created Relationship
475 $relationshipRecent = array(
477 'type' => 'Relationship',
479 CRM_Utils_Recent
::del($relationshipRecent);
481 return $relationship;
485 * Disable/enable the relationship
487 * @param int $id relationship id
494 public static function disableEnableRelationship($id, $action) {
495 $relationship = self
::clearCurrentEmployer($id, $action);
496 if (CRM_Core_Permission
::access('CiviMember')) {
497 // create $params array which isrequired to delete memberships
498 // of the related contacts.
500 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
501 'contact_check' => array($relationship->contact_id_b
=> 1),
505 // calling relatedMemberships to delete/add the memberships of
507 if ($action & CRM_Core_Action
::DISABLE
) {
508 CRM_Contact_BAO_Relationship
::relatedMemberships($relationship->contact_id_a
,
511 CRM_Core_Action
::DELETE
,
515 elseif ($action & CRM_Core_Action
::ENABLE
) {
516 $ids['contact'] = $relationship->contact_id_a
;
517 CRM_Contact_BAO_Relationship
::relatedMemberships($relationship->contact_id_a
,
520 CRM_Core_Action
::ADD
,
528 * Delete the object records that are associated with this contact
530 * @param int $contactId id of the contact to delete
535 public static function deleteContact($contactId) {
536 $relationship = new CRM_Contact_DAO_Relationship();
537 $relationship->contact_id_a
= $contactId;
538 $relationship->delete();
540 $relationship = new CRM_Contact_DAO_Relationship();
541 $relationship->contact_id_b
= $contactId;
542 $relationship->delete();
544 CRM_Contact_BAO_Household
::updatePrimaryContact(NULL, $contactId);
548 * Get the other contact in a relationship
550 * @param int $id relationship id
552 * $returns returns the contact ids in the realtionship
554 * @return \CRM_Contact_DAO_Relationship
557 public static function getContactIds($id) {
558 $relationship = new CRM_Contact_DAO_Relationship();
560 $relationship->id
= $id;
561 $relationship->selectAdd();
562 $relationship->selectAdd('contact_id_a, contact_id_b');
563 $relationship->find(TRUE);
565 return $relationship;
569 * Check if the relationship type selected between two contacts is correct
571 * @param int $contact_a 1st contact id
572 * @param int $contact_b 2nd contact id
573 * @param int $relationshipTypeId relationship type id
575 * @return boolean true if it is valid relationship else false
578 public static function checkRelationshipType($contact_a, $contact_b, $relationshipTypeId) {
579 $relationshipType = new CRM_Contact_DAO_RelationshipType();
580 $relationshipType->id
= $relationshipTypeId;
581 $relationshipType->selectAdd();
582 $relationshipType->selectAdd('contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b');
583 if ($relationshipType->find(TRUE)) {
584 $contact_type_a = CRM_Contact_BAO_Contact
::getContactType($contact_a);
585 $contact_type_b = CRM_Contact_BAO_Contact
::getContactType($contact_b);
587 $contact_sub_type_a = CRM_Contact_BAO_Contact
::getContactSubType($contact_a);
588 $contact_sub_type_b = CRM_Contact_BAO_Contact
::getContactSubType($contact_b);
590 if (((!$relationshipType->contact_type_a
) ||
($relationshipType->contact_type_a
== $contact_type_a)) &&
591 ((!$relationshipType->contact_type_b
) ||
($relationshipType->contact_type_b
== $contact_type_b)) &&
592 ((!$relationshipType->contact_sub_type_a
) ||
(in_array($relationshipType->contact_sub_type_a
,
595 ((!$relationshipType->contact_sub_type_b
) ||
(in_array($relationshipType->contact_sub_type_b
,
609 * This function does the validtion for valid relationship
611 * @param array $params this array contains the values there are subitted by the form
612 * @param array $ids the array that holds all the db ids
613 * @param integer $contactId this is contact id for adding relationship
619 public static function checkValidRelationship(&$params, &$ids, $contactId) {
622 // get the string of relationship type
623 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
624 list($type, $first, $second) = explode('_', $relationshipTypes);
625 $
{'contact_' . $first} = CRM_Utils_Array
::value('contact', $ids);
626 $
{'contact_' . $second} = $contactId;
627 // function to check if the relationship selected is correct
628 // i.e. employer relationship can exit between Individual and Organization (not between Individual and Individual)
629 if (!CRM_Contact_BAO_Relationship
::checkRelationshipType($contact_a, $contact_b, $type)) {
630 $errors = 'Please select valid relationship between these two contacts.';
636 * This function checks for duplicate relationship
638 * @param array $params (reference ) an assoc array of name/value pairs
639 * @param integer $id this the id of the contact whom we are adding relationship
640 * @param integer $contactId this is contact id for adding relationship
641 * @param integer $relationshipId this is relationship id for the contact
643 * @return boolean true if record exists else false
646 public static function checkDuplicateRelationship(&$params, $id, $contactId = 0, $relationshipId = 0) {
647 $relationshipTypeId = CRM_Utils_Array
::value('relationship_type_id', $params);
648 list($type, $first, $second) = explode('_', $relationshipTypeId);
652 FROM civicrm_relationship
653 WHERE relationship_type_id = " . CRM_Utils_Type
::escape($type, 'Integer');
656 * CRM-11792 - date fields from API are in ISO format, but this function
657 * supports date arrays BAO has increasingly standardised to ISO format
658 * so I believe this function should support ISO rather than make API
659 * format it - however, need to support array format for now to avoid breakage
660 * @ time of writing this function is called from Relationship::create (twice)
661 * CRM_BAO_Contact_Utils::clearCurrentEmployer (seemingly without dates)
662 * CRM_Contact_Form_Task_AddToOrganization::postProcess &
663 * CRM_Contact_Form_Task_AddToHousehold::postProcess
664 * (I don't think the last 2 support dates but not sure
667 $dateFields = array('end_date', 'start_date');
668 foreach ($dateFields as $dateField){
669 if(array_key_exists($dateField, $params)) {
670 if (empty($params[$dateField]) ||
$params[$dateField] == 'null'){
671 //this is most likely coming from an api call & probably loaded
672 // from the DB to deal with some of the
673 // other myriad of excessive checks still in place both in
674 // the api & the create functions
675 $queryString .= " AND $dateField IS NULL";
678 elseif (is_array($params[$dateField])){
679 $queryString .= " AND $dateField = " .
680 CRM_Utils_Type
::escape(CRM_Utils_Date
::format($params[$dateField]), 'Date');
683 $queryString .= " AND $dateField = " .
684 CRM_Utils_Type
::escape($params[$dateField], 'Date');
690 " AND ( ( contact_id_a = " . CRM_Utils_Type
::escape($id, 'Integer') .
691 " AND contact_id_b = " . CRM_Utils_Type
::escape($contactId, 'Integer') .
692 " ) OR ( contact_id_a = " . CRM_Utils_Type
::escape($contactId, 'Integer') .
693 " AND contact_id_b = " . CRM_Utils_Type
::escape($id, 'Integer') . " ) ) ";
695 //if caseId is provided, include it duplicate checking.
696 if ($caseId = CRM_Utils_Array
::value('case_id', $params)) {
697 $queryString .= " AND case_id = " . CRM_Utils_Type
::escape($caseId, 'Integer');
700 if ($relationshipId) {
701 $queryString .= " AND id !=" . CRM_Utils_Type
::escape($relationshipId, 'Integer');
704 $relationship = new CRM_Contact_BAO_Relationship();
705 $relationship->query($queryString);
706 $relationship->fetch();
707 $relationship->free();
708 return ($relationship->id
) ?
TRUE : FALSE;
712 * Update the is_active flag in the db
714 * @param int $id id of the database record
715 * @param boolean $is_active value we want to set the is_active field
717 * @throws CiviCRM_API3_Exception
718 * @return Object DAO object on success, null otherwise
721 public static function setIsActive($id, $is_active) {
722 // as both the create & add functions have a bunch of logic in them that
723 // doesn't seem to cope with a normal update we will call the api which
724 // has tested handling for this
725 // however, a longer term solution would be to simplify the add, create & api functions
726 // to be more standard. It is debatable @ that point whether it's better to call the BAO
727 // direct as the api is more tested.
728 $result = civicrm_api('relationship', 'create', array(
730 'is_active' => $is_active,
734 if (is_array($result) && !empty($result['is_error']) && $result['error_message'] != 'Relationship already exists') {
735 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array
::value('error_code', $result, 'undefined'), $result);
738 // call (undocumented possibly deprecated) hook
739 CRM_Utils_Hook
::enableDisable('CRM_Contact_BAO_Relationship', $id, $is_active);
745 * Given the list of params in the params array, fetch the object
746 * and store the values in the values array
748 * @param array $params input parameters to find object
749 * @param array $values output values of the object
751 * @return array (reference) the values that could be potentially assigned to smarty
754 public static function &getValues(&$params, &$values) {
755 if (empty($params)) {
760 // get the specific number of relationship or all relationships.
761 if (!empty($params['numRelationship'])) {
762 $v['data'] = &CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'], NULL, $params['numRelationship']);
765 $v['data'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id']);
768 // get the total count of relationships
769 $v['totalCount'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'], NULL, NULL, TRUE);
771 $values['relationship']['data'] = &$v['data'];
772 $values['relationship']['totalCount'] = &$v['totalCount'];
778 * Helper function to form the sql for relationship retrieval
780 * @param int $contactId contact id
781 * @param int $status (check const at top of file)
782 * @param int $numRelationship no of relationships to display (limit)
783 * @param int $count get the no of relationships
784 * $param int $relationshipId relationship id
785 * @param int $relationshipId
786 * @param string $direction the direction we are interested in a_b or b_a
787 * @param array $params array of extra values including relationship_type_id per api spec
789 * return string the query for this diretion
794 public static function makeURLClause($contactId, $status, $numRelationship, $count, $relationshipId, $direction, $params = array()) {
795 $select = $from = $where = '';
799 if ($direction == 'a_b') {
800 $select .= ' SELECT count(DISTINCT civicrm_relationship.id) as cnt1, 0 as cnt2 ';
803 $select .= ' SELECT 0 as cnt1, count(DISTINCT civicrm_relationship.id) as cnt2 ';
807 $select .= ' SELECT civicrm_relationship.id as civicrm_relationship_id,
808 civicrm_contact.sort_name as sort_name,
809 civicrm_contact.display_name as display_name,
810 civicrm_contact.job_title as job_title,
811 civicrm_contact.employer_id as employer_id,
812 civicrm_contact.organization_name as organization_name,
813 civicrm_address.street_address as street_address,
814 civicrm_address.city as city,
815 civicrm_address.postal_code as postal_code,
816 civicrm_state_province.abbreviation as state,
817 civicrm_country.name as country,
818 civicrm_email.email as email,
819 civicrm_contact.contact_type as contact_type,
820 civicrm_phone.phone as phone,
821 civicrm_contact.id as civicrm_contact_id,
822 civicrm_relationship.contact_id_b as contact_id_b,
823 civicrm_relationship.contact_id_a as contact_id_a,
824 civicrm_relationship_type.id as civicrm_relationship_type_id,
825 civicrm_relationship.start_date as start_date,
826 civicrm_relationship.end_date as end_date,
827 civicrm_relationship.description as description,
828 civicrm_relationship.is_active as is_active,
829 civicrm_relationship.is_permission_a_b as is_permission_a_b,
830 civicrm_relationship.is_permission_b_a as is_permission_b_a,
831 civicrm_relationship.case_id as case_id';
833 if ($direction == 'a_b') {
834 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
835 civicrm_relationship_type.label_b_a as relation ';
838 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
839 civicrm_relationship_type.label_a_b as relation ';
844 FROM civicrm_relationship
845 INNER JOIN civicrm_relationship_type ON ( civicrm_relationship.relationship_type_id = civicrm_relationship_type.id )
846 INNER JOIN civicrm_contact ";
847 if ($direction == 'a_b') {
848 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_a ) ';
851 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_b ) ';
854 LEFT JOIN civicrm_address ON (civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1)
855 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
856 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id AND civicrm_email.is_primary = 1)
857 LEFT JOIN civicrm_state_province ON (civicrm_address.state_province_id = civicrm_state_province.id)
858 LEFT JOIN civicrm_country ON (civicrm_address.country_id = civicrm_country.id)
860 $where = 'WHERE ( 1 )';
862 if ($direction == 'a_b') {
863 $where .= ' AND civicrm_relationship.contact_id_b = ' . CRM_Utils_Type
::escape($contactId, 'Positive');
866 $where .= ' AND civicrm_relationship.contact_id_a = ' . CRM_Utils_Type
::escape($contactId, 'Positive') . '
867 AND civicrm_relationship.contact_id_a != civicrm_relationship.contact_id_b ';
870 if ($relationshipId) {
871 $where .= ' AND civicrm_relationship.id = ' . CRM_Utils_Type
::escape($relationshipId, 'Positive');
874 $date = date('Y-m-d');
875 if ($status == self
::PAST
) {
876 //this case for showing past relationship
877 $where .= ' AND civicrm_relationship.is_active = 1 ';
878 $where .= " AND civicrm_relationship.end_date < '" . $date . "'";
880 elseif ($status == self
::DISABLED
) {
881 // this case for showing disabled relationship
882 $where .= ' AND civicrm_relationship.is_active = 0 ';
884 elseif ($status == self
::CURRENT
) {
885 //this case for showing current relationship
886 $where .= ' AND civicrm_relationship.is_active = 1 ';
887 $where .= " AND (civicrm_relationship.end_date >= '" . $date . "' OR civicrm_relationship.end_date IS NULL) ";
889 elseif ($status == self
::INACTIVE
) {
890 //this case for showing inactive relationships
891 $where .= " AND (civicrm_relationship.end_date < '" . $date . "'";
892 $where .= ' OR civicrm_relationship.is_active = 0 )';
896 $where .= ' AND civicrm_contact.is_deleted = 0';
897 if(!empty($params['membership_type_id']) && empty($params['relationship_type_id'])) {
898 $where .= self
::membershipTypeToRelationshipTypes($params, $direction);
900 if(!empty($params['relationship_type_id'])) {
901 if(is_array($params['relationship_type_id'])) {
902 $where .= " AND " . CRM_Core_DAO
::createSQLFilter('relationship_type_id', $params['relationship_type_id'], 'Integer');
905 $where .= ' AND relationship_type_id = ' . CRM_Utils_Type
::escape($params['relationship_type_id'], 'Positive');
908 if ($direction == 'a_b') {
909 $where .= ' ) UNION ';
915 return array($select, $from, $where);
919 * This is the function to get the list of relationships
921 * @param int $contactId contact id
922 * @param int $status 1: Past 2: Disabled 3: Current
923 * @param int $numRelationship no of relationships to display (limit)
924 * @param int $count get the no of relationships
925 * $param int $relationshipId relationship id
926 * $param array $links the list of links to display
927 * $param int $permissionMask the permission mask to be applied for the actions
928 * $param boolean $permissionedContact to return only permissioned Contact
929 * $param array $params array of variables consistent with filters supported by the api
930 * return array $values relationship records
931 * @param int $relationshipId
933 * @param null $permissionMask
934 * @param bool $permissionedContact
935 * @param array $params
940 static function getRelationship($contactId = NULL,
941 $status = 0, $numRelationship = 0,
942 $count = 0, $relationshipId = 0,
943 $links = NULL, $permissionMask = NULL,
944 $permissionedContact = FALSE,
948 if (!$contactId && !$relationshipId) {
952 list($select1, $from1, $where1) = self
::makeURLClause($contactId, $status, $numRelationship,
953 $count, $relationshipId, 'a_b', $params
955 list($select2, $from2, $where2) = self
::makeURLClause($contactId, $status, $numRelationship,
956 $count, $relationshipId, 'b_a', $params
959 $order = $limit = '';
961 if (empty($params['sort'])) {
962 $order = ' ORDER BY civicrm_relationship_type_id, sort_name ';
965 $order = " ORDER BY {$params['sort']} ";
969 if (!empty($params['offset']) && $params['offset'] > 0) {
970 $offset = $params['offset'];
973 if ($numRelationship) {
974 $limit = " LIMIT {$offset}, $numRelationship";
978 // building the query string
979 $queryString = $select1 . $from1 . $where1 . $select2 . $from2 . $where2 . $order . $limit;
981 $relationship = new CRM_Contact_DAO_Relationship();
983 $relationship->query($queryString);
986 $relationshipCount = 0;
987 while ($relationship->fetch()) {
988 $relationshipCount +
= $relationship->cnt1 +
$relationship->cnt2
;
990 return $relationshipCount;
995 if ($status != self
::INACTIVE
) {
997 $mask = array_sum(array_keys($links));
998 if ($mask & CRM_Core_Action
::DISABLE
) {
999 $mask -= CRM_Core_Action
::DISABLE
;
1001 if ($mask & CRM_Core_Action
::ENABLE
) {
1002 $mask -= CRM_Core_Action
::ENABLE
;
1005 if ($status == self
::CURRENT
) {
1006 $mask |
= CRM_Core_Action
::DISABLE
;
1008 elseif ($status == self
::DISABLED
) {
1009 $mask |
= CRM_Core_Action
::ENABLE
;
1011 $mask = $mask & $permissionMask;
1014 while ($relationship->fetch()) {
1015 $rid = $relationship->civicrm_relationship_id
;
1016 $cid = $relationship->civicrm_contact_id
;
1017 if (($permissionedContact) &&
1018 (!CRM_Contact_BAO_Contact_Permission
::relationship($cid, $contactId))
1022 $values[$rid]['id'] = $rid;
1023 $values[$rid]['cid'] = $cid;
1024 $values[$rid]['contact_id_a'] = $relationship->contact_id_a
;
1025 $values[$rid]['contact_id_b'] = $relationship->contact_id_b
;
1026 $values[$rid]['contact_type'] = $relationship->contact_type
;
1027 $values[$rid]['relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1028 $values[$rid]['relation'] = $relationship->relation
;
1029 $values[$rid]['name'] = $relationship->sort_name
;
1030 $values[$rid]['display_name'] = $relationship->display_name
;
1031 $values[$rid]['job_title'] = $relationship->job_title
;
1032 $values[$rid]['email'] = $relationship->email
;
1033 $values[$rid]['phone'] = $relationship->phone
;
1034 $values[$rid]['employer_id'] = $relationship->employer_id
;
1035 $values[$rid]['organization_name'] = $relationship->organization_name
;
1036 $values[$rid]['country'] = $relationship->country
;
1037 $values[$rid]['city'] = $relationship->city
;
1038 $values[$rid]['state'] = $relationship->state
;
1039 $values[$rid]['start_date'] = $relationship->start_date
;
1040 $values[$rid]['end_date'] = $relationship->end_date
;
1041 $values[$rid]['description'] = $relationship->description
;
1042 $values[$rid]['is_active'] = $relationship->is_active
;
1043 $values[$rid]['is_permission_a_b'] = $relationship->is_permission_a_b
;
1044 $values[$rid]['is_permission_b_a'] = $relationship->is_permission_b_a
;
1045 $values[$rid]['case_id'] = $relationship->case_id
;
1048 $values[$rid]['status'] = $status;
1051 $values[$rid]['civicrm_relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1053 if ($relationship->contact_id_a
== $contactId) {
1054 $values[$rid]['rtype'] = 'a_b';
1057 $values[$rid]['rtype'] = 'b_a';
1063 'rtype' => $values[$rid]['rtype'],
1064 'cid' => $contactId,
1065 'cbid' => $values[$rid]['cid'],
1066 'caseid' => $values[$rid]['case_id'],
1067 'clientid' => $contactId,
1070 if ($status == self
::INACTIVE
) {
1071 // setting links for inactive relationships
1072 $mask = array_sum(array_keys($links));
1073 if (!$values[$rid]['is_active']) {
1074 $mask -= CRM_Core_Action
::DISABLE
;
1077 $mask -= CRM_Core_Action
::ENABLE
;
1078 $mask -= CRM_Core_Action
::DISABLE
;
1082 // Give access to manage case link by copying to MAX_ACTION index temporarily, depending on case permission of user.
1083 if ($values[$rid]['case_id']) {
1084 // Borrowed logic from CRM_Case_Page_Tab
1085 $hasCaseAccess = FALSE;
1086 if (CRM_Core_Permission
::check('access all cases and activities')) {
1087 $hasCaseAccess = TRUE;
1090 $userCases = CRM_Case_BAO_Case
::getCases(FALSE);
1091 if (array_key_exists($values[$rid]['case_id'], $userCases)) {
1092 $hasCaseAccess = TRUE;
1096 if ($hasCaseAccess) {
1097 // give access by copying to MAX_ACTION temporarily, otherwise leave at NONE which won't display
1098 $links[CRM_Core_Action
::MAX_ACTION
] = $links[CRM_Core_Action
::NONE
];
1099 $links[CRM_Core_Action
::MAX_ACTION
]['name'] = ts('Manage Case #%1', array(1 => $values[$rid]['case_id']));
1100 $links[CRM_Core_Action
::MAX_ACTION
]['class'] = 'no-popup';
1102 // Also make sure we have the right client cid since can get here from multiple relationship tabs.
1103 if ($values[$rid]['rtype'] == 'b_a') {
1104 $replace['clientid'] = $values[$rid]['cid'];
1109 $values[$rid]['action'] = CRM_Core_Action
::formLink(
1115 'relationship.selector.row',
1118 unset($links[CRM_Core_Action
::MAX_ACTION
]);
1122 $relationship->free();
1128 * Get get list of relationship type based on the target contact type.
1130 * @param string $targetContactType it's valid contact tpye(may be Individual , Organization , Household)
1132 * @return array - array reference of all relationship types with context to current contact type .
1135 public function getRelationType($targetContactType) {
1136 $relationshipType = array();
1137 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType();
1139 foreach ($allRelationshipType as $key => $type) {
1140 if ($type['contact_type_b'] == $targetContactType) {
1141 $relationshipType[$key . '_a_b'] = $type['label_a_b'];
1145 return $relationshipType;
1149 * Create / update / delete membership for related contacts.
1151 * This function will create/update/delete membership for related
1152 * contact based on 1) contact have active membership 2) that
1153 * membership is is extedned by the same relationship type to that
1154 * of the existing relationship.
1156 * @param $contactId Int contact id
1157 * @param $params array array of values submitted by POST
1158 * @param $ids array array of ids
1159 * @param \const|\which $action which action called this function
1161 * @param bool $active
1165 public static function relatedMemberships($contactId, &$params, $ids, $action = CRM_Core_Action
::ADD
, $active = TRUE) {
1166 // Check the end date and set the status of the relationship
1168 $status = self
::CURRENT
;
1170 if (!empty($params['end_date'])) {
1171 $endDate = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Date
::format($params['end_date']), NULL, 'Ymd');
1172 $today = date('Ymd');
1174 if ($today > $endDate) {
1175 $status = self
::PAST
;
1179 if (($action & CRM_Core_Action
::ADD
) &&
1180 ($status & self
::PAST
)
1182 // if relationship is PAST and action is ADD, no qustion
1183 // of creating RELATED membership and return back to
1188 $rel = explode('_', $params['relationship_type_id']);
1190 $relTypeId = $rel[0];
1191 $relDirection = "_{$rel[1]}_{$rel[2]}";
1192 $targetContact = array();
1193 if (($action & CRM_Core_Action
::ADD
) ||
1194 ($action & CRM_Core_Action
::DELETE
)
1196 $contact = $contactId;
1197 $targetContact = CRM_Utils_Array
::value('contact_check', $params);
1199 elseif ($action & CRM_Core_Action
::UPDATE
) {
1200 $contact = $ids['contact'];
1201 $targetContact = array($ids['contactTarget'] => 1);
1204 // Build the 'values' array for
1207 // This will allow us to check if either of the contacts in
1208 // relationship have active memberships.
1213 $values[$contact] = array(
1214 'relatedContacts' => $targetContact,
1215 'relationshipTypeId' => $relTypeId,
1216 'relationshipTypeDirection' => $relDirection,
1219 if (!empty($targetContact)) {
1220 foreach ($targetContact as $cid => $donCare) {
1221 $values[$cid] = array(
1222 'relatedContacts' => array($contact => 1),
1223 'relationshipTypeId' => $relTypeId,
1226 $relTypeParams = array('id' => $relTypeId);
1227 $relTypeValues = array();
1228 CRM_Contact_BAO_RelationshipType
::retrieve($relTypeParams, $relTypeValues);
1230 if (CRM_Utils_Array
::value('name_a_b', $relTypeValues) == CRM_Utils_Array
::value('name_b_a', $relTypeValues)) {
1231 $values[$cid]['relationshipTypeDirection'] = '_a_b';
1234 $values[$cid]['relationshipTypeDirection'] = ($relDirection == '_a_b') ?
'_b_a' : '_a_b';
1239 // Now get the active memberships for all the contacts.
1240 // If contact have any valid membership(s), then add it to
1242 foreach ($values as $cid => $subValues) {
1243 $memParams = array('contact_id' => $cid);
1244 $memberships = array();
1246 CRM_Member_BAO_Membership
::getValues($memParams, $memberships, $active);
1248 if (empty($memberships)) {
1252 $values[$cid]['memberships'] = $memberships;
1254 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1256 // done with 'values' array.
1257 // Finally add / edit / delete memberships for the related contacts
1258 foreach ($values as $cid => $details) {
1259 if (!array_key_exists('memberships', $details)) {
1263 $mainRelatedContactId = key(CRM_Utils_Array
::value('relatedContacts', $details, array()));
1265 foreach ($details['memberships'] as $membershipId => $membershipValues) {
1266 $relTypeIds = array();
1267 if ($action & CRM_Core_Action
::DELETE
) {
1268 // Delete memberships of the related contacts only if relationship type exists for membership type
1270 SELECT relationship_type_id, relationship_direction
1271 FROM civicrm_membership_type
1272 WHERE id = {$membershipValues['membership_type_id']}";
1273 $dao = CRM_Core_DAO
::executeQuery($query);
1274 $relTypeDirs = array();
1275 while ($dao->fetch()) {
1276 $relTypeId = $dao->relationship_type_id
;
1277 $relDirection = $dao->relationship_direction
;
1279 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $relTypeId);
1280 if (in_array($values[$cid]['relationshipTypeId'], $relTypeIds)) {
1281 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $mainRelatedContactId);
1285 if (($action & CRM_Core_Action
::UPDATE
) &&
1286 ($status & self
::PAST
) &&
1287 ($membershipValues['owner_membership_id'])
1289 // If relationship is PAST and action is UPDATE
1290 // then delete the RELATED membership
1291 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipValues['owner_membership_id'],
1292 $membershipValues['membership_contact_id']
1297 // add / edit the memberships for related
1300 // Get the Membership Type Details.
1301 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipValues['membership_type_id']);
1302 // Check if contact's relationship type exists in membership type
1303 $relTypeDirs = array();
1304 if (!empty($membershipType['relationship_type_id'])) {
1305 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_type_id']);
1307 if (!empty($membershipType['relationship_direction'])) {
1308 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_direction']);
1310 foreach ($relTypeIds as $key => $value) {
1311 $relTypeDirs[] = $value . '_' . $relDirections[$key];
1313 $relTypeDir = $details['relationshipTypeId'] . $details['relationshipTypeDirection'];
1314 if (in_array($relTypeDir, $relTypeDirs)) {
1315 // Check if relationship being created/updated is
1316 // similar to that of membership type's
1319 $membershipValues['owner_membership_id'] = $membershipId;
1320 unset($membershipValues['id']);
1321 unset($membershipValues['membership_contact_id']);
1322 unset($membershipValues['contact_id']);
1323 unset($membershipValues['membership_id']);
1324 foreach ($details['relatedContacts'] as $relatedContactId => $donCare) {
1325 $membershipValues['contact_id'] = $relatedContactId;
1326 if ($deceasedStatusId &&
1327 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $relatedContactId, 'is_deceased')
1329 $membershipValues['status_id'] = $deceasedStatusId;
1330 $membershipValues['skipStatusCal'] = TRUE;
1333 'join_date', 'start_date', 'end_date') as $dateField) {
1334 if (!empty($membershipValues[$dateField])) {
1335 $membershipValues[$dateField] = CRM_Utils_Date
::processDate($membershipValues[$dateField]);
1339 if ($action & CRM_Core_Action
::UPDATE
) {
1340 //delete the membership record for related
1341 //contact before creating new membership record.
1342 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $relatedContactId);
1345 // check whether we have some related memberships still available
1348 FROM civicrm_membership
1349 LEFT JOIN civicrm_membership_status ON (civicrm_membership_status.id = civicrm_membership.status_id)
1350 WHERE membership_type_id = {$membershipValues['membership_type_id']} AND owner_membership_id = {$membershipValues['owner_membership_id']}
1351 AND is_current_member = 1";
1352 $result = CRM_Core_DAO
::singleValueQuery($query);
1353 if ($result < CRM_Utils_Array
::value('max_related', $membershipValues, PHP_INT_MAX
)) {
1354 CRM_Member_BAO_Membership
::create($membershipValues, CRM_Core_DAO
::$_nullArray);
1358 elseif ($action & CRM_Core_Action
::UPDATE
) {
1359 // if action is update and updated relationship do
1360 // not match with the existing
1361 // membership=>relationship then we need to
1362 // delete the membership record created for
1363 // previous relationship.
1365 if (self
::isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, CRM_Utils_Array
::value('relationship_ids', $params))) {
1366 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $mainRelatedContactId);
1374 * Helper function to check whether to delete the membership or
1380 public static function isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, $relIds) {
1381 if (in_array($relTypeId, $relTypeIds)) {
1385 if (empty($relIds)) {
1389 $relParamas = array(1 => array($contactId, 'Integer'),
1390 2 => array($mainRelatedContactId, 'Integer'),
1393 if ($contactId == $mainRelatedContactId) {
1394 $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);
1395 if ($recordsFound) {
1401 $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);
1403 if ($recordsFound) {
1411 * Get Current Employer for Contact
1413 * @param $contactIds Contact Ids
1415 * @return array $currentEmployer array of the current employer@static
1417 public static function getCurrentEmployer($contactIds) {
1418 $contacts = implode(',', $contactIds);
1421 SELECT organization_name, id, employer_id
1422 FROM civicrm_contact
1423 WHERE id IN ( {$contacts} )
1426 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1427 $currentEmployer = array();
1428 while ($dao->fetch()) {
1429 $currentEmployer[$dao->id
]['org_id'] = $dao->employer_id
;
1430 $currentEmployer[$dao->id
]['org_name'] = $dao->organization_name
;
1433 return $currentEmployer;
1437 * Return list of permissioned employer for a given contact.
1439 * @param $contactID int contact id whose employers
1441 * @param $name string employers sort name
1445 * @return array array of employers.
1448 public static function getPermissionedEmployer($contactID, $name = NULL) {
1449 //get the relationship id
1450 $relTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType',
1451 'Employee of', 'id', 'name_a_b'
1454 return self
::getPermissionedContacts($contactID, $relTypeId, $name);
1459 * Function to return list of permissioned contacts for a given contact and relationship type
1461 * @param $contactID int contact id whose permissioned contacts are to be found.
1462 * @param $relTypeId string one or more relationship type id's
1463 * @param $name string
1467 * @return array of contacts
1469 public static function getPermissionedContacts($contactID, $relTypeId, $name = NULL) {
1470 $contacts = array();
1474 SELECT cc.id as id, cc.sort_name as name
1475 FROM civicrm_relationship cr, civicrm_contact cc
1477 cr.contact_id_a = %1 AND
1478 cr.relationship_type_id IN (%2) AND
1479 cr.is_permission_a_b = 1 AND
1480 IF(cr.end_date IS NULL, 1, (DATEDIFF( CURDATE( ), cr.end_date ) <= 0)) AND
1481 cr.is_active = 1 AND
1482 cc.id = cr.contact_id_b AND
1485 if (!empty($name)) {
1486 $name = CRM_Utils_Type
::escape($name, 'String');
1488 AND cc.sort_name LIKE '%$name%'";
1491 $args = array(1 => array($contactID, 'Integer'), 2 => array($relTypeId, 'String'));
1492 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1494 while ($dao->fetch()) {
1495 $contacts[$dao->id
] = array(
1496 'name' => $dao->name
,
1497 'value' => $dao->id
,
1505 * Merge relationships from otherContact to mainContact
1506 * Called during contact merge operation
1508 * @param int $mainId contact id of main contact record.
1509 * @param int $otherId contact id of record which is going to merge.
1510 * @param array $sqls (reference) array of sql statements to append to.
1512 * @see CRM_Dedupe_Merger::cpTables()
1516 public static function mergeRelationships($mainId, $otherId, &$sqls) {
1517 // Delete circular relationships
1518 $sqls[] = "DELETE FROM civicrm_relationship
1519 WHERE (contact_id_a = $mainId AND contact_id_b = $otherId)
1520 OR (contact_id_b = $mainId AND contact_id_a = $otherId)";
1522 // Delete relationship from other contact if main contact already has that relationship
1523 $sqls[] = "DELETE r2
1524 FROM civicrm_relationship r1, civicrm_relationship r2
1525 WHERE r1.relationship_type_id = r2.relationship_type_id
1528 r1.contact_id_a = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_b = r2.contact_id_b
1529 OR r1.contact_id_b = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_a = r2.contact_id_a
1531 (r1.contact_id_a = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_b = r2.contact_id_a
1532 OR r1.contact_id_b = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_a = r2.contact_id_b)
1533 AND r1.relationship_type_id IN (SELECT id FROM civicrm_relationship_type WHERE name_b_a = name_a_b)
1537 // Move relationships
1538 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_a = $mainId WHERE contact_id_a = $otherId";
1539 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_b = $mainId WHERE contact_id_b = $otherId";
1541 // Move current employer id (name will get updated later)
1542 $sqls[] = "UPDATE civicrm_contact SET employer_id = $mainId WHERE employer_id = $otherId";
1546 * Set 'is_valid' field to false for all relationships whose end date is in the past, ie. are expired.
1548 * @return True on success, false if error is encountered.
1550 public static function disableExpiredRelationships() {
1551 $query = "SELECT id FROM civicrm_relationship WHERE is_active = 1 AND end_date < CURDATE()";
1553 $dao = CRM_Core_DAO
::executeQuery($query);
1554 while ($dao->fetch()) {
1555 $result = CRM_Contact_BAO_Relationship
::setIsActive($dao->id
, FALSE);
1556 // Result will be NULL if error occurred. We abort early if error detected.
1557 if ($result == NULL) {
1565 * Function filters the query by possible relationships for the membership type
1566 * It is intended to be called when constructing queries for the api (reciprocal & non-reciprocal)
1567 * and to add clauses to limit the return to those relationships which COULD inherit a membership type
1568 * (as opposed to those who inherit a particular membership
1570 * @param array $params api input array
1571 * @param null $direction
1575 public static function membershipTypeToRelationshipTypes(&$params, $direction = NULL) {
1576 $membershipType = civicrm_api3('membership_type', 'getsingle', array('id' => $params['membership_type_id'], 'return' => 'relationship_type_id, relationship_direction'));
1577 $relationshipTypes = $membershipType['relationship_type_id'];
1578 if(empty($relationshipTypes)) {
1581 // if we don't have any contact data we can only filter on type
1582 if(empty($params['contact_id']) && empty($params['contact_id_a']) && empty($params['contact_id_a'])) {
1583 $params['relationship_type_id'] = array('IN' => $relationshipTypes);
1587 $relationshipDirections = (array) $membershipType['relationship_direction'];
1588 // if we have contact_id_a OR contact_id_b we can make a call here
1589 // if we have contact??
1590 foreach ($relationshipDirections as $index => $mtdirection) {
1591 if(isset($params['contact_id_a']) && $mtdirection == 'a_b' ||
$direction == 'a_b') {
1592 $types[] = $relationshipTypes[$index];
1594 if(isset($params['contact_id_b']) && $mtdirection == 'b_a' ||
$direction == 'b_a') {
1595 $types[] = $relationshipTypes[$index];
1598 if(!empty($types)) {
1599 $params['relationship_type_id'] = array('IN' => $types);
1601 elseif(!empty($clauses)) {
1602 return explode(' OR ', $clauses);
1605 // effectively setting it to return no results
1606 $params['relationship_type_id'] = 0;
1613 * This function is a wrapper for contact relationship selector
1615 * @param array $params associated array for params record id.
1617 * @return array $contactRelationships associated array of contact relationships
1619 public static function getContactRelationshipSelector(&$params) {
1620 // format the params
1621 $params['offset'] = ($params['page'] - 1) * $params['rp'];
1622 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
1624 if ($params['context'] == 'past') {
1625 $relationshipStatus = CRM_Contact_BAO_Relationship
::INACTIVE
;
1628 $relationshipStatus = CRM_Contact_BAO_Relationship
::CURRENT
;
1631 // check logged in user for permission
1632 $page = new CRM_Core_Page();
1633 CRM_Contact_Page_View
::checkUserPermission($page, $params['contact_id']);
1634 $permissions = array($page->_permission
);
1635 if ($page->_permission
== CRM_Core_Permission
::EDIT
) {
1636 $permissions[] = CRM_Core_Permission
::DELETE
;
1638 $mask = CRM_Core_Action
::mask($permissions);
1640 if ($params['context'] != 'user') {
1641 $links = CRM_Contact_Page_View_Relationship
::links();
1642 $permissionedContacts = FALSE;
1645 $links = CRM_Contact_Page_View_UserDashBoard
::links();
1646 $permissionedContacts = TRUE;
1649 // get contact relationships
1650 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1651 $relationshipStatus,
1652 $params['rp'], 0, 0,
1654 $permissionedContacts,
1658 $contactRelationships = array();
1659 $params['total'] = 0;
1660 if (!empty($relationships)) {
1661 // get the total relationships
1662 if ($params['context'] != 'user') {
1663 $params['total'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1664 $relationshipStatus, 0, 1, 0, NULL, NULL, $permissionedContacts);
1667 // FIX ME: we cannot directly determine total permissioned relationship, hence re-fire query
1668 $permissionedRelationships = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1669 $relationshipStatus,
1673 $params['total'] = count($permissionedRelationships);
1677 foreach ($relationships as $relationshipId => $values) {
1678 //Add image icon for related contacts: CRM-14919
1679 $icon = CRM_Contact_BAO_Contact_Utils
::getImage($values['contact_type'],
1683 $contactRelationships[$relationshipId]['name'] = $icon.' '.CRM_Utils_System
::href(
1685 'civicrm/contact/view',
1686 "reset=1&cid={$values['cid']}");
1688 $contactRelationships[$relationshipId]['relation'] = CRM_Utils_System
::href(
1689 $values['relation'],
1690 'civicrm/contact/view/rel',
1691 "action=view&reset=1&cid={$values['cid']}&id={$values['id']}&rtype={$values['rtype']}");
1693 if ($params['context'] == 'current') {
1694 if (($params['contact_id'] == $values['contact_id_a'] AND $values['is_permission_a_b'] == 1) OR
1695 ($params['contact_id'] == $values['contact_id_b'] AND $values['is_permission_b_a'] == 1)
1697 $contactRelationships[$relationshipId]['name'] .= '<span id="permission-a-b" class="crm-marker permission-relationship"> *</span>';
1700 if (($values['cid'] == $values['contact_id_a'] AND $values['is_permission_a_b'] == 1) OR
1701 ($values['cid'] == $values['contact_id_b'] AND $values['is_permission_b_a'] == 1)
1703 $contactRelationships[$relationshipId]['relation'] .= '<span id="permission-b-a" class="crm-marker permission-relationship"> *</span>';
1707 if (!empty($values['description'])) {
1708 $contactRelationships[$relationshipId]['relation'] .= "<p class='description'>{$values['description']}</p>";
1711 $contactRelationships[$relationshipId]['start_date'] = CRM_Utils_Date
::customFormat($values['start_date']);
1712 $contactRelationships[$relationshipId]['end_date'] = CRM_Utils_Date
::customFormat($values['end_date']);
1713 $contactRelationships[$relationshipId]['city'] = $values['city'];
1714 $contactRelationships[$relationshipId]['state'] = $values['state'];
1715 $contactRelationships[$relationshipId]['email'] = $values['email'];
1716 $contactRelationships[$relationshipId]['phone'] = $values['phone'];
1717 $contactRelationships[$relationshipId]['links'] = $values['action'];
1718 $contactRelationships[$relationshipId]['id'] = $values['id'];
1719 $contactRelationships[$relationshipId]['is_active'] = $values['is_active'];
1722 return $contactRelationships;