3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
35 class CRM_Contact_BAO_Relationship
extends CRM_Contact_DAO_Relationship
{
38 * Various constants to indicate different type of relationships
42 const PAST
= 1, DISABLED
= 2, CURRENT
= 4, INACTIVE
= 8;
45 * Create function. (Use the API instead)
46 * Note that the previous create function has been renamed 'createMultiple'
47 * and this is new in 4.6
48 * All existing calls have been changed to createMultiple except the api call - however, it is recommended
49 * that you call that as the end to end testing here is based on the api & refactoring may still be done
50 * @param array $params
51 * @return \CRM_Contact_BAO_Relationship
52 * @throws \CRM_Core_Exception
54 public static function create(&$params) {
55 self
::setContactABFromIDs($params);
56 if (self
::checkDuplicateRelationship($params, $params['contact_id_a'], $params['contact_id_b'], CRM_Utils_Array
::value('id', $params, 0))) {
57 throw new CRM_Core_Exception('Duplicate Relationship');
59 if (self
::checkValidRelationship($params, $params, 0)) {
60 throw new CRM_Core_Exception('Invalid Relationship');
62 $relationship = self
::add($params);
63 if (!empty($params['contact_id_a'])) {
64 $ids = array('contactTarget' => $relationship->contact_id_b
, 'contact' => $params['contact_id_a']);
65 CRM_Contact_BAO_Relationship
::relatedMemberships($params['contact_id_a'], $values, $ids, (empty($params['id']) ? CRM_Core_Action
::ADD
: CRM_Core_Action
::UPDATE
));
67 self
::addRecent($params, $relationship);
72 * Takes an associative array and creates a relationship object
73 * @deprecated For single creates use the api instead (it's tested).
74 * For multiple a new variant of this function needs to be written and migrated to as this is a bit
77 * @param array $params
78 * (reference ) an assoc array of name/value pairs.
80 * The array that holds all the db ids.
81 * per http://wiki.civicrm.org/confluence/display/CRM/Database+layer
82 * "we are moving away from the $ids param "
84 * @return CRM_Contact_BAO_Relationship
86 public static function createMultiple(&$params, $ids = array()) {
87 $valid = $invalid = $duplicate = $saved = 0;
88 $relationships = $relationshipIds = array();
89 $relationshipId = CRM_Utils_Array
::value('relationship', $ids, CRM_Utils_Array
::value('id', $params));
90 //CRM-9015 - the hooks are called here & in add (since add doesn't call create)
91 // but in future should be tidied per ticket
92 if (empty($relationshipId)) {
94 $action = CRM_Core_Action
::ADD
;
98 $action = CRM_Core_Action
::UPDATE
;
101 CRM_Utils_Hook
::pre($hook, 'Relationship', $relationshipId, $params);
103 if (!$relationshipId) {
104 // creating a new relationship
105 $dataExists = self
::dataExists($params);
107 return array(FALSE, TRUE, FALSE, FALSE, NULL);
109 $relationshipIds = array();
110 foreach ($params['contact_check'] as $key => $value) {
112 // check if the relationship is valid between contacts.
113 // step 1: check if the relationship is valid if not valid skip and keep the count
114 // step 2: check the if two contacts already have a relationship if yes skip and keep the count
115 // step 3: if valid relationship then add the relation and keep the count
118 $errors = self
::checkValidRelationship($params, $ids, $key);
125 self
::checkDuplicateRelationship(
127 CRM_Utils_Array
::value('contact', $ids),
135 self
::setContactABFromIDs($params, $ids, $key);
136 $relationship = self
::add($params);
137 $relationshipIds[] = $relationship->id
;
138 $relationships[$relationship->id
] = $relationship;
141 // editing the relationship
144 // check for duplicate relationship
145 // @todo this code doesn't cope well with updates - causes e-Notices.
146 // API has a lot of code to work around
147 // this but should review this code & remove the extra handling from the api
148 // it seems doubtful any of this is relevant if the contact fields & relationship
149 // type fields are not set
151 self
::checkDuplicateRelationship(
153 CRM_Utils_Array
::value('contact', $ids),
154 $ids['contactTarget'],
159 return array($valid, $invalid, $duplicate, $saved, NULL);
162 $validContacts = TRUE;
163 //validate contacts in update mode also.
164 if (!empty($ids['contact']) && !empty($ids['contactTarget'])) {
165 if (self
::checkValidRelationship($params, $ids, $ids['contactTarget'])) {
166 $validContacts = FALSE;
170 if ($validContacts) {
171 // editing an existing relationship
172 $relationship = self
::add($params, $ids, $ids['contactTarget']);
173 $relationshipIds[] = $relationship->id
;
174 $relationships[$relationship->id
] = $relationship;
179 // do not add to recent items for import, CRM-4399
180 if (!(!empty($params['skipRecentView']) ||
$invalid ||
$duplicate)) {
181 self
::addRecent($params, $relationship);
184 return array($valid, $invalid, $duplicate, $saved, $relationshipIds, $relationships);
188 * This is the function that check/add if the relationship created is valid
190 * @param array $params
191 * (reference ) an assoc array of name/value pairs.
192 * @param int $contactId
193 * This is contact id for adding relationship.
195 * The array that holds all the db ids.
197 * @return CRM_Contact_BAO_Relationship
199 public static function add(&$params, $ids = array(), $contactId = NULL) {
201 CRM_Utils_Array
::value('relationship', $ids, CRM_Utils_Array
::value('id', $params));
204 if ($relationshipId) {
207 //@todo hook are called from create and add - remove one
208 CRM_Utils_Hook
::pre($hook, 'Relationship', $relationshipId, $params);
210 self
::setContactABFromIDs($params);
211 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
213 // explode the string with _ to get the relationship type id
214 // and to know which contact has to be inserted in
215 // contact_id_a and which one in contact_id_b
216 list($type) = explode('_', $relationshipTypes);
218 // check if the relationship type is Head of Household then update the
219 // household's primary contact with this contact.
221 CRM_Contact_BAO_Household
::updatePrimaryContact($params['contact_id_b'], $params['contact_id_a']);
224 $relationship = new CRM_Contact_BAO_Relationship();
225 //@todo this code needs to be updated for the possibility that not all fields are set
227 $relationship->contact_id_b
= $params['contact_id_b'];
228 $relationship->contact_id_a
= $params['contact_id_a'];
229 $relationship->relationship_type_id
= $type;
230 $relationship->id
= $relationshipId;
232 $dateFields = array('end_date', 'start_date');
234 foreach (self
::getdefaults() as $defaultField => $defaultValue) {
235 if (isset($params[$defaultField])) {
236 if (in_array($defaultField, $dateFields)) {
237 $relationship->$defaultField = CRM_Utils_Date
::format(CRM_Utils_Array
::value($defaultField, $params));
238 if (!$relationship->$defaultField) {
239 $relationship->$defaultField = 'NULL';
243 $relationship->$defaultField = $params[$defaultField];
246 elseif (!$relationshipId) {
247 $relationship->$defaultField = $defaultValue;
251 $relationship->save();
253 // add custom field values
254 if (!empty($params['custom'])) {
255 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_relationship', $relationship->id
);
258 $relationship->free();
260 CRM_Utils_Hook
::post($hook, 'Relationship', $relationship->id
, $relationship);
262 return $relationship;
266 * Add relationship to recent links
267 * @param array $params
268 * @param CRM_Contact_DAO_Relationship $relationship
270 public static function addRecent($params, $relationship) {
271 $url = CRM_Utils_System
::url('civicrm/contact/view/rel',
272 "action=view&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&context=home"
274 $session = CRM_Core_Session
::singleton();
275 $recentOther = array();
276 if (($session->get('userID') == $relationship->contact_id_a
) ||
277 CRM_Contact_BAO_Contact_Permission
::allow($relationship->contact_id_a
, CRM_Core_Permission
::EDIT
)
279 $rType = substr(CRM_Utils_Array
::value('relationship_type_id', $params), -3);
280 $recentOther = array(
281 'editUrl' => CRM_Utils_System
::url('civicrm/contact/view/rel',
282 "action=update&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
284 'deleteUrl' => CRM_Utils_System
::url('civicrm/contact/view/rel',
285 "action=delete&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
289 $title = CRM_Contact_BAO_Contact
::displayName($relationship->contact_id_a
) . ' (' . CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType',
290 $relationship->relationship_type_id
, 'label_a_b'
291 ) . ' ' . CRM_Contact_BAO_Contact
::displayName($relationship->contact_id_b
) . ')';
293 CRM_Utils_Recent
::add($title,
297 $relationship->contact_id_a
,
304 * Resolve passed in contact IDs to contact_id_a & contact_id_b
305 * @param array $params
307 * @param null $contactID
308 * @throws \CRM_Core_Exception
310 public static function setContactABFromIDs(&$params, $ids = array(), $contactID = NULL) {
311 if (!empty($params['contact_id_a']) && !empty($params['contact_id_b'])) {
314 if (empty($ids['contact'])) {
315 if (!empty($params['id'])) {
316 //let's load the missing ids here since other things tend to rely on them.
317 $fieldsToFill = array('contact_id_a', 'contact_id_b', 'relationship_type_id');
318 $result = CRM_Core_DAO
::executeQuery("SELECT " . implode(',', $fieldsToFill) . " FROM civicrm_relationship WHERE id = %1", array(
324 while ($result->fetch()) {
325 foreach ($fieldsToFill as $field) {
326 $params[$field] = !empty($params[$field]) ?
$params[$field] : $result->$field;
331 throw new CRM_Core_Exception('Cannot create relationship, insufficient contact IDs provided');
333 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
334 list($relationshipTypeID, $first, $second) = explode('_', $relationshipTypes);
335 if (empty($params['relationship_type_id'])) {
336 $params['relationship_type_id'] = $relationshipTypeID;
338 foreach (array('a', 'b') as $contactLetter) {
339 if (empty($params['contact_' . $contactLetter])) {
340 if ($first == $contactLetter) {
341 $params['contact_id_' . $contactLetter] = CRM_Utils_Array
::value('contact', $ids);
344 $params['contact_id_' . $contactLetter] = $contactID;
351 * Specifiy defaults for creating a relationship
354 * array of defaults for creating relationship
356 public static function getdefaults() {
359 'is_permission_a_b' => 0,
360 'is_permission_b_a' => 0,
362 'start_date' => 'NULL',
364 'end_date' => 'NULL',
370 * Check if there is data to create the object
372 * @param array $params
373 * (reference ) an assoc array of name/value pairs.
377 public static function dataExists(&$params) {
378 // return if no data present
379 if (!is_array(CRM_Utils_Array
::value('contact_check', $params))) {
386 * Get get list of relationship type based on the contact type.
388 * @param int $contactId
389 * This is the contact id of the current contact.
390 * @param null $contactSuffix
391 * @param string $relationshipId
392 * The id of the existing relationship if any.
393 * @param string $contactType
396 * If true returns relationship types in both the direction.
397 * @param string $column
398 * Name/label that going to retrieve from db.
399 * @param bool $biDirectional
400 * @param string $contactSubType
401 * Includes relationshiptypes between this subtype.
402 * @param bool $onlySubTypeRelationTypes
403 * If set only subtype which is passed by $contactSubType.
404 * related relationshiptypes get return
408 * array reference of all relationship types with context to current contact.
410 static function getContactRelationshipType(
412 $contactSuffix = NULL,
413 $relationshipId = NULL,
417 $biDirectional = TRUE,
418 $contactSubType = NULL,
419 $onlySubTypeRelationTypes = FALSE
421 $allRelationshipType = array();
422 $relationshipType = array();
423 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType($column);
425 $otherContactType = NULL;
426 if ($relationshipId) {
427 $relationship = new CRM_Contact_DAO_Relationship();
428 $relationship->id
= $relationshipId;
429 if ($relationship->find(TRUE)) {
430 $contact = new CRM_Contact_DAO_Contact();
431 $contact->id
= ($relationship->contact_id_a
=== $contactId) ?
$relationship->contact_id_b
: $relationship->contact_id_a
;
433 if ($contact->find(TRUE)) {
434 $otherContactType = $contact->contact_type
;
435 //CRM-5125 for contact subtype specific relationshiptypes
436 if ($contact->contact_sub_type
) {
437 $otherContactSubType = $contact->contact_sub_type
;
443 $contactSubType = array();
445 $contactType = CRM_Contact_BAO_Contact
::getContactType($contactId);
446 $contactSubType = CRM_Contact_BAO_Contact
::getContactSubType($contactId);
449 foreach ($allRelationshipType as $key => $value) {
450 // the contact type is required or matches
451 if (((!$value['contact_type_a']) ||
452 $value['contact_type_a'] == $contactType
454 // the other contact type is required or present or matches
455 ((!$value['contact_type_b']) ||
456 (!$otherContactType) ||
457 $value['contact_type_b'] == $otherContactType
459 (in_array($value['contact_sub_type_a'], $contactSubType) ||
460 in_array($value['contact_sub_type_b'], $contactSubType) ||
461 (!$value['contact_sub_type_a'] && !$onlySubTypeRelationTypes)
464 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
467 if (((!$value['contact_type_b']) ||
468 $value['contact_type_b'] == $contactType
470 ((!$value['contact_type_a']) ||
471 (!$otherContactType) ||
472 $value['contact_type_a'] == $otherContactType
474 (in_array($value['contact_sub_type_b'], $contactSubType) ||
475 in_array($value['contact_sub_type_a'], $contactSubType) ||
476 (!$value['contact_sub_type_b'] && !$onlySubTypeRelationTypes)
479 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
483 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
484 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
488 if ($biDirectional) {
489 // lets clean up the data and eliminate all duplicate values
490 // (i.e. the relationship is bi-directional)
491 $relationshipType = array_unique($relationshipType);
494 // sort the relationshipType in ascending order CRM-7736
495 asort($relationshipType);
496 return $relationshipType;
503 * @return CRM_Contact_DAO_Relationship
505 public static function clearCurrentEmployer($id, $action) {
506 $relationship = new CRM_Contact_DAO_Relationship();
507 $relationship->id
= $id;
508 $relationship->find(TRUE);
510 //to delete relationship between household and individual \
511 //or between individual and orgnization
512 if (($action & CRM_Core_Action
::DISABLE
) ||
($action & CRM_Core_Action
::DELETE
)) {
513 $relTypes = CRM_Utils_Array
::index(array('name_a_b'), CRM_Core_PseudoConstant
::relationshipType('name'));
514 if ($relationship->relationship_type_id
== $relTypes['Employee of']['id'] ||
515 $relationship->relationship_type_id
== $relTypes['Household Member of']['id']
517 $sharedContact = new CRM_Contact_DAO_Contact();
518 $sharedContact->id
= $relationship->contact_id_a
;
519 $sharedContact->find(TRUE);
521 if ($relationship->relationship_type_id
== 4 && $relationship->contact_id_b
== $sharedContact->employer_id
) {
522 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($relationship->contact_id_a
);
526 return $relationship;
530 * Delete the relationship
538 public static function del($id) {
539 // delete from relationship table
540 CRM_Utils_Hook
::pre('delete', 'Relationship', $id, CRM_Core_DAO
::$_nullArray);
542 $relationship = self
::clearCurrentEmployer($id, CRM_Core_Action
::DELETE
);
543 if (CRM_Core_Permission
::access('CiviMember')) {
544 // create $params array which isrequired to delete memberships
545 // of the related contacts.
547 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
548 'contact_check' => array($relationship->contact_id_b
=> 1),
552 // calling relatedMemberships to delete the memberships of
554 self
::relatedMemberships($relationship->contact_id_a
,
557 CRM_Core_Action
::DELETE
,
562 $relationship->delete();
563 CRM_Core_Session
::setStatus(ts('Selected relationship has been deleted successfully.'), ts('Record Deleted'), 'success');
565 CRM_Utils_Hook
::post('delete', 'Relationship', $id, $relationship);
567 // delete the recently created Relationship
568 $relationshipRecent = array(
570 'type' => 'Relationship',
572 CRM_Utils_Recent
::del($relationshipRecent);
574 return $relationship;
578 * Disable/enable the relationship
587 public static function disableEnableRelationship($id, $action) {
588 $relationship = self
::clearCurrentEmployer($id, $action);
589 if (CRM_Core_Permission
::access('CiviMember')) {
590 // create $params array which isrequired to delete memberships
591 // of the related contacts.
593 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
594 'contact_check' => array($relationship->contact_id_b
=> 1),
598 // calling relatedMemberships to delete/add the memberships of
600 if ($action & CRM_Core_Action
::DISABLE
) {
601 CRM_Contact_BAO_Relationship
::relatedMemberships($relationship->contact_id_a
,
604 CRM_Core_Action
::DELETE
,
608 elseif ($action & CRM_Core_Action
::ENABLE
) {
609 $ids['contact'] = $relationship->contact_id_a
;
610 CRM_Contact_BAO_Relationship
::relatedMemberships($relationship->contact_id_a
,
613 CRM_Core_Action
::ADD
,
621 * Delete the object records that are associated with this contact
623 * @param int $contactId
624 * Id of the contact to delete.
628 public static function deleteContact($contactId) {
629 $relationship = new CRM_Contact_DAO_Relationship();
630 $relationship->contact_id_a
= $contactId;
631 $relationship->delete();
633 $relationship = new CRM_Contact_DAO_Relationship();
634 $relationship->contact_id_b
= $contactId;
635 $relationship->delete();
637 CRM_Contact_BAO_Household
::updatePrimaryContact(NULL, $contactId);
641 * Get the other contact in a relationship
646 * $returns returns the contact ids in the realtionship
648 * @return \CRM_Contact_DAO_Relationship
650 public static function getContactIds($id) {
651 $relationship = new CRM_Contact_DAO_Relationship();
653 $relationship->id
= $id;
654 $relationship->selectAdd();
655 $relationship->selectAdd('contact_id_a, contact_id_b');
656 $relationship->find(TRUE);
658 return $relationship;
662 * Check if the relationship type selected between two contacts is correct
664 * @param int $contact_a
666 * @param int $contact_b
668 * @param int $relationshipTypeId
669 * Relationship type id.
672 * true if it is valid relationship else false
674 public static function checkRelationshipType($contact_a, $contact_b, $relationshipTypeId) {
675 $relationshipType = new CRM_Contact_DAO_RelationshipType();
676 $relationshipType->id
= $relationshipTypeId;
677 $relationshipType->selectAdd();
678 $relationshipType->selectAdd('contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b');
679 if ($relationshipType->find(TRUE)) {
680 $contact_type_a = CRM_Contact_BAO_Contact
::getContactType($contact_a);
681 $contact_type_b = CRM_Contact_BAO_Contact
::getContactType($contact_b);
683 $contact_sub_type_a = CRM_Contact_BAO_Contact
::getContactSubType($contact_a);
684 $contact_sub_type_b = CRM_Contact_BAO_Contact
::getContactSubType($contact_b);
686 if (((!$relationshipType->contact_type_a
) ||
($relationshipType->contact_type_a
== $contact_type_a)) &&
687 ((!$relationshipType->contact_type_b
) ||
($relationshipType->contact_type_b
== $contact_type_b)) &&
688 ((!$relationshipType->contact_sub_type_a
) ||
(in_array($relationshipType->contact_sub_type_a
,
691 ((!$relationshipType->contact_sub_type_b
) ||
(in_array($relationshipType->contact_sub_type_b
,
705 * This function does the validtion for valid relationship
707 * @param array $params
708 * This array contains the values there are subitted by the form.
710 * The array that holds all the db ids.
711 * @param int $contactId
712 * This is contact id for adding relationship.
716 public static function checkValidRelationship($params, $ids, $contactId) {
718 self
::setContactABFromIDs($params, $ids, $contactId);
719 // get the string of relationship type
720 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
721 list($type) = explode('_', $relationshipTypes);
722 // function to check if the relationship selected is correct
723 // i.e. employer relationship can exit between Individual and Organization (not between Individual and Individual)
724 if (!CRM_Contact_BAO_Relationship
::checkRelationshipType($params['contact_id_a'], $params['contact_id_b'], $type)) {
725 $errors = 'Please select valid relationship between these two contacts.';
731 * This function checks for duplicate relationship
733 * @param array $params
734 * (reference ) an assoc array of name/value pairs.
736 * This the id of the contact whom we are adding relationship.
737 * @param int $contactId
738 * This is contact id for adding relationship.
739 * @param int $relationshipId
740 * This is relationship id for the contact.
743 * true if record exists else false
745 public static function checkDuplicateRelationship(&$params, $id, $contactId = 0, $relationshipId = 0) {
746 $relationshipTypeId = CRM_Utils_Array
::value('relationship_type_id', $params);
747 list($type) = explode('_', $relationshipTypeId);
751 FROM civicrm_relationship
752 WHERE relationship_type_id = " . CRM_Utils_Type
::escape($type, 'Integer');
755 * CRM-11792 - date fields from API are in ISO format, but this function
756 * supports date arrays BAO has increasingly standardised to ISO format
757 * so I believe this function should support ISO rather than make API
758 * format it - however, need to support array format for now to avoid breakage
759 * @ time of writing this function is called from Relationship::createMultiple (twice)
760 * CRM_BAO_Contact_Utils::clearCurrentEmployer (seemingly without dates)
761 * CRM_Contact_Form_Task_AddToOrganization::postProcess &
762 * CRM_Contact_Form_Task_AddToHousehold::postProcess
763 * (I don't think the last 2 support dates but not sure
766 $dateFields = array('end_date', 'start_date');
767 foreach ($dateFields as $dateField) {
768 if (array_key_exists($dateField, $params)) {
769 if (empty($params[$dateField]) ||
$params[$dateField] == 'null') {
770 //this is most likely coming from an api call & probably loaded
771 // from the DB to deal with some of the
772 // other myriad of excessive checks still in place both in
773 // the api & the create functions
774 $queryString .= " AND $dateField IS NULL";
777 elseif (is_array($params[$dateField])) {
778 $queryString .= " AND $dateField = " .
779 CRM_Utils_Type
::escape(CRM_Utils_Date
::format($params[$dateField]), 'Date');
782 $queryString .= " AND $dateField = " .
783 CRM_Utils_Type
::escape($params[$dateField], 'Date');
789 " AND ( ( contact_id_a = " . CRM_Utils_Type
::escape($id, 'Integer') .
790 " AND contact_id_b = " . CRM_Utils_Type
::escape($contactId, 'Integer') .
791 " ) OR ( contact_id_a = " . CRM_Utils_Type
::escape($contactId, 'Integer') .
792 " AND contact_id_b = " . CRM_Utils_Type
::escape($id, 'Integer') . " ) ) ";
794 //if caseId is provided, include it duplicate checking.
795 if ($caseId = CRM_Utils_Array
::value('case_id', $params)) {
796 $queryString .= " AND case_id = " . CRM_Utils_Type
::escape($caseId, 'Integer');
799 if ($relationshipId) {
800 $queryString .= " AND id !=" . CRM_Utils_Type
::escape($relationshipId, 'Integer');
803 $relationship = new CRM_Contact_BAO_Relationship();
804 $relationship->query($queryString);
805 $relationship->fetch();
806 $relationship->free();
807 return ($relationship->id
) ?
TRUE : FALSE;
811 * Update the is_active flag in the db
814 * Id of the database record.
815 * @param bool $is_active
816 * Value we want to set the is_active field.
818 * @throws CiviCRM_API3_Exception
820 * DAO object on success, null otherwise
822 public static function setIsActive($id, $is_active) {
823 // as both the create & add functions have a bunch of logic in them that
824 // doesn't seem to cope with a normal update we will call the api which
825 // has tested handling for this
826 // however, a longer term solution would be to simplify the add, create & api functions
827 // to be more standard. It is debatable @ that point whether it's better to call the BAO
828 // direct as the api is more tested.
829 $result = civicrm_api('relationship', 'create', array(
831 'is_active' => $is_active,
835 if (is_array($result) && !empty($result['is_error']) && $result['error_message'] != 'Relationship already exists') {
836 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array
::value('error_code', $result, 'undefined'), $result);
839 // call (undocumented possibly deprecated) hook
840 CRM_Utils_Hook
::enableDisable('CRM_Contact_BAO_Relationship', $id, $is_active);
846 * Given the list of params in the params array, fetch the object
847 * and store the values in the values array
849 * @param array $params
850 * Input parameters to find object.
851 * @param array $values
852 * Output values of the object.
855 * (reference) the values that could be potentially assigned to smarty
857 public static function &getValues(&$params, &$values) {
858 if (empty($params)) {
863 // get the specific number of relationship or all relationships.
864 if (!empty($params['numRelationship'])) {
865 $v['data'] = &CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'], NULL, $params['numRelationship']);
868 $v['data'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id']);
871 // get the total count of relationships
872 $v['totalCount'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'], NULL, NULL, TRUE);
874 $values['relationship']['data'] = &$v['data'];
875 $values['relationship']['totalCount'] = &$v['totalCount'];
881 * Helper function to form the sql for relationship retrieval
883 * @param int $contactId
886 * (check const at top of file).
887 * @param int $numRelationship
888 * No of relationships to display (limit).
890 * Get the no of relationships.
891 * $param int $relationshipId relationship id
892 * @param int $relationshipId
893 * @param string $direction
894 * The direction we are interested in a_b or b_a.
895 * @param array $params
896 * Array of extra values including relationship_type_id per api spec.
898 * return string the query for this diretion
902 public static function makeURLClause($contactId, $status, $numRelationship, $count, $relationshipId, $direction, $params = array()) {
903 $select = $from = $where = '';
907 if ($direction == 'a_b') {
908 $select .= ' SELECT count(DISTINCT civicrm_relationship.id) as cnt1, 0 as cnt2 ';
911 $select .= ' SELECT 0 as cnt1, count(DISTINCT civicrm_relationship.id) as cnt2 ';
915 $select .= ' SELECT civicrm_relationship.id as civicrm_relationship_id,
916 civicrm_contact.sort_name as sort_name,
917 civicrm_contact.display_name as display_name,
918 civicrm_contact.job_title as job_title,
919 civicrm_contact.employer_id as employer_id,
920 civicrm_contact.organization_name as organization_name,
921 civicrm_address.street_address as street_address,
922 civicrm_address.city as city,
923 civicrm_address.postal_code as postal_code,
924 civicrm_state_province.abbreviation as state,
925 civicrm_country.name as country,
926 civicrm_email.email as email,
927 civicrm_contact.contact_type as contact_type,
928 civicrm_phone.phone as phone,
929 civicrm_contact.id as civicrm_contact_id,
930 civicrm_relationship.contact_id_b as contact_id_b,
931 civicrm_relationship.contact_id_a as contact_id_a,
932 civicrm_relationship_type.id as civicrm_relationship_type_id,
933 civicrm_relationship.start_date as start_date,
934 civicrm_relationship.end_date as end_date,
935 civicrm_relationship.description as description,
936 civicrm_relationship.is_active as is_active,
937 civicrm_relationship.is_permission_a_b as is_permission_a_b,
938 civicrm_relationship.is_permission_b_a as is_permission_b_a,
939 civicrm_relationship.case_id as case_id';
941 if ($direction == 'a_b') {
942 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
943 civicrm_relationship_type.label_b_a as relation ';
946 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
947 civicrm_relationship_type.label_a_b as relation ';
952 FROM civicrm_relationship
953 INNER JOIN civicrm_relationship_type ON ( civicrm_relationship.relationship_type_id = civicrm_relationship_type.id )
954 INNER JOIN civicrm_contact ";
955 if ($direction == 'a_b') {
956 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_a ) ';
959 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_b ) ';
962 LEFT JOIN civicrm_address ON (civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1)
963 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
964 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id AND civicrm_email.is_primary = 1)
965 LEFT JOIN civicrm_state_province ON (civicrm_address.state_province_id = civicrm_state_province.id)
966 LEFT JOIN civicrm_country ON (civicrm_address.country_id = civicrm_country.id)
968 $where = 'WHERE ( 1 )';
970 if ($direction == 'a_b') {
971 $where .= ' AND civicrm_relationship.contact_id_b = ' . CRM_Utils_Type
::escape($contactId, 'Positive');
974 $where .= ' AND civicrm_relationship.contact_id_a = ' . CRM_Utils_Type
::escape($contactId, 'Positive') . '
975 AND civicrm_relationship.contact_id_a != civicrm_relationship.contact_id_b ';
978 if ($relationshipId) {
979 $where .= ' AND civicrm_relationship.id = ' . CRM_Utils_Type
::escape($relationshipId, 'Positive');
982 $date = date('Y-m-d');
983 if ($status == self
::PAST
) {
984 //this case for showing past relationship
985 $where .= ' AND civicrm_relationship.is_active = 1 ';
986 $where .= " AND civicrm_relationship.end_date < '" . $date . "'";
988 elseif ($status == self
::DISABLED
) {
989 // this case for showing disabled relationship
990 $where .= ' AND civicrm_relationship.is_active = 0 ';
992 elseif ($status == self
::CURRENT
) {
993 //this case for showing current relationship
994 $where .= ' AND civicrm_relationship.is_active = 1 ';
995 $where .= " AND (civicrm_relationship.end_date >= '" . $date . "' OR civicrm_relationship.end_date IS NULL) ";
997 elseif ($status == self
::INACTIVE
) {
998 //this case for showing inactive relationships
999 $where .= " AND (civicrm_relationship.end_date < '" . $date . "'";
1000 $where .= ' OR civicrm_relationship.is_active = 0 )';
1004 $where .= ' AND civicrm_contact.is_deleted = 0';
1005 if (!empty($params['membership_type_id']) && empty($params['relationship_type_id'])) {
1006 $where .= self
::membershipTypeToRelationshipTypes($params, $direction);
1008 if (!empty($params['relationship_type_id'])) {
1009 if (is_array($params['relationship_type_id'])) {
1010 $where .= " AND " . CRM_Core_DAO
::createSQLFilter('relationship_type_id', $params['relationship_type_id'], 'Integer');
1013 $where .= ' AND relationship_type_id = ' . CRM_Utils_Type
::escape($params['relationship_type_id'], 'Positive');
1016 if ($direction == 'a_b') {
1017 $where .= ' ) UNION ';
1023 return array($select, $from, $where);
1027 * This is the function to get the list of relationships
1029 * @param int $contactId
1031 * @param int $status
1032 * 1: Past 2: Disabled 3: Current.
1033 * @param int $numRelationship
1034 * No of relationships to display (limit).
1036 * Get the no of relationships.
1037 * $param int $relationshipId relationship id
1038 * $param array $links the list of links to display
1039 * $param int $permissionMask the permission mask to be applied for the actions
1040 * $param boolean $permissionedContact to return only permissioned Contact
1041 * $param array $params array of variables consistent with filters supported by the api
1042 * return array $values relationship records
1043 * @param int $relationshipId
1044 * @param null $links
1045 * @param null $permissionMask
1046 * @param bool $permissionedContact
1047 * @param array $params
1051 static function getRelationship(
1053 $status = 0, $numRelationship = 0,
1054 $count = 0, $relationshipId = 0,
1055 $links = NULL, $permissionMask = NULL,
1056 $permissionedContact = FALSE,
1060 if (!$contactId && !$relationshipId) {
1064 list($select1, $from1, $where1) = self
::makeURLClause($contactId, $status, $numRelationship,
1065 $count, $relationshipId, 'a_b', $params
1067 list($select2, $from2, $where2) = self
::makeURLClause($contactId, $status, $numRelationship,
1068 $count, $relationshipId, 'b_a', $params
1071 $order = $limit = '';
1073 if (empty($params['sort'])) {
1074 $order = ' ORDER BY civicrm_relationship_type_id, sort_name ';
1077 $order = " ORDER BY {$params['sort']} ";
1081 if (!empty($params['offset']) && $params['offset'] > 0) {
1082 $offset = $params['offset'];
1085 if ($numRelationship) {
1086 $limit = " LIMIT {$offset}, $numRelationship";
1090 // building the query string
1091 $queryString = $select1 . $from1 . $where1 . $select2 . $from2 . $where2 . $order . $limit;
1093 $relationship = new CRM_Contact_DAO_Relationship();
1095 $relationship->query($queryString);
1098 $relationshipCount = 0;
1099 while ($relationship->fetch()) {
1100 $relationshipCount +
= $relationship->cnt1 +
$relationship->cnt2
;
1102 return $relationshipCount;
1107 if ($status != self
::INACTIVE
) {
1109 $mask = array_sum(array_keys($links));
1110 if ($mask & CRM_Core_Action
::DISABLE
) {
1111 $mask -= CRM_Core_Action
::DISABLE
;
1113 if ($mask & CRM_Core_Action
::ENABLE
) {
1114 $mask -= CRM_Core_Action
::ENABLE
;
1117 if ($status == self
::CURRENT
) {
1118 $mask |
= CRM_Core_Action
::DISABLE
;
1120 elseif ($status == self
::DISABLED
) {
1121 $mask |
= CRM_Core_Action
::ENABLE
;
1123 $mask = $mask & $permissionMask;
1126 while ($relationship->fetch()) {
1127 $rid = $relationship->civicrm_relationship_id
;
1128 $cid = $relationship->civicrm_contact_id
;
1129 if (($permissionedContact) &&
1130 (!CRM_Contact_BAO_Contact_Permission
::relationship($cid, $contactId))
1134 $values[$rid]['id'] = $rid;
1135 $values[$rid]['cid'] = $cid;
1136 $values[$rid]['contact_id_a'] = $relationship->contact_id_a
;
1137 $values[$rid]['contact_id_b'] = $relationship->contact_id_b
;
1138 $values[$rid]['contact_type'] = $relationship->contact_type
;
1139 $values[$rid]['relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1140 $values[$rid]['relation'] = $relationship->relation
;
1141 $values[$rid]['name'] = $relationship->sort_name
;
1142 $values[$rid]['display_name'] = $relationship->display_name
;
1143 $values[$rid]['job_title'] = $relationship->job_title
;
1144 $values[$rid]['email'] = $relationship->email
;
1145 $values[$rid]['phone'] = $relationship->phone
;
1146 $values[$rid]['employer_id'] = $relationship->employer_id
;
1147 $values[$rid]['organization_name'] = $relationship->organization_name
;
1148 $values[$rid]['country'] = $relationship->country
;
1149 $values[$rid]['city'] = $relationship->city
;
1150 $values[$rid]['state'] = $relationship->state
;
1151 $values[$rid]['start_date'] = $relationship->start_date
;
1152 $values[$rid]['end_date'] = $relationship->end_date
;
1153 $values[$rid]['description'] = $relationship->description
;
1154 $values[$rid]['is_active'] = $relationship->is_active
;
1155 $values[$rid]['is_permission_a_b'] = $relationship->is_permission_a_b
;
1156 $values[$rid]['is_permission_b_a'] = $relationship->is_permission_b_a
;
1157 $values[$rid]['case_id'] = $relationship->case_id
;
1160 $values[$rid]['status'] = $status;
1163 $values[$rid]['civicrm_relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1165 if ($relationship->contact_id_a
== $contactId) {
1166 $values[$rid]['rtype'] = 'a_b';
1169 $values[$rid]['rtype'] = 'b_a';
1175 'rtype' => $values[$rid]['rtype'],
1176 'cid' => $contactId,
1177 'cbid' => $values[$rid]['cid'],
1178 'caseid' => $values[$rid]['case_id'],
1179 'clientid' => $contactId,
1182 if ($status == self
::INACTIVE
) {
1183 // setting links for inactive relationships
1184 $mask = array_sum(array_keys($links));
1185 if (!$values[$rid]['is_active']) {
1186 $mask -= CRM_Core_Action
::DISABLE
;
1189 $mask -= CRM_Core_Action
::ENABLE
;
1190 $mask -= CRM_Core_Action
::DISABLE
;
1194 // Give access to manage case link by copying to MAX_ACTION index temporarily, depending on case permission of user.
1195 if ($values[$rid]['case_id']) {
1196 // Borrowed logic from CRM_Case_Page_Tab
1197 $hasCaseAccess = FALSE;
1198 if (CRM_Core_Permission
::check('access all cases and activities')) {
1199 $hasCaseAccess = TRUE;
1202 $userCases = CRM_Case_BAO_Case
::getCases(FALSE);
1203 if (array_key_exists($values[$rid]['case_id'], $userCases)) {
1204 $hasCaseAccess = TRUE;
1208 if ($hasCaseAccess) {
1209 // give access by copying to MAX_ACTION temporarily, otherwise leave at NONE which won't display
1210 $links[CRM_Core_Action
::MAX_ACTION
] = $links[CRM_Core_Action
::NONE
];
1211 $links[CRM_Core_Action
::MAX_ACTION
]['name'] = ts('Manage Case #%1', array(1 => $values[$rid]['case_id']));
1212 $links[CRM_Core_Action
::MAX_ACTION
]['class'] = 'no-popup';
1214 // Also make sure we have the right client cid since can get here from multiple relationship tabs.
1215 if ($values[$rid]['rtype'] == 'b_a') {
1216 $replace['clientid'] = $values[$rid]['cid'];
1221 $values[$rid]['action'] = CRM_Core_Action
::formLink(
1227 'relationship.selector.row',
1230 unset($links[CRM_Core_Action
::MAX_ACTION
]);
1234 $relationship->free();
1240 * Get get list of relationship type based on the target contact type.
1242 * @param string $targetContactType
1243 * It's valid contact tpye(may be Individual , Organization , Household).
1246 * array reference of all relationship types with context to current contact type .
1248 public function getRelationType($targetContactType) {
1249 $relationshipType = array();
1250 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType();
1252 foreach ($allRelationshipType as $key => $type) {
1253 if ($type['contact_type_b'] == $targetContactType) {
1254 $relationshipType[$key . '_a_b'] = $type['label_a_b'];
1258 return $relationshipType;
1262 * Create / update / delete membership for related contacts.
1264 * This function will create/update/delete membership for related
1265 * contact based on 1) contact have active membership 2) that
1266 * membership is is extedned by the same relationship type to that
1267 * of the existing relationship.
1269 * @param int $contactId
1271 * @param array $params
1272 * array of values submitted by POST.
1275 * @param \const|\which $action which action called this function
1277 * @param bool $active
1280 public static function relatedMemberships($contactId, &$params, $ids, $action = CRM_Core_Action
::ADD
, $active = TRUE) {
1281 // Check the end date and set the status of the relationship
1283 $status = self
::CURRENT
;
1285 if (!empty($params['end_date'])) {
1286 $endDate = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Date
::format($params['end_date']), NULL, 'Ymd');
1287 $today = date('Ymd');
1289 if ($today > $endDate) {
1290 $status = self
::PAST
;
1294 if (($action & CRM_Core_Action
::ADD
) &&
1295 ($status & self
::PAST
)
1297 // if relationship is PAST and action is ADD, no qustion
1298 // of creating RELATED membership and return back to
1303 $rel = explode('_', $params['relationship_type_id']);
1305 $relTypeId = $rel[0];
1306 if (!empty($rel[1])) {
1307 $relDirection = "_{$rel[1]}_{$rel[2]}";
1310 // this call is coming from somewhere where the direction was resolved early on (e.g an api call)
1311 // so we can assume _a_b
1312 $relDirection = "_a_b";
1314 $targetContact = array();
1315 if (($action & CRM_Core_Action
::ADD
) ||
1316 ($action & CRM_Core_Action
::DELETE
)
1318 $contact = $contactId;
1319 $targetContact = CRM_Utils_Array
::value('contact_check', $params);
1321 elseif ($action & CRM_Core_Action
::UPDATE
) {
1322 $contact = $ids['contact'];
1323 $targetContact = array($ids['contactTarget'] => 1);
1326 // Build the 'values' array for
1329 // This will allow us to check if either of the contacts in
1330 // relationship have active memberships.
1335 $values[$contact] = array(
1336 'relatedContacts' => $targetContact,
1337 'relationshipTypeId' => $relTypeId,
1338 'relationshipTypeDirection' => $relDirection,
1341 if (!empty($targetContact)) {
1342 foreach ($targetContact as $cid => $donCare) {
1343 $values[$cid] = array(
1344 'relatedContacts' => array($contact => 1),
1345 'relationshipTypeId' => $relTypeId,
1348 $relTypeParams = array('id' => $relTypeId);
1349 $relTypeValues = array();
1350 CRM_Contact_BAO_RelationshipType
::retrieve($relTypeParams, $relTypeValues);
1352 if (CRM_Utils_Array
::value('name_a_b', $relTypeValues) == CRM_Utils_Array
::value('name_b_a', $relTypeValues)) {
1353 $values[$cid]['relationshipTypeDirection'] = '_a_b';
1356 $values[$cid]['relationshipTypeDirection'] = ($relDirection == '_a_b') ?
'_b_a' : '_a_b';
1361 // Now get the active memberships for all the contacts.
1362 // If contact have any valid membership(s), then add it to
1364 foreach ($values as $cid => $subValues) {
1365 $memParams = array('contact_id' => $cid);
1366 $memberships = array();
1368 CRM_Member_BAO_Membership
::getValues($memParams, $memberships, $active);
1370 if (empty($memberships)) {
1374 $values[$cid]['memberships'] = $memberships;
1376 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1378 // done with 'values' array.
1379 // Finally add / edit / delete memberships for the related contacts
1380 foreach ($values as $cid => $details) {
1381 if (!array_key_exists('memberships', $details)) {
1385 $mainRelatedContactId = key(CRM_Utils_Array
::value('relatedContacts', $details, array()));
1387 foreach ($details['memberships'] as $membershipId => $membershipValues) {
1388 $relTypeIds = array();
1389 if ($action & CRM_Core_Action
::DELETE
) {
1390 // Delete memberships of the related contacts only if relationship type exists for membership type
1392 SELECT relationship_type_id, relationship_direction
1393 FROM civicrm_membership_type
1394 WHERE id = {$membershipValues['membership_type_id']}";
1395 $dao = CRM_Core_DAO
::executeQuery($query);
1396 $relTypeDirs = array();
1397 while ($dao->fetch()) {
1398 $relTypeId = $dao->relationship_type_id
;
1399 $relDirection = $dao->relationship_direction
;
1401 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $relTypeId);
1402 if (in_array($values[$cid]['relationshipTypeId'], $relTypeIds)) {
1403 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $mainRelatedContactId);
1407 if (($action & CRM_Core_Action
::UPDATE
) &&
1408 ($status & self
::PAST
) &&
1409 ($membershipValues['owner_membership_id'])
1411 // If relationship is PAST and action is UPDATE
1412 // then delete the RELATED membership
1413 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipValues['owner_membership_id'],
1414 $membershipValues['membership_contact_id']
1419 // add / edit the memberships for related
1422 // Get the Membership Type Details.
1423 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipValues['membership_type_id']);
1424 // Check if contact's relationship type exists in membership type
1425 $relTypeDirs = array();
1426 if (!empty($membershipType['relationship_type_id'])) {
1427 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_type_id']);
1429 if (!empty($membershipType['relationship_direction'])) {
1430 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_direction']);
1432 foreach ($relTypeIds as $key => $value) {
1433 $relTypeDirs[] = $value . '_' . $relDirections[$key];
1435 $relTypeDir = $details['relationshipTypeId'] . $details['relationshipTypeDirection'];
1436 if (in_array($relTypeDir, $relTypeDirs)) {
1437 // Check if relationship being created/updated is
1438 // similar to that of membership type's
1441 $membershipValues['owner_membership_id'] = $membershipId;
1442 unset($membershipValues['id']);
1443 unset($membershipValues['membership_contact_id']);
1444 unset($membershipValues['contact_id']);
1445 unset($membershipValues['membership_id']);
1446 foreach ($details['relatedContacts'] as $relatedContactId => $donCare) {
1447 $membershipValues['contact_id'] = $relatedContactId;
1448 if ($deceasedStatusId &&
1449 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $relatedContactId, 'is_deceased')
1451 $membershipValues['status_id'] = $deceasedStatusId;
1452 $membershipValues['skipStatusCal'] = TRUE;
1459 if (!empty($membershipValues[$dateField])) {
1460 $membershipValues[$dateField] = CRM_Utils_Date
::processDate($membershipValues[$dateField]);
1464 if ($action & CRM_Core_Action
::UPDATE
) {
1465 //delete the membership record for related
1466 //contact before creating new membership record.
1467 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $relatedContactId);
1470 // check whether we have some related memberships still available
1473 FROM civicrm_membership
1474 LEFT JOIN civicrm_membership_status ON (civicrm_membership_status.id = civicrm_membership.status_id)
1475 WHERE membership_type_id = {$membershipValues['membership_type_id']} AND owner_membership_id = {$membershipValues['owner_membership_id']}
1476 AND is_current_member = 1";
1477 $result = CRM_Core_DAO
::singleValueQuery($query);
1478 if ($result < CRM_Utils_Array
::value('max_related', $membershipValues, PHP_INT_MAX
)) {
1479 CRM_Member_BAO_Membership
::create($membershipValues, CRM_Core_DAO
::$_nullArray);
1483 elseif ($action & CRM_Core_Action
::UPDATE
) {
1484 // if action is update and updated relationship do
1485 // not match with the existing
1486 // membership=>relationship then we need to
1487 // delete the membership record created for
1488 // previous relationship.
1490 if (self
::isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, CRM_Utils_Array
::value('relationship_ids', $params))) {
1491 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $mainRelatedContactId);
1499 * Helper function to check whether to delete the membership or
1503 public static function isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, $relIds) {
1504 if (in_array($relTypeId, $relTypeIds)) {
1508 if (empty($relIds)) {
1512 $relParamas = array(
1513 1 => array($contactId, 'Integer'),
1514 2 => array($mainRelatedContactId, 'Integer'),
1517 if ($contactId == $mainRelatedContactId) {
1518 $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);
1519 if ($recordsFound) {
1525 $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);
1527 if ($recordsFound) {
1535 * Get Current Employer for Contact
1537 * @param $contactIds
1541 * array of the current employer
1543 public static function getCurrentEmployer($contactIds) {
1544 $contacts = implode(',', $contactIds);
1547 SELECT organization_name, id, employer_id
1548 FROM civicrm_contact
1549 WHERE id IN ( {$contacts} )
1552 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1553 $currentEmployer = array();
1554 while ($dao->fetch()) {
1555 $currentEmployer[$dao->id
]['org_id'] = $dao->employer_id
;
1556 $currentEmployer[$dao->id
]['org_name'] = $dao->organization_name
;
1559 return $currentEmployer;
1563 * Return list of permissioned employer for a given contact.
1565 * @param int $contactID
1566 * contact id whose employers.
1568 * @param string $name
1569 * employers sort name.
1573 * array of employers.
1575 public static function getPermissionedEmployer($contactID, $name = NULL) {
1576 //get the relationship id
1577 $relTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType',
1578 'Employee of', 'id', 'name_a_b'
1581 return self
::getPermissionedContacts($contactID, $relTypeId, $name);
1586 * Function to return list of permissioned contacts for a given contact and relationship type
1588 * @param int $contactID
1589 * contact id whose permissioned contacts are to be found.
1590 * @param string $relTypeId
1591 * one or more relationship type id's.
1592 * @param string $name
1598 public static function getPermissionedContacts($contactID, $relTypeId, $name = NULL) {
1599 $contacts = array();
1603 SELECT cc.id as id, cc.sort_name as name
1604 FROM civicrm_relationship cr, civicrm_contact cc
1606 cr.contact_id_a = %1 AND
1607 cr.relationship_type_id IN (%2) AND
1608 cr.is_permission_a_b = 1 AND
1609 IF(cr.end_date IS NULL, 1, (DATEDIFF( CURDATE( ), cr.end_date ) <= 0)) AND
1610 cr.is_active = 1 AND
1611 cc.id = cr.contact_id_b AND
1614 if (!empty($name)) {
1615 $name = CRM_Utils_Type
::escape($name, 'String');
1617 AND cc.sort_name LIKE '%$name%'";
1620 $args = array(1 => array($contactID, 'Integer'), 2 => array($relTypeId, 'String'));
1621 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1623 while ($dao->fetch()) {
1624 $contacts[$dao->id
] = array(
1625 'name' => $dao->name
,
1626 'value' => $dao->id
,
1634 * Merge relationships from otherContact to mainContact
1635 * Called during contact merge operation
1637 * @param int $mainId
1638 * Contact id of main contact record.
1639 * @param int $otherId
1640 * Contact id of record which is going to merge.
1641 * @param array $sqls
1642 * (reference) array of sql statements to append to.
1644 * @see CRM_Dedupe_Merger::cpTables()
1647 public static function mergeRelationships($mainId, $otherId, &$sqls) {
1648 // Delete circular relationships
1649 $sqls[] = "DELETE FROM civicrm_relationship
1650 WHERE (contact_id_a = $mainId AND contact_id_b = $otherId)
1651 OR (contact_id_b = $mainId AND contact_id_a = $otherId)";
1653 // Delete relationship from other contact if main contact already has that relationship
1654 $sqls[] = "DELETE r2
1655 FROM civicrm_relationship r1, civicrm_relationship r2
1656 WHERE r1.relationship_type_id = r2.relationship_type_id
1659 r1.contact_id_a = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_b = r2.contact_id_b
1660 OR r1.contact_id_b = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_a = r2.contact_id_a
1662 (r1.contact_id_a = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_b = r2.contact_id_a
1663 OR r1.contact_id_b = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_a = r2.contact_id_b)
1664 AND r1.relationship_type_id IN (SELECT id FROM civicrm_relationship_type WHERE name_b_a = name_a_b)
1668 // Move relationships
1669 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_a = $mainId WHERE contact_id_a = $otherId";
1670 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_b = $mainId WHERE contact_id_b = $otherId";
1672 // Move current employer id (name will get updated later)
1673 $sqls[] = "UPDATE civicrm_contact SET employer_id = $mainId WHERE employer_id = $otherId";
1677 * Set 'is_valid' field to false for all relationships whose end date is in the past, ie. are expired.
1680 * True on success, false if error is encountered.
1682 public static function disableExpiredRelationships() {
1683 $query = "SELECT id FROM civicrm_relationship WHERE is_active = 1 AND end_date < CURDATE()";
1685 $dao = CRM_Core_DAO
::executeQuery($query);
1686 while ($dao->fetch()) {
1687 $result = CRM_Contact_BAO_Relationship
::setIsActive($dao->id
, FALSE);
1688 // Result will be NULL if error occurred. We abort early if error detected.
1689 if ($result == NULL) {
1697 * Function filters the query by possible relationships for the membership type
1698 * It is intended to be called when constructing queries for the api (reciprocal & non-reciprocal)
1699 * and to add clauses to limit the return to those relationships which COULD inherit a membership type
1700 * (as opposed to those who inherit a particular membership
1702 * @param array $params
1704 * @param null $direction
1708 public static function membershipTypeToRelationshipTypes(&$params, $direction = NULL) {
1709 $membershipType = civicrm_api3('membership_type', 'getsingle', array(
1710 'id' => $params['membership_type_id'],
1711 'return' => 'relationship_type_id, relationship_direction',
1713 $relationshipTypes = $membershipType['relationship_type_id'];
1714 if (empty($relationshipTypes)) {
1717 // if we don't have any contact data we can only filter on type
1718 if (empty($params['contact_id']) && empty($params['contact_id_a']) && empty($params['contact_id_a'])) {
1719 $params['relationship_type_id'] = array('IN' => $relationshipTypes);
1723 $relationshipDirections = (array) $membershipType['relationship_direction'];
1724 // if we have contact_id_a OR contact_id_b we can make a call here
1725 // if we have contact??
1726 foreach ($relationshipDirections as $index => $mtdirection) {
1727 if (isset($params['contact_id_a']) && $mtdirection == 'a_b' ||
$direction == 'a_b') {
1728 $types[] = $relationshipTypes[$index];
1730 if (isset($params['contact_id_b']) && $mtdirection == 'b_a' ||
$direction == 'b_a') {
1731 $types[] = $relationshipTypes[$index];
1734 if (!empty($types)) {
1735 $params['relationship_type_id'] = array('IN' => $types);
1737 elseif (!empty($clauses)) {
1738 return explode(' OR ', $clauses);
1741 // effectively setting it to return no results
1742 $params['relationship_type_id'] = 0;
1749 * wrapper for contact relationship selector
1751 * @param array $params
1752 * Associated array for params record id.
1755 * associated array of contact relationships
1757 public static function getContactRelationshipSelector(&$params) {
1758 // format the params
1759 $params['offset'] = ($params['page'] - 1) * $params['rp'];
1760 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
1762 if ($params['context'] == 'past') {
1763 $relationshipStatus = CRM_Contact_BAO_Relationship
::INACTIVE
;
1766 $relationshipStatus = CRM_Contact_BAO_Relationship
::CURRENT
;
1769 // check logged in user for permission
1770 $page = new CRM_Core_Page();
1771 CRM_Contact_Page_View
::checkUserPermission($page, $params['contact_id']);
1772 $permissions = array($page->_permission
);
1773 if ($page->_permission
== CRM_Core_Permission
::EDIT
) {
1774 $permissions[] = CRM_Core_Permission
::DELETE
;
1776 $mask = CRM_Core_Action
::mask($permissions);
1778 if ($params['context'] != 'user') {
1779 $links = CRM_Contact_Page_View_Relationship
::links();
1780 $permissionedContacts = FALSE;
1783 $links = CRM_Contact_Page_View_UserDashBoard
::links();
1784 $permissionedContacts = TRUE;
1787 // get contact relationships
1788 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1789 $relationshipStatus,
1790 $params['rp'], 0, 0,
1792 $permissionedContacts,
1796 $contactRelationships = array();
1797 $params['total'] = 0;
1798 if (!empty($relationships)) {
1799 // get the total relationships
1800 if ($params['context'] != 'user') {
1801 $params['total'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1802 $relationshipStatus, 0, 1, 0, NULL, NULL, $permissionedContacts);
1805 // FIX ME: we cannot directly determine total permissioned relationship, hence re-fire query
1806 $permissionedRelationships = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1807 $relationshipStatus,
1811 $params['total'] = count($permissionedRelationships);
1815 foreach ($relationships as $relationshipId => $values) {
1816 //Add image icon for related contacts: CRM-14919
1817 $icon = CRM_Contact_BAO_Contact_Utils
::getImage($values['contact_type'],
1821 $contactRelationships[$relationshipId]['name'] = $icon . ' ' . CRM_Utils_System
::href(
1823 'civicrm/contact/view',
1824 "reset=1&cid={$values['cid']}");
1826 $contactRelationships[$relationshipId]['relation'] = CRM_Utils_System
::href(
1827 $values['relation'],
1828 'civicrm/contact/view/rel',
1829 "action=view&reset=1&cid={$values['cid']}&id={$values['id']}&rtype={$values['rtype']}");
1831 if ($params['context'] == 'current') {
1832 if (($params['contact_id'] == $values['contact_id_a'] AND $values['is_permission_a_b'] == 1) OR
1833 ($params['contact_id'] == $values['contact_id_b'] AND $values['is_permission_b_a'] == 1)
1835 $contactRelationships[$relationshipId]['name'] .= '<span id="permission-a-b" class="crm-marker permission-relationship"> *</span>';
1838 if (($values['cid'] == $values['contact_id_a'] AND $values['is_permission_a_b'] == 1) OR
1839 ($values['cid'] == $values['contact_id_b'] AND $values['is_permission_b_a'] == 1)
1841 $contactRelationships[$relationshipId]['relation'] .= '<span id="permission-b-a" class="crm-marker permission-relationship"> *</span>';
1845 if (!empty($values['description'])) {
1846 $contactRelationships[$relationshipId]['relation'] .= "<p class='description'>{$values['description']}</p>";
1849 $contactRelationships[$relationshipId]['start_date'] = CRM_Utils_Date
::customFormat($values['start_date']);
1850 $contactRelationships[$relationshipId]['end_date'] = CRM_Utils_Date
::customFormat($values['end_date']);
1851 $contactRelationships[$relationshipId]['city'] = $values['city'];
1852 $contactRelationships[$relationshipId]['state'] = $values['state'];
1853 $contactRelationships[$relationshipId]['email'] = $values['email'];
1854 $contactRelationships[$relationshipId]['phone'] = $values['phone'];
1855 $contactRelationships[$relationshipId]['links'] = $values['action'];
1856 $contactRelationships[$relationshipId]['id'] = $values['id'];
1857 $contactRelationships[$relationshipId]['is_active'] = $values['is_active'];
1860 return $contactRelationships;