3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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 +--------------------------------------------------------------------+
29 * Class CRM_Contact_BAO_Relationship.
31 class CRM_Contact_BAO_Relationship
extends CRM_Contact_DAO_Relationship
{
34 * Various constants to indicate different type of relationships.
38 const ALL
= 0, PAST
= 1, DISABLED
= 2, CURRENT
= 4, INACTIVE
= 8;
41 * Create function - use the API instead.
43 * Note that the previous create function has been renamed 'legacyCreateMultiple'
44 * and this is new in 4.6
45 * All existing calls have been changed to legacyCreateMultiple except the api call - however, it is recommended
46 * that you call that as the end to end testing here is based on the api & refactoring may still be done.
48 * @param array $params
50 * @return \CRM_Contact_BAO_Relationship
51 * @throws \CRM_Core_Exception
53 public static function create(&$params) {
55 $extendedParams = self
::loadExistingRelationshipDetails($params);
56 // When id is specified we always wan't to update, so we don't need to
57 // check for duplicate relations.
58 if (!isset($params['id']) && self
::checkDuplicateRelationship($extendedParams, $extendedParams['contact_id_a'], $extendedParams['contact_id_b'], CRM_Utils_Array
::value('id', $extendedParams, 0))) {
59 throw new CRM_Core_Exception('Duplicate Relationship');
61 $params = $extendedParams;
62 if (self
::checkValidRelationship($params, $params, 0)) {
63 throw new CRM_Core_Exception('Invalid Relationship');
65 $relationship = self
::add($params);
66 if (!empty($params['contact_id_a'])) {
68 'contactTarget' => $relationship->contact_id_b
,
69 'contact' => $params['contact_id_a'],
72 //CRM-16087 removed additional call to function relatedMemberships which is already called by disableEnableRelationship
73 //resulting in membership being created twice
74 if (array_key_exists('is_active', $params) && empty($params['is_active'])) {
75 $action = CRM_Core_Action
::DISABLE
;
79 $action = CRM_Core_Action
::ENABLE
;
82 $id = empty($params['id']) ?
$relationship->id
: $params['id'];
83 self
::disableEnableRelationship($id, $action, $params, $ids, $active);
86 self
::addRecent($params, $relationship);
91 * Create multiple relationships for one contact.
93 * The relationship details are the same for each relationship except the secondary contact
96 * @param array $params
97 * Parameters for creating multiple relationships.
98 * The parameters are the same as for relationship create function except that the non-primary
99 * end of the relationship should be an array of one or more contact IDs.
100 * @param string $primaryContactLetter
101 * a or b to denote the primary contact for this action. The secondary may be multiple contacts
102 * and should be an array.
105 * @throws \CRM_Core_Exception
107 public static function createMultiple($params, $primaryContactLetter) {
108 $secondaryContactLetter = ($primaryContactLetter == 'a') ?
'b' : 'a';
109 $secondaryContactIDs = $params['contact_id_' . $secondaryContactLetter];
110 $valid = $invalid = $duplicate = $saved = 0;
111 $relationshipIDs = array();
112 foreach ($secondaryContactIDs as $secondaryContactID) {
114 $params['contact_id_' . $secondaryContactLetter] = $secondaryContactID;
115 $relationship = civicrm_api3('relationship', 'create', $params);
116 $relationshipIDs[] = $relationship['id'];
119 catch (CiviCRM_API3_Exception
$e) {
120 switch ($e->getMessage()) {
121 case 'Duplicate Relationship':
125 case 'Invalid Relationship':
130 throw new CRM_Core_Exception('unknown relationship create error ' . $e->getMessage());
137 'invalid' => $invalid,
138 'duplicate' => $duplicate,
140 'relationship_ids' => $relationshipIDs,
145 * Takes an associative array and creates a relationship object.
146 * @deprecated For single creates use the api instead (it's tested).
147 * For multiple a new variant of this function needs to be written and migrated to as this is a bit
150 * @param array $params
151 * (reference ) an assoc array of name/value pairs.
153 * The array that holds all the db ids.
154 * per http://wiki.civicrm.org/confluence/display/CRM/Database+layer
155 * "we are moving away from the $ids param "
157 * @return CRM_Contact_BAO_Relationship
159 public static function legacyCreateMultiple(&$params, $ids = array()) {
160 $valid = $invalid = $duplicate = $saved = 0;
161 $relationships = $relationshipIds = array();
162 $relationshipId = CRM_Utils_Array
::value('relationship', $ids, CRM_Utils_Array
::value('id', $params));
164 //CRM-9015 - the hooks are called here & in add (since add doesn't call create)
165 // but in future should be tidied per ticket
166 if (empty($relationshipId)) {
173 CRM_Utils_Hook
::pre($hook, 'Relationship', $relationshipId, $params);
175 if (!$relationshipId) {
176 // creating a new relationship
177 $dataExists = self
::dataExists($params);
179 return array(FALSE, TRUE, FALSE, FALSE, NULL);
181 $relationshipIds = array();
182 foreach ($params['contact_check'] as $key => $value) {
183 // check if the relationship is valid between contacts.
184 // step 1: check if the relationship is valid if not valid skip and keep the count
185 // step 2: check the if two contacts already have a relationship if yes skip and keep the count
186 // step 3: if valid relationship then add the relation and keep the count
189 $contactFields = self
::setContactABFromIDs($params, $ids, $key);
190 $errors = self
::checkValidRelationship($contactFields, $ids, $key);
196 //CRM-16978:check duplicate relationship as per case id.
197 if ($caseId = CRM_Utils_Array
::value('case_id', $params)) {
198 $contactFields['case_id'] = $caseId;
201 self
::checkDuplicateRelationship(
203 CRM_Utils_Array
::value('contact', $ids),
212 $singleInstanceParams = array_merge($params, $contactFields);
213 $relationship = self
::add($singleInstanceParams);
214 $relationshipIds[] = $relationship->id
;
215 $relationships[$relationship->id
] = $relationship;
218 // editing the relationship
221 // check for duplicate relationship
222 // @todo this code doesn't cope well with updates - causes e-Notices.
223 // API has a lot of code to work around
224 // this but should review this code & remove the extra handling from the api
225 // it seems doubtful any of this is relevant if the contact fields & relationship
226 // type fields are not set
228 self
::checkDuplicateRelationship(
230 CRM_Utils_Array
::value('contact', $ids),
231 $ids['contactTarget'],
236 return array($valid, $invalid, $duplicate, $saved, NULL);
239 $validContacts = TRUE;
240 //validate contacts in update mode also.
241 $contactFields = self
::setContactABFromIDs($params, $ids, $ids['contactTarget']);
242 if (!empty($ids['contact']) && !empty($ids['contactTarget'])) {
243 if (self
::checkValidRelationship($contactFields, $ids, $ids['contactTarget'])) {
244 $validContacts = FALSE;
248 if ($validContacts) {
249 // editing an existing relationship
250 $singleInstanceParams = array_merge($params, $contactFields);
251 $relationship = self
::add($singleInstanceParams, $ids, $ids['contactTarget']);
252 $relationshipIds[] = $relationship->id
;
253 $relationships[$relationship->id
] = $relationship;
258 // do not add to recent items for import, CRM-4399
259 if (!(!empty($params['skipRecentView']) ||
$invalid ||
$duplicate)) {
260 self
::addRecent($params, $relationship);
263 return array($valid, $invalid, $duplicate, $saved, $relationshipIds, $relationships);
267 * This is the function that check/add if the relationship created is valid.
269 * @param array $params
270 * (reference ) an assoc array of name/value pairs.
272 * The array that holds all the db ids.
273 * @param int $contactId
274 * This is contact id for adding relationship.
276 * @return CRM_Contact_BAO_Relationship
278 public static function add(&$params, $ids = array(), $contactId = NULL) {
279 $relationshipId = CRM_Utils_Array
::value('relationship', $ids, CRM_Utils_Array
::value('id', $params));
282 if ($relationshipId) {
285 //@todo hook are called from create and add - remove one
286 CRM_Utils_Hook
::pre($hook, 'Relationship', $relationshipId, $params);
288 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
290 // explode the string with _ to get the relationship type id
291 // and to know which contact has to be inserted in
292 // contact_id_a and which one in contact_id_b
293 list($type) = explode('_', $relationshipTypes);
295 // check if the relationship type is Head of Household then update the
296 // household's primary contact with this contact.
298 CRM_Contact_BAO_Household
::updatePrimaryContact($params['contact_id_b'], $params['contact_id_a']);
301 $relationship = new CRM_Contact_BAO_Relationship();
302 //@todo this code needs to be updated for the possibility that not all fields are set
303 // by using $relationship->copyValues($params);
305 $relationship->contact_id_b
= $params['contact_id_b'];
306 $relationship->contact_id_a
= $params['contact_id_a'];
307 $relationship->relationship_type_id
= $type;
308 $relationship->id
= $relationshipId;
310 $dateFields = array('end_date', 'start_date');
312 foreach (self
::getdefaults() as $defaultField => $defaultValue) {
313 if (isset($params[$defaultField])) {
314 if (in_array($defaultField, $dateFields)) {
315 $relationship->$defaultField = CRM_Utils_Date
::format(CRM_Utils_Array
::value($defaultField, $params));
316 if (!$relationship->$defaultField) {
317 $relationship->$defaultField = 'NULL';
321 $relationship->$defaultField = $params[$defaultField];
324 elseif (!$relationshipId) {
325 $relationship->$defaultField = $defaultValue;
329 $relationship->save();
331 // add custom field values
332 if (!empty($params['custom'])) {
333 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_relationship', $relationship->id
);
336 $relationship->free();
338 CRM_Utils_Hook
::post($hook, 'Relationship', $relationship->id
, $relationship);
340 return $relationship;
344 * Add relationship to recent links.
346 * @param array $params
347 * @param CRM_Contact_DAO_Relationship $relationship
349 public static function addRecent($params, $relationship) {
350 $url = CRM_Utils_System
::url('civicrm/contact/view/rel',
351 "action=view&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&context=home"
353 $session = CRM_Core_Session
::singleton();
354 $recentOther = array();
355 if (($session->get('userID') == $relationship->contact_id_a
) ||
356 CRM_Contact_BAO_Contact_Permission
::allow($relationship->contact_id_a
, CRM_Core_Permission
::EDIT
)
358 $rType = substr(CRM_Utils_Array
::value('relationship_type_id', $params), -3);
359 $recentOther = array(
360 'editUrl' => CRM_Utils_System
::url('civicrm/contact/view/rel',
361 "action=update&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
363 'deleteUrl' => CRM_Utils_System
::url('civicrm/contact/view/rel',
364 "action=delete&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
368 $title = CRM_Contact_BAO_Contact
::displayName($relationship->contact_id_a
) . ' (' . CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType',
369 $relationship->relationship_type_id
, 'label_a_b'
370 ) . ' ' . CRM_Contact_BAO_Contact
::displayName($relationship->contact_id_b
) . ')';
372 CRM_Utils_Recent
::add($title,
376 $relationship->contact_id_a
,
383 * Load contact ids and relationship type id when doing a create call if not provided.
385 * There are are various checks done in create which require this information which is optional
388 * @param array $params
389 * Parameters passed to create call.
392 * Parameters with missing fields added if required.
394 public static function loadExistingRelationshipDetails($params) {
395 if (!empty($params['contact_id_a'])
396 && !empty($params['contact_id_b'])
397 && is_numeric($params['relationship_type_id'])) {
400 if (empty($params['id'])) {
404 $fieldsToFill = array('contact_id_a', 'contact_id_b', 'relationship_type_id');
405 $result = CRM_Core_DAO
::executeQuery("SELECT " . implode(',', $fieldsToFill) . " FROM civicrm_relationship WHERE id = %1", array(
411 while ($result->fetch()) {
412 foreach ($fieldsToFill as $field) {
413 $params[$field] = !empty($params[$field]) ?
$params[$field] : $result->$field;
420 * Resolve passed in contact IDs to contact_id_a & contact_id_b.
422 * @param array $params
424 * @param null $contactID
427 * @throws \CRM_Core_Exception
429 public static function setContactABFromIDs($params, $ids = array(), $contactID = NULL) {
430 $returnFields = array();
432 // $ids['contact'] is deprecated but comes from legacyCreateMultiple function.
433 if (empty($ids['contact'])) {
434 if (!empty($params['id'])) {
435 return self
::loadExistingRelationshipDetails($params);
437 throw new CRM_Core_Exception('Cannot create relationship, insufficient contact IDs provided');
439 if (isset($params['relationship_type_id']) && !is_numeric($params['relationship_type_id'])) {
440 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
441 list($relationshipTypeID, $first) = explode('_', $relationshipTypes);
442 $returnFields['relationship_type_id'] = $relationshipTypeID;
444 foreach (array('a', 'b') as $contactLetter) {
445 if (empty($params['contact_' . $contactLetter])) {
446 if ($first == $contactLetter) {
447 $returnFields['contact_id_' . $contactLetter] = CRM_Utils_Array
::value('contact', $ids);
450 $returnFields['contact_id_' . $contactLetter] = $contactID;
456 return $returnFields;
460 * Specify defaults for creating a relationship.
463 * array of defaults for creating relationship
465 public static function getdefaults() {
468 'is_permission_a_b' => 0,
469 'is_permission_b_a' => 0,
471 'start_date' => 'NULL',
473 'end_date' => 'NULL',
479 * Check if there is data to create the object.
481 * @param array $params
482 * (reference ) an assoc array of name/value pairs.
486 public static function dataExists(&$params) {
487 // return if no data present
488 if (!is_array(CRM_Utils_Array
::value('contact_check', $params))) {
495 * Get get list of relationship type based on the contact type.
497 * @param int $contactId
498 * This is the contact id of the current contact.
499 * @param null $contactSuffix
500 * @param string $relationshipId
501 * The id of the existing relationship if any.
502 * @param string $contactType
505 * If true returns relationship types in both the direction.
506 * @param string $column
507 * Name/label that going to retrieve from db.
508 * @param bool $biDirectional
509 * @param string $contactSubType
510 * Includes relationship types between this subtype.
511 * @param bool $onlySubTypeRelationTypes
512 * If set only subtype which is passed by $contactSubType
513 * related relationship types get return
516 * array reference of all relationship types with context to current contact.
518 public static function getContactRelationshipType(
520 $contactSuffix = NULL,
521 $relationshipId = NULL,
525 $biDirectional = TRUE,
526 $contactSubType = NULL,
527 $onlySubTypeRelationTypes = FALSE
530 $relationshipType = array();
531 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType($column);
533 $otherContactType = NULL;
534 if ($relationshipId) {
535 $relationship = new CRM_Contact_DAO_Relationship();
536 $relationship->id
= $relationshipId;
537 if ($relationship->find(TRUE)) {
538 $contact = new CRM_Contact_DAO_Contact();
539 $contact->id
= ($relationship->contact_id_a
=== $contactId) ?
$relationship->contact_id_b
: $relationship->contact_id_a
;
541 if ($contact->find(TRUE)) {
542 $otherContactType = $contact->contact_type
;
543 //CRM-5125 for contact subtype specific relationshiptypes
544 if ($contact->contact_sub_type
) {
545 $otherContactSubType = $contact->contact_sub_type
;
551 $contactSubType = array();
553 $contactType = CRM_Contact_BAO_Contact
::getContactType($contactId);
554 $contactSubType = CRM_Contact_BAO_Contact
::getContactSubType($contactId);
557 foreach ($allRelationshipType as $key => $value) {
558 // the contact type is required or matches
559 if (((!$value['contact_type_a']) ||
560 $value['contact_type_a'] == $contactType
562 // the other contact type is required or present or matches
563 ((!$value['contact_type_b']) ||
564 (!$otherContactType) ||
565 $value['contact_type_b'] == $otherContactType
567 (in_array($value['contact_sub_type_a'], $contactSubType) ||
568 (!$value['contact_sub_type_a'] && !$onlySubTypeRelationTypes)
571 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
574 if (((!$value['contact_type_b']) ||
575 $value['contact_type_b'] == $contactType
577 ((!$value['contact_type_a']) ||
578 (!$otherContactType) ||
579 $value['contact_type_a'] == $otherContactType
581 (in_array($value['contact_sub_type_b'], $contactSubType) ||
582 (!$value['contact_sub_type_b'] && !$onlySubTypeRelationTypes)
585 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
589 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
590 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
594 if ($biDirectional) {
595 // lets clean up the data and eliminate all duplicate values
596 // (i.e. the relationship is bi-directional)
597 $relationshipType = array_unique($relationshipType);
600 // sort the relationshipType in ascending order CRM-7736
601 asort($relationshipType);
602 return $relationshipType;
606 * Delete current employer relationship.
611 * @return CRM_Contact_DAO_Relationship
613 public static function clearCurrentEmployer($id, $action) {
614 $relationship = new CRM_Contact_DAO_Relationship();
615 $relationship->id
= $id;
616 $relationship->find(TRUE);
618 //to delete relationship between household and individual \
619 //or between individual and organization
620 if (($action & CRM_Core_Action
::DISABLE
) ||
($action & CRM_Core_Action
::DELETE
)) {
621 $relTypes = CRM_Utils_Array
::index(array('name_a_b'), CRM_Core_PseudoConstant
::relationshipType('name'));
622 if ($relationship->relationship_type_id
== $relTypes['Employee of']['id'] ||
623 $relationship->relationship_type_id
== $relTypes['Household Member of']['id']
625 $sharedContact = new CRM_Contact_DAO_Contact();
626 $sharedContact->id
= $relationship->contact_id_a
;
627 $sharedContact->find(TRUE);
630 // changed FROM "...relationship->relationship_type_id == 4..." TO "...relationship->relationship_type_id == 5..."
631 // As the system should be looking for type "employer of" (id 5) and not "sibling of" (id 4)
632 // As suggested by @davecivicrm, the employee relationship type id is fetched using the CRM_Core_DAO::getFieldValue() class and method, since these ids differ from system to system.
633 $employerRelTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b');
635 if ($relationship->relationship_type_id
== $employerRelTypeId && $relationship->contact_id_b
== $sharedContact->employer_id
) {
636 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($relationship->contact_id_a
);
641 return $relationship;
645 * Delete the relationship.
652 public static function del($id) {
653 // delete from relationship table
654 CRM_Utils_Hook
::pre('delete', 'Relationship', $id, CRM_Core_DAO
::$_nullArray);
656 $relationship = self
::clearCurrentEmployer($id, CRM_Core_Action
::DELETE
);
657 if (CRM_Core_Permission
::access('CiviMember')) {
658 // create $params array which isrequired to delete memberships
659 // of the related contacts.
661 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
662 'contact_check' => array($relationship->contact_id_b
=> 1),
666 // calling relatedMemberships to delete the memberships of
668 self
::relatedMemberships($relationship->contact_id_a
,
671 CRM_Core_Action
::DELETE
,
676 $relationship->delete();
677 CRM_Core_Session
::setStatus(ts('Selected relationship has been deleted successfully.'), ts('Record Deleted'), 'success');
679 CRM_Utils_Hook
::post('delete', 'Relationship', $id, $relationship);
681 // delete the recently created Relationship
682 $relationshipRecent = array(
684 'type' => 'Relationship',
686 CRM_Utils_Recent
::del($relationshipRecent);
688 return $relationship;
692 * Disable/enable the relationship.
698 * @param array $params
700 * @param bool $active
702 public static function disableEnableRelationship($id, $action, $params = array(), $ids = array(), $active = FALSE) {
703 $relationship = self
::clearCurrentEmployer($id, $action);
706 // create $params array which is required to delete memberships
707 // of the related contacts.
708 if (empty($params)) {
710 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
711 'contact_check' => array($relationship->contact_id_b
=> 1),
714 $contact_id_a = empty($params['contact_id_a']) ?
$relationship->contact_id_a
: $params['contact_id_a'];
715 // calling relatedMemberships to delete/add the memberships of
717 if ($action & CRM_Core_Action
::DISABLE
) {
718 CRM_Contact_BAO_Relationship
::relatedMemberships($contact_id_a,
721 CRM_Core_Action
::DELETE
,
725 elseif ($action & CRM_Core_Action
::ENABLE
) {
726 $ids['contact'] = empty($ids['contact']) ?
$contact_id_a : $ids['contact'];
727 CRM_Contact_BAO_Relationship
::relatedMemberships($contact_id_a,
730 empty($params['id']) ? CRM_Core_Action
::ADD
: CRM_Core_Action
::UPDATE
,
738 * Delete the object records that are associated with this contact.
740 * @param int $contactId
741 * Id of the contact to delete.
743 public static function deleteContact($contactId) {
744 $relationship = new CRM_Contact_DAO_Relationship();
745 $relationship->contact_id_a
= $contactId;
746 $relationship->delete();
748 $relationship = new CRM_Contact_DAO_Relationship();
749 $relationship->contact_id_b
= $contactId;
750 $relationship->delete();
752 CRM_Contact_BAO_Household
::updatePrimaryContact(NULL, $contactId);
756 * Get the other contact in a relationship.
761 * $returns returns the contact ids in the realtionship
763 * @return \CRM_Contact_DAO_Relationship
765 public static function getRelationshipByID($id) {
766 $relationship = new CRM_Contact_DAO_Relationship();
768 $relationship->id
= $id;
769 $relationship->selectAdd();
770 $relationship->selectAdd('contact_id_a, contact_id_b');
771 $relationship->find(TRUE);
773 return $relationship;
777 * Check if the relationship type selected between two contacts is correct.
779 * @param int $contact_a
781 * @param int $contact_b
783 * @param int $relationshipTypeId
784 * Relationship type id.
787 * true if it is valid relationship else false
789 public static function checkRelationshipType($contact_a, $contact_b, $relationshipTypeId) {
790 $relationshipType = new CRM_Contact_DAO_RelationshipType();
791 $relationshipType->id
= $relationshipTypeId;
792 $relationshipType->selectAdd();
793 $relationshipType->selectAdd('contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b');
794 if ($relationshipType->find(TRUE)) {
795 $contact_type_a = CRM_Contact_BAO_Contact
::getContactType($contact_a);
796 $contact_type_b = CRM_Contact_BAO_Contact
::getContactType($contact_b);
798 $contact_sub_type_a = CRM_Contact_BAO_Contact
::getContactSubType($contact_a);
799 $contact_sub_type_b = CRM_Contact_BAO_Contact
::getContactSubType($contact_b);
801 if (((!$relationshipType->contact_type_a
) ||
($relationshipType->contact_type_a
== $contact_type_a)) &&
802 ((!$relationshipType->contact_type_b
) ||
($relationshipType->contact_type_b
== $contact_type_b)) &&
803 ((!$relationshipType->contact_sub_type_a
) ||
(in_array($relationshipType->contact_sub_type_a
,
806 ((!$relationshipType->contact_sub_type_b
) ||
(in_array($relationshipType->contact_sub_type_b
,
820 * This function does the validtion for valid relationship.
822 * @param array $params
823 * This array contains the values there are subitted by the form.
825 * The array that holds all the db ids.
826 * @param int $contactId
827 * This is contact id for adding relationship.
831 public static function checkValidRelationship($params, $ids, $contactId) {
833 // function to check if the relationship selected is correct
834 // i.e. employer relationship can exit between Individual and Organization (not between Individual and Individual)
835 if (!CRM_Contact_BAO_Relationship
::checkRelationshipType($params['contact_id_a'], $params['contact_id_b'],
836 $params['relationship_type_id'])) {
837 $errors = 'Please select valid relationship between these two contacts.';
843 * This function checks for duplicate relationship.
845 * @param array $params
846 * (reference ) an assoc array of name/value pairs.
848 * This the id of the contact whom we are adding relationship.
849 * @param int $contactId
850 * This is contact id for adding relationship.
851 * @param int $relationshipId
852 * This is relationship id for the contact.
855 * true if record exists else false
857 public static function checkDuplicateRelationship(&$params, $id, $contactId = 0, $relationshipId = 0) {
858 $relationshipTypeId = CRM_Utils_Array
::value('relationship_type_id', $params);
859 list($type) = explode('_', $relationshipTypeId);
863 FROM civicrm_relationship
864 WHERE relationship_type_id = " . CRM_Utils_Type
::escape($type, 'Integer');
867 * CRM-11792 - date fields from API are in ISO format, but this function
868 * supports date arrays BAO has increasingly standardised to ISO format
869 * so I believe this function should support ISO rather than make API
870 * format it - however, need to support array format for now to avoid breakage
871 * @ time of writing this function is called from Relationship::legacyCreateMultiple (twice)
872 * CRM_BAO_Contact_Utils::clearCurrentEmployer (seemingly without dates)
873 * CRM_Contact_Form_Task_AddToOrganization::postProcess &
874 * CRM_Contact_Form_Task_AddToHousehold::postProcess
875 * (I don't think the last 2 support dates but not sure
878 $dateFields = array('end_date', 'start_date');
879 foreach ($dateFields as $dateField) {
880 if (array_key_exists($dateField, $params)) {
881 if (empty($params[$dateField]) ||
$params[$dateField] == 'null') {
882 //this is most likely coming from an api call & probably loaded
883 // from the DB to deal with some of the
884 // other myriad of excessive checks still in place both in
885 // the api & the create functions
886 $queryString .= " AND $dateField IS NULL";
889 elseif (is_array($params[$dateField])) {
890 $queryString .= " AND $dateField = " .
891 CRM_Utils_Type
::escape(CRM_Utils_Date
::format($params[$dateField]), 'Date');
894 $queryString .= " AND $dateField = " .
895 CRM_Utils_Type
::escape($params[$dateField], 'Date');
901 " AND ( ( contact_id_a = " . CRM_Utils_Type
::escape($id, 'Integer') .
902 " AND contact_id_b = " . CRM_Utils_Type
::escape($contactId, 'Integer') .
903 " ) OR ( contact_id_a = " . CRM_Utils_Type
::escape($contactId, 'Integer') .
904 " AND contact_id_b = " . CRM_Utils_Type
::escape($id, 'Integer') . " ) ) ";
906 //if caseId is provided, include it duplicate checking.
907 if ($caseId = CRM_Utils_Array
::value('case_id', $params)) {
908 $queryString .= " AND case_id = " . CRM_Utils_Type
::escape($caseId, 'Integer');
911 if ($relationshipId) {
912 $queryString .= " AND id !=" . CRM_Utils_Type
::escape($relationshipId, 'Integer');
915 $relationship = new CRM_Contact_BAO_Relationship();
916 $relationship->query($queryString);
917 $relationship->fetch();
918 $relationship->free();
919 return ($relationship->id
) ?
TRUE : FALSE;
923 * Update the is_active flag in the db.
926 * Id of the database record.
927 * @param bool $is_active
928 * Value we want to set the is_active field.
930 * @throws CiviCRM_API3_Exception
932 * DAO object on success, null otherwise
934 public static function setIsActive($id, $is_active) {
935 // as both the create & add functions have a bunch of logic in them that
936 // doesn't seem to cope with a normal update we will call the api which
937 // has tested handling for this
938 // however, a longer term solution would be to simplify the add, create & api functions
939 // to be more standard. It is debatable @ that point whether it's better to call the BAO
940 // direct as the api is more tested.
941 $result = civicrm_api('relationship', 'create', array(
943 'is_active' => $is_active,
947 if (is_array($result) && !empty($result['is_error']) && $result['error_message'] != 'Relationship already exists') {
948 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array
::value('error_code', $result, 'undefined'), $result);
955 * Fetch a relationship object and store the values in the values array.
957 * @param array $params
958 * Input parameters to find object.
959 * @param array $values
960 * Output values of the object.
963 * (reference) the values that could be potentially assigned to smarty
965 public static function &getValues(&$params, &$values) {
966 if (empty($params)) {
971 // get the specific number of relationship or all relationships.
972 if (!empty($params['numRelationship'])) {
973 $v['data'] = &CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'], NULL, $params['numRelationship']);
976 $v['data'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id']);
979 // get the total count of relationships
980 $v['totalCount'] = count($v['data']);
982 $values['relationship']['data'] = &$v['data'];
983 $values['relationship']['totalCount'] = &$v['totalCount'];
989 * Helper function to form the sql for relationship retrieval.
991 * @param int $contactId
994 * (check const at top of file).
995 * @param int $numRelationship
996 * No of relationships to display (limit).
998 * Get the no of relationships.
999 * $param int $relationshipId relationship id
1000 * @param int $relationshipId
1001 * @param string $direction
1002 * The direction we are interested in a_b or b_a.
1003 * @param array $params
1004 * Array of extra values including relationship_type_id per api spec.
1007 * [select, from, where]
1009 public static function makeURLClause($contactId, $status, $numRelationship, $count, $relationshipId, $direction, $params = array()) {
1010 $select = $from = $where = '';
1014 if ($direction == 'a_b') {
1015 $select .= ' SELECT count(DISTINCT civicrm_relationship.id) as cnt1, 0 as cnt2 ';
1018 $select .= ' SELECT 0 as cnt1, count(DISTINCT civicrm_relationship.id) as cnt2 ';
1022 $select .= ' SELECT civicrm_relationship.id as civicrm_relationship_id,
1023 civicrm_contact.sort_name as sort_name,
1024 civicrm_contact.display_name as display_name,
1025 civicrm_contact.job_title as job_title,
1026 civicrm_contact.employer_id as employer_id,
1027 civicrm_contact.organization_name as organization_name,
1028 civicrm_address.street_address as street_address,
1029 civicrm_address.city as city,
1030 civicrm_address.postal_code as postal_code,
1031 civicrm_state_province.abbreviation as state,
1032 civicrm_country.name as country,
1033 civicrm_email.email as email,
1034 civicrm_contact.contact_type as contact_type,
1035 civicrm_phone.phone as phone,
1036 civicrm_contact.id as civicrm_contact_id,
1037 civicrm_relationship.contact_id_b as contact_id_b,
1038 civicrm_relationship.contact_id_a as contact_id_a,
1039 civicrm_relationship_type.id as civicrm_relationship_type_id,
1040 civicrm_relationship.start_date as start_date,
1041 civicrm_relationship.end_date as end_date,
1042 civicrm_relationship.description as description,
1043 civicrm_relationship.is_active as is_active,
1044 civicrm_relationship.is_permission_a_b as is_permission_a_b,
1045 civicrm_relationship.is_permission_b_a as is_permission_b_a,
1046 civicrm_relationship.case_id as case_id';
1048 if ($direction == 'a_b') {
1049 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
1050 civicrm_relationship_type.label_b_a as relation ';
1053 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
1054 civicrm_relationship_type.label_a_b as relation ';
1059 FROM civicrm_relationship
1060 INNER JOIN civicrm_relationship_type ON ( civicrm_relationship.relationship_type_id = civicrm_relationship_type.id )
1061 INNER JOIN civicrm_contact ";
1062 if ($direction == 'a_b') {
1063 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_a ) ';
1066 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_b ) ';
1069 LEFT JOIN civicrm_address ON (civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1)
1070 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
1071 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id AND civicrm_email.is_primary = 1)
1072 LEFT JOIN civicrm_state_province ON (civicrm_address.state_province_id = civicrm_state_province.id)
1073 LEFT JOIN civicrm_country ON (civicrm_address.country_id = civicrm_country.id)
1075 $where = 'WHERE ( 1 )';
1077 if ($direction == 'a_b') {
1078 $where .= ' AND civicrm_relationship.contact_id_b = ' . CRM_Utils_Type
::escape($contactId, 'Positive');
1081 $where .= ' AND civicrm_relationship.contact_id_a = ' . CRM_Utils_Type
::escape($contactId, 'Positive') . '
1082 AND civicrm_relationship.contact_id_a != civicrm_relationship.contact_id_b ';
1085 if ($relationshipId) {
1086 $where .= ' AND civicrm_relationship.id = ' . CRM_Utils_Type
::escape($relationshipId, 'Positive');
1089 $date = date('Y-m-d');
1090 if ($status == self
::PAST
) {
1091 //this case for showing past relationship
1092 $where .= ' AND civicrm_relationship.is_active = 1 ';
1093 $where .= " AND civicrm_relationship.end_date < '" . $date . "'";
1095 elseif ($status == self
::DISABLED
) {
1096 // this case for showing disabled relationship
1097 $where .= ' AND civicrm_relationship.is_active = 0 ';
1099 elseif ($status == self
::CURRENT
) {
1100 //this case for showing current relationship
1101 $where .= ' AND civicrm_relationship.is_active = 1 ';
1102 $where .= " AND (civicrm_relationship.end_date >= '" . $date . "' OR civicrm_relationship.end_date IS NULL) ";
1104 elseif ($status == self
::INACTIVE
) {
1105 //this case for showing inactive relationships
1106 $where .= " AND (civicrm_relationship.end_date < '" . $date . "'";
1107 $where .= ' OR civicrm_relationship.is_active = 0 )';
1111 $where .= ' AND civicrm_contact.is_deleted = 0';
1112 if (!empty($params['membership_type_id']) && empty($params['relationship_type_id'])) {
1113 $where .= self
::membershipTypeToRelationshipTypes($params, $direction);
1115 if (!empty($params['relationship_type_id'])) {
1116 if (is_array($params['relationship_type_id'])) {
1117 $where .= " AND " . CRM_Core_DAO
::createSQLFilter('relationship_type_id', $params['relationship_type_id'], 'Integer');
1120 $where .= ' AND relationship_type_id = ' . CRM_Utils_Type
::escape($params['relationship_type_id'], 'Positive');
1123 if ($direction == 'a_b') {
1124 $where .= ' ) UNION ';
1130 return array($select, $from, $where);
1134 * Get a list of relationships.
1136 * @param int $contactId
1138 * @param int $status
1139 * 1: Past 2: Disabled 3: Current.
1140 * @param int $numRelationship
1141 * No of relationships to display (limit).
1143 * Get the no of relationships.
1144 * @param int $relationshipId
1145 * @param array $links
1146 * the list of links to display
1147 * @param int $permissionMask
1148 * the permission mask to be applied for the actions
1149 * @param bool $permissionedContact
1150 * to return only permissioned Contact
1151 * @param array $params
1154 * relationship records
1156 public static function getRelationship(
1158 $status = 0, $numRelationship = 0,
1159 $count = 0, $relationshipId = 0,
1160 $links = NULL, $permissionMask = NULL,
1161 $permissionedContact = FALSE,
1165 if (!$contactId && !$relationshipId) {
1169 list($select1, $from1, $where1) = self
::makeURLClause($contactId, $status, $numRelationship,
1170 $count, $relationshipId, 'a_b', $params
1172 list($select2, $from2, $where2) = self
::makeURLClause($contactId, $status, $numRelationship,
1173 $count, $relationshipId, 'b_a', $params
1176 $order = $limit = '';
1178 if (empty($params['sort'])) {
1179 $order = ' ORDER BY civicrm_relationship_type_id, sort_name ';
1182 $order = " ORDER BY {$params['sort']} ";
1186 if (!empty($params['offset']) && $params['offset'] > 0) {
1187 $offset = $params['offset'];
1190 if ($numRelationship) {
1191 $limit = " LIMIT {$offset}, $numRelationship";
1195 // building the query string
1196 $queryString = $select1 . $from1 . $where1 . $select2 . $from2 . $where2 . $order . $limit;
1198 $relationship = new CRM_Contact_DAO_Relationship();
1200 $relationship->query($queryString);
1203 $relationshipCount = 0;
1204 while ($relationship->fetch()) {
1205 $relationshipCount +
= $relationship->cnt1 +
$relationship->cnt2
;
1207 return $relationshipCount;
1212 if ($status != self
::INACTIVE
) {
1214 $mask = array_sum(array_keys($links));
1215 if ($mask & CRM_Core_Action
::DISABLE
) {
1216 $mask -= CRM_Core_Action
::DISABLE
;
1218 if ($mask & CRM_Core_Action
::ENABLE
) {
1219 $mask -= CRM_Core_Action
::ENABLE
;
1222 if ($status == self
::CURRENT
) {
1223 $mask |
= CRM_Core_Action
::DISABLE
;
1225 elseif ($status == self
::DISABLED
) {
1226 $mask |
= CRM_Core_Action
::ENABLE
;
1228 $mask = $mask & $permissionMask;
1232 while ($relationship->fetch()) {
1233 $rid = $relationship->civicrm_relationship_id
;
1234 $cid = $relationship->civicrm_contact_id
;
1235 if (($permissionedContact &&
1236 (!CRM_Contact_BAO_Contact_Permission
::relationship($cid, $contactId))
1238 (!CRM_Contact_BAO_Contact_Permission
::allow($cid))
1242 $values[$rid]['id'] = $rid;
1243 $values[$rid]['cid'] = $cid;
1244 $values[$rid]['contact_id_a'] = $relationship->contact_id_a
;
1245 $values[$rid]['contact_id_b'] = $relationship->contact_id_b
;
1246 $values[$rid]['contact_type'] = $relationship->contact_type
;
1247 $values[$rid]['relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1248 $values[$rid]['relation'] = $relationship->relation
;
1249 $values[$rid]['name'] = $relationship->sort_name
;
1250 $values[$rid]['display_name'] = $relationship->display_name
;
1251 $values[$rid]['job_title'] = $relationship->job_title
;
1252 $values[$rid]['email'] = $relationship->email
;
1253 $values[$rid]['phone'] = $relationship->phone
;
1254 $values[$rid]['employer_id'] = $relationship->employer_id
;
1255 $values[$rid]['organization_name'] = $relationship->organization_name
;
1256 $values[$rid]['country'] = $relationship->country
;
1257 $values[$rid]['city'] = $relationship->city
;
1258 $values[$rid]['state'] = $relationship->state
;
1259 $values[$rid]['start_date'] = $relationship->start_date
;
1260 $values[$rid]['end_date'] = $relationship->end_date
;
1261 $values[$rid]['description'] = $relationship->description
;
1262 $values[$rid]['is_active'] = $relationship->is_active
;
1263 $values[$rid]['is_permission_a_b'] = $relationship->is_permission_a_b
;
1264 $values[$rid]['is_permission_b_a'] = $relationship->is_permission_b_a
;
1265 $values[$rid]['case_id'] = $relationship->case_id
;
1268 $values[$rid]['status'] = $status;
1271 $values[$rid]['civicrm_relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1273 if ($relationship->contact_id_a
== $contactId) {
1274 $values[$rid]['rtype'] = 'a_b';
1277 $values[$rid]['rtype'] = 'b_a';
1283 'rtype' => $values[$rid]['rtype'],
1284 'cid' => $contactId,
1285 'cbid' => $values[$rid]['cid'],
1286 'caseid' => $values[$rid]['case_id'],
1287 'clientid' => $contactId,
1290 if ($status == self
::INACTIVE
) {
1291 // setting links for inactive relationships
1292 $mask = array_sum(array_keys($links));
1293 if (!$values[$rid]['is_active']) {
1294 $mask -= CRM_Core_Action
::DISABLE
;
1297 $mask -= CRM_Core_Action
::ENABLE
;
1298 $mask -= CRM_Core_Action
::DISABLE
;
1300 $mask = $mask & $permissionMask;
1303 // Give access to manage case link by copying to MAX_ACTION index temporarily, depending on case permission of user.
1304 if ($values[$rid]['case_id']) {
1305 // Borrowed logic from CRM_Case_Page_Tab
1306 $hasCaseAccess = FALSE;
1307 if (CRM_Core_Permission
::check('access all cases and activities')) {
1308 $hasCaseAccess = TRUE;
1311 $userCases = CRM_Case_BAO_Case
::getCases(FALSE);
1312 if (array_key_exists($values[$rid]['case_id'], $userCases)) {
1313 $hasCaseAccess = TRUE;
1317 if ($hasCaseAccess) {
1318 // give access by copying to MAX_ACTION temporarily, otherwise leave at NONE which won't display
1319 $links[CRM_Core_Action
::MAX_ACTION
] = $links[CRM_Core_Action
::NONE
];
1320 $links[CRM_Core_Action
::MAX_ACTION
]['name'] = ts('Manage Case #%1', array(1 => $values[$rid]['case_id']));
1321 $links[CRM_Core_Action
::MAX_ACTION
]['class'] = 'no-popup';
1323 // Also make sure we have the right client cid since can get here from multiple relationship tabs.
1324 if ($values[$rid]['rtype'] == 'b_a') {
1325 $replace['clientid'] = $values[$rid]['cid'];
1330 $values[$rid]['action'] = CRM_Core_Action
::formLink(
1336 'relationship.selector.row',
1339 unset($links[CRM_Core_Action
::MAX_ACTION
]);
1343 $relationship->free();
1349 * Get get list of relationship type based on the target contact type.
1351 * @param string $targetContactType
1352 * It's valid contact tpye(may be Individual , Organization , Household).
1355 * array reference of all relationship types with context to current contact type .
1357 static public function getRelationType($targetContactType) {
1358 $relationshipType = array();
1359 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType();
1361 foreach ($allRelationshipType as $key => $type) {
1362 if ($type['contact_type_b'] == $targetContactType) {
1363 $relationshipType[$key . '_a_b'] = $type['label_a_b'];
1367 return $relationshipType;
1371 * Create / update / delete membership for related contacts.
1373 * This function will create/update/delete membership for related
1374 * contact based on 1) contact have active membership 2) that
1375 * membership is is extedned by the same relationship type to that
1376 * of the existing relationship.
1378 * @param int $contactId
1380 * @param array $params
1381 * array of values submitted by POST.
1384 * @param \const|int $action which action called this function
1386 * @param bool $active
1388 * @throws \CRM_Core_Exception
1390 public static function relatedMemberships($contactId, &$params, $ids, $action = CRM_Core_Action
::ADD
, $active = TRUE) {
1391 // Check the end date and set the status of the relationship
1393 $status = self
::CURRENT
;
1394 $targetContact = $targetContact = CRM_Utils_Array
::value('contact_check', $params, array());
1396 if (!empty($params['end_date'])) {
1397 $endDate = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Date
::format($params['end_date']), NULL, 'Ymd');
1398 $today = date('Ymd');
1400 if ($today > $endDate) {
1401 $status = self
::PAST
;
1405 if (($action & CRM_Core_Action
::ADD
) &&
1406 ($status & self
::PAST
)
1408 // if relationship is PAST and action is ADD, no qustion
1409 // of creating RELATED membership and return back to
1414 $rel = explode('_', $params['relationship_type_id']);
1416 $relTypeId = $rel[0];
1417 if (!empty($rel[1])) {
1418 $relDirection = "_{$rel[1]}_{$rel[2]}";
1421 // this call is coming from somewhere where the direction was resolved early on (e.g an api call)
1422 // so we can assume _a_b
1423 $relDirection = "_a_b";
1424 $targetContact = array($params['contact_id_b'] => 1);
1427 if (($action & CRM_Core_Action
::ADD
) ||
1428 ($action & CRM_Core_Action
::DELETE
)
1430 $contact = $contactId;
1432 elseif ($action & CRM_Core_Action
::UPDATE
) {
1433 $contact = $ids['contact'];
1434 $targetContact = array($ids['contactTarget'] => 1);
1437 // Build the 'values' array for
1440 // This will allow us to check if either of the contacts in
1441 // relationship have active memberships.
1446 $values[$contact] = array(
1447 'relatedContacts' => $targetContact,
1448 'relationshipTypeId' => $relTypeId,
1449 'relationshipTypeDirection' => $relDirection,
1452 if (!empty($targetContact)) {
1453 foreach ($targetContact as $cid => $donCare) {
1454 $values[$cid] = array(
1455 'relatedContacts' => array($contact => 1),
1456 'relationshipTypeId' => $relTypeId,
1459 $relTypeParams = array('id' => $relTypeId);
1460 $relTypeValues = array();
1461 CRM_Contact_BAO_RelationshipType
::retrieve($relTypeParams, $relTypeValues);
1463 if (CRM_Utils_Array
::value('name_a_b', $relTypeValues) == CRM_Utils_Array
::value('name_b_a', $relTypeValues)) {
1464 $values[$cid]['relationshipTypeDirection'] = '_a_b';
1467 $values[$cid]['relationshipTypeDirection'] = ($relDirection == '_a_b') ?
'_b_a' : '_a_b';
1472 // CRM-15829 UPDATES
1473 // If we're looking for active memberships we must consider pending (id: 5) ones too.
1474 // Hence we can't just call CRM_Member_BAO_Membership::getValues below with the active flag, is it would completely miss pending relatioships.
1475 // As suggested by @davecivicrm, the pending status id is fetched using the CRM_Member_PseudoConstant::membershipStatus() class and method, since these ids differ from system to system.
1476 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
1478 $query = 'SELECT * FROM `civicrm_membership_status`';
1480 $query .= 'WHERE `is_current_member` = 1 OR `id` = %1 ';
1483 $params[1] = array($pendingStatusId, 'String');
1484 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1486 while ($dao->fetch()) {
1487 $membershipStatusRecordIds[$dao->id
] = $dao->id
;
1490 // Now get the active memberships for all the contacts.
1491 // If contact have any valid membership(s), then add it to
1493 foreach ($values as $cid => $subValues) {
1494 $memParams = array('contact_id' => $cid);
1495 $memberships = array();
1497 // CRM-15829 UPDATES
1498 // Since we want PENDING memberships as well, the $active flag needs to be set to false so that this will return all memberships and we can then filter the memberships based on the status IDs recieved above.
1499 CRM_Member_BAO_Membership
::getValues($memParams, $memberships, FALSE, TRUE);
1501 // CRM-15829 UPDATES
1502 // filter out the memberships returned by CRM_Member_BAO_Membership::getValues based on the status IDs fetched on line ~1462
1503 foreach ($memberships as $key => $membership) {
1505 if (!isset($memberships[$key]['status_id'])) {
1509 $membershipStatusId = $memberships[$key]['status_id'];
1510 if (!isset($membershipStatusRecordIds[$membershipStatusId])) {
1511 unset($memberships[$key]);
1515 if (empty($memberships)) {
1519 //get ownerMembershipIds for related Membership
1520 //this is to handle memberships being deleted and recreated
1521 if (!empty($memberships['owner_membership_ids'])) {
1522 $ownerMemIds[$cid] = $memberships['owner_membership_ids'];
1523 unset($memberships['owner_membership_ids']);
1526 $values[$cid]['memberships'] = $memberships;
1528 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1530 // done with 'values' array.
1531 // Finally add / edit / delete memberships for the related contacts
1533 foreach ($values as $cid => $details) {
1534 if (!array_key_exists('memberships', $details)) {
1538 $relatedContacts = array_keys(CRM_Utils_Array
::value('relatedContacts', $details, array()));
1539 $mainRelatedContactId = reset($relatedContacts);
1541 foreach ($details['memberships'] as $membershipId => $membershipValues) {
1542 $relTypeIds = array();
1543 if ($action & CRM_Core_Action
::DELETE
) {
1544 // Delete memberships of the related contacts only if relationship type exists for membership type
1546 SELECT relationship_type_id, relationship_direction
1547 FROM civicrm_membership_type
1548 WHERE id = {$membershipValues['membership_type_id']}";
1549 $dao = CRM_Core_DAO
::executeQuery($query);
1550 $relTypeDirs = array();
1551 while ($dao->fetch()) {
1552 $relTypeId = $dao->relationship_type_id
;
1553 $relDirection = $dao->relationship_direction
;
1555 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $relTypeId);
1556 if (in_array($values[$cid]['relationshipTypeId'], $relTypeIds
1557 //CRM-16300 check if owner membership exist for related membership
1558 ) && !empty($membershipValues['owner_membership_id']) && !empty($values[$mainRelatedContactId]['memberships'][$membershipValues['owner_membership_id']])) {
1559 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipValues['owner_membership_id'], $membershipValues['membership_contact_id']);
1563 if (($action & CRM_Core_Action
::UPDATE
) &&
1564 ($status & self
::PAST
) &&
1565 ($membershipValues['owner_membership_id'])
1567 // If relationship is PAST and action is UPDATE
1568 // then delete the RELATED membership
1569 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipValues['owner_membership_id'],
1570 $membershipValues['membership_contact_id']
1575 // add / edit the memberships for related
1578 // Get the Membership Type Details.
1579 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipValues['membership_type_id']);
1580 // Check if contact's relationship type exists in membership type
1581 $relTypeDirs = array();
1582 if (!empty($membershipType['relationship_type_id'])) {
1583 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_type_id']);
1585 if (!empty($membershipType['relationship_direction'])) {
1586 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_direction']);
1588 foreach ($relTypeIds as $key => $value) {
1589 $relTypeDirs[] = $value . '_' . $relDirections[$key];
1591 $relTypeDir = $details['relationshipTypeId'] . $details['relationshipTypeDirection'];
1592 if (in_array($relTypeDir, $relTypeDirs)) {
1593 // Check if relationship being created/updated is
1594 // similar to that of membership type's
1597 $membershipValues['owner_membership_id'] = $membershipId;
1598 unset($membershipValues['id']);
1599 unset($membershipValues['membership_contact_id']);
1600 unset($membershipValues['contact_id']);
1601 unset($membershipValues['membership_id']);
1602 foreach ($details['relatedContacts'] as $relatedContactId => $donCare) {
1603 $membershipValues['contact_id'] = $relatedContactId;
1604 if ($deceasedStatusId &&
1605 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $relatedContactId, 'is_deceased')
1607 $membershipValues['status_id'] = $deceasedStatusId;
1608 $membershipValues['skipStatusCal'] = TRUE;
1615 if (!empty($membershipValues[$dateField])) {
1616 $membershipValues[$dateField] = CRM_Utils_Date
::processDate($membershipValues[$dateField]);
1620 if ($action & CRM_Core_Action
::UPDATE
) {
1621 //if updated relationship is already related to contact don't delete existing inherited membership
1622 if (in_array($relTypeId, $relTypeIds
1623 ) && !empty($values[$relatedContactId]['memberships']) && !empty($ownerMemIds
1624 ) && in_array($membershipValues['owner_membership_id'], $ownerMemIds[$relatedContactId])) {
1628 //delete the membership record for related
1629 //contact before creating new membership record.
1630 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $relatedContactId);
1633 // check whether we have some related memberships still available
1636 FROM civicrm_membership
1637 LEFT JOIN civicrm_membership_status ON (civicrm_membership_status.id = civicrm_membership.status_id)
1638 WHERE membership_type_id = {$membershipValues['membership_type_id']} AND owner_membership_id = {$membershipValues['owner_membership_id']}
1639 AND is_current_member = 1";
1640 $result = CRM_Core_DAO
::singleValueQuery($query);
1641 if ($result < CRM_Utils_Array
::value('max_related', $membershipValues, PHP_INT_MAX
)) {
1642 CRM_Member_BAO_Membership
::create($membershipValues, CRM_Core_DAO
::$_nullArray);
1646 elseif ($action & CRM_Core_Action
::UPDATE
) {
1647 // if action is update and updated relationship do
1648 // not match with the existing
1649 // membership=>relationship then we need to
1650 // delete the membership record created for
1651 // previous relationship.
1652 // CRM-16087 we need to pass ownerMembershipId to deleteRelatedMemberships function
1653 if (empty($params['relationship_ids']) && !empty($params['id'])) {
1654 $relIds = array($params['id']);
1657 $relIds = CRM_Utils_Array
::value('relationship_ids', $params);
1659 if (self
::isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId,
1660 $relIds) && !empty($membershipValues['owner_membership_id']
1661 ) && !empty($values[$mainRelatedContactId]['memberships'][$membershipValues['owner_membership_id']])) {
1662 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipValues['owner_membership_id'], $membershipValues['membership_contact_id']);
1670 * Helper function to check whether to delete the membership or not.
1672 * Function takes a list of related membership types and if it is not also passed a
1673 * relationship ID of that types evaluates whether the membership should be deleted.
1675 * @param array $membershipTypeRelationshipTypeIDs
1676 * Relation type IDs related to the given membership type.
1677 * @param int $contactId
1678 * @param int $mainRelatedContactId
1679 * @param int $relTypeId
1680 * @param array $relIds
1684 public static function isDeleteRelatedMembership($membershipTypeRelationshipTypeIDs, $contactId, $mainRelatedContactId, $relTypeId, $relIds) {
1685 if (empty($membershipTypeRelationshipTypeIDs) ||
in_array($relTypeId, $membershipTypeRelationshipTypeIDs)) {
1689 if (empty($relIds)) {
1693 $relParamas = array(
1694 1 => array($contactId, 'Integer'),
1695 2 => array($mainRelatedContactId, 'Integer'),
1698 if ($contactId == $mainRelatedContactId) {
1699 $recordsFound = (int) CRM_Core_DAO
::singleValueQuery("SELECT COUNT(*) FROM civicrm_relationship WHERE relationship_type_id IN ( " . implode(',', $membershipTypeRelationshipTypeIDs) . " ) AND
1700 contact_id_a IN ( %1 ) OR contact_id_b IN ( %1 ) AND id IN (" . implode(',', $relIds) . ")", $relParamas);
1701 if ($recordsFound) {
1707 $recordsFound = (int) CRM_Core_DAO
::singleValueQuery("SELECT COUNT(*) FROM civicrm_relationship WHERE relationship_type_id IN ( " . implode(',', $membershipTypeRelationshipTypeIDs) . " ) AND contact_id_a IN ( %1, %2 ) AND contact_id_b IN ( %1, %2 ) AND id NOT IN (" . implode(',', $relIds) . ")", $relParamas);
1709 if ($recordsFound) {
1717 * Get Current Employer for Contact.
1719 * @param $contactIds
1723 * array of the current employer
1725 public static function getCurrentEmployer($contactIds) {
1726 $contacts = implode(',', $contactIds);
1729 SELECT organization_name, id, employer_id
1730 FROM civicrm_contact
1731 WHERE id IN ( {$contacts} )
1734 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1735 $currentEmployer = array();
1736 while ($dao->fetch()) {
1737 $currentEmployer[$dao->id
]['org_id'] = $dao->employer_id
;
1738 $currentEmployer[$dao->id
]['org_name'] = $dao->organization_name
;
1741 return $currentEmployer;
1745 * Return list of permissioned employer for a given contact.
1747 * @param int $contactID
1748 * contact id whose employers.
1750 * @param string $name
1751 * employers sort name.
1754 * array of employers.
1756 public static function getPermissionedEmployer($contactID, $name = NULL) {
1757 //get the relationship id
1758 $relTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType',
1759 'Employee of', 'id', 'name_a_b'
1762 return self
::getPermissionedContacts($contactID, $relTypeId, $name);
1767 * Function to return list of permissioned contacts for a given contact and relationship type.
1769 * @param int $contactID
1770 * contact id whose permissioned contacts are to be found.
1771 * @param string $relTypeId
1772 * one or more relationship type id's.
1773 * @param string $name
1778 public static function getPermissionedContacts($contactID, $relTypeId, $name = NULL) {
1779 $contacts = array();
1783 SELECT cc.id as id, cc.sort_name as name
1784 FROM civicrm_relationship cr, civicrm_contact cc
1786 cr.contact_id_a = %1 AND
1787 cr.relationship_type_id IN (%2) AND
1788 cr.is_permission_a_b = 1 AND
1789 IF(cr.end_date IS NULL, 1, (DATEDIFF( CURDATE( ), cr.end_date ) <= 0)) AND
1790 cr.is_active = 1 AND
1791 cc.id = cr.contact_id_b AND
1794 if (!empty($name)) {
1795 $name = CRM_Utils_Type
::escape($name, 'String');
1797 AND cc.sort_name LIKE '%$name%'";
1800 $args = array(1 => array($contactID, 'Integer'), 2 => array($relTypeId, 'String'));
1801 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1803 while ($dao->fetch()) {
1804 $contacts[$dao->id
] = array(
1805 'name' => $dao->name
,
1806 'value' => $dao->id
,
1814 * Merge relationships from otherContact to mainContact.
1816 * Called during contact merge operation
1818 * @param int $mainId
1819 * Contact id of main contact record.
1820 * @param int $otherId
1821 * Contact id of record which is going to merge.
1822 * @param array $sqls
1823 * (reference) array of sql statements to append to.
1825 * @see CRM_Dedupe_Merger::cpTables()
1827 public static function mergeRelationships($mainId, $otherId, &$sqls) {
1828 // Delete circular relationships
1829 $sqls[] = "DELETE FROM civicrm_relationship
1830 WHERE (contact_id_a = $mainId AND contact_id_b = $otherId)
1831 OR (contact_id_b = $mainId AND contact_id_a = $otherId)";
1833 // Delete relationship from other contact if main contact already has that relationship
1834 $sqls[] = "DELETE r2
1835 FROM civicrm_relationship r1, civicrm_relationship r2
1836 WHERE r1.relationship_type_id = r2.relationship_type_id
1839 r1.contact_id_a = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_b = r2.contact_id_b
1840 OR r1.contact_id_b = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_a = r2.contact_id_a
1842 (r1.contact_id_a = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_b = r2.contact_id_a
1843 OR r1.contact_id_b = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_a = r2.contact_id_b)
1844 AND r1.relationship_type_id IN (SELECT id FROM civicrm_relationship_type WHERE name_b_a = name_a_b)
1848 // Move relationships
1849 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_a = $mainId WHERE contact_id_a = $otherId";
1850 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_b = $mainId WHERE contact_id_b = $otherId";
1852 // Move current employer id (name will get updated later)
1853 $sqls[] = "UPDATE civicrm_contact SET employer_id = $mainId WHERE employer_id = $otherId";
1857 * Set 'is_valid' field to false for all relationships whose end date is in the past, ie. are expired.
1860 * True on success, false if error is encountered.
1862 public static function disableExpiredRelationships() {
1863 $query = "SELECT id FROM civicrm_relationship WHERE is_active = 1 AND end_date < CURDATE()";
1865 $dao = CRM_Core_DAO
::executeQuery($query);
1866 while ($dao->fetch()) {
1867 $result = CRM_Contact_BAO_Relationship
::setIsActive($dao->id
, FALSE);
1868 // Result will be NULL if error occurred. We abort early if error detected.
1869 if ($result == NULL) {
1877 * Function filters the query by possible relationships for the membership type.
1879 * It is intended to be called when constructing queries for the api (reciprocal & non-reciprocal)
1880 * and to add clauses to limit the return to those relationships which COULD inherit a membership type
1881 * (as opposed to those who inherit a particular membership
1883 * @param array $params
1885 * @param null $direction
1887 * @return array|void
1889 public static function membershipTypeToRelationshipTypes(&$params, $direction = NULL) {
1890 $membershipType = civicrm_api3('membership_type', 'getsingle', array(
1891 'id' => $params['membership_type_id'],
1892 'return' => 'relationship_type_id, relationship_direction',
1894 $relationshipTypes = $membershipType['relationship_type_id'];
1895 if (empty($relationshipTypes)) {
1898 // if we don't have any contact data we can only filter on type
1899 if (empty($params['contact_id']) && empty($params['contact_id_a']) && empty($params['contact_id_a'])) {
1900 $params['relationship_type_id'] = array('IN' => $relationshipTypes);
1904 $relationshipDirections = (array) $membershipType['relationship_direction'];
1905 // if we have contact_id_a OR contact_id_b we can make a call here
1906 // if we have contact??
1907 foreach ($relationshipDirections as $index => $mtdirection) {
1908 if (isset($params['contact_id_a']) && $mtdirection == 'a_b' ||
$direction == 'a_b') {
1909 $types[] = $relationshipTypes[$index];
1911 if (isset($params['contact_id_b']) && $mtdirection == 'b_a' ||
$direction == 'b_a') {
1912 $types[] = $relationshipTypes[$index];
1915 if (!empty($types)) {
1916 $params['relationship_type_id'] = array('IN' => $types);
1918 elseif (!empty($clauses)) {
1919 return explode(' OR ', $clauses);
1922 // effectively setting it to return no results
1923 $params['relationship_type_id'] = 0;
1930 * Wrapper for contact relationship selector.
1932 * @param array $params
1933 * Associated array for params record id.
1936 * associated array of contact relationships
1938 public static function getContactRelationshipSelector(&$params) {
1939 // format the params
1940 $params['offset'] = ($params['page'] - 1) * $params['rp'];
1941 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
1943 if ($params['context'] == 'past') {
1944 $relationshipStatus = CRM_Contact_BAO_Relationship
::INACTIVE
;
1946 elseif ($params['context'] == 'all') {
1947 $relationshipStatus = CRM_Contact_BAO_Relationship
::ALL
;
1950 $relationshipStatus = CRM_Contact_BAO_Relationship
::CURRENT
;
1953 // check logged in user for permission
1954 $page = new CRM_Core_Page();
1955 CRM_Contact_Page_View
::checkUserPermission($page, $params['contact_id']);
1956 $permissions = array($page->_permission
);
1957 if ($page->_permission
== CRM_Core_Permission
::EDIT
) {
1958 $permissions[] = CRM_Core_Permission
::DELETE
;
1960 $mask = CRM_Core_Action
::mask($permissions);
1962 if ($params['context'] != 'user') {
1963 $links = CRM_Contact_Page_View_Relationship
::links();
1964 $permissionedContacts = FALSE;
1967 $links = CRM_Contact_Page_View_UserDashBoard
::links();
1968 $permissionedContacts = TRUE;
1971 // get contact relationships
1972 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1973 $relationshipStatus,
1974 $params['rp'], 0, 0,
1976 $permissionedContacts,
1980 $contactRelationships = array();
1981 $params['total'] = 0;
1982 if (!empty($relationships)) {
1983 // FIXME: we cannot directly determine total permissioned relationship, hence re-fire query
1984 $params['total'] = $permissionedRelationships = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1985 $relationshipStatus,
1988 $permissionedContacts
1992 foreach ($relationships as $relationshipId => $values) {
1993 $relationship = array();
1995 $relationship['DT_RowClass'] = 'crm-entity';
1996 if ($values['is_active'] == 0) {
1997 $relationship['DT_RowClass'] .= ' disabled';
2000 $relationship['DT_RowData'] = array();
2001 $relationship['DT_RowData']['entity'] = 'relationship';
2002 $relationship['DT_RowData']['id'] = $values['id'];
2004 //Add image icon for related contacts: CRM-14919
2005 $icon = CRM_Contact_BAO_Contact_Utils
::getImage($values['contact_type'],
2009 $relationship['sort_name'] = $icon . ' ' . CRM_Utils_System
::href(
2011 'civicrm/contact/view',
2012 "reset=1&cid={$values['cid']}");
2014 $relationship['relation'] = CRM_Utils_System
::href(
2015 $values['relation'],
2016 'civicrm/contact/view/rel',
2017 "action=view&reset=1&cid={$values['cid']}&id={$values['id']}&rtype={$values['rtype']}");
2019 if ($params['context'] == 'current') {
2020 if (($params['contact_id'] == $values['contact_id_a'] AND $values['is_permission_a_b'] == 1) OR
2021 ($params['contact_id'] == $values['contact_id_b'] AND $values['is_permission_b_a'] == 1)
2023 $relationship['sort_name'] .= '<span id="permission-a-b" class="crm-marker permission-relationship"> *</span>';
2026 if (($values['cid'] == $values['contact_id_a'] AND $values['is_permission_a_b'] == 1) OR
2027 ($values['cid'] == $values['contact_id_b'] AND $values['is_permission_b_a'] == 1)
2029 $relationship['relation'] .= '<span id="permission-b-a" class="crm-marker permission-relationship"> *</span>';
2033 if (!empty($values['description'])) {
2034 $relationship['relation'] .= "<p class='description'>{$values['description']}</p>";
2037 $relationship['start_date'] = CRM_Utils_Date
::customFormat($values['start_date']);
2038 $relationship['end_date'] = CRM_Utils_Date
::customFormat($values['end_date']);
2039 $relationship['city'] = $values['city'];
2040 $relationship['state'] = $values['state'];
2041 $relationship['email'] = $values['email'];
2042 $relationship['phone'] = $values['phone'];
2043 $relationship['links'] = $values['action'];
2045 array_push($contactRelationships, $relationship);
2049 $relationshipsDT = array();
2050 $relationshipsDT['data'] = $contactRelationships;
2051 $relationshipsDT['recordsTotal'] = $params['total'];
2052 $relationshipsDT['recordsFiltered'] = $params['total'];
2054 return $relationshipsDT;