3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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 object CRM_Contact_BAO_Relationship object
57 static function create(&$params, $ids = array()) {
58 $valid = $invalid = $duplicate = $saved = 0;
59 $relationships = $relationshipIds = 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 (!empty($ids['contact']) && !empty($ids['contactTarget'])) {
136 if (self
::checkValidRelationship($params, $ids, $ids['contactTarget'])) {
137 $validContacts = FALSE;
141 if ($validContacts) {
142 // editing an existing relationship
143 $relationship = self
::add($params, $ids, $ids['contactTarget']);
144 $relationshipIds[] = $relationship->id
;
145 $relationships[$relationship->id
] = $relationship;
150 // do not add to recent items for import, CRM-4399
151 if (!(!empty($params['skipRecentView']) ||
$invalid ||
$duplicate)) {
152 $url = CRM_Utils_System
::url('civicrm/contact/view/rel',
153 "action=view&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&context=home"
157 $session = CRM_Core_Session
::singleton();
158 $recentOther = array();
159 if (($session->get('userID') == $relationship->contact_id_a
) ||
160 CRM_Contact_BAO_Contact_Permission
::allow($relationship->contact_id_a
, CRM_Core_Permission
::EDIT
)
162 $rType = substr(CRM_Utils_Array
::value('relationship_type_id', $params), -3);
163 $recentOther = array(
164 'editUrl' => CRM_Utils_System
::url('civicrm/contact/view/rel',
165 "action=update&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
167 'deleteUrl' => CRM_Utils_System
::url('civicrm/contact/view/rel',
168 "action=delete&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
173 $title = CRM_Contact_BAO_Contact
::displayName($relationship->contact_id_a
) . ' (' . CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType',
174 $relationship->relationship_type_id
, 'label_a_b'
175 ) . ' ' . CRM_Contact_BAO_Contact
::displayName($relationship->contact_id_b
) . ')';
176 // add the recently created Relationship
177 CRM_Utils_Recent
::add($title,
181 $relationship->contact_id_a
,
187 return array($valid, $invalid, $duplicate, $saved, $relationshipIds, $relationships);
191 * This is the function that check/add if the relationship created is valid
193 * @param array $params (reference ) an assoc array of name/value pairs
194 * @param integer $contactId this is contact id for adding relationship
195 * @param array $ids the array that holds all the db ids
197 * @return object CRM_Contact_BAO_Relationship
201 static function add(&$params, $ids = array(), $contactId = NULL) {
203 CRM_Utils_Array
::value('relationship', $ids, CRM_Utils_Array
::value('id', $params));
206 if($relationshipId) {
209 //@todo hook are called from create and add - remove one
210 CRM_Utils_Hook
::pre($hook , 'Relationship', $relationshipId, $params);
212 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
214 // explode the string with _ to get the relationship type id
215 // and to know which contact has to be inserted in
216 // contact_id_a and which one in contact_id_b
217 list($type, $first, $second) = explode('_', $relationshipTypes);
219 $
{'contact_' . $first} = CRM_Utils_Array
::value('contact', $ids);
220 $
{'contact_' . $second} = $contactId;
222 // check if the relationship type is Head of Household then update the
223 // household's primary contact with this contact.
225 CRM_Contact_BAO_Household
::updatePrimaryContact($contact_b, $contact_a);
228 $relationship = new CRM_Contact_BAO_Relationship();
229 //@todo this code needs to be updated for the possibility that not all fields are set
231 $relationship->contact_id_b
= $contact_b;
232 $relationship->contact_id_a
= $contact_a;
233 $relationship->relationship_type_id
= $type;
234 $relationship->id
= $relationshipId;
236 $dateFields = array('end_date', 'start_date');
238 foreach (self
::getdefaults() as $defaultField => $defaultValue){
239 if(isset($params[$defaultField])){
240 if(in_array($defaultField, $dateFields)){
241 $relationship->$defaultField = CRM_Utils_Date
::format(CRM_Utils_Array
::value($defaultField, $params));
242 if(!$relationship->$defaultField){
243 $relationship->$defaultField = 'NULL';
247 $relationship->$defaultField = $params[$defaultField];
250 elseif(!$relationshipId){
251 $relationship->$defaultField = $defaultValue;
255 $relationship->save();
257 // add custom field values
258 if (!empty($params['custom'])) {
259 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_relationship', $relationship->id
);
262 $relationship->free();
264 CRM_Utils_Hook
::post($hook, 'Relationship', $relationshipId, $relationship);
266 return $relationship;
269 * Specifiy defaults for creating a relationship
271 * @return array $defaults array of defaults for creating relationship
275 static function getdefaults() {
278 'is_permission_a_b' => 0,
279 'is_permission_b_a' => 0,
281 'start_date' => 'NULL',
283 'end_date' => 'NULL',
289 * Check if there is data to create the object
291 * @param array $params (reference ) an assoc array of name/value pairs
297 static function dataExists(&$params) {
298 // return if no data present
299 if (!is_array(CRM_Utils_Array
::value('contact_check', $params))) {
306 * Function to get get list of relationship type based on the contact type.
308 * @param int $contactId this is the contact id of the current contact.
309 * @param null $contactSuffix
310 * @param string $relationshipId the id of the existing relationship if any
311 * @param string $contactType contact type
312 * @param boolean $all if true returns relationship types in both the direction
313 * @param string $column name/label that going to retrieve from db.
316 * @param bool $biDirectional
317 * @param string $contactSubType includes relationshiptypes between this subtype
319 * @param boolean $onlySubTypeRelationTypes if set only subtype which is passed by $contactSubType
320 * related relationshiptypes get return
322 * @internal param string $strContact this value is currently ignored, keeping it there for legacy reasons
326 * @return array - array reference of all relationship types with context to current contact.
328 static function getContactRelationshipType($contactId = NULL,
329 $contactSuffix = NULL,
330 $relationshipId = NULL,
334 $biDirectional = TRUE,
335 $contactSubType = NULL,
336 $onlySubTypeRelationTypes = FALSE
338 $allRelationshipType = array();
339 $relationshipType = array();
340 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType($column);
342 $otherContactType = NULL;
343 if ($relationshipId) {
344 $relationship = new CRM_Contact_DAO_Relationship();
345 $relationship->id
= $relationshipId;
346 if ($relationship->find(TRUE)) {
347 $contact = new CRM_Contact_DAO_Contact();
348 $contact->id
= ($relationship->contact_id_a
=== $contactId) ?
$relationship->contact_id_b
: $relationship->contact_id_a
;
350 if ($contact->find(TRUE)) {
351 $otherContactType = $contact->contact_type
;
352 //CRM-5125 for contact subtype specific relationshiptypes
353 if ($contact->contact_sub_type
) {
354 $otherContactSubType = $contact->contact_sub_type
;
360 $contactSubType = array();
362 $contactType = CRM_Contact_BAO_Contact
::getContactType($contactId);
363 $contactSubType = CRM_Contact_BAO_Contact
::getContactSubType($contactId);
366 foreach ($allRelationshipType as $key => $value) {
367 // the contact type is required or matches
368 if (((!$value['contact_type_a']) ||
369 $value['contact_type_a'] == $contactType
371 // the other contact type is required or present or matches
372 ((!$value['contact_type_b']) ||
373 (!$otherContactType) ||
374 $value['contact_type_b'] == $otherContactType
377 (in_array($value['contact_sub_type_a'], $contactSubType) ||
378 ((!$value['contact_sub_type_b'] &&
379 !$value['contact_sub_type_a']
381 !$onlySubTypeRelationTypes
386 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
389 if (((!$value['contact_type_b']) ||
390 $value['contact_type_b'] == $contactType
392 ((!$value['contact_type_a']) ||
393 (!$otherContactType) ||
394 $value['contact_type_a'] == $otherContactType
397 (in_array($value['contact_sub_type_b'], $contactSubType) ||
398 ((!$value['contact_sub_type_a'] &&
399 !$value['contact_sub_type_b']
401 !$onlySubTypeRelationTypes
406 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
410 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
411 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
415 if ($biDirectional) {
416 // lets clean up the data and eliminate all duplicate values
417 // (i.e. the relationship is bi-directional)
418 $relationshipType = array_unique($relationshipType);
421 // sort the relationshipType in ascending order CRM-7736
422 asort($relationshipType);
423 return $relationshipType;
426 static function clearCurrentEmployer($id, $action) {
427 $relationship = new CRM_Contact_DAO_Relationship();
428 $relationship->id
= $id;
429 $relationship->find(TRUE);
431 //to delete relationship between household and individual \
432 //or between individual and orgnization
433 if (($action & CRM_Core_Action
::DISABLE
) ||
($action & CRM_Core_Action
::DELETE
)) {
434 $relTypes = CRM_Utils_Array
::index(array('name_a_b'), CRM_Core_PseudoConstant
::relationshipType('name'));
435 if ($relationship->relationship_type_id
== $relTypes['Employee of']['id'] ||
436 $relationship->relationship_type_id
== $relTypes['Household Member of']['id']) {
437 $sharedContact = new CRM_Contact_DAO_Contact();
438 $sharedContact->id
= $relationship->contact_id_a
;
439 $sharedContact->find(TRUE);
441 if ($relationship->relationship_type_id
== 4 && $relationship->contact_id_b
== $sharedContact->employer_id
) {
442 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($relationship->contact_id_a
);
446 return $relationship;
450 * Function to delete the relationship
452 * @param int $id relationship id
459 static function del($id) {
460 // delete from relationship table
461 CRM_Utils_Hook
::pre('delete', 'Relationship', $id, CRM_Core_DAO
::$_nullArray);
463 $relationship = self
::clearCurrentEmployer($id, CRM_Core_Action
::DELETE
);
464 if (CRM_Core_Permission
::access('CiviMember')) {
465 // create $params array which isrequired to delete memberships
466 // of the related contacts.
468 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
469 'contact_check' => array($relationship->contact_id_b
=> 1),
473 // calling relatedMemberships to delete the memberships of
475 self
::relatedMemberships($relationship->contact_id_a
,
478 CRM_Core_Action
::DELETE
,
483 $relationship->delete();
484 CRM_Core_Session
::setStatus(ts('Selected relationship has been deleted successfully.'), ts('Record Deleted'), 'success');
486 CRM_Utils_Hook
::post('delete', 'Relationship', $relationship->id
, $relationship);
488 // delete the recently created Relationship
489 $relationshipRecent = array(
491 'type' => 'Relationship',
493 CRM_Utils_Recent
::del($relationshipRecent);
495 return $relationship;
499 * Function to disable/enable the relationship
501 * @param int $id relationship id
509 static function disableEnableRelationship($id, $action) {
510 $relationship = self
::clearCurrentEmployer($id, $action);
511 if (CRM_Core_Permission
::access('CiviMember')) {
512 // create $params array which isrequired to delete memberships
513 // of the related contacts.
515 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
516 'contact_check' => array($relationship->contact_id_b
=> 1),
520 // calling relatedMemberships to delete/add the memberships of
522 if ($action & CRM_Core_Action
::DISABLE
) {
523 CRM_Contact_BAO_Relationship
::relatedMemberships($relationship->contact_id_a
,
526 CRM_Core_Action
::DELETE
,
530 elseif ($action & CRM_Core_Action
::ENABLE
) {
531 $ids['contact'] = $relationship->contact_id_a
;
532 CRM_Contact_BAO_Relationship
::relatedMemberships($relationship->contact_id_a
,
535 CRM_Core_Action
::ADD
,
543 * Delete the object records that are associated with this contact
545 * @param int $contactId id of the contact to delete
551 static function deleteContact($contactId) {
552 $relationship = new CRM_Contact_DAO_Relationship();
553 $relationship->contact_id_a
= $contactId;
554 $relationship->delete();
556 $relationship = new CRM_Contact_DAO_Relationship();
557 $relationship->contact_id_b
= $contactId;
558 $relationship->delete();
560 CRM_Contact_BAO_Household
::updatePrimaryContact(NULL, $contactId);
564 * Function to get the other contact in a relationship
566 * @param int $id relationship id
568 * $returns returns the contact ids in the realtionship
570 * @return \CRM_Contact_DAO_Relationship
574 static function getContactIds($id) {
575 $relationship = new CRM_Contact_DAO_Relationship();
577 $relationship->id
= $id;
578 $relationship->selectAdd();
579 $relationship->selectAdd('contact_id_a, contact_id_b');
580 $relationship->find(TRUE);
582 return $relationship;
586 * Function to check if the relationship type selected between two contacts is correct
588 * @param int $contact_a 1st contact id
589 * @param int $contact_b 2nd contact id
590 * @param int $relationshipTypeId relationship type id
592 * @return boolean true if it is valid relationship else false
596 static function checkRelationshipType($contact_a, $contact_b, $relationshipTypeId) {
597 $relationshipType = new CRM_Contact_DAO_RelationshipType();
598 $relationshipType->id
= $relationshipTypeId;
599 $relationshipType->selectAdd();
600 $relationshipType->selectAdd('contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b');
601 if ($relationshipType->find(TRUE)) {
602 $contact_type_a = CRM_Contact_BAO_Contact
::getContactType($contact_a);
603 $contact_type_b = CRM_Contact_BAO_Contact
::getContactType($contact_b);
605 $contact_sub_type_a = CRM_Contact_BAO_Contact
::getContactSubType($contact_a);
606 $contact_sub_type_b = CRM_Contact_BAO_Contact
::getContactSubType($contact_b);
608 if (((!$relationshipType->contact_type_a
) ||
($relationshipType->contact_type_a
== $contact_type_a)) &&
609 ((!$relationshipType->contact_type_b
) ||
($relationshipType->contact_type_b
== $contact_type_b)) &&
610 ((!$relationshipType->contact_sub_type_a
) ||
(in_array($relationshipType->contact_sub_type_a
,
613 ((!$relationshipType->contact_sub_type_b
) ||
(in_array($relationshipType->contact_sub_type_b
,
627 * this function does the validtion for valid relationship
629 * @param array $params this array contains the values there are subitted by the form
630 * @param array $ids the array that holds all the db ids
631 * @param integer $contactId this is contact id for adding relationship
637 static function checkValidRelationship(&$params, &$ids, $contactId) {
640 // get the string of relationship type
641 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
642 list($type, $first, $second) = explode('_', $relationshipTypes);
643 $
{'contact_' . $first} = CRM_Utils_Array
::value('contact', $ids);
644 $
{'contact_' . $second} = $contactId;
645 // function to check if the relationship selected is correct
646 // i.e. employer relationship can exit between Individual and Organization (not between Individual and Individual)
647 if (!CRM_Contact_BAO_Relationship
::checkRelationshipType($contact_a, $contact_b, $type)) {
648 $errors = 'Please select valid relationship between these two contacts.';
654 * this function checks for duplicate relationship
656 * @param array $params (reference ) an assoc array of name/value pairs
657 * @param integer $id this the id of the contact whom we are adding relationship
658 * @param integer $contactId this is contact id for adding relationship
659 * @param integer $relationshipId this is relationship id for the contact
661 * @return boolean true if record exists else false
665 static function checkDuplicateRelationship(&$params, $id, $contactId = 0, $relationshipId = 0) {
666 $relationshipTypeId = CRM_Utils_Array
::value('relationship_type_id', $params);
667 list($type, $first, $second) = explode('_', $relationshipTypeId);
671 FROM civicrm_relationship
672 WHERE relationship_type_id = " . CRM_Utils_Type
::escape($type, 'Integer');
675 * CRM-11792 - date fields from API are in ISO format, but this function
676 * supports date arrays BAO has increasingly standardised to ISO format
677 * so I believe this function should support ISO rather than make API
678 * format it - however, need to support array format for now to avoid breakage
679 * @ time of writing this function is called from Relationship::create (twice)
680 * CRM_BAO_Contact_Utils::clearCurrentEmployer (seemingly without dates)
681 * CRM_Contact_Form_Task_AddToOrganization::postProcess &
682 * CRM_Contact_Form_Task_AddToHousehold::postProcess
683 * (I don't think the last 2 support dates but not sure
686 $dateFields = array('end_date', 'start_date');
687 foreach ($dateFields as $dateField){
688 if(array_key_exists($dateField, $params)) {
689 if (empty($params[$dateField]) ||
$params[$dateField] == 'null'){
690 //this is most likely coming from an api call & probably loaded
691 // from the DB to deal with some of the
692 // other myriad of excessive checks still in place both in
693 // the api & the create functions
694 $queryString .= " AND $dateField IS NULL";
697 elseif (is_array($params[$dateField])){
698 $queryString .= " AND $dateField = " .
699 CRM_Utils_Type
::escape(CRM_Utils_Date
::format($params[$dateField]), 'Date');
702 $queryString .= " AND $dateField = " .
703 CRM_Utils_Type
::escape($params[$dateField], 'Date');
709 " AND ( ( contact_id_a = " . CRM_Utils_Type
::escape($id, 'Integer') .
710 " AND contact_id_b = " . CRM_Utils_Type
::escape($contactId, 'Integer') .
711 " ) OR ( contact_id_a = " . CRM_Utils_Type
::escape($contactId, 'Integer') .
712 " AND contact_id_b = " . CRM_Utils_Type
::escape($id, 'Integer') . " ) ) ";
714 //if caseId is provided, include it duplicate checking.
715 if ($caseId = CRM_Utils_Array
::value('case_id', $params)) {
716 $queryString .= " AND case_id = " . CRM_Utils_Type
::escape($caseId, 'Integer');
719 if ($relationshipId) {
720 $queryString .= " AND id !=" . CRM_Utils_Type
::escape($relationshipId, 'Integer');
723 $relationship = new CRM_Contact_BAO_Relationship();
724 $relationship->query($queryString);
725 $relationship->fetch();
726 $relationship->free();
727 return ($relationship->id
) ?
TRUE : FALSE;
731 * update the is_active flag in the db
733 * @param int $id id of the database record
734 * @param boolean $is_active value we want to set the is_active field
736 * @throws CiviCRM_API3_Exception
737 * @return Object DAO object on success, null otherwise
740 static function setIsActive($id, $is_active) {
741 // as both the create & add functions have a bunch of logic in them that
742 // doesn't seem to cope with a normal update we will call the api which
743 // has tested handling for this
744 // however, a longer term solution would be to simplify the add, create & api functions
745 // to be more standard. It is debatable @ that point whether it's better to call the BAO
746 // direct as the api is more tested.
747 $result = civicrm_api('relationship', 'create', array(
749 'is_active' => $is_active,
753 if (is_array($result) && !empty($result['is_error']) && $result['error_message'] != 'Relationship already exists') {
754 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array
::value('error_code', $result, 'undefined'), $result);
757 // call (undocumented possibly deprecated) hook
758 CRM_Utils_Hook
::enableDisable('CRM_Contact_BAO_Relationship', $id, $is_active);
764 * Given the list of params in the params array, fetch the object
765 * and store the values in the values array
767 * @param array $params input parameters to find object
768 * @param array $values output values of the object
769 * @internal param array $ids the array that holds all the db ids
771 * @return array (reference) the values that could be potentially assigned to smarty
775 static function &getValues(&$params, &$values) {
776 if (empty($params)) {
781 // get the specific number of relationship or all relationships.
782 if (!empty($params['numRelationship'])) {
783 $v['data'] = &CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'], NULL, $params['numRelationship']);
786 $v['data'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id']);
789 // get the total count of relationships
790 $v['totalCount'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'], NULL, NULL, TRUE);
792 $values['relationship']['data'] = &$v['data'];
793 $values['relationship']['totalCount'] = &$v['totalCount'];
799 * helper function to form the sql for relationship retrieval
801 * @param int $contactId contact id
802 * @param int $status (check const at top of file)
803 * @param int $numRelationship no of relationships to display (limit)
804 * @param int $count get the no of relationships
805 * $param int $relationshipId relationship id
806 * @param $relationshipId
807 * @param string $direction the direction we are interested in a_b or b_a
808 * @param array $params array of extra values including relationship_type_id per api spec
810 * return string the query for this diretion
816 static function makeURLClause($contactId, $status, $numRelationship, $count, $relationshipId, $direction, $params = array()) {
817 $select = $from = $where = '';
821 if ($direction == 'a_b') {
822 $select .= ' SELECT count(DISTINCT civicrm_relationship.id) as cnt1, 0 as cnt2 ';
825 $select .= ' SELECT 0 as cnt1, count(DISTINCT civicrm_relationship.id) as cnt2 ';
829 $select .= ' SELECT civicrm_relationship.id as civicrm_relationship_id,
830 civicrm_contact.sort_name as sort_name,
831 civicrm_contact.display_name as display_name,
832 civicrm_contact.job_title as job_title,
833 civicrm_contact.employer_id as employer_id,
834 civicrm_contact.organization_name as organization_name,
835 civicrm_address.street_address as street_address,
836 civicrm_address.city as city,
837 civicrm_address.postal_code as postal_code,
838 civicrm_state_province.abbreviation as state,
839 civicrm_country.name as country,
840 civicrm_email.email as email,
841 civicrm_phone.phone as phone,
842 civicrm_contact.id as civicrm_contact_id,
843 civicrm_contact.contact_type as contact_type,
844 civicrm_relationship.contact_id_b as contact_id_b,
845 civicrm_relationship.contact_id_a as contact_id_a,
846 civicrm_relationship_type.id as civicrm_relationship_type_id,
847 civicrm_relationship.start_date as start_date,
848 civicrm_relationship.end_date as end_date,
849 civicrm_relationship.description as description,
850 civicrm_relationship.is_active as is_active,
851 civicrm_relationship.is_permission_a_b as is_permission_a_b,
852 civicrm_relationship.is_permission_b_a as is_permission_b_a,
853 civicrm_relationship.case_id as case_id';
855 if ($direction == 'a_b') {
856 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
857 civicrm_relationship_type.label_b_a as relation ';
860 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
861 civicrm_relationship_type.label_a_b as relation ';
866 FROM civicrm_relationship
867 INNER JOIN civicrm_relationship_type ON ( civicrm_relationship.relationship_type_id = civicrm_relationship_type.id )
868 INNER JOIN civicrm_contact ";
869 if ($direction == 'a_b') {
870 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_a ) ';
873 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_b ) ';
876 LEFT JOIN civicrm_address ON (civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1)
877 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
878 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id AND civicrm_email.is_primary = 1)
879 LEFT JOIN civicrm_state_province ON (civicrm_address.state_province_id = civicrm_state_province.id)
880 LEFT JOIN civicrm_country ON (civicrm_address.country_id = civicrm_country.id)
882 $where = 'WHERE ( 1 )';
884 if ($direction == 'a_b') {
885 $where .= ' AND civicrm_relationship.contact_id_b = ' . CRM_Utils_Type
::escape($contactId, 'Positive');
888 $where .= ' AND civicrm_relationship.contact_id_a = ' . CRM_Utils_Type
::escape($contactId, 'Positive') . '
889 AND civicrm_relationship.contact_id_a != civicrm_relationship.contact_id_b ';
892 if ($relationshipId) {
893 $where .= ' AND civicrm_relationship.id = ' . CRM_Utils_Type
::escape($relationshipId, 'Positive');
896 $date = date('Y-m-d');
897 if ($status == self
::PAST
) {
898 //this case for showing past relationship
899 $where .= ' AND civicrm_relationship.is_active = 1 ';
900 $where .= " AND civicrm_relationship.end_date < '" . $date . "'";
902 elseif ($status == self
::DISABLED
) {
903 // this case for showing disabled relationship
904 $where .= ' AND civicrm_relationship.is_active = 0 ';
906 elseif ($status == self
::CURRENT
) {
907 //this case for showing current relationship
908 $where .= ' AND civicrm_relationship.is_active = 1 ';
909 $where .= " AND (civicrm_relationship.end_date >= '" . $date . "' OR civicrm_relationship.end_date IS NULL) ";
911 elseif ($status == self
::INACTIVE
) {
912 //this case for showing inactive relationships
913 $where .= " AND (civicrm_relationship.end_date < '" . $date . "'";
914 $where .= ' OR civicrm_relationship.is_active = 0 )';
918 $where .= ' AND civicrm_contact.is_deleted = 0';
919 if(!empty($params['membership_type_id']) && empty($params['relationship_type_id'])) {
920 $where .= self
::membershipTypeToRelationshipTypes($params, $direction);
922 if(!empty($params['relationship_type_id'])) {
923 if(is_array($params['relationship_type_id'])) {
924 $where .= " AND " . CRM_Core_DAO
::createSQLFilter('relationship_type_id', $params['relationship_type_id'], 'Integer');
927 $where .= ' AND relationship_type_id = ' . CRM_Utils_Type
::escape($params['relationship_type_id'], 'Positive');
930 if ($direction == 'a_b') {
931 $where .= ' ) UNION ';
937 return array($select, $from, $where);
941 * This is the function to get the list of relationships
943 * @param int $contactId contact id
944 * @param int $status 1: Past 2: Disabled 3: Current
945 * @param int $numRelationship no of relationships to display (limit)
946 * @param int $count get the no of relationships
947 * $param int $relationshipId relationship id
948 * $param array $links the list of links to display
949 * $param int $permissionMask the permission mask to be applied for the actions
950 * $param boolean $permissionedContact to return only permissioned Contact
951 * $param array $params array of variables consistent with filters supported by the api
952 * return array $values relationship records
953 * @param int $relationshipId
955 * @param null $permissionMask
956 * @param bool $permissionedContact
957 * @param array $params
963 static function getRelationship($contactId = NULL,
964 $status = 0, $numRelationship = 0,
965 $count = 0, $relationshipId = 0,
966 $links = NULL, $permissionMask = NULL,
967 $permissionedContact = FALSE,
971 if (!$contactId && !$relationshipId) {
975 list($select1, $from1, $where1) = self
::makeURLClause($contactId, $status, $numRelationship,
976 $count, $relationshipId, 'a_b', $params
978 list($select2, $from2, $where2) = self
::makeURLClause($contactId, $status, $numRelationship,
979 $count, $relationshipId, 'b_a', $params
982 $order = $limit = '';
984 if (empty($params['sort'])) {
985 $order = ' ORDER BY civicrm_relationship_type_id, sort_name ';
988 $order = " ORDER BY {$params['sort']} ";
992 if (!empty($params['offset']) && $params['offset'] > 0) {
993 $offset = $params['offset'];
996 if ($numRelationship) {
997 $limit = " LIMIT {$offset}, $numRelationship";
1001 // building the query string
1002 $queryString = $select1 . $from1 . $where1 . $select2 . $from2 . $where2 . $order . $limit;
1004 $relationship = new CRM_Contact_DAO_Relationship();
1006 $relationship->query($queryString);
1009 $relationshipCount = 0;
1010 while ($relationship->fetch()) {
1011 $relationshipCount +
= $relationship->cnt1 +
$relationship->cnt2
;
1013 return $relationshipCount;
1018 if ($status != self
::INACTIVE
) {
1020 $mask = array_sum(array_keys($links));
1021 if ($mask & CRM_Core_Action
::DISABLE
) {
1022 $mask -= CRM_Core_Action
::DISABLE
;
1024 if ($mask & CRM_Core_Action
::ENABLE
) {
1025 $mask -= CRM_Core_Action
::ENABLE
;
1028 if ($status == self
::CURRENT
) {
1029 $mask |
= CRM_Core_Action
::DISABLE
;
1031 elseif ($status == self
::DISABLED
) {
1032 $mask |
= CRM_Core_Action
::ENABLE
;
1034 $mask = $mask & $permissionMask;
1037 while ($relationship->fetch()) {
1038 $rid = $relationship->civicrm_relationship_id
;
1039 $cid = $relationship->civicrm_contact_id
;
1040 if (($permissionedContact) &&
1041 (!CRM_Contact_BAO_Contact_Permission
::relationship($cid, $contactId))
1045 $values[$rid]['id'] = $rid;
1046 $values[$rid]['cid'] = $cid;
1047 $values[$rid]['contact_id_a'] = $relationship->contact_id_a
;
1048 $values[$rid]['contact_id_b'] = $relationship->contact_id_b
;
1049 $values[$rid]['relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1050 $values[$rid]['relation'] = $relationship->relation
;
1051 $values[$rid]['name'] = $relationship->sort_name
;
1052 $values[$rid]['display_name'] = $relationship->display_name
;
1053 $values[$rid]['job_title'] = $relationship->job_title
;
1054 $values[$rid]['email'] = $relationship->email
;
1055 $values[$rid]['phone'] = $relationship->phone
;
1056 $values[$rid]['employer_id'] = $relationship->employer_id
;
1057 $values[$rid]['organization_name'] = $relationship->organization_name
;
1058 $values[$rid]['country'] = $relationship->country
;
1059 $values[$rid]['city'] = $relationship->city
;
1060 $values[$rid]['state'] = $relationship->state
;
1061 $values[$rid]['start_date'] = $relationship->start_date
;
1062 $values[$rid]['end_date'] = $relationship->end_date
;
1063 $values[$rid]['description'] = $relationship->description
;
1064 $values[$rid]['is_active'] = $relationship->is_active
;
1065 $values[$rid]['is_permission_a_b'] = $relationship->is_permission_a_b
;
1066 $values[$rid]['is_permission_b_a'] = $relationship->is_permission_b_a
;
1067 $values[$rid]['case_id'] = $relationship->case_id
;
1070 $values[$rid]['status'] = $status;
1073 $values[$rid]['civicrm_relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1075 if ($relationship->contact_id_a
== $contactId) {
1076 $values[$rid]['rtype'] = 'a_b';
1079 $values[$rid]['rtype'] = 'b_a';
1085 'rtype' => $values[$rid]['rtype'],
1086 'cid' => $contactId,
1087 'cbid' => $values[$rid]['cid'],
1088 'caseid' => $values[$rid]['case_id'],
1089 'clientid' => $contactId,
1092 if ($status == self
::INACTIVE
) {
1093 // setting links for inactive relationships
1094 $mask = array_sum(array_keys($links));
1095 if (!$values[$rid]['is_active']) {
1096 $mask -= CRM_Core_Action
::DISABLE
;
1099 $mask -= CRM_Core_Action
::ENABLE
;
1100 $mask -= CRM_Core_Action
::DISABLE
;
1104 // Give access to manage case link by copying to MAX_ACTION index temporarily, depending on case permission of user.
1105 if ($values[$rid]['case_id']) {
1106 // Borrowed logic from CRM_Case_Page_Tab
1107 $hasCaseAccess = FALSE;
1108 if (CRM_Core_Permission
::check('access all cases and activities')) {
1109 $hasCaseAccess = TRUE;
1112 $userCases = CRM_Case_BAO_Case
::getCases(FALSE);
1113 if (array_key_exists($values[$rid]['case_id'], $userCases)) {
1114 $hasCaseAccess = TRUE;
1118 if ($hasCaseAccess) {
1119 // give access by copying to MAX_ACTION temporarily, otherwise leave at NONE which won't display
1120 $links[CRM_Core_Action
::MAX_ACTION
] = $links[CRM_Core_Action
::NONE
];
1121 $links[CRM_Core_Action
::MAX_ACTION
]['name'] = ts('Manage Case #%1', array(1 => $values[$rid]['case_id']));
1122 $links[CRM_Core_Action
::MAX_ACTION
]['class'] = 'no-popup';
1124 // Also make sure we have the right client cid since can get here from multiple relationship tabs.
1125 if ($values[$rid]['rtype'] == 'b_a') {
1126 $replace['clientid'] = $values[$rid]['cid'];
1131 $values[$rid]['action'] = CRM_Core_Action
::formLink(
1137 'relationship.selector.row',
1140 unset($links[CRM_Core_Action
::MAX_ACTION
]);
1144 $relationship->free();
1150 * Function to get get list of relationship type based on the target contact type.
1152 * @param string $targetContactType it's valid contact tpye(may be Individual , Organization , Household)
1154 * @return array - array reference of all relationship types with context to current contact type .
1157 function getRelationType($targetContactType) {
1158 $relationshipType = array();
1159 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType();
1161 foreach ($allRelationshipType as $key => $type) {
1162 if ($type['contact_type_b'] == $targetContactType) {
1163 $relationshipType[$key . '_a_b'] = $type['label_a_b'];
1167 return $relationshipType;
1171 * Function to create / update / delete membership for related contacts.
1173 * This function will create/update/delete membership for related
1174 * contact based on 1) contact have active membership 2) that
1175 * membership is is extedned by the same relationship type to that
1176 * of the existing relationship.
1178 * @param $contactId Int contact id
1179 * @param $params array array of values submitted by POST
1180 * @param $ids array array of ids
1181 * @param \const|\which $action which action called this function
1183 * @param bool $active
1187 static function relatedMemberships($contactId, &$params, $ids, $action = CRM_Core_Action
::ADD
, $active = TRUE) {
1188 // Check the end date and set the status of the relationship
1190 $status = self
::CURRENT
;
1192 if (!empty($params['end_date'])) {
1193 $endDate = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Date
::format($params['end_date']), NULL, 'Ymd');
1194 $today = date('Ymd');
1196 if ($today > $endDate) {
1197 $status = self
::PAST
;
1201 if (($action & CRM_Core_Action
::ADD
) &&
1202 ($status & self
::PAST
)
1204 // if relationship is PAST and action is ADD, no qustion
1205 // of creating RELATED membership and return back to
1210 $rel = explode('_', $params['relationship_type_id']);
1212 $relTypeId = $rel[0];
1213 $relDirection = "_{$rel[1]}_{$rel[2]}";
1214 $targetContact = array();
1215 if (($action & CRM_Core_Action
::ADD
) ||
1216 ($action & CRM_Core_Action
::DELETE
)
1218 $contact = $contactId;
1219 $targetContact = CRM_Utils_Array
::value('contact_check', $params);
1221 elseif ($action & CRM_Core_Action
::UPDATE
) {
1222 $contact = $ids['contact'];
1223 $targetContact = array($ids['contactTarget'] => 1);
1226 // Build the 'values' array for
1229 // This will allow us to check if either of the contacts in
1230 // relationship have active memberships.
1235 $values[$contact] = array(
1236 'relatedContacts' => $targetContact,
1237 'relationshipTypeId' => $relTypeId,
1238 'relationshipTypeDirection' => $relDirection,
1241 if (!empty($targetContact)) {
1242 foreach ($targetContact as $cid => $donCare) {
1243 $values[$cid] = array(
1244 'relatedContacts' => array($contact => 1),
1245 'relationshipTypeId' => $relTypeId,
1248 $relTypeParams = array('id' => $relTypeId);
1249 $relTypeValues = array();
1250 CRM_Contact_BAO_RelationshipType
::retrieve($relTypeParams, $relTypeValues);
1252 if (CRM_Utils_Array
::value('name_a_b', $relTypeValues) == CRM_Utils_Array
::value('name_b_a', $relTypeValues)) {
1253 $values[$cid]['relationshipTypeDirection'] = '_a_b';
1256 $values[$cid]['relationshipTypeDirection'] = ($relDirection == '_a_b') ?
'_b_a' : '_a_b';
1261 // Now get the active memberships for all the contacts.
1262 // If contact have any valid membership(s), then add it to
1264 foreach ($values as $cid => $subValues) {
1265 $memParams = array('contact_id' => $cid);
1266 $memberships = array();
1268 CRM_Member_BAO_Membership
::getValues($memParams, $memberships, $active);
1270 if (empty($memberships)) {
1274 $values[$cid]['memberships'] = $memberships;
1276 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1278 // done with 'values' array.
1279 // Finally add / edit / delete memberships for the related contacts
1280 foreach ($values as $cid => $details) {
1281 if (!array_key_exists('memberships', $details)) {
1285 $mainRelatedContactId = key(CRM_Utils_Array
::value('relatedContacts', $details, array()));
1287 foreach ($details['memberships'] as $membershipId => $membershipValues) {
1288 $relTypeIds = array();
1289 if ($action & CRM_Core_Action
::DELETE
) {
1290 // Delete memberships of the related contacts only if relationship type exists for membership type
1292 SELECT relationship_type_id, relationship_direction
1293 FROM civicrm_membership_type
1294 WHERE id = {$membershipValues['membership_type_id']}";
1295 $dao = CRM_Core_DAO
::executeQuery($query);
1296 $relTypeDirs = array();
1297 while ($dao->fetch()) {
1298 $relTypeId = $dao->relationship_type_id
;
1299 $relDirection = $dao->relationship_direction
;
1301 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $relTypeId);
1302 if (in_array($values[$cid]['relationshipTypeId'], $relTypeIds)) {
1303 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $mainRelatedContactId);
1307 if (($action & CRM_Core_Action
::UPDATE
) &&
1308 ($status & self
::PAST
) &&
1309 ($membershipValues['owner_membership_id'])
1311 // If relationship is PAST and action is UPDATE
1312 // then delete the RELATED membership
1313 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipValues['owner_membership_id'],
1314 $membershipValues['membership_contact_id']
1319 // add / edit the memberships for related
1322 // Get the Membership Type Details.
1323 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipValues['membership_type_id']);
1324 // Check if contact's relationship type exists in membership type
1325 $relTypeDirs = array();
1326 if (!empty($membershipType['relationship_type_id'])) {
1327 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_type_id']);
1329 if (!empty($membershipType['relationship_direction'])) {
1330 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_direction']);
1332 foreach ($relTypeIds as $key => $value) {
1333 $relTypeDirs[] = $value . '_' . $relDirections[$key];
1335 $relTypeDir = $details['relationshipTypeId'] . $details['relationshipTypeDirection'];
1336 if (in_array($relTypeDir, $relTypeDirs)) {
1337 // Check if relationship being created/updated is
1338 // similar to that of membership type's
1341 $membershipValues['owner_membership_id'] = $membershipId;
1342 unset($membershipValues['id']);
1343 unset($membershipValues['membership_contact_id']);
1344 unset($membershipValues['contact_id']);
1345 unset($membershipValues['membership_id']);
1346 foreach ($details['relatedContacts'] as $relatedContactId => $donCare) {
1347 $membershipValues['contact_id'] = $relatedContactId;
1348 if ($deceasedStatusId &&
1349 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $relatedContactId, 'is_deceased')
1351 $membershipValues['status_id'] = $deceasedStatusId;
1352 $membershipValues['skipStatusCal'] = TRUE;
1355 'join_date', 'start_date', 'end_date') as $dateField) {
1356 if (!empty($membershipValues[$dateField])) {
1357 $membershipValues[$dateField] = CRM_Utils_Date
::processDate($membershipValues[$dateField]);
1361 if ($action & CRM_Core_Action
::UPDATE
) {
1362 //delete the membership record for related
1363 //contact before creating new membership record.
1364 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $relatedContactId);
1367 // check whether we have some related memberships still available
1370 FROM civicrm_membership
1371 LEFT JOIN civicrm_membership_status ON (civicrm_membership_status.id = civicrm_membership.status_id)
1372 WHERE membership_type_id = {$membershipValues['membership_type_id']} AND owner_membership_id = {$membershipValues['owner_membership_id']}
1373 AND is_current_member = 1";
1374 $result = CRM_Core_DAO
::singleValueQuery($query);
1375 if ($result < CRM_Utils_Array
::value('max_related', $membershipValues, PHP_INT_MAX
)) {
1376 CRM_Member_BAO_Membership
::create($membershipValues, CRM_Core_DAO
::$_nullArray);
1380 elseif ($action & CRM_Core_Action
::UPDATE
) {
1381 // if action is update and updated relationship do
1382 // not match with the existing
1383 // membership=>relationship then we need to
1384 // delete the membership record created for
1385 // previous relationship.
1387 if (self
::isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, CRM_Utils_Array
::value('relationship_ids', $params))) {
1388 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $mainRelatedContactId);
1396 * Helper function to check whether to delete the membership or
1402 static function isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, $relIds) {
1403 if (in_array($relTypeId, $relTypeIds)) {
1407 if (empty($relIds)) {
1411 $relParamas = array(1 => array($contactId, 'Integer'),
1412 2 => array($mainRelatedContactId, 'Integer'),
1415 if ($contactId == $mainRelatedContactId) {
1416 $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);
1417 if ($recordsFound) {
1423 $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);
1425 if ($recordsFound) {
1433 * Function to get Current Employer for Contact
1435 * @param $contactIds Contact Ids
1437 * @return array $currentEmployer array of the current employer@static
1439 static function getCurrentEmployer($contactIds) {
1440 $contacts = implode(',', $contactIds);
1443 SELECT organization_name, id, employer_id
1444 FROM civicrm_contact
1445 WHERE id IN ( {$contacts} )
1448 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1449 $currentEmployer = array();
1450 while ($dao->fetch()) {
1451 $currentEmployer[$dao->id
]['org_id'] = $dao->employer_id
;
1452 $currentEmployer[$dao->id
]['org_name'] = $dao->organization_name
;
1455 return $currentEmployer;
1459 * Function to return list of permissioned employer for a given contact.
1461 * @param $contactID int contact id whose employers
1463 * @param $name string employers sort name
1467 * @return array array of employers.
1470 static function getPermissionedEmployer($contactID, $name = NULL) {
1471 //get the relationship id
1472 $relTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType',
1473 'Employee of', 'id', 'name_a_b'
1476 return self
::getPermissionedContacts($contactID, $relTypeId, $name);
1481 * Function to return list of permissioned contacts for a given contact and relationship type
1483 * @param $contactID int contact id whose permissioned contacts are to be found.
1484 * @param $relTypeId string one or more relationship type id's
1485 * @param $name string
1489 * @return array of contacts
1491 static function getPermissionedContacts($contactID, $relTypeId, $name = NULL) {
1492 $contacts = array();
1496 SELECT cc.id as id, cc.sort_name as name
1497 FROM civicrm_relationship cr, civicrm_contact cc
1499 cr.contact_id_a = %1 AND
1500 cr.relationship_type_id IN (%2) AND
1501 cr.is_permission_a_b = 1 AND
1502 IF(cr.end_date IS NULL, 1, (DATEDIFF( CURDATE( ), cr.end_date ) <= 0)) AND
1503 cr.is_active = 1 AND
1504 cc.id = cr.contact_id_b";
1506 if (!empty($name)) {
1507 $name = CRM_Utils_Type
::escape($name, 'String');
1509 AND cc.sort_name LIKE '%$name%'";
1512 $args = array(1 => array($contactID, 'Integer'), 2 => array($relTypeId, 'String'));
1513 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1515 while ($dao->fetch()) {
1516 $contacts[$dao->id
] = array(
1517 'name' => $dao->name
,
1518 'value' => $dao->id
,
1526 * Merge relationships from otherContact to mainContact
1527 * Called during contact merge operation
1529 * @param int $mainId contact id of main contact record.
1530 * @param int $otherId contact id of record which is going to merge.
1531 * @param array $sqls (reference) array of sql statements to append to.
1533 * @see CRM_Dedupe_Merger::cpTables()
1537 static function mergeRelationships($mainId, $otherId, &$sqls) {
1538 // Delete circular relationships
1539 $sqls[] = "DELETE FROM civicrm_relationship
1540 WHERE (contact_id_a = $mainId AND contact_id_b = $otherId)
1541 OR (contact_id_b = $mainId AND contact_id_a = $otherId)";
1543 // Delete relationship from other contact if main contact already has that relationship
1544 $sqls[] = "DELETE r2
1545 FROM civicrm_relationship r1, civicrm_relationship r2
1546 WHERE r1.relationship_type_id = r2.relationship_type_id
1549 r1.contact_id_a = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_b = r2.contact_id_b
1550 OR r1.contact_id_b = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_a = r2.contact_id_a
1552 (r1.contact_id_a = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_b = r2.contact_id_a
1553 OR r1.contact_id_b = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_a = r2.contact_id_b)
1554 AND r1.relationship_type_id IN (SELECT id FROM civicrm_relationship_type WHERE name_b_a = name_a_b)
1558 // Move relationships
1559 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_a = $mainId WHERE contact_id_a = $otherId";
1560 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_b = $mainId WHERE contact_id_b = $otherId";
1562 // Move current employer id (name will get updated later)
1563 $sqls[] = "UPDATE civicrm_contact SET employer_id = $mainId WHERE employer_id = $otherId";
1567 * Set 'is_valid' field to false for all relationships whose end date is in the past, ie. are expired.
1569 * @return True on success, false if error is encountered.
1571 static function disableExpiredRelationships() {
1572 $query = "SELECT id FROM civicrm_relationship WHERE is_active = 1 AND end_date < CURDATE()";
1574 $dao = CRM_Core_DAO
::executeQuery($query);
1575 while ($dao->fetch()) {
1576 $result = CRM_Contact_BAO_Relationship
::setIsActive($dao->id
, FALSE);
1577 // Result will be NULL if error occurred. We abort early if error detected.
1578 if ($result == NULL) {
1586 * Function filters the query by possible relationships for the membership type
1587 * It is intended to be called when constructing queries for the api (reciprocal & non-reciprocal)
1588 * and to add clauses to limit the return to those relationships which COULD inherit a membership type
1589 * (as opposed to those who inherit a particular membership
1591 * @param array $params api input array
1592 * @param null $direction
1596 static function membershipTypeToRelationshipTypes(&$params, $direction = NULL) {
1597 $membershipType = civicrm_api3('membership_type', 'getsingle', array('id' => $params['membership_type_id'], 'return' => 'relationship_type_id, relationship_direction'));
1598 $relationshipTypes = $membershipType['relationship_type_id'];
1599 if(empty($relationshipTypes)) {
1602 // if we don't have any contact data we can only filter on type
1603 if(empty($params['contact_id']) && empty($params['contact_id_a']) && empty($params['contact_id_a'])) {
1604 $params['relationship_type_id'] = array('IN' => $relationshipTypes);
1608 $relationshipDirections = (array) $membershipType['relationship_direction'];
1609 // if we have contact_id_a OR contact_id_b we can make a call here
1610 // if we have contact??
1611 foreach ($relationshipDirections as $index => $mtdirection) {
1612 if(isset($params['contact_id_a']) && $mtdirection == 'a_b' ||
$direction == 'a_b') {
1613 $types[] = $relationshipTypes[$index];
1615 if(isset($params['contact_id_b']) && $mtdirection == 'b_a' ||
$direction == 'b_a') {
1616 $types[] = $relationshipTypes[$index];
1619 if(!empty($types)) {
1620 $params['relationship_type_id'] = array('IN' => $types);
1622 elseif(!empty($clauses)) {
1623 return explode(' OR ', $clauses);
1626 // effectively setting it to return no results
1627 $params['relationship_type_id'] = 0;
1634 * This function is a wrapper for contact relationship selector
1636 * @param array $params associated array for params record id.
1638 * @return array $contactRelationships associated array of contact relationships
1641 public static function getContactRelationshipSelector(&$params) {
1642 // format the params
1643 $params['offset'] = ($params['page'] - 1) * $params['rp'];
1644 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
1646 if ($params['context'] == 'past') {
1647 $relationshipStatus = CRM_Contact_BAO_Relationship
::INACTIVE
;
1650 $relationshipStatus = CRM_Contact_BAO_Relationship
::CURRENT
;
1653 // check logged in user for permission
1654 $page = new CRM_Core_Page();
1655 CRM_Contact_Page_View
::checkUserPermission($page, $params['contact_id']);
1656 $permissions = array($page->_permission
);
1657 if ($page->_permission
== CRM_Core_Permission
::EDIT
) {
1658 $permissions[] = CRM_Core_Permission
::DELETE
;
1660 $mask = CRM_Core_Action
::mask($permissions);
1662 if ($params['context'] != 'user') {
1663 $links = CRM_Contact_Page_View_Relationship
::links();
1664 $permissionedContacts = FALSE;
1667 $links = CRM_Contact_Page_View_UserDashBoard
::links();
1668 $permissionedContacts = TRUE;
1671 // get contact relationships
1672 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1673 $relationshipStatus,
1674 $params['rp'], 0, 0,
1676 $permissionedContacts,
1680 $contactRelationships = array();
1681 $params['total'] = 0;
1682 if (!empty($relationships)) {
1683 // get the total relationships
1684 if ($params['context'] != 'user') {
1685 $params['total'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1686 $relationshipStatus, 0, 1, 0, NULL, NULL, $permissionedContacts);
1689 // FIX ME: we cannot directly determine total permissioned relationship, hence re-fire query
1690 $permissionedRelationships = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1691 $relationshipStatus,
1695 $params['total'] = count($permissionedRelationships);
1699 foreach ($relationships as $relationshipId => $values) {
1700 $contactRelationships[$relationshipId]['name'] = CRM_Utils_System
::href(
1702 'civicrm/contact/view',
1703 "reset=1&cid={$values['contact_id_b']}");
1705 $contactRelationships[$relationshipId]['relation'] = CRM_Utils_System
::href(
1706 $values['relation'],
1707 'civicrm/contact/view/rel',
1708 "action=view&reset=1&cid={$values['contact_id_a']}&id={$values['id']}&rtype={$values['rtype']}");
1710 if ($params['context'] == 'current') {
1711 if (($params['contact_id'] == $values['contact_id_a'] AND $values['is_permission_a_b'] == 1) OR
1712 ($params['contact_id'] == $values['contact_id_b'] AND $values['is_permission_b_a'] == 1)
1714 $contactRelationships[$relationshipId]['name'] .= '<span id="permission-a-b" class="crm-marker permission-relationship"> *</span>';
1717 if (($values['cid'] == $values['contact_id_a'] AND $values['is_permission_a_b'] == 1) OR
1718 ($values['cid'] == $values['contact_id_b'] AND $values['is_permission_b_a'] == 1)
1720 $contactRelationships[$relationshipId]['relation'] .= '<span id="permission-b-a" class="crm-marker permission-relationship"> *</span>';
1724 if (!empty($values['description'])) {
1725 $contactRelationships[$relationshipId]['relation'] .= "<p class='description'>{$values['description']}</p>";
1728 $contactRelationships[$relationshipId]['start_date'] = CRM_Utils_Date
::customFormat($values['start_date']);
1729 $contactRelationships[$relationshipId]['end_date'] = CRM_Utils_Date
::customFormat($values['end_date']);
1730 $contactRelationships[$relationshipId]['city'] = $values['city'];
1731 $contactRelationships[$relationshipId]['state'] = $values['state'];
1732 $contactRelationships[$relationshipId]['email'] = $values['email'];
1733 $contactRelationships[$relationshipId]['phone'] = $values['phone'];
1734 $contactRelationships[$relationshipId]['links'] = $values['action'];
1735 $contactRelationships[$relationshipId]['id'] = $values['id'];
1736 $contactRelationships[$relationshipId]['is_active'] = $values['is_active'];
1739 return $contactRelationships;