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 = 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 string $strContact this value is currently ignored, keeping it there for legacy reasons
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 string $contactSubType includes relationshiptypes between this subtype
318 * @param boolean $onlySubTypeRelationTypes if set only subtype which is passed by $contactSubType
319 * related relationshiptypes get return
323 * @return array - array reference of all relationship types with context to current contact.
325 static function getContactRelationshipType($contactId = NULL,
326 $contactSuffix = NULL,
327 $relationshipId = NULL,
331 $biDirectional = TRUE,
332 $contactSubType = NULL,
333 $onlySubTypeRelationTypes = FALSE
335 $allRelationshipType = array();
336 $relationshipType = array();
337 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType($column);
339 $otherContactType = NULL;
340 if ($relationshipId) {
341 $relationship = new CRM_Contact_DAO_Relationship();
342 $relationship->id
= $relationshipId;
343 if ($relationship->find(TRUE)) {
344 $contact = new CRM_Contact_DAO_Contact();
345 $contact->id
= ($relationship->contact_id_a
=== $contactId) ?
$relationship->contact_id_b
: $relationship->contact_id_a
;
347 if ($contact->find(TRUE)) {
348 $otherContactType = $contact->contact_type
;
349 //CRM-5125 for contact subtype specific relationshiptypes
350 if ($contact->contact_sub_type
) {
351 $otherContactSubType = $contact->contact_sub_type
;
357 $contactSubType = array();
359 $contactType = CRM_Contact_BAO_Contact
::getContactType($contactId);
360 $contactSubType = CRM_Contact_BAO_Contact
::getContactSubType($contactId);
363 foreach ($allRelationshipType as $key => $value) {
364 // the contact type is required or matches
365 if (((!$value['contact_type_a']) ||
366 $value['contact_type_a'] == $contactType
368 // the other contact type is required or present or matches
369 ((!$value['contact_type_b']) ||
370 (!$otherContactType) ||
371 $value['contact_type_b'] == $otherContactType
374 (in_array($value['contact_sub_type_a'], $contactSubType) ||
375 ((!$value['contact_sub_type_b'] &&
376 !$value['contact_sub_type_a']
378 !$onlySubTypeRelationTypes
383 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
386 if (((!$value['contact_type_b']) ||
387 $value['contact_type_b'] == $contactType
389 ((!$value['contact_type_a']) ||
390 (!$otherContactType) ||
391 $value['contact_type_a'] == $otherContactType
394 (in_array($value['contact_sub_type_b'], $contactSubType) ||
395 ((!$value['contact_sub_type_a'] &&
396 !$value['contact_sub_type_b']
398 !$onlySubTypeRelationTypes
403 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
407 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
408 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
412 if ($biDirectional) {
413 // lets clean up the data and eliminate all duplicate values
414 // (i.e. the relationship is bi-directional)
415 $relationshipType = array_unique($relationshipType);
418 // sort the relationshipType in ascending order CRM-7736
419 asort($relationshipType);
420 return $relationshipType;
423 static function clearCurrentEmployer($id, $action) {
424 $relationship = new CRM_Contact_DAO_Relationship();
425 $relationship->id
= $id;
426 $relationship->find(TRUE);
428 //to delete relationship between household and individual \
429 //or between individual and orgnization
430 if (($action & CRM_Core_Action
::DISABLE
) ||
($action & CRM_Core_Action
::DELETE
)) {
431 $relTypes = CRM_Utils_Array
::index(array('name_a_b'), CRM_Core_PseudoConstant
::relationshipType('name'));
432 if ($relationship->relationship_type_id
== $relTypes['Employee of']['id'] ||
433 $relationship->relationship_type_id
== $relTypes['Household Member of']['id']) {
434 $sharedContact = new CRM_Contact_DAO_Contact();
435 $sharedContact->id
= $relationship->contact_id_a
;
436 $sharedContact->find(TRUE);
438 if ($relationship->relationship_type_id
== 4 && $relationship->contact_id_b
== $sharedContact->employer_id
) {
439 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($relationship->contact_id_a
);
443 return $relationship;
447 * Function to delete the relationship
449 * @param int $id relationship id
456 static function del($id) {
457 // delete from relationship table
458 CRM_Utils_Hook
::pre('delete', 'Relationship', $id, CRM_Core_DAO
::$_nullArray);
460 $relationship = self
::clearCurrentEmployer($id, CRM_Core_Action
::DELETE
);
461 if (CRM_Core_Permission
::access('CiviMember')) {
462 // create $params array which isrequired to delete memberships
463 // of the related contacts.
465 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
466 'contact_check' => array($relationship->contact_id_b
=> 1),
470 // calling relatedMemberships to delete the memberships of
472 self
::relatedMemberships($relationship->contact_id_a
,
475 CRM_Core_Action
::DELETE
,
480 $relationship->delete();
481 CRM_Core_Session
::setStatus(ts('Selected relationship has been deleted successfully.'), ts('Record Deleted'), 'success');
483 CRM_Utils_Hook
::post('delete', 'Relationship', $relationship->id
, $relationship);
485 // delete the recently created Relationship
486 $relationshipRecent = array(
488 'type' => 'Relationship',
490 CRM_Utils_Recent
::del($relationshipRecent);
492 return $relationship;
496 * Function to disable/enable the relationship
498 * @param int $id relationship id
505 static function disableEnableRelationship($id, $action) {
506 $relationship = self
::clearCurrentEmployer($id, $action);
507 if (CRM_Core_Permission
::access('CiviMember')) {
508 // create $params array which isrequired to delete memberships
509 // of the related contacts.
511 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
512 'contact_check' => array($relationship->contact_id_b
=> 1),
516 // calling relatedMemberships to delete/add the memberships of
518 if ($action & CRM_Core_Action
::DISABLE
) {
519 CRM_Contact_BAO_Relationship
::relatedMemberships($relationship->contact_id_a
,
522 CRM_Core_Action
::DELETE
,
526 elseif ($action & CRM_Core_Action
::ENABLE
) {
527 $ids['contact'] = $relationship->contact_id_a
;
528 CRM_Contact_BAO_Relationship
::relatedMemberships($relationship->contact_id_a
,
531 CRM_Core_Action
::ADD
,
539 * Delete the object records that are associated with this contact
541 * @param int $contactId id of the contact to delete
547 static function deleteContact($contactId) {
548 $relationship = new CRM_Contact_DAO_Relationship();
549 $relationship->contact_id_a
= $contactId;
550 $relationship->delete();
552 $relationship = new CRM_Contact_DAO_Relationship();
553 $relationship->contact_id_b
= $contactId;
554 $relationship->delete();
556 CRM_Contact_BAO_Household
::updatePrimaryContact(NULL, $contactId);
560 * Function to get the other contact in a relationship
562 * @param int $id relationship id
564 * $returns returns the contact ids in the realtionship
568 static function getContactIds($id) {
569 $relationship = new CRM_Contact_DAO_Relationship();
571 $relationship->id
= $id;
572 $relationship->selectAdd();
573 $relationship->selectAdd('contact_id_a, contact_id_b');
574 $relationship->find(TRUE);
576 return $relationship;
580 * Function to check if the relationship type selected between two contacts is correct
582 * @param int $contact_a 1st contact id
583 * @param int $contact_b 2nd contact id
584 * @param int $relationshipTypeId relationship type id
586 * @return boolean true if it is valid relationship else false
590 static function checkRelationshipType($contact_a, $contact_b, $relationshipTypeId) {
591 $relationshipType = new CRM_Contact_DAO_RelationshipType();
592 $relationshipType->id
= $relationshipTypeId;
593 $relationshipType->selectAdd();
594 $relationshipType->selectAdd('contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b');
595 if ($relationshipType->find(TRUE)) {
596 $contact_type_a = CRM_Contact_BAO_Contact
::getContactType($contact_a);
597 $contact_type_b = CRM_Contact_BAO_Contact
::getContactType($contact_b);
599 $contact_sub_type_a = CRM_Contact_BAO_Contact
::getContactSubType($contact_a);
600 $contact_sub_type_b = CRM_Contact_BAO_Contact
::getContactSubType($contact_b);
602 if (((!$relationshipType->contact_type_a
) ||
($relationshipType->contact_type_a
== $contact_type_a)) &&
603 ((!$relationshipType->contact_type_b
) ||
($relationshipType->contact_type_b
== $contact_type_b)) &&
604 ((!$relationshipType->contact_sub_type_a
) ||
(in_array($relationshipType->contact_sub_type_a
,
607 ((!$relationshipType->contact_sub_type_b
) ||
(in_array($relationshipType->contact_sub_type_b
,
621 * this function does the validtion for valid relationship
623 * @param array $params this array contains the values there are subitted by the form
624 * @param array $ids the array that holds all the db ids
625 * @param integer $contactId this is contact id for adding relationship
631 static function checkValidRelationship(&$params, &$ids, $contactId) {
634 // get the string of relationship type
635 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
636 list($type, $first, $second) = explode('_', $relationshipTypes);
637 $
{'contact_' . $first} = CRM_Utils_Array
::value('contact', $ids);
638 $
{'contact_' . $second} = $contactId;
639 // function to check if the relationship selected is correct
640 // i.e. employer relationship can exit between Individual and Organization (not between Individual and Individual)
641 if (!CRM_Contact_BAO_Relationship
::checkRelationshipType($contact_a, $contact_b, $type)) {
642 $errors = 'Please select valid relationship between these two contacts.';
648 * this function checks for duplicate relationship
650 * @param array $params (reference ) an assoc array of name/value pairs
651 * @param integer $id this the id of the contact whom we are adding relationship
652 * @param integer $contactId this is contact id for adding relationship
653 * @param integer $relationshipId this is relationship id for the contact
655 * @return boolean true if record exists else false
659 static function checkDuplicateRelationship(&$params, $id, $contactId = 0, $relationshipId = 0) {
660 $relationshipTypeId = CRM_Utils_Array
::value('relationship_type_id', $params);
661 list($type, $first, $second) = explode('_', $relationshipTypeId);
665 FROM civicrm_relationship
666 WHERE relationship_type_id = " . CRM_Utils_Type
::escape($type, 'Integer');
669 * CRM-11792 - date fields from API are in ISO format, but this function
670 * supports date arrays BAO has increasingly standardised to ISO format
671 * so I believe this function should support ISO rather than make API
672 * format it - however, need to support array format for now to avoid breakage
673 * @ time of writing this function is called from Relationship::create (twice)
674 * CRM_BAO_Contact_Utils::clearCurrentEmployer (seemingly without dates)
675 * CRM_Contact_Form_Task_AddToOrganization::postProcess &
676 * CRM_Contact_Form_Task_AddToHousehold::postProcess
677 * (I don't think the last 2 support dates but not sure
680 $dateFields = array('end_date', 'start_date');
681 foreach ($dateFields as $dateField){
682 if(array_key_exists($dateField, $params)) {
683 if (empty($params[$dateField]) ||
$params[$dateField] == 'null'){
684 //this is most likely coming from an api call & probably loaded
685 // from the DB to deal with some of the
686 // other myriad of excessive checks still in place both in
687 // the api & the create functions
688 $queryString .= " AND $dateField IS NULL";
691 elseif (is_array($params[$dateField])){
692 $queryString .= " AND $dateField = " .
693 CRM_Utils_Type
::escape(CRM_Utils_Date
::format($params[$dateField]), 'Date');
696 $queryString .= " AND $dateField = " .
697 CRM_Utils_Type
::escape($params[$dateField], 'Date');
703 " AND ( ( contact_id_a = " . CRM_Utils_Type
::escape($id, 'Integer') .
704 " AND contact_id_b = " . CRM_Utils_Type
::escape($contactId, 'Integer') .
705 " ) OR ( contact_id_a = " . CRM_Utils_Type
::escape($contactId, 'Integer') .
706 " AND contact_id_b = " . CRM_Utils_Type
::escape($id, 'Integer') . " ) ) ";
708 //if caseId is provided, include it duplicate checking.
709 if ($caseId = CRM_Utils_Array
::value('case_id', $params)) {
710 $queryString .= " AND case_id = " . CRM_Utils_Type
::escape($caseId, 'Integer');
713 if ($relationshipId) {
714 $queryString .= " AND id !=" . CRM_Utils_Type
::escape($relationshipId, 'Integer');
717 $relationship = new CRM_Contact_BAO_Relationship();
718 $relationship->query($queryString);
719 $relationship->fetch();
720 $relationship->free();
721 return ($relationship->id
) ?
TRUE : FALSE;
725 * update the is_active flag in the db
727 * @param int $id id of the database record
728 * @param boolean $is_active value we want to set the is_active field
730 * @return Object DAO object on success, null otherwise
733 static function setIsActive($id, $is_active) {
734 // as both the create & add functions have a bunch of logic in them that
735 // doesn't seem to cope with a normal update we will call the api which
736 // has tested handling for this
737 // however, a longer term solution would be to simplify the add, create & api functions
738 // to be more standard. It is debatable @ that point whether it's better to call the BAO
739 // direct as the api is more tested.
740 $result = civicrm_api('relationship', 'create', array(
742 'is_active' => $is_active,
746 if (is_array($result) && !empty($result['is_error']) && $result['error_message'] != 'Relationship already exists') {
747 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array
::value('error_code', $result, 'undefined'), $result);
750 // call (undocumented possibly deprecated) hook
751 CRM_Utils_Hook
::enableDisable('CRM_Contact_BAO_Relationship', $id, $is_active);
757 * Given the list of params in the params array, fetch the object
758 * and store the values in the values array
760 * @param array $params input parameters to find object
761 * @param array $values output values of the object
762 * @param array $ids the array that holds all the db ids
764 * @return array (reference) the values that could be potentially assigned to smarty
768 static function &getValues(&$params, &$values) {
769 if (empty($params)) {
774 // get the specific number of relationship or all relationships.
775 if (!empty($params['numRelationship'])) {
776 $v['data'] = &CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'], NULL, $params['numRelationship']);
779 $v['data'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id']);
782 // get the total count of relationships
783 $v['totalCount'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'], NULL, NULL, TRUE);
785 $values['relationship']['data'] = &$v['data'];
786 $values['relationship']['totalCount'] = &$v['totalCount'];
792 * helper function to form the sql for relationship retrieval
794 * @param int $contactId contact id
795 * @param int $status (check const at top of file)
796 * @param int $numRelationship no of relationships to display (limit)
797 * @param int $count get the no of relationships
798 * $param int $relationshipId relationship id
799 * @param string $direction the direction we are interested in a_b or b_a
800 * @param array $params array of extra values including relationship_type_id per api spec
802 * return string the query for this diretion
806 static function makeURLClause($contactId, $status, $numRelationship, $count, $relationshipId, $direction, $params = array()) {
807 $select = $from = $where = '';
811 if ($direction == 'a_b') {
812 $select .= ' SELECT count(DISTINCT civicrm_relationship.id) as cnt1, 0 as cnt2 ';
815 $select .= ' SELECT 0 as cnt1, count(DISTINCT civicrm_relationship.id) as cnt2 ';
819 $select .= ' SELECT civicrm_relationship.id as civicrm_relationship_id,
820 civicrm_contact.sort_name as sort_name,
821 civicrm_contact.display_name as display_name,
822 civicrm_contact.job_title as job_title,
823 civicrm_contact.employer_id as employer_id,
824 civicrm_contact.organization_name as organization_name,
825 civicrm_address.street_address as street_address,
826 civicrm_address.city as city,
827 civicrm_address.postal_code as postal_code,
828 civicrm_state_province.abbreviation as state,
829 civicrm_country.name as country,
830 civicrm_email.email as email,
831 civicrm_phone.phone as phone,
832 civicrm_contact.id as civicrm_contact_id,
833 civicrm_contact.contact_type as contact_type,
834 civicrm_relationship.contact_id_b as contact_id_b,
835 civicrm_relationship.contact_id_a as contact_id_a,
836 civicrm_relationship_type.id as civicrm_relationship_type_id,
837 civicrm_relationship.start_date as start_date,
838 civicrm_relationship.end_date as end_date,
839 civicrm_relationship.description as description,
840 civicrm_relationship.is_active as is_active,
841 civicrm_relationship.is_permission_a_b as is_permission_a_b,
842 civicrm_relationship.is_permission_b_a as is_permission_b_a,
843 civicrm_relationship.case_id as case_id';
845 if ($direction == 'a_b') {
846 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
847 civicrm_relationship_type.label_b_a as relation ';
850 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
851 civicrm_relationship_type.label_a_b as relation ';
856 FROM civicrm_relationship
857 INNER JOIN civicrm_relationship_type ON ( civicrm_relationship.relationship_type_id = civicrm_relationship_type.id )
858 INNER JOIN civicrm_contact ";
859 if ($direction == 'a_b') {
860 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_a ) ';
863 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_b ) ';
866 LEFT JOIN civicrm_address ON (civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1)
867 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
868 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id AND civicrm_email.is_primary = 1)
869 LEFT JOIN civicrm_state_province ON (civicrm_address.state_province_id = civicrm_state_province.id)
870 LEFT JOIN civicrm_country ON (civicrm_address.country_id = civicrm_country.id)
872 $where = 'WHERE ( 1 )';
874 if ($direction == 'a_b') {
875 $where .= ' AND civicrm_relationship.contact_id_b = ' . CRM_Utils_Type
::escape($contactId, 'Positive');
878 $where .= ' AND civicrm_relationship.contact_id_a = ' . CRM_Utils_Type
::escape($contactId, 'Positive') . '
879 AND civicrm_relationship.contact_id_a != civicrm_relationship.contact_id_b ';
882 if ($relationshipId) {
883 $where .= ' AND civicrm_relationship.id = ' . CRM_Utils_Type
::escape($relationshipId, 'Positive');
886 $date = date('Y-m-d');
887 if ($status == self
::PAST
) {
888 //this case for showing past relationship
889 $where .= ' AND civicrm_relationship.is_active = 1 ';
890 $where .= " AND civicrm_relationship.end_date < '" . $date . "'";
892 elseif ($status == self
::DISABLED
) {
893 // this case for showing disabled relationship
894 $where .= ' AND civicrm_relationship.is_active = 0 ';
896 elseif ($status == self
::CURRENT
) {
897 //this case for showing current relationship
898 $where .= ' AND civicrm_relationship.is_active = 1 ';
899 $where .= " AND (civicrm_relationship.end_date >= '" . $date . "' OR civicrm_relationship.end_date IS NULL) ";
901 elseif ($status == self
::INACTIVE
) {
902 //this case for showing inactive relationships
903 $where .= " AND (civicrm_relationship.end_date < '" . $date . "'";
904 $where .= ' OR civicrm_relationship.is_active = 0 )';
908 $where .= ' AND civicrm_contact.is_deleted = 0';
909 if(!empty($params['membership_type_id']) && empty($params['relationship_type_id'])) {
910 $where .= self
::membershipTypeToRelationshipTypes($params, $direction);
912 if(!empty($params['relationship_type_id'])) {
913 if(is_array($params['relationship_type_id'])) {
914 $where .= " AND " . CRM_Core_DAO
::createSQLFilter('relationship_type_id', $params['relationship_type_id'], 'Integer');
917 $where .= ' AND relationship_type_id = ' . CRM_Utils_Type
::escape($params['relationship_type_id'], 'Positive');
920 if ($direction == 'a_b') {
921 $where .= ' ) UNION ';
927 return array($select, $from, $where);
931 * This is the function to get the list of relationships
933 * @param int $contactId contact id
934 * @param int $status 1: Past 2: Disabled 3: Current
935 * @param int $numRelationship no of relationships to display (limit)
936 * @param int $count get the no of relationships
937 * $param int $relationshipId relationship id
938 * $param array $links the list of links to display
939 * $param int $permissionMask the permission mask to be applied for the actions
940 * $param boolean $permissionedContact to return only permissioned Contact
941 * $param array $params array of variables consistent with filters supported by the api
942 * return array $values relationship records
946 static function getRelationship($contactId = NULL,
947 $status = 0, $numRelationship = 0,
948 $count = 0, $relationshipId = 0,
949 $links = NULL, $permissionMask = NULL,
950 $permissionedContact = FALSE,
954 if (!$contactId && !$relationshipId) {
958 list($select1, $from1, $where1) = self
::makeURLClause($contactId, $status, $numRelationship,
959 $count, $relationshipId, 'a_b', $params
961 list($select2, $from2, $where2) = self
::makeURLClause($contactId, $status, $numRelationship,
962 $count, $relationshipId, 'b_a', $params
965 $order = $limit = '';
967 if (empty($params['sort'])) {
968 $order = ' ORDER BY civicrm_relationship_type_id, sort_name ';
971 $order = " ORDER BY {$params['sort']} ";
975 if (!empty($params['offset']) && $params['offset'] > 0) {
976 $offset = $params['offset'];
979 if ($numRelationship) {
980 $limit = " LIMIT {$offset}, $numRelationship";
984 // building the query string
985 $queryString = $select1 . $from1 . $where1 . $select2 . $from2 . $where2 . $order . $limit;
987 $relationship = new CRM_Contact_DAO_Relationship();
989 $relationship->query($queryString);
992 $relationshipCount = 0;
993 while ($relationship->fetch()) {
994 $relationshipCount +
= $relationship->cnt1 +
$relationship->cnt2
;
996 return $relationshipCount;
1001 if ($status != self
::INACTIVE
) {
1003 $mask = array_sum(array_keys($links));
1004 if ($mask & CRM_Core_Action
::DISABLE
) {
1005 $mask -= CRM_Core_Action
::DISABLE
;
1007 if ($mask & CRM_Core_Action
::ENABLE
) {
1008 $mask -= CRM_Core_Action
::ENABLE
;
1011 if ($status == self
::CURRENT
) {
1012 $mask |
= CRM_Core_Action
::DISABLE
;
1014 elseif ($status == self
::DISABLED
) {
1015 $mask |
= CRM_Core_Action
::ENABLE
;
1017 $mask = $mask & $permissionMask;
1020 while ($relationship->fetch()) {
1021 $rid = $relationship->civicrm_relationship_id
;
1022 $cid = $relationship->civicrm_contact_id
;
1023 if (($permissionedContact) &&
1024 (!CRM_Contact_BAO_Contact_Permission
::relationship($cid, $contactId))
1028 $values[$rid]['id'] = $rid;
1029 $values[$rid]['cid'] = $cid;
1030 $values[$rid]['contact_id_a'] = $relationship->contact_id_a
;
1031 $values[$rid]['contact_id_b'] = $relationship->contact_id_b
;
1032 $values[$rid]['relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1033 $values[$rid]['relation'] = $relationship->relation
;
1034 $values[$rid]['name'] = $relationship->sort_name
;
1035 $values[$rid]['display_name'] = $relationship->display_name
;
1036 $values[$rid]['job_title'] = $relationship->job_title
;
1037 $values[$rid]['email'] = $relationship->email
;
1038 $values[$rid]['phone'] = $relationship->phone
;
1039 $values[$rid]['employer_id'] = $relationship->employer_id
;
1040 $values[$rid]['organization_name'] = $relationship->organization_name
;
1041 $values[$rid]['country'] = $relationship->country
;
1042 $values[$rid]['city'] = $relationship->city
;
1043 $values[$rid]['state'] = $relationship->state
;
1044 $values[$rid]['start_date'] = $relationship->start_date
;
1045 $values[$rid]['end_date'] = $relationship->end_date
;
1046 $values[$rid]['description'] = $relationship->description
;
1047 $values[$rid]['is_active'] = $relationship->is_active
;
1048 $values[$rid]['is_permission_a_b'] = $relationship->is_permission_a_b
;
1049 $values[$rid]['is_permission_b_a'] = $relationship->is_permission_b_a
;
1050 $values[$rid]['case_id'] = $relationship->case_id
;
1053 $values[$rid]['status'] = $status;
1056 $values[$rid]['civicrm_relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1058 if ($relationship->contact_id_a
== $contactId) {
1059 $values[$rid]['rtype'] = 'a_b';
1062 $values[$rid]['rtype'] = 'b_a';
1068 'rtype' => $values[$rid]['rtype'],
1069 'cid' => $contactId,
1070 'cbid' => $values[$rid]['cid'],
1071 'caseid' => $values[$rid]['case_id'],
1072 'clientid' => $contactId,
1075 if ($status == self
::INACTIVE
) {
1076 // setting links for inactive relationships
1077 $mask = array_sum(array_keys($links));
1078 if (!$values[$rid]['is_active']) {
1079 $mask -= CRM_Core_Action
::DISABLE
;
1082 $mask -= CRM_Core_Action
::ENABLE
;
1083 $mask -= CRM_Core_Action
::DISABLE
;
1087 // Give access to manage case link by copying to MAX_ACTION index temporarily, depending on case permission of user.
1088 if ($values[$rid]['case_id']) {
1089 // Borrowed logic from CRM_Case_Page_Tab
1090 $hasCaseAccess = FALSE;
1091 if (CRM_Core_Permission
::check('access all cases and activities')) {
1092 $hasCaseAccess = TRUE;
1095 $userCases = CRM_Case_BAO_Case
::getCases(FALSE);
1096 if (array_key_exists($values[$rid]['case_id'], $userCases)) {
1097 $hasCaseAccess = TRUE;
1101 if ($hasCaseAccess) {
1102 // give access by copying to MAX_ACTION temporarily, otherwise leave at NONE which won't display
1103 $links[CRM_Core_Action
::MAX_ACTION
] = $links[CRM_Core_Action
::NONE
];
1104 $links[CRM_Core_Action
::MAX_ACTION
]['name'] = ts('Manage Case #%1', array(1 => $values[$rid]['case_id']));
1105 $links[CRM_Core_Action
::MAX_ACTION
]['class'] = 'no-popup';
1107 // Also make sure we have the right client cid since can get here from multiple relationship tabs.
1108 if ($values[$rid]['rtype'] == 'b_a') {
1109 $replace['clientid'] = $values[$rid]['cid'];
1114 $values[$rid]['action'] = CRM_Core_Action
::formLink(
1120 'relationship.selector.row',
1123 unset($links[CRM_Core_Action
::MAX_ACTION
]);
1127 $relationship->free();
1133 * Function to get get list of relationship type based on the target contact type.
1135 * @param string $targetContactType it's valid contact tpye(may be Individual , Organization , Household)
1137 * @return array - array reference of all relationship types with context to current contact type .
1140 function getRelationType($targetContactType) {
1141 $relationshipType = array();
1142 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType();
1144 foreach ($allRelationshipType as $key => $type) {
1145 if ($type['contact_type_b'] == $targetContactType) {
1146 $relationshipType[$key . '_a_b'] = $type['label_a_b'];
1150 return $relationshipType;
1154 * Function to create / update / delete membership for related contacts.
1156 * This function will create/update/delete membership for related
1157 * contact based on 1) contact have active membership 2) that
1158 * membership is is extedned by the same relationship type to that
1159 * of the existing relationship.
1161 * @param $contactId Int contact id
1162 * @param $params array array of values submitted by POST
1163 * @param $ids array array of ids
1164 * @param $action which action called this function
1169 static function relatedMemberships($contactId, &$params, $ids, $action = CRM_Core_Action
::ADD
, $active = TRUE) {
1170 // Check the end date and set the status of the relationship
1172 $status = self
::CURRENT
;
1174 if (!empty($params['end_date'])) {
1175 $endDate = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Date
::format($params['end_date']), NULL, 'Ymd');
1176 $today = date('Ymd');
1178 if ($today > $endDate) {
1179 $status = self
::PAST
;
1183 if (($action & CRM_Core_Action
::ADD
) &&
1184 ($status & self
::PAST
)
1186 // if relationship is PAST and action is ADD, no qustion
1187 // of creating RELATED membership and return back to
1192 $rel = explode('_', $params['relationship_type_id']);
1194 $relTypeId = $rel[0];
1195 $relDirection = "_{$rel[1]}_{$rel[2]}";
1196 $targetContact = array();
1197 if (($action & CRM_Core_Action
::ADD
) ||
1198 ($action & CRM_Core_Action
::DELETE
)
1200 $contact = $contactId;
1201 $targetContact = CRM_Utils_Array
::value('contact_check', $params);
1203 elseif ($action & CRM_Core_Action
::UPDATE
) {
1204 $contact = $ids['contact'];
1205 $targetContact = array($ids['contactTarget'] => 1);
1208 // Build the 'values' array for
1211 // This will allow us to check if either of the contacts in
1212 // relationship have active memberships.
1217 $values[$contact] = array(
1218 'relatedContacts' => $targetContact,
1219 'relationshipTypeId' => $relTypeId,
1220 'relationshipTypeDirection' => $relDirection,
1223 if (!empty($targetContact)) {
1224 foreach ($targetContact as $cid => $donCare) {
1225 $values[$cid] = array(
1226 'relatedContacts' => array($contact => 1),
1227 'relationshipTypeId' => $relTypeId,
1230 $relTypeParams = array('id' => $relTypeId);
1231 $relTypeValues = array();
1232 CRM_Contact_BAO_RelationshipType
::retrieve($relTypeParams, $relTypeValues);
1234 if (CRM_Utils_Array
::value('name_a_b', $relTypeValues) == CRM_Utils_Array
::value('name_b_a', $relTypeValues)) {
1235 $values[$cid]['relationshipTypeDirection'] = '_a_b';
1238 $values[$cid]['relationshipTypeDirection'] = ($relDirection == '_a_b') ?
'_b_a' : '_a_b';
1243 // Now get the active memberships for all the contacts.
1244 // If contact have any valid membership(s), then add it to
1246 foreach ($values as $cid => $subValues) {
1247 $memParams = array('contact_id' => $cid);
1248 $memberships = array();
1250 CRM_Member_BAO_Membership
::getValues($memParams, $memberships, $active);
1252 if (empty($memberships)) {
1256 $values[$cid]['memberships'] = $memberships;
1258 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1260 // done with 'values' array.
1261 // Finally add / edit / delete memberships for the related contacts
1262 foreach ($values as $cid => $details) {
1263 if (!array_key_exists('memberships', $details)) {
1267 $mainRelatedContactId = key(CRM_Utils_Array
::value('relatedContacts', $details, array()));
1269 foreach ($details['memberships'] as $membershipId => $membershipValues) {
1270 $relTypeIds = array();
1271 if ($action & CRM_Core_Action
::DELETE
) {
1272 // Delete memberships of the related contacts only if relationship type exists for membership type
1274 SELECT relationship_type_id, relationship_direction
1275 FROM civicrm_membership_type
1276 WHERE id = {$membershipValues['membership_type_id']}";
1277 $dao = CRM_Core_DAO
::executeQuery($query);
1278 $relTypeDirs = array();
1279 while ($dao->fetch()) {
1280 $relTypeId = $dao->relationship_type_id
;
1281 $relDirection = $dao->relationship_direction
;
1283 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $relTypeId);
1284 if (in_array($values[$cid]['relationshipTypeId'], $relTypeIds)) {
1285 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $mainRelatedContactId);
1289 if (($action & CRM_Core_Action
::UPDATE
) &&
1290 ($status & self
::PAST
) &&
1291 ($membershipValues['owner_membership_id'])
1293 // If relationship is PAST and action is UPDATE
1294 // then delete the RELATED membership
1295 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipValues['owner_membership_id'],
1296 $membershipValues['membership_contact_id']
1301 // add / edit the memberships for related
1304 // Get the Membership Type Details.
1305 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipValues['membership_type_id']);
1306 // Check if contact's relationship type exists in membership type
1307 $relTypeDirs = array();
1308 if (!empty($membershipType['relationship_type_id'])) {
1309 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_type_id']);
1311 if (!empty($membershipType['relationship_direction'])) {
1312 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_direction']);
1314 foreach ($relTypeIds as $key => $value) {
1315 $relTypeDirs[] = $value . '_' . $relDirections[$key];
1317 $relTypeDir = $details['relationshipTypeId'] . $details['relationshipTypeDirection'];
1318 if (in_array($relTypeDir, $relTypeDirs)) {
1319 // Check if relationship being created/updated is
1320 // similar to that of membership type's
1323 $membershipValues['owner_membership_id'] = $membershipId;
1324 unset($membershipValues['id']);
1325 unset($membershipValues['membership_contact_id']);
1326 unset($membershipValues['contact_id']);
1327 unset($membershipValues['membership_id']);
1328 foreach ($details['relatedContacts'] as $relatedContactId => $donCare) {
1329 $membershipValues['contact_id'] = $relatedContactId;
1330 if ($deceasedStatusId &&
1331 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $relatedContactId, 'is_deceased')
1333 $membershipValues['status_id'] = $deceasedStatusId;
1334 $membershipValues['skipStatusCal'] = TRUE;
1337 'join_date', 'start_date', 'end_date') as $dateField) {
1338 if (!empty($membershipValues[$dateField])) {
1339 $membershipValues[$dateField] = CRM_Utils_Date
::processDate($membershipValues[$dateField]);
1343 if ($action & CRM_Core_Action
::UPDATE
) {
1344 //delete the membership record for related
1345 //contact before creating new membership record.
1346 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $relatedContactId);
1349 // check whether we have some related memberships still available
1352 FROM civicrm_membership
1353 LEFT JOIN civicrm_membership_status ON (civicrm_membership_status.id = civicrm_membership.status_id)
1354 WHERE membership_type_id = {$membershipValues['membership_type_id']} AND owner_membership_id = {$membershipValues['owner_membership_id']}
1355 AND is_current_member = 1";
1356 $result = CRM_Core_DAO
::singleValueQuery($query);
1357 if ($result < CRM_Utils_Array
::value('max_related', $membershipValues, PHP_INT_MAX
)) {
1358 CRM_Member_BAO_Membership
::create($membershipValues, CRM_Core_DAO
::$_nullArray);
1362 elseif ($action & CRM_Core_Action
::UPDATE
) {
1363 // if action is update and updated relationship do
1364 // not match with the existing
1365 // membership=>relationship then we need to
1366 // delete the membership record created for
1367 // previous relationship.
1369 if (self
::isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, CRM_Utils_Array
::value('relationship_ids', $params))) {
1370 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $mainRelatedContactId);
1378 * Helper function to check whether to delete the membership or
1384 static function isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, $relIds) {
1385 if (in_array($relTypeId, $relTypeIds)) {
1389 if (empty($relIds)) {
1393 $relParamas = array(1 => array($contactId, 'Integer'),
1394 2 => array($mainRelatedContactId, 'Integer'),
1397 if ($contactId == $mainRelatedContactId) {
1398 $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);
1399 if ($recordsFound) {
1405 $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);
1407 if ($recordsFound) {
1415 * Function to get Current Employer for Contact
1417 * @param $contactIds Contact Ids
1419 * @return $currentEmployer array of the current employer
1424 static function getCurrentEmployer($contactIds) {
1425 $contacts = implode(',', $contactIds);
1428 SELECT organization_name, id, employer_id
1429 FROM civicrm_contact
1430 WHERE id IN ( {$contacts} )
1433 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1434 $currentEmployer = array();
1435 while ($dao->fetch()) {
1436 $currentEmployer[$dao->id
]['org_id'] = $dao->employer_id
;
1437 $currentEmployer[$dao->id
]['org_name'] = $dao->organization_name
;
1440 return $currentEmployer;
1444 * Function to return list of permissioned employer for a given contact.
1446 * @param $contactID int contact id whose employers
1448 * @param $name string employers sort name
1452 * @return array array of employers.
1455 static function getPermissionedEmployer($contactID, $name = NULL) {
1456 //get the relationship id
1457 $relTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType',
1458 'Employee of', 'id', 'name_a_b'
1461 return self
::getPermissionedContacts($contactID, $relTypeId, $name);
1466 * Function to return list of permissioned contacts for a given contact and relationship type
1468 * @param $contactID int contact id whose permissioned contacts are to be found.
1469 * @param $relTypeId string one or more relationship type id's
1470 * @param $name string
1474 * @return array of contacts
1476 static function getPermissionedContacts($contactID, $relTypeId, $name = NULL) {
1477 $contacts = array();
1481 SELECT cc.id as id, cc.sort_name as name
1482 FROM civicrm_relationship cr, civicrm_contact cc
1484 cr.contact_id_a = %1 AND
1485 cr.relationship_type_id IN (%2) AND
1486 cr.is_permission_a_b = 1 AND
1487 IF(cr.end_date IS NULL, 1, (DATEDIFF( CURDATE( ), cr.end_date ) <= 0)) AND
1488 cr.is_active = 1 AND
1489 cc.id = cr.contact_id_b";
1491 if (!empty($name)) {
1492 $name = CRM_Utils_Type
::escape($name, 'String');
1494 AND cc.sort_name LIKE '%$name%'";
1497 $args = array(1 => array($contactID, 'Integer'), 2 => array($relTypeId, 'String'));
1498 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1500 while ($dao->fetch()) {
1501 $contacts[$dao->id
] = array(
1502 'name' => $dao->name
,
1503 'value' => $dao->id
,
1511 * Merge relationships from otherContact to mainContact
1512 * Called during contact merge operation
1514 * @param int $mainId contact id of main contact record.
1515 * @param int $otherId contact id of record which is going to merge.
1516 * @param array $sqls (reference) array of sql statements to append to.
1518 * @see CRM_Dedupe_Merger::cpTables()
1522 static function mergeRelationships($mainId, $otherId, &$sqls) {
1523 // Delete circular relationships
1524 $sqls[] = "DELETE FROM civicrm_relationship
1525 WHERE (contact_id_a = $mainId AND contact_id_b = $otherId)
1526 OR (contact_id_b = $mainId AND contact_id_a = $otherId)";
1528 // Delete relationship from other contact if main contact already has that relationship
1529 $sqls[] = "DELETE r2
1530 FROM civicrm_relationship r1, civicrm_relationship r2
1531 WHERE r1.relationship_type_id = r2.relationship_type_id
1534 r1.contact_id_a = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_b = r2.contact_id_b
1535 OR r1.contact_id_b = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_a = r2.contact_id_a
1537 (r1.contact_id_a = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_b = r2.contact_id_a
1538 OR r1.contact_id_b = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_a = r2.contact_id_b)
1539 AND r1.relationship_type_id IN (SELECT id FROM civicrm_relationship_type WHERE name_b_a = name_a_b)
1543 // Move relationships
1544 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_a = $mainId WHERE contact_id_a = $otherId";
1545 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_b = $mainId WHERE contact_id_b = $otherId";
1547 // Move current employer id (name will get updated later)
1548 $sqls[] = "UPDATE civicrm_contact SET employer_id = $mainId WHERE employer_id = $otherId";
1552 * Set 'is_valid' field to false for all relationships whose end date is in the past, ie. are expired.
1554 * @return True on success, false if error is encountered.
1556 static function disableExpiredRelationships() {
1557 $query = "SELECT id FROM civicrm_relationship WHERE is_active = 1 AND end_date < CURDATE()";
1559 $dao = CRM_Core_DAO
::executeQuery($query);
1560 while ($dao->fetch()) {
1561 $result = CRM_Contact_BAO_Relationship
::setIsActive($dao->id
, FALSE);
1562 // Result will be NULL if error occurred. We abort early if error detected.
1563 if ($result == NULL) {
1571 * Function filters the query by possible relationships for the membership type
1572 * It is intended to be called when constructing queries for the api (reciprocal & non-reciprocal)
1573 * and to add clauses to limit the return to those relationships which COULD inherit a membership type
1574 * (as opposed to those who inherit a particular membership
1576 * @param array $params api input array
1578 static function membershipTypeToRelationshipTypes(&$params, $direction = NULL) {
1579 $membershipType = civicrm_api3('membership_type', 'getsingle', array('id' => $params['membership_type_id'], 'return' => 'relationship_type_id, relationship_direction'));
1580 $relationshipTypes = $membershipType['relationship_type_id'];
1581 if(empty($relationshipTypes)) {
1584 // if we don't have any contact data we can only filter on type
1585 if(empty($params['contact_id']) && empty($params['contact_id_a']) && empty($params['contact_id_a'])) {
1586 $params['relationship_type_id'] = array('IN' => $relationshipTypes);
1590 $relationshipDirections = (array) $membershipType['relationship_direction'];
1591 // if we have contact_id_a OR contact_id_b we can make a call here
1592 // if we have contact??
1593 foreach ($relationshipDirections as $index => $mtdirection) {
1594 if(isset($params['contact_id_a']) && $mtdirection == 'a_b' ||
$direction == 'a_b') {
1595 $types[] = $relationshipTypes[$index];
1597 if(isset($params['contact_id_b']) && $mtdirection == 'b_a' ||
$direction == 'b_a') {
1598 $types[] = $relationshipTypes[$index];
1601 if(!empty($types)) {
1602 $params['relationship_type_id'] = array('IN' => $types);
1604 elseif(!empty($clauses)) {
1605 return explode(' OR ', $clauses);
1608 // effectively setting it to return no results
1609 $params['relationship_type_id'] = 0;
1616 * This function is a wrapper for contact relationship selector
1618 * @param array $params associated array for params record id.
1620 * @return array $contactRelationships associated array of contact relationships
1623 public static function getContactRelationshipSelector(&$params) {
1624 // format the params
1625 $params['offset'] = ($params['page'] - 1) * $params['rp'];
1626 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
1628 if ($params['context'] == 'past') {
1629 $relationshipStatus = CRM_Contact_BAO_Relationship
::INACTIVE
;
1632 $relationshipStatus = CRM_Contact_BAO_Relationship
::CURRENT
;
1635 // check logged in user for permission
1636 $page = new CRM_Core_Page();
1637 CRM_Contact_Page_View
::checkUserPermission($page, $params['contact_id']);
1638 $permissions = array($page->_permission
);
1639 if ($page->_permission
== CRM_Core_Permission
::EDIT
) {
1640 $permissions[] = CRM_Core_Permission
::DELETE
;
1642 $mask = CRM_Core_Action
::mask($permissions);
1644 if ($params['context'] != 'user') {
1645 $links = CRM_Contact_Page_View_Relationship
::links();
1646 $permissionedContacts = FALSE;
1649 $links = CRM_Contact_Page_View_UserDashBoard
::links();
1650 $permissionedContacts = TRUE;
1653 // get contact relationships
1654 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1655 $relationshipStatus,
1656 $params['rp'], 0, 0,
1658 $permissionedContacts,
1662 $contactRelationships = array();
1663 $params['total'] = 0;
1664 if (!empty($relationships)) {
1665 // get the total relationships
1666 if ($params['context'] != 'user') {
1667 $params['total'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1668 $relationshipStatus, 0, 1, 0, NULL, NULL, $permissionedContacts);
1671 // FIX ME: we cannot directly determine total permissioned relationship, hence re-fire query
1672 $permissionedRelationships = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1673 $relationshipStatus,
1677 $params['total'] = count($permissionedRelationships);
1681 foreach ($relationships as $relationshipId => $values) {
1682 $contactRelationships[$relationshipId]['name'] = CRM_Utils_System
::href(
1684 'civicrm/contact/view',
1685 "reset=1&cid={$values['contact_id_b']}");
1687 $contactRelationships[$relationshipId]['relation'] = CRM_Utils_System
::href(
1688 $values['relation'],
1689 'civicrm/contact/view/rel',
1690 "action=view&reset=1&cid={$values['contact_id_a']}&id={$values['id']}&rtype={$values['rtype']}");
1692 if ($params['context'] == 'current') {
1693 if (($params['contact_id'] == $values['contact_id_a'] AND $values['is_permission_a_b'] == 1) OR
1694 ($params['contact_id'] == $values['contact_id_b'] AND $values['is_permission_b_a'] == 1)
1696 $contactRelationships[$relationshipId]['name'] .= '<span id="permission-a-b" class="crm-marker permission-relationship"> *</span>';
1699 if (($values['cid'] == $values['contact_id_a'] AND $values['is_permission_a_b'] == 1) OR
1700 ($values['cid'] == $values['contact_id_b'] AND $values['is_permission_b_a'] == 1)
1702 $contactRelationships[$relationshipId]['relation'] .= '<span id="permission-b-a" class="crm-marker permission-relationship"> *</span>';
1706 if (!empty($values['description'])) {
1707 $contactRelationships[$relationshipId]['relation'] .= "<p class='description'>{$values['description']}</p>";
1710 $contactRelationships[$relationshipId]['start_date'] = CRM_Utils_Date
::customFormat($values['start_date']);
1711 $contactRelationships[$relationshipId]['end_date'] = CRM_Utils_Date
::customFormat($values['end_date']);
1712 $contactRelationships[$relationshipId]['city'] = $values['city'];
1713 $contactRelationships[$relationshipId]['state'] = $values['state'];
1714 $contactRelationships[$relationshipId]['email'] = $values['email'];
1715 $contactRelationships[$relationshipId]['phone'] = $values['phone'];
1716 $contactRelationships[$relationshipId]['links'] = $values['action'];
1717 $contactRelationships[$relationshipId]['id'] = $values['id'];
1718 $contactRelationships[$relationshipId]['is_active'] = $values['is_active'];
1721 return $contactRelationships;