3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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 * Constants for is_permission fields.
42 * Note: the slightly non-obvious ordering is due to history...
44 const NONE
= 0, EDIT
= 1, VIEW
= 2;
47 * Create function - use the API instead.
49 * Note that the previous create function has been renamed 'legacyCreateMultiple'
50 * and this is new in 4.6
51 * All existing calls have been changed to legacyCreateMultiple except the api call - however, it is recommended
52 * that you call that as the end to end testing here is based on the api & refactoring may still be done.
54 * @param array $params
56 * @return \CRM_Contact_BAO_Relationship
57 * @throws \CRM_Core_Exception
59 public static function create(&$params) {
61 $extendedParams = self
::loadExistingRelationshipDetails($params);
62 // When id is specified we always wan't to update, so we don't need to
63 // check for duplicate relations.
64 if (!isset($params['id']) && self
::checkDuplicateRelationship($extendedParams, $extendedParams['contact_id_a'], $extendedParams['contact_id_b'], CRM_Utils_Array
::value('id', $extendedParams, 0))) {
65 throw new CRM_Core_Exception('Duplicate Relationship');
67 $params = $extendedParams;
68 if (self
::checkValidRelationship($params, $params, 0)) {
69 throw new CRM_Core_Exception('Invalid Relationship');
71 $relationship = self
::add($params);
72 if (!empty($params['contact_id_a'])) {
74 'contactTarget' => $relationship->contact_id_b
,
75 'contact' => $params['contact_id_a'],
78 //CRM-16087 removed additional call to function relatedMemberships which is already called by disableEnableRelationship
79 //resulting in membership being created twice
80 if (array_key_exists('is_active', $params) && empty($params['is_active'])) {
81 $action = CRM_Core_Action
::DISABLE
;
85 $action = CRM_Core_Action
::ENABLE
;
88 $id = empty($params['id']) ?
$relationship->id
: $params['id'];
89 self
::disableEnableRelationship($id, $action, $params, $ids, $active);
92 if (empty($params['skipRecentView'])) {
93 self
::addRecent($params, $relationship);
100 * Create multiple relationships for one contact.
102 * The relationship details are the same for each relationship except the secondary contact
103 * id can be an array.
105 * @param array $params
106 * Parameters for creating multiple relationships.
107 * The parameters are the same as for relationship create function except that the non-primary
108 * end of the relationship should be an array of one or more contact IDs.
109 * @param string $primaryContactLetter
110 * a or b to denote the primary contact for this action. The secondary may be multiple contacts
111 * and should be an array.
114 * @throws \CRM_Core_Exception
116 public static function createMultiple($params, $primaryContactLetter) {
117 $secondaryContactLetter = ($primaryContactLetter == 'a') ?
'b' : 'a';
118 $secondaryContactIDs = $params['contact_id_' . $secondaryContactLetter];
119 $valid = $invalid = $duplicate = $saved = 0;
120 $relationshipIDs = array();
121 foreach ($secondaryContactIDs as $secondaryContactID) {
123 $params['contact_id_' . $secondaryContactLetter] = $secondaryContactID;
124 $relationship = civicrm_api3('relationship', 'create', $params);
125 $relationshipIDs[] = $relationship['id'];
128 catch (CiviCRM_API3_Exception
$e) {
129 switch ($e->getMessage()) {
130 case 'Duplicate Relationship':
134 case 'Invalid Relationship':
139 throw new CRM_Core_Exception('unknown relationship create error ' . $e->getMessage());
146 'invalid' => $invalid,
147 'duplicate' => $duplicate,
149 'relationship_ids' => $relationshipIDs,
154 * Takes an associative array and creates a relationship object.
155 * @deprecated For single creates use the api instead (it's tested).
156 * For multiple a new variant of this function needs to be written and migrated to as this is a bit
159 * @param array $params
160 * (reference ) an assoc array of name/value pairs.
162 * The array that holds all the db ids.
163 * per http://wiki.civicrm.org/confluence/display/CRM/Database+layer
164 * "we are moving away from the $ids param "
166 * @return CRM_Contact_BAO_Relationship
168 public static function legacyCreateMultiple(&$params, $ids = array()) {
169 $valid = $invalid = $duplicate = $saved = 0;
170 $relationships = $relationshipIds = array();
171 $relationshipId = CRM_Utils_Array
::value('relationship', $ids, CRM_Utils_Array
::value('id', $params));
173 //CRM-9015 - the hooks are called here & in add (since add doesn't call create)
174 // but in future should be tidied per ticket
175 if (empty($relationshipId)) {
182 CRM_Utils_Hook
::pre($hook, 'Relationship', $relationshipId, $params);
184 if (!$relationshipId) {
185 // creating a new relationship
186 $dataExists = self
::dataExists($params);
188 return array(FALSE, TRUE, FALSE, FALSE, NULL);
190 $relationshipIds = array();
191 foreach ($params['contact_check'] as $key => $value) {
192 // check if the relationship is valid between contacts.
193 // step 1: check if the relationship is valid if not valid skip and keep the count
194 // step 2: check the if two contacts already have a relationship if yes skip and keep the count
195 // step 3: if valid relationship then add the relation and keep the count
198 $contactFields = self
::setContactABFromIDs($params, $ids, $key);
199 $errors = self
::checkValidRelationship($contactFields, $ids, $key);
205 //CRM-16978:check duplicate relationship as per case id.
206 if ($caseId = CRM_Utils_Array
::value('case_id', $params)) {
207 $contactFields['case_id'] = $caseId;
210 self
::checkDuplicateRelationship(
212 CRM_Utils_Array
::value('contact', $ids),
221 $singleInstanceParams = array_merge($params, $contactFields);
222 $relationship = self
::add($singleInstanceParams);
223 $relationshipIds[] = $relationship->id
;
224 $relationships[$relationship->id
] = $relationship;
227 // editing the relationship
230 // check for duplicate relationship
231 // @todo this code doesn't cope well with updates - causes e-Notices.
232 // API has a lot of code to work around
233 // this but should review this code & remove the extra handling from the api
234 // it seems doubtful any of this is relevant if the contact fields & relationship
235 // type fields are not set
237 self
::checkDuplicateRelationship(
239 CRM_Utils_Array
::value('contact', $ids),
240 $ids['contactTarget'],
245 return array($valid, $invalid, $duplicate, $saved, NULL);
248 $validContacts = TRUE;
249 //validate contacts in update mode also.
250 $contactFields = self
::setContactABFromIDs($params, $ids, $ids['contactTarget']);
251 if (!empty($ids['contact']) && !empty($ids['contactTarget'])) {
252 if (self
::checkValidRelationship($contactFields, $ids, $ids['contactTarget'])) {
253 $validContacts = FALSE;
257 if ($validContacts) {
258 // editing an existing relationship
259 $singleInstanceParams = array_merge($params, $contactFields);
260 $relationship = self
::add($singleInstanceParams, $ids, $ids['contactTarget']);
261 $relationshipIds[] = $relationship->id
;
262 $relationships[$relationship->id
] = $relationship;
267 // do not add to recent items for import, CRM-4399
268 if (!(!empty($params['skipRecentView']) ||
$invalid ||
$duplicate)) {
269 self
::addRecent($params, $relationship);
272 return array($valid, $invalid, $duplicate, $saved, $relationshipIds, $relationships);
276 * This is the function that check/add if the relationship created is valid.
278 * @param array $params
279 * (reference ) an assoc array of name/value pairs.
281 * The array that holds all the db ids.
282 * @param int $contactId
283 * This is contact id for adding relationship.
285 * @return CRM_Contact_BAO_Relationship
287 public static function add(&$params, $ids = array(), $contactId = NULL) {
288 $relationshipId = CRM_Utils_Array
::value('relationship', $ids, CRM_Utils_Array
::value('id', $params));
291 if ($relationshipId) {
294 //@todo hook are called from create and add - remove one
295 CRM_Utils_Hook
::pre($hook, 'Relationship', $relationshipId, $params);
297 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
299 // explode the string with _ to get the relationship type id
300 // and to know which contact has to be inserted in
301 // contact_id_a and which one in contact_id_b
302 list($type) = explode('_', $relationshipTypes);
304 // check if the relationship type is Head of Household then update the
305 // household's primary contact with this contact.
307 CRM_Contact_BAO_Household
::updatePrimaryContact($params['contact_id_b'], $params['contact_id_a']);
309 if (!empty($relationshipId) && self
::isCurrentEmployerNeedingToBeCleared($params, $relationshipId, $type)) {
310 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($params['contact_id_a']);
312 $relationship = new CRM_Contact_BAO_Relationship();
313 //@todo this code needs to be updated for the possibility that not all fields are set
314 // by using $relationship->copyValues($params);
316 $relationship->contact_id_b
= $params['contact_id_b'];
317 $relationship->contact_id_a
= $params['contact_id_a'];
318 $relationship->relationship_type_id
= $type;
319 $relationship->id
= $relationshipId;
321 $dateFields = array('end_date', 'start_date');
323 foreach (self
::getdefaults() as $defaultField => $defaultValue) {
324 if (isset($params[$defaultField])) {
325 if (in_array($defaultField, $dateFields)) {
326 $relationship->$defaultField = CRM_Utils_Date
::format(CRM_Utils_Array
::value($defaultField, $params));
327 if (!$relationship->$defaultField) {
328 $relationship->$defaultField = 'NULL';
332 $relationship->$defaultField = $params[$defaultField];
335 elseif (!$relationshipId) {
336 $relationship->$defaultField = $defaultValue;
340 $relationship->save();
342 // add custom field values
343 if (!empty($params['custom'])) {
344 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_relationship', $relationship->id
);
347 $relationship->free();
349 CRM_Utils_Hook
::post($hook, 'Relationship', $relationship->id
, $relationship);
351 return $relationship;
355 * Add relationship to recent links.
357 * @param array $params
358 * @param CRM_Contact_DAO_Relationship $relationship
360 public static function addRecent($params, $relationship) {
361 $url = CRM_Utils_System
::url('civicrm/contact/view/rel',
362 "action=view&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&context=home"
364 $session = CRM_Core_Session
::singleton();
365 $recentOther = array();
366 if (($session->get('userID') == $relationship->contact_id_a
) ||
367 CRM_Contact_BAO_Contact_Permission
::allow($relationship->contact_id_a
, CRM_Core_Permission
::EDIT
)
369 $rType = substr(CRM_Utils_Array
::value('relationship_type_id', $params), -3);
370 $recentOther = array(
371 'editUrl' => CRM_Utils_System
::url('civicrm/contact/view/rel',
372 "action=update&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
374 'deleteUrl' => CRM_Utils_System
::url('civicrm/contact/view/rel',
375 "action=delete&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
379 $title = CRM_Contact_BAO_Contact
::displayName($relationship->contact_id_a
) . ' (' . CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType',
380 $relationship->relationship_type_id
, 'label_a_b'
381 ) . ' ' . CRM_Contact_BAO_Contact
::displayName($relationship->contact_id_b
) . ')';
383 CRM_Utils_Recent
::add($title,
387 $relationship->contact_id_a
,
394 * Load contact ids and relationship type id when doing a create call if not provided.
396 * There are are various checks done in create which require this information which is optional
399 * @param array $params
400 * Parameters passed to create call.
403 * Parameters with missing fields added if required.
405 public static function loadExistingRelationshipDetails($params) {
406 if (!empty($params['contact_id_a'])
407 && !empty($params['contact_id_b'])
408 && is_numeric($params['relationship_type_id'])) {
411 if (empty($params['id'])) {
415 $fieldsToFill = array('contact_id_a', 'contact_id_b', 'relationship_type_id');
416 $result = CRM_Core_DAO
::executeQuery("SELECT " . implode(',', $fieldsToFill) . " FROM civicrm_relationship WHERE id = %1", array(
422 while ($result->fetch()) {
423 foreach ($fieldsToFill as $field) {
424 $params[$field] = !empty($params[$field]) ?
$params[$field] : $result->$field;
431 * Resolve passed in contact IDs to contact_id_a & contact_id_b.
433 * @param array $params
435 * @param null $contactID
438 * @throws \CRM_Core_Exception
440 public static function setContactABFromIDs($params, $ids = array(), $contactID = NULL) {
441 $returnFields = array();
443 // $ids['contact'] is deprecated but comes from legacyCreateMultiple function.
444 if (empty($ids['contact'])) {
445 if (!empty($params['id'])) {
446 return self
::loadExistingRelationshipDetails($params);
448 throw new CRM_Core_Exception('Cannot create relationship, insufficient contact IDs provided');
450 if (isset($params['relationship_type_id']) && !is_numeric($params['relationship_type_id'])) {
451 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
452 list($relationshipTypeID, $first) = explode('_', $relationshipTypes);
453 $returnFields['relationship_type_id'] = $relationshipTypeID;
455 foreach (array('a', 'b') as $contactLetter) {
456 if (empty($params['contact_' . $contactLetter])) {
457 if ($first == $contactLetter) {
458 $returnFields['contact_id_' . $contactLetter] = CRM_Utils_Array
::value('contact', $ids);
461 $returnFields['contact_id_' . $contactLetter] = $contactID;
467 return $returnFields;
471 * Specify defaults for creating a relationship.
474 * array of defaults for creating relationship
476 public static function getdefaults() {
479 'is_permission_a_b' => self
::NONE
,
480 'is_permission_b_a' => self
::NONE
,
482 'start_date' => 'NULL',
484 'end_date' => 'NULL',
490 * Check if there is data to create the object.
492 * @param array $params
493 * (reference ) an assoc array of name/value pairs.
497 public static function dataExists(&$params) {
498 // return if no data present
499 if (!is_array(CRM_Utils_Array
::value('contact_check', $params))) {
506 * Get get list of relationship type based on the contact type.
508 * @param int $contactId
509 * This is the contact id of the current contact.
510 * @param null $contactSuffix
511 * @param string $relationshipId
512 * The id of the existing relationship if any.
513 * @param string $contactType
516 * If true returns relationship types in both the direction.
517 * @param string $column
518 * Name/label that going to retrieve from db.
519 * @param bool $biDirectional
520 * @param array $contactSubType
521 * Includes relationship types between this subtype.
522 * @param bool $onlySubTypeRelationTypes
523 * If set only subtype which is passed by $contactSubType
524 * related relationship types get return
527 * array reference of all relationship types with context to current contact.
529 public static function getContactRelationshipType(
531 $contactSuffix = NULL,
532 $relationshipId = NULL,
536 $biDirectional = TRUE,
537 $contactSubType = NULL,
538 $onlySubTypeRelationTypes = FALSE
541 $relationshipType = array();
542 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType($column);
544 $otherContactType = NULL;
545 if ($relationshipId) {
546 $relationship = new CRM_Contact_DAO_Relationship();
547 $relationship->id
= $relationshipId;
548 if ($relationship->find(TRUE)) {
549 $contact = new CRM_Contact_DAO_Contact();
550 $contact->id
= ($relationship->contact_id_a
== $contactId) ?
$relationship->contact_id_b
: $relationship->contact_id_a
;
552 if ($contact->find(TRUE)) {
553 $otherContactType = $contact->contact_type
;
554 //CRM-5125 for contact subtype specific relationshiptypes
555 if ($contact->contact_sub_type
) {
556 $otherContactSubType = $contact->contact_sub_type
;
562 $contactSubType = (array) $contactSubType;
564 $contactType = CRM_Contact_BAO_Contact
::getContactType($contactId);
565 $contactSubType = CRM_Contact_BAO_Contact
::getContactSubType($contactId);
568 foreach ($allRelationshipType as $key => $value) {
569 // the contact type is required or matches
570 if (((!$value['contact_type_a']) ||
571 $value['contact_type_a'] == $contactType
573 // the other contact type is required or present or matches
574 ((!$value['contact_type_b']) ||
575 (!$otherContactType) ||
576 $value['contact_type_b'] == $otherContactType
578 (in_array($value['contact_sub_type_a'], $contactSubType) ||
579 (!$value['contact_sub_type_a'] && !$onlySubTypeRelationTypes)
582 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
585 if (((!$value['contact_type_b']) ||
586 $value['contact_type_b'] == $contactType
588 ((!$value['contact_type_a']) ||
589 (!$otherContactType) ||
590 $value['contact_type_a'] == $otherContactType
592 (in_array($value['contact_sub_type_b'], $contactSubType) ||
593 (!$value['contact_sub_type_b'] && !$onlySubTypeRelationTypes)
596 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
600 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
601 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
605 if ($biDirectional) {
606 $relationshipType = self
::removeRelationshipTypeDuplicates($relationshipType, $contactSuffix);
609 // sort the relationshipType in ascending order CRM-7736
610 asort($relationshipType);
611 return $relationshipType;
615 * Given a list of relationship types, return the list with duplicate types
616 * removed, being careful to retain only the duplicate which matches the given
617 * 'a_b' or 'b_a' suffix.
619 * @param array $relationshipTypeList A list of relationship types, in the format
620 * returned by self::getContactRelationshipType().
621 * @param string $suffix Either 'a_b' or 'b_a'; defaults to 'a_b'
623 * @return array The modified value of $relationshipType
625 public static function removeRelationshipTypeDuplicates($relationshipTypeList, $suffix = NULL) {
626 if (empty($suffix)) {
630 // Find those labels which are listed more than once.
631 $duplicateValues = array_diff_assoc($relationshipTypeList, array_unique($relationshipTypeList));
633 // For each duplicate label, find its keys, and remove from $relationshipType
634 // the key which does not match $suffix.
635 foreach ($duplicateValues as $value) {
636 $keys = array_keys($relationshipTypeList, $value);
637 foreach ($keys as $key) {
638 if (substr($key, -3) != $suffix) {
639 unset($relationshipTypeList[$key]);
643 return $relationshipTypeList;
647 * Delete current employer relationship.
652 * @return CRM_Contact_DAO_Relationship
654 public static function clearCurrentEmployer($id, $action) {
655 $relationship = new CRM_Contact_DAO_Relationship();
656 $relationship->id
= $id;
657 $relationship->find(TRUE);
659 //to delete relationship between household and individual \
660 //or between individual and organization
661 if (($action & CRM_Core_Action
::DISABLE
) ||
($action & CRM_Core_Action
::DELETE
)) {
662 $relTypes = CRM_Utils_Array
::index(array('name_a_b'), CRM_Core_PseudoConstant
::relationshipType('name'));
664 (isset($relTypes['Employee of']) && $relationship->relationship_type_id
== $relTypes['Employee of']['id']) ||
665 (isset($relTypes['Household Member of']) && $relationship->relationship_type_id
== $relTypes['Household Member of']['id'])
667 $sharedContact = new CRM_Contact_DAO_Contact();
668 $sharedContact->id
= $relationship->contact_id_a
;
669 $sharedContact->find(TRUE);
672 // changed FROM "...relationship->relationship_type_id == 4..." TO "...relationship->relationship_type_id == 5..."
673 // As the system should be looking for type "employer of" (id 5) and not "sibling of" (id 4)
674 // 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.
675 $employerRelTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b');
677 if ($relationship->relationship_type_id
== $employerRelTypeId && $relationship->contact_id_b
== $sharedContact->employer_id
) {
678 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($relationship->contact_id_a
);
683 return $relationship;
687 * Delete the relationship.
694 public static function del($id) {
695 // delete from relationship table
696 CRM_Utils_Hook
::pre('delete', 'Relationship', $id, CRM_Core_DAO
::$_nullArray);
698 $relationship = self
::clearCurrentEmployer($id, CRM_Core_Action
::DELETE
);
699 if (CRM_Core_Permission
::access('CiviMember')) {
700 // create $params array which isrequired to delete memberships
701 // of the related contacts.
703 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
704 'contact_check' => array($relationship->contact_id_b
=> 1),
708 // calling relatedMemberships to delete the memberships of
710 self
::relatedMemberships($relationship->contact_id_a
,
713 CRM_Core_Action
::DELETE
,
718 $relationship->delete();
719 CRM_Core_Session
::setStatus(ts('Selected relationship has been deleted successfully.'), ts('Record Deleted'), 'success');
721 CRM_Utils_Hook
::post('delete', 'Relationship', $id, $relationship);
723 // delete the recently created Relationship
724 $relationshipRecent = array(
726 'type' => 'Relationship',
728 CRM_Utils_Recent
::del($relationshipRecent);
730 return $relationship;
734 * Disable/enable the relationship.
740 * @param array $params
742 * @param bool $active
744 public static function disableEnableRelationship($id, $action, $params = array(), $ids = array(), $active = FALSE) {
745 $relationship = self
::clearCurrentEmployer($id, $action);
748 // create $params array which is required to delete memberships
749 // of the related contacts.
750 if (empty($params)) {
752 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
753 'contact_check' => array($relationship->contact_id_b
=> 1),
756 $contact_id_a = empty($params['contact_id_a']) ?
$relationship->contact_id_a
: $params['contact_id_a'];
757 // calling relatedMemberships to delete/add the memberships of
759 if ($action & CRM_Core_Action
::DISABLE
) {
760 CRM_Contact_BAO_Relationship
::relatedMemberships($contact_id_a,
763 CRM_Core_Action
::DELETE
,
767 elseif ($action & CRM_Core_Action
::ENABLE
) {
768 $ids['contact'] = empty($ids['contact']) ?
$contact_id_a : $ids['contact'];
769 CRM_Contact_BAO_Relationship
::relatedMemberships($contact_id_a,
772 empty($params['id']) ? CRM_Core_Action
::ADD
: CRM_Core_Action
::UPDATE
,
780 * Delete the object records that are associated with this contact.
782 * @param int $contactId
783 * Id of the contact to delete.
785 public static function deleteContact($contactId) {
786 $relationship = new CRM_Contact_DAO_Relationship();
787 $relationship->contact_id_a
= $contactId;
788 $relationship->delete();
790 $relationship = new CRM_Contact_DAO_Relationship();
791 $relationship->contact_id_b
= $contactId;
792 $relationship->delete();
794 CRM_Contact_BAO_Household
::updatePrimaryContact(NULL, $contactId);
798 * Get the other contact in a relationship.
803 * $returns returns the contact ids in the realtionship
805 * @return \CRM_Contact_DAO_Relationship
807 public static function getRelationshipByID($id) {
808 $relationship = new CRM_Contact_DAO_Relationship();
810 $relationship->id
= $id;
811 $relationship->selectAdd();
812 $relationship->selectAdd('contact_id_a, contact_id_b');
813 $relationship->find(TRUE);
815 return $relationship;
819 * Check if the relationship type selected between two contacts is correct.
821 * @param int $contact_a
823 * @param int $contact_b
825 * @param int $relationshipTypeId
826 * Relationship type id.
829 * true if it is valid relationship else false
831 public static function checkRelationshipType($contact_a, $contact_b, $relationshipTypeId) {
832 $relationshipType = new CRM_Contact_DAO_RelationshipType();
833 $relationshipType->id
= $relationshipTypeId;
834 $relationshipType->selectAdd();
835 $relationshipType->selectAdd('contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b');
836 if ($relationshipType->find(TRUE)) {
837 $contact_type_a = CRM_Contact_BAO_Contact
::getContactType($contact_a);
838 $contact_type_b = CRM_Contact_BAO_Contact
::getContactType($contact_b);
840 $contact_sub_type_a = CRM_Contact_BAO_Contact
::getContactSubType($contact_a);
841 $contact_sub_type_b = CRM_Contact_BAO_Contact
::getContactSubType($contact_b);
843 if (((!$relationshipType->contact_type_a
) ||
($relationshipType->contact_type_a
== $contact_type_a)) &&
844 ((!$relationshipType->contact_type_b
) ||
($relationshipType->contact_type_b
== $contact_type_b)) &&
845 ((!$relationshipType->contact_sub_type_a
) ||
(in_array($relationshipType->contact_sub_type_a
,
848 ((!$relationshipType->contact_sub_type_b
) ||
(in_array($relationshipType->contact_sub_type_b
,
862 * This function does the validtion for valid relationship.
864 * @param array $params
865 * This array contains the values there are subitted by the form.
867 * The array that holds all the db ids.
868 * @param int $contactId
869 * This is contact id for adding relationship.
873 public static function checkValidRelationship($params, $ids, $contactId) {
875 // function to check if the relationship selected is correct
876 // i.e. employer relationship can exit between Individual and Organization (not between Individual and Individual)
877 if (!CRM_Contact_BAO_Relationship
::checkRelationshipType($params['contact_id_a'], $params['contact_id_b'],
878 $params['relationship_type_id'])) {
879 $errors = 'Please select valid relationship between these two contacts.';
885 * This function checks for duplicate relationship.
887 * @param array $params
888 * (reference ) an assoc array of name/value pairs.
890 * This the id of the contact whom we are adding relationship.
891 * @param int $contactId
892 * This is contact id for adding relationship.
893 * @param int $relationshipId
894 * This is relationship id for the contact.
897 * true if record exists else false
899 public static function checkDuplicateRelationship(&$params, $id, $contactId = 0, $relationshipId = 0) {
900 $relationshipTypeId = CRM_Utils_Array
::value('relationship_type_id', $params);
901 list($type) = explode('_', $relationshipTypeId);
905 FROM civicrm_relationship
906 WHERE relationship_type_id = " . CRM_Utils_Type
::escape($type, 'Integer');
909 * CRM-11792 - date fields from API are in ISO format, but this function
910 * supports date arrays BAO has increasingly standardised to ISO format
911 * so I believe this function should support ISO rather than make API
912 * format it - however, need to support array format for now to avoid breakage
913 * @ time of writing this function is called from Relationship::legacyCreateMultiple (twice)
914 * CRM_BAO_Contact_Utils::clearCurrentEmployer (seemingly without dates)
915 * CRM_Contact_Form_Task_AddToOrganization::postProcess &
916 * CRM_Contact_Form_Task_AddToHousehold::postProcess
917 * (I don't think the last 2 support dates but not sure
920 $dateFields = array('end_date', 'start_date');
921 foreach ($dateFields as $dateField) {
922 if (array_key_exists($dateField, $params)) {
923 if (empty($params[$dateField]) ||
$params[$dateField] == 'null') {
924 //this is most likely coming from an api call & probably loaded
925 // from the DB to deal with some of the
926 // other myriad of excessive checks still in place both in
927 // the api & the create functions
928 $queryString .= " AND $dateField IS NULL";
931 elseif (is_array($params[$dateField])) {
932 $queryString .= " AND $dateField = " .
933 CRM_Utils_Type
::escape(CRM_Utils_Date
::format($params[$dateField]), 'Date');
936 $queryString .= " AND $dateField = " .
937 CRM_Utils_Type
::escape($params[$dateField], 'Date');
943 " AND ( ( contact_id_a = " . CRM_Utils_Type
::escape($id, 'Integer') .
944 " AND contact_id_b = " . CRM_Utils_Type
::escape($contactId, 'Integer') .
945 " ) OR ( contact_id_a = " . CRM_Utils_Type
::escape($contactId, 'Integer') .
946 " AND contact_id_b = " . CRM_Utils_Type
::escape($id, 'Integer') . " ) ) ";
948 //if caseId is provided, include it duplicate checking.
949 if ($caseId = CRM_Utils_Array
::value('case_id', $params)) {
950 $queryString .= " AND case_id = " . CRM_Utils_Type
::escape($caseId, 'Integer');
953 if ($relationshipId) {
954 $queryString .= " AND id !=" . CRM_Utils_Type
::escape($relationshipId, 'Integer');
957 $relationship = new CRM_Contact_BAO_Relationship();
958 $relationship->query($queryString);
959 while ($relationship->fetch()) {
960 // Check whether the custom field values are identical.
961 $result = self
::checkDuplicateCustomFields($params, $relationship->id
);
963 $relationship->free();
967 $relationship->free();
972 * this function checks whether the values of the custom fields in $params are
973 * the same as the values of the custom fields of the relation with given
976 * @param array $params (reference) an assoc array of name/value pairs
977 * @param int $relationshipId ID of an existing duplicate relation
979 * @return boolean true if custom field values are identical
983 private static function checkDuplicateCustomFields(&$params, $relationshipId) {
984 // Get the custom values of the existing relationship.
985 $existingValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($relationshipId, 'Relationship');
986 // Create a similar array for the new relationship.
987 $newValues = array();
988 if (array_key_exists('custom', $params)) {
989 // $params['custom'] seems to be an array. Each value is again an array.
990 // This array contains one value (key -1), and this value seems to be
991 // an array with the information about the custom value.
992 foreach ($params['custom'] as $value) {
993 foreach ($value as $customValue) {
994 $newValues[$customValue['custom_field_id']] = $customValue['value'];
999 // Calculate difference between arrays. If the only key-value pairs
1000 // that are in one array but not in the other are empty, the
1001 // custom fields are considered to be equal.
1002 // See https://github.com/civicrm/civicrm-core/pull/6515#issuecomment-137985667
1003 $diff1 = array_diff_assoc($existingValues, $newValues);
1004 $diff2 = array_diff_assoc($newValues, $existingValues);
1006 return !array_filter($diff1) && !array_filter($diff2);
1010 * Update the is_active flag in the db.
1013 * Id of the database record.
1014 * @param bool $is_active
1015 * Value we want to set the is_active field.
1017 * @throws CiviCRM_API3_Exception
1019 * DAO object on success, null otherwise
1021 public static function setIsActive($id, $is_active) {
1022 // as both the create & add functions have a bunch of logic in them that
1023 // doesn't seem to cope with a normal update we will call the api which
1024 // has tested handling for this
1025 // however, a longer term solution would be to simplify the add, create & api functions
1026 // to be more standard. It is debatable @ that point whether it's better to call the BAO
1027 // direct as the api is more tested.
1028 $result = civicrm_api('relationship', 'create', array(
1030 'is_active' => $is_active,
1034 if (is_array($result) && !empty($result['is_error']) && $result['error_message'] != 'Duplicate Relationship') {
1035 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array
::value('error_code', $result, 'undefined'), $result);
1042 * Fetch a relationship object and store the values in the values array.
1044 * @param array $params
1045 * Input parameters to find object.
1046 * @param array $values
1047 * Output values of the object.
1050 * (reference) the values that could be potentially assigned to smarty
1052 public static function &getValues(&$params, &$values) {
1053 if (empty($params)) {
1058 // get the specific number of relationship or all relationships.
1059 if (!empty($params['numRelationship'])) {
1060 $v['data'] = &CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'], NULL, $params['numRelationship']);
1063 $v['data'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id']);
1066 // get the total count of relationships
1067 $v['totalCount'] = count($v['data']);
1069 $values['relationship']['data'] = &$v['data'];
1070 $values['relationship']['totalCount'] = &$v['totalCount'];
1076 * Helper function to form the sql for relationship retrieval.
1078 * @param int $contactId
1080 * @param int $status
1081 * (check const at top of file).
1082 * @param int $numRelationship
1083 * No of relationships to display (limit).
1085 * Get the no of relationships.
1086 * $param int $relationshipId relationship id
1087 * @param int $relationshipId
1088 * @param string $direction
1089 * The direction we are interested in a_b or b_a.
1090 * @param array $params
1091 * Array of extra values including relationship_type_id per api spec.
1094 * [select, from, where]
1096 public static function makeURLClause($contactId, $status, $numRelationship, $count, $relationshipId, $direction, $params = array()) {
1097 $select = $from = $where = '';
1101 if ($direction == 'a_b') {
1102 $select .= ' SELECT count(DISTINCT civicrm_relationship.id) as cnt1, 0 as cnt2 ';
1105 $select .= ' SELECT 0 as cnt1, count(DISTINCT civicrm_relationship.id) as cnt2 ';
1109 $select .= ' SELECT civicrm_relationship.id as civicrm_relationship_id,
1110 civicrm_contact.sort_name as sort_name,
1111 civicrm_contact.display_name as display_name,
1112 civicrm_contact.job_title as job_title,
1113 civicrm_contact.employer_id as employer_id,
1114 civicrm_contact.organization_name as organization_name,
1115 civicrm_address.street_address as street_address,
1116 civicrm_address.city as city,
1117 civicrm_address.postal_code as postal_code,
1118 civicrm_state_province.abbreviation as state,
1119 civicrm_country.name as country,
1120 civicrm_email.email as email,
1121 civicrm_contact.contact_type as contact_type,
1122 civicrm_contact.contact_sub_type as contact_sub_type,
1123 civicrm_phone.phone as phone,
1124 civicrm_contact.id as civicrm_contact_id,
1125 civicrm_relationship.contact_id_b as contact_id_b,
1126 civicrm_relationship.contact_id_a as contact_id_a,
1127 civicrm_relationship_type.id as civicrm_relationship_type_id,
1128 civicrm_relationship.start_date as start_date,
1129 civicrm_relationship.end_date as end_date,
1130 civicrm_relationship.description as description,
1131 civicrm_relationship.is_active as is_active,
1132 civicrm_relationship.is_permission_a_b as is_permission_a_b,
1133 civicrm_relationship.is_permission_b_a as is_permission_b_a,
1134 civicrm_relationship.case_id as case_id';
1136 if ($direction == 'a_b') {
1137 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
1138 civicrm_relationship_type.label_b_a as relation ';
1141 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
1142 civicrm_relationship_type.label_a_b as relation ';
1147 FROM civicrm_relationship
1148 INNER JOIN civicrm_relationship_type ON ( civicrm_relationship.relationship_type_id = civicrm_relationship_type.id )
1149 INNER JOIN civicrm_contact ";
1150 if ($direction == 'a_b') {
1151 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_a ) ';
1154 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_b ) ';
1159 LEFT JOIN civicrm_address ON (civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1)
1160 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
1161 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id AND civicrm_email.is_primary = 1)
1162 LEFT JOIN civicrm_state_province ON (civicrm_address.state_province_id = civicrm_state_province.id)
1163 LEFT JOIN civicrm_country ON (civicrm_address.country_id = civicrm_country.id)
1167 $where = 'WHERE ( 1 )';
1169 if ($direction == 'a_b') {
1170 $where .= ' AND civicrm_relationship.contact_id_b = ' . CRM_Utils_Type
::escape($contactId, 'Positive');
1173 $where .= ' AND civicrm_relationship.contact_id_a = ' . CRM_Utils_Type
::escape($contactId, 'Positive') . '
1174 AND civicrm_relationship.contact_id_a != civicrm_relationship.contact_id_b ';
1177 if ($relationshipId) {
1178 $where .= ' AND civicrm_relationship.id = ' . CRM_Utils_Type
::escape($relationshipId, 'Positive');
1181 $date = date('Y-m-d');
1182 if ($status == self
::PAST
) {
1183 //this case for showing past relationship
1184 $where .= ' AND civicrm_relationship.is_active = 1 ';
1185 $where .= " AND civicrm_relationship.end_date < '" . $date . "'";
1187 elseif ($status == self
::DISABLED
) {
1188 // this case for showing disabled relationship
1189 $where .= ' AND civicrm_relationship.is_active = 0 ';
1191 elseif ($status == self
::CURRENT
) {
1192 //this case for showing current relationship
1193 $where .= ' AND civicrm_relationship.is_active = 1 ';
1194 $where .= " AND (civicrm_relationship.end_date >= '" . $date . "' OR civicrm_relationship.end_date IS NULL) ";
1196 elseif ($status == self
::INACTIVE
) {
1197 //this case for showing inactive relationships
1198 $where .= " AND (civicrm_relationship.end_date < '" . $date . "'";
1199 $where .= ' OR civicrm_relationship.is_active = 0 )';
1203 $where .= ' AND civicrm_contact.is_deleted = 0';
1204 if (!empty($params['membership_type_id']) && empty($params['relationship_type_id'])) {
1205 $where .= self
::membershipTypeToRelationshipTypes($params, $direction);
1207 if (!empty($params['relationship_type_id'])) {
1208 if (is_array($params['relationship_type_id'])) {
1209 $where .= " AND " . CRM_Core_DAO
::createSQLFilter('relationship_type_id', $params['relationship_type_id'], 'Integer');
1212 $where .= ' AND relationship_type_id = ' . CRM_Utils_Type
::escape($params['relationship_type_id'], 'Positive');
1215 if ($direction == 'a_b') {
1216 $where .= ' ) UNION ';
1222 return array($select, $from, $where);
1226 * Get a list of relationships.
1228 * @param int $contactId
1230 * @param int $status
1231 * 1: Past 2: Disabled 3: Current.
1232 * @param int $numRelationship
1233 * No of relationships to display (limit).
1235 * Get the no of relationships.
1236 * @param int $relationshipId
1237 * @param array $links
1238 * the list of links to display
1239 * @param int $permissionMask
1240 * the permission mask to be applied for the actions
1241 * @param bool $permissionedContact
1242 * to return only permissioned Contact
1243 * @param array $params
1244 * @param bool $includeTotalCount
1245 * Should we return a count of total accessable relationships
1248 * relationship records
1250 public static function getRelationship(
1252 $status = 0, $numRelationship = 0,
1253 $count = 0, $relationshipId = 0,
1254 $links = NULL, $permissionMask = NULL,
1255 $permissionedContact = FALSE,
1256 $params = array(), $includeTotalCount = FALSE
1259 if (!$contactId && !$relationshipId) {
1263 list($select1, $from1, $where1) = self
::makeURLClause($contactId, $status, $numRelationship,
1264 $count, $relationshipId, 'a_b', $params
1266 list($select2, $from2, $where2) = self
::makeURLClause($contactId, $status, $numRelationship,
1267 $count, $relationshipId, 'b_a', $params
1270 $order = $limit = '';
1272 if (empty($params['sort'])) {
1273 $order = ' ORDER BY civicrm_relationship_type_id, sort_name ';
1276 $order = " ORDER BY {$params['sort']} ";
1280 if (!empty($params['offset']) && $params['offset'] > 0) {
1281 $offset = $params['offset'];
1284 if ($numRelationship) {
1285 $limit = " LIMIT {$offset}, $numRelationship";
1289 // building the query string
1290 $queryString = $select1 . $from1 . $where1 . $select2 . $from2 . $where2;
1292 $relationship = new CRM_Contact_DAO_Relationship();
1294 $relationship->query($queryString . $order . $limit);
1297 $relationshipCount = 0;
1298 while ($relationship->fetch()) {
1299 $relationshipCount +
= $relationship->cnt1 +
$relationship->cnt2
;
1301 return $relationshipCount;
1305 if ($includeTotalCount) {
1306 $values['total_relationships'] = CRM_Core_DAO
::singleValueQuery("SELECT count(*) FROM ({$queryString}) AS r");
1310 if ($status != self
::INACTIVE
) {
1312 $mask = array_sum(array_keys($links));
1313 if ($mask & CRM_Core_Action
::DISABLE
) {
1314 $mask -= CRM_Core_Action
::DISABLE
;
1316 if ($mask & CRM_Core_Action
::ENABLE
) {
1317 $mask -= CRM_Core_Action
::ENABLE
;
1320 if ($status == self
::CURRENT
) {
1321 $mask |
= CRM_Core_Action
::DISABLE
;
1323 elseif ($status == self
::DISABLED
) {
1324 $mask |
= CRM_Core_Action
::ENABLE
;
1327 // temporary hold the value of $mask.
1331 while ($relationship->fetch()) {
1332 $rid = $relationship->civicrm_relationship_id
;
1333 $cid = $relationship->civicrm_contact_id
;
1335 if ($permissionedContact &&
1336 (!CRM_Contact_BAO_Contact_Permission
::allow($cid))
1340 if ($status != self
::INACTIVE
&& $links) {
1341 // assign the original value to $mask
1343 // display action links if $cid has edit permission for the relationship.
1344 if (!($permissionMask & CRM_Core_Permission
::EDIT
) && CRM_Contact_BAO_Contact_Permission
::allow($cid, CRM_Core_Permission
::EDIT
)) {
1345 $permissions[] = CRM_Core_Permission
::EDIT
;
1346 $permissions[] = CRM_Core_Permission
::DELETE
;
1347 $permissionMask = CRM_Core_Action
::mask($permissions);
1349 $mask = $mask & $permissionMask;
1351 $values[$rid]['id'] = $rid;
1352 $values[$rid]['cid'] = $cid;
1353 $values[$rid]['contact_id_a'] = $relationship->contact_id_a
;
1354 $values[$rid]['contact_id_b'] = $relationship->contact_id_b
;
1355 $values[$rid]['contact_type'] = $relationship->contact_type
;
1356 $values[$rid]['contact_sub_type'] = $relationship->contact_sub_type
;
1357 $values[$rid]['relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1358 $values[$rid]['relation'] = $relationship->relation
;
1359 $values[$rid]['name'] = $relationship->sort_name
;
1360 $values[$rid]['display_name'] = $relationship->display_name
;
1361 $values[$rid]['job_title'] = $relationship->job_title
;
1362 $values[$rid]['email'] = $relationship->email
;
1363 $values[$rid]['phone'] = $relationship->phone
;
1364 $values[$rid]['employer_id'] = $relationship->employer_id
;
1365 $values[$rid]['organization_name'] = $relationship->organization_name
;
1366 $values[$rid]['country'] = $relationship->country
;
1367 $values[$rid]['city'] = $relationship->city
;
1368 $values[$rid]['state'] = $relationship->state
;
1369 $values[$rid]['start_date'] = $relationship->start_date
;
1370 $values[$rid]['end_date'] = $relationship->end_date
;
1371 $values[$rid]['description'] = $relationship->description
;
1372 $values[$rid]['is_active'] = $relationship->is_active
;
1373 $values[$rid]['is_permission_a_b'] = $relationship->is_permission_a_b
;
1374 $values[$rid]['is_permission_b_a'] = $relationship->is_permission_b_a
;
1375 $values[$rid]['case_id'] = $relationship->case_id
;
1378 $values[$rid]['status'] = $status;
1381 $values[$rid]['civicrm_relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1383 if ($relationship->contact_id_a
== $contactId) {
1384 $values[$rid]['rtype'] = 'a_b';
1387 $values[$rid]['rtype'] = 'b_a';
1393 'rtype' => $values[$rid]['rtype'],
1394 'cid' => $contactId,
1395 'cbid' => $values[$rid]['cid'],
1396 'caseid' => $values[$rid]['case_id'],
1397 'clientid' => $contactId,
1400 if ($status == self
::INACTIVE
) {
1401 // setting links for inactive relationships
1402 $mask = array_sum(array_keys($links));
1403 if (!$values[$rid]['is_active']) {
1404 $mask -= CRM_Core_Action
::DISABLE
;
1407 $mask -= CRM_Core_Action
::ENABLE
;
1408 $mask -= CRM_Core_Action
::DISABLE
;
1410 $mask = $mask & $permissionMask;
1413 // Give access to manage case link by copying to MAX_ACTION index temporarily, depending on case permission of user.
1414 if ($values[$rid]['case_id']) {
1415 // Borrowed logic from CRM_Case_Page_Tab
1416 $hasCaseAccess = FALSE;
1417 if (CRM_Core_Permission
::check('access all cases and activities')) {
1418 $hasCaseAccess = TRUE;
1421 $userCases = CRM_Case_BAO_Case
::getCases(FALSE);
1422 if (array_key_exists($values[$rid]['case_id'], $userCases)) {
1423 $hasCaseAccess = TRUE;
1427 if ($hasCaseAccess) {
1428 // give access by copying to MAX_ACTION temporarily, otherwise leave at NONE which won't display
1429 $links[CRM_Core_Action
::MAX_ACTION
] = $links[CRM_Core_Action
::NONE
];
1430 $links[CRM_Core_Action
::MAX_ACTION
]['name'] = ts('Manage Case #%1', array(1 => $values[$rid]['case_id']));
1431 $links[CRM_Core_Action
::MAX_ACTION
]['class'] = 'no-popup';
1433 // Also make sure we have the right client cid since can get here from multiple relationship tabs.
1434 if ($values[$rid]['rtype'] == 'b_a') {
1435 $replace['clientid'] = $values[$rid]['cid'];
1440 $values[$rid]['action'] = CRM_Core_Action
::formLink(
1446 'relationship.selector.row',
1449 unset($links[CRM_Core_Action
::MAX_ACTION
]);
1453 $relationship->free();
1459 * Get get list of relationship type based on the target contact type.
1461 * @param string $targetContactType
1462 * It's valid contact tpye(may be Individual , Organization , Household).
1465 * array reference of all relationship types with context to current contact type .
1467 static public function getRelationType($targetContactType) {
1468 $relationshipType = array();
1469 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType();
1471 foreach ($allRelationshipType as $key => $type) {
1472 if ($type['contact_type_b'] == $targetContactType) {
1473 $relationshipType[$key . '_a_b'] = $type['label_a_b'];
1477 return $relationshipType;
1481 * Create / update / delete membership for related contacts.
1483 * This function will create/update/delete membership for related
1484 * contact based on 1) contact have active membership 2) that
1485 * membership is is extedned by the same relationship type to that
1486 * of the existing relationship.
1488 * @param int $contactId
1490 * @param array $params
1491 * array of values submitted by POST.
1494 * @param \const|int $action which action called this function
1496 * @param bool $active
1498 * @throws \CRM_Core_Exception
1500 public static function relatedMemberships($contactId, &$params, $ids, $action = CRM_Core_Action
::ADD
, $active = TRUE) {
1501 // Check the end date and set the status of the relationship
1503 $status = self
::CURRENT
;
1504 $targetContact = $targetContact = CRM_Utils_Array
::value('contact_check', $params, array());
1505 $today = date('Ymd');
1507 // If a relationship hasn't yet started, just return for now
1508 // TODO: handle edge-case of updating start_date of an existing relationship
1509 if (!empty($params['start_date'])) {
1510 $startDate = substr(CRM_Utils_Date
::format($params['start_date']), 0, 8);
1511 if ($today < $startDate) {
1516 if (!empty($params['end_date'])) {
1517 $endDate = substr(CRM_Utils_Date
::format($params['end_date']), 0, 8);
1518 if ($today > $endDate) {
1519 $status = self
::PAST
;
1523 if (($action & CRM_Core_Action
::ADD
) && ($status & self
::PAST
)) {
1524 // If relationship is PAST and action is ADD, do nothing.
1528 $rel = explode('_', $params['relationship_type_id']);
1530 $relTypeId = $rel[0];
1531 if (!empty($rel[1])) {
1532 $relDirection = "_{$rel[1]}_{$rel[2]}";
1535 // this call is coming from somewhere where the direction was resolved early on (e.g an api call)
1536 // so we can assume _a_b
1537 $relDirection = "_a_b";
1538 $targetContact = array($params['contact_id_b'] => 1);
1541 if (($action & CRM_Core_Action
::ADD
) ||
1542 ($action & CRM_Core_Action
::DELETE
)
1544 $contact = $contactId;
1546 elseif ($action & CRM_Core_Action
::UPDATE
) {
1547 $contact = $ids['contact'];
1548 $targetContact = array($ids['contactTarget'] => 1);
1551 // Build the 'values' array for
1554 // This will allow us to check if either of the contacts in
1555 // relationship have active memberships.
1560 $values[$contact] = array(
1561 'relatedContacts' => $targetContact,
1562 'relationshipTypeId' => $relTypeId,
1563 'relationshipTypeDirection' => $relDirection,
1566 if (!empty($targetContact)) {
1567 foreach ($targetContact as $cid => $donCare) {
1568 $values[$cid] = array(
1569 'relatedContacts' => array($contact => 1),
1570 'relationshipTypeId' => $relTypeId,
1573 $relTypeParams = array('id' => $relTypeId);
1574 $relTypeValues = array();
1575 CRM_Contact_BAO_RelationshipType
::retrieve($relTypeParams, $relTypeValues);
1577 if (CRM_Utils_Array
::value('name_a_b', $relTypeValues) == CRM_Utils_Array
::value('name_b_a', $relTypeValues)) {
1578 $values[$cid]['relationshipTypeDirection'] = '_a_b';
1581 $values[$cid]['relationshipTypeDirection'] = ($relDirection == '_a_b') ?
'_b_a' : '_a_b';
1586 // CRM-15829 UPDATES
1587 // If we're looking for active memberships we must consider pending (id: 5) ones too.
1588 // Hence we can't just call CRM_Member_BAO_Membership::getValues below with the active flag, is it would completely miss pending relatioships.
1589 // 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.
1590 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
1592 $query = 'SELECT * FROM `civicrm_membership_status`';
1594 $query .= ' WHERE `is_current_member` = 1 OR `id` = %1 ';
1597 $dao = CRM_Core_DAO
::executeQuery($query, array(1 => array($pendingStatusId, 'Integer')));
1599 while ($dao->fetch()) {
1600 $membershipStatusRecordIds[$dao->id
] = $dao->id
;
1603 // Now get the active memberships for all the contacts.
1604 // If contact have any valid membership(s), then add it to
1606 foreach ($values as $cid => $subValues) {
1607 $memParams = array('contact_id' => $cid);
1608 $memberships = array();
1610 // CRM-15829 UPDATES
1611 // 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.
1612 CRM_Member_BAO_Membership
::getValues($memParams, $memberships, FALSE, TRUE);
1614 // CRM-15829 UPDATES
1615 // filter out the memberships returned by CRM_Member_BAO_Membership::getValues based on the status IDs fetched on line ~1462
1616 foreach ($memberships as $key => $membership) {
1618 if (!isset($memberships[$key]['status_id'])) {
1622 $membershipStatusId = $memberships[$key]['status_id'];
1623 if (!isset($membershipStatusRecordIds[$membershipStatusId])) {
1624 unset($memberships[$key]);
1628 if (empty($memberships)) {
1632 //get ownerMembershipIds for related Membership
1633 //this is to handle memberships being deleted and recreated
1634 if (!empty($memberships['owner_membership_ids'])) {
1635 $ownerMemIds[$cid] = $memberships['owner_membership_ids'];
1636 unset($memberships['owner_membership_ids']);
1639 $values[$cid]['memberships'] = $memberships;
1641 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1643 // done with 'values' array.
1644 // Finally add / edit / delete memberships for the related contacts
1646 foreach ($values as $cid => $details) {
1647 if (!array_key_exists('memberships', $details)) {
1651 $relatedContacts = array_keys(CRM_Utils_Array
::value('relatedContacts', $details, array()));
1652 $mainRelatedContactId = reset($relatedContacts);
1654 foreach ($details['memberships'] as $membershipId => $membershipValues) {
1655 $relTypeIds = array();
1656 if ($action & CRM_Core_Action
::DELETE
) {
1657 // Delete memberships of the related contacts only if relationship type exists for membership type
1659 SELECT relationship_type_id, relationship_direction
1660 FROM civicrm_membership_type
1661 WHERE id = {$membershipValues['membership_type_id']}";
1662 $dao = CRM_Core_DAO
::executeQuery($query);
1663 $relTypeDirs = array();
1664 while ($dao->fetch()) {
1665 $relTypeId = $dao->relationship_type_id
;
1666 $relDirection = $dao->relationship_direction
;
1668 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $relTypeId);
1669 if (in_array($values[$cid]['relationshipTypeId'], $relTypeIds
1670 //CRM-16300 check if owner membership exist for related membership
1671 ) && !empty($membershipValues['owner_membership_id']) && !empty($values[$mainRelatedContactId]['memberships'][$membershipValues['owner_membership_id']])) {
1672 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipValues['owner_membership_id'], $membershipValues['membership_contact_id']);
1676 if (($action & CRM_Core_Action
::UPDATE
) &&
1677 ($status & self
::PAST
) &&
1678 ($membershipValues['owner_membership_id'])
1680 // If relationship is PAST and action is UPDATE
1681 // then delete the RELATED membership
1682 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipValues['owner_membership_id'],
1683 $membershipValues['membership_contact_id']
1688 // add / edit the memberships for related
1691 // Get the Membership Type Details.
1692 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipValues['membership_type_id']);
1693 // Check if contact's relationship type exists in membership type
1694 $relTypeDirs = array();
1695 if (!empty($membershipType['relationship_type_id'])) {
1696 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_type_id']);
1698 if (!empty($membershipType['relationship_direction'])) {
1699 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_direction']);
1701 foreach ($relTypeIds as $key => $value) {
1702 $relTypeDirs[] = $value . '_' . $relDirections[$key];
1704 $relTypeDir = $details['relationshipTypeId'] . $details['relationshipTypeDirection'];
1705 if (in_array($relTypeDir, $relTypeDirs)) {
1706 // Check if relationship being created/updated is
1707 // similar to that of membership type's
1710 $membershipValues['owner_membership_id'] = $membershipId;
1711 unset($membershipValues['id']);
1712 unset($membershipValues['membership_contact_id']);
1713 unset($membershipValues['contact_id']);
1714 unset($membershipValues['membership_id']);
1715 foreach ($details['relatedContacts'] as $relatedContactId => $donCare) {
1716 $membershipValues['contact_id'] = $relatedContactId;
1717 if ($deceasedStatusId &&
1718 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $relatedContactId, 'is_deceased')
1720 $membershipValues['status_id'] = $deceasedStatusId;
1721 $membershipValues['skipStatusCal'] = TRUE;
1728 if (!empty($membershipValues[$dateField])) {
1729 $membershipValues[$dateField] = CRM_Utils_Date
::processDate($membershipValues[$dateField]);
1733 if ($action & CRM_Core_Action
::UPDATE
) {
1734 //if updated relationship is already related to contact don't delete existing inherited membership
1735 if (in_array($relTypeId, $relTypeIds
1736 ) && !empty($values[$relatedContactId]['memberships']) && !empty($ownerMemIds
1737 ) && in_array($membershipValues['owner_membership_id'], $ownerMemIds[$relatedContactId])) {
1741 //delete the membership record for related
1742 //contact before creating new membership record.
1743 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $relatedContactId);
1745 //skip status calculation for pay later memberships.
1746 if (!empty($membershipValues['status_id']) && $membershipValues['status_id'] == $pendingStatusId) {
1747 $membershipValues['skipStatusCal'] = TRUE;
1750 // check whether we have some related memberships still available
1753 FROM civicrm_membership
1754 LEFT JOIN civicrm_membership_status ON (civicrm_membership_status.id = civicrm_membership.status_id)
1755 WHERE membership_type_id = {$membershipValues['membership_type_id']} AND owner_membership_id = {$membershipValues['owner_membership_id']}
1756 AND is_current_member = 1";
1757 $result = CRM_Core_DAO
::singleValueQuery($query);
1758 if ($result < CRM_Utils_Array
::value('max_related', $membershipValues, PHP_INT_MAX
)) {
1759 CRM_Member_BAO_Membership
::create($membershipValues, CRM_Core_DAO
::$_nullArray);
1763 elseif ($action & CRM_Core_Action
::UPDATE
) {
1764 // if action is update and updated relationship do
1765 // not match with the existing
1766 // membership=>relationship then we need to
1767 // change the status of the membership record to expired for
1768 // previous relationship -- CRM-12078.
1769 // CRM-16087 we need to pass ownerMembershipId to isRelatedMembershipExpired function
1770 if (empty($params['relationship_ids']) && !empty($params['id'])) {
1771 $relIds = array($params['id']);
1774 $relIds = CRM_Utils_Array
::value('relationship_ids', $params);
1776 if (self
::isRelatedMembershipExpired($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId,
1777 $relIds) && !empty($membershipValues['owner_membership_id']
1778 ) && !empty($values[$mainRelatedContactId]['memberships'][$membershipValues['owner_membership_id']])) {
1779 $membershipValues['status_id'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus', 'Expired', 'id', 'label');
1780 $type = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $membershipValues['membership_type_id'], 'name', 'id');
1781 CRM_Member_BAO_Membership
::add($membershipValues);
1782 CRM_Core_Session
::setStatus(ts("Inherited membership {$type} status was changed to Expired due to the change in relationship type."), ts('Record Updated'), 'alert');
1790 * Helper function to check whether the membership is expired or not.
1792 * Function takes a list of related membership types and if it is not also passed a
1793 * relationship ID of that types evaluates whether the membership status should be changed to expired.
1795 * @param array $membershipTypeRelationshipTypeIDs
1796 * Relation type IDs related to the given membership type.
1797 * @param int $contactId
1798 * @param int $mainRelatedContactId
1799 * @param int $relTypeId
1800 * @param array $relIds
1804 public static function isRelatedMembershipExpired($membershipTypeRelationshipTypeIDs, $contactId, $mainRelatedContactId, $relTypeId, $relIds) {
1805 if (empty($membershipTypeRelationshipTypeIDs) ||
in_array($relTypeId, $membershipTypeRelationshipTypeIDs)) {
1809 if (empty($relIds)) {
1813 $relParamas = array(
1814 1 => array($contactId, 'Integer'),
1815 2 => array($mainRelatedContactId, 'Integer'),
1818 if ($contactId == $mainRelatedContactId) {
1819 $recordsFound = (int) CRM_Core_DAO
::singleValueQuery("SELECT COUNT(*) FROM civicrm_relationship WHERE relationship_type_id IN ( " . implode(',', $membershipTypeRelationshipTypeIDs) . " ) AND
1820 contact_id_a IN ( %1 ) OR contact_id_b IN ( %1 ) AND id IN (" . implode(',', $relIds) . ")", $relParamas);
1821 if ($recordsFound) {
1827 $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);
1829 if ($recordsFound) {
1837 * Get Current Employer for Contact.
1839 * @param $contactIds
1843 * array of the current employer
1845 public static function getCurrentEmployer($contactIds) {
1846 $contacts = implode(',', $contactIds);
1849 SELECT organization_name, id, employer_id
1850 FROM civicrm_contact
1851 WHERE id IN ( {$contacts} )
1854 $dao = CRM_Core_DAO
::executeQuery($query);
1855 $currentEmployer = array();
1856 while ($dao->fetch()) {
1857 $currentEmployer[$dao->id
]['org_id'] = $dao->employer_id
;
1858 $currentEmployer[$dao->id
]['org_name'] = $dao->organization_name
;
1861 return $currentEmployer;
1865 * Function to return list of permissioned contacts for a given contact and relationship type.
1867 * @param int $contactID
1868 * contact id whose permissioned contacts are to be found.
1869 * @param int $relTypeId
1870 * one or more relationship type id's.
1871 * @param string $name
1872 * @param string $contactType
1877 public static function getPermissionedContacts($contactID, $relTypeId = NULL, $name = NULL, $contactType = NULL) {
1878 $contacts = array();
1879 $args = array(1 => array($contactID, 'Integer'));
1880 $relationshipTypeClause = $contactTypeClause = '';
1883 // @todo relTypeId is only ever passed in as an int. Change this to reflect that -
1884 // probably being overly conservative by not doing so but working on stable release.
1885 $relationshipTypeClause = 'AND cr.relationship_type_id IN (%2) ';
1886 $args[2] = array($relTypeId, 'String');
1890 $contactTypeClause = ' AND cr.relationship_type_id = crt.id AND crt.contact_type_b = %3 ';
1891 $args[3] = array($contactType, 'String');
1895 SELECT cc.id as id, cc.sort_name as name
1896 FROM civicrm_relationship cr, civicrm_contact cc, civicrm_relationship_type crt
1898 cr.contact_id_a = %1 AND
1899 cr.is_permission_a_b = 1 AND
1900 IF(cr.end_date IS NULL, 1, (DATEDIFF( CURDATE( ), cr.end_date ) <= 0)) AND
1901 cr.is_active = 1 AND
1902 cc.id = cr.contact_id_b AND
1904 $relationshipTypeClause
1908 if (!empty($name)) {
1909 $name = CRM_Utils_Type
::escape($name, 'String');
1911 AND cc.sort_name LIKE '%$name%'";
1914 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1915 while ($dao->fetch()) {
1916 $contacts[$dao->id
] = array(
1917 'name' => $dao->name
,
1918 'value' => $dao->id
,
1926 * Merge relationships from otherContact to mainContact.
1928 * Called during contact merge operation
1930 * @param int $mainId
1931 * Contact id of main contact record.
1932 * @param int $otherId
1933 * Contact id of record which is going to merge.
1934 * @param array $sqls
1935 * (reference) array of sql statements to append to.
1937 * @see CRM_Dedupe_Merger::cpTables()
1939 public static function mergeRelationships($mainId, $otherId, &$sqls) {
1940 // Delete circular relationships
1941 $sqls[] = "DELETE FROM civicrm_relationship
1942 WHERE (contact_id_a = $mainId AND contact_id_b = $otherId)
1943 OR (contact_id_b = $mainId AND contact_id_a = $otherId)";
1945 // Delete relationship from other contact if main contact already has that relationship
1946 $sqls[] = "DELETE r2
1947 FROM civicrm_relationship r1, civicrm_relationship r2
1948 WHERE r1.relationship_type_id = r2.relationship_type_id
1951 r1.contact_id_a = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_b = r2.contact_id_b
1952 OR r1.contact_id_b = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_a = r2.contact_id_a
1954 (r1.contact_id_a = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_b = r2.contact_id_a
1955 OR r1.contact_id_b = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_a = r2.contact_id_b)
1956 AND r1.relationship_type_id IN (SELECT id FROM civicrm_relationship_type WHERE name_b_a = name_a_b)
1960 // Move relationships
1961 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_a = $mainId WHERE contact_id_a = $otherId";
1962 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_b = $mainId WHERE contact_id_b = $otherId";
1964 // Move current employer id (name will get updated later)
1965 $sqls[] = "UPDATE civicrm_contact SET employer_id = $mainId WHERE employer_id = $otherId";
1969 * Set 'is_valid' field to false for all relationships whose end date is in the past, ie. are expired.
1972 * True on success, false if error is encountered.
1974 public static function disableExpiredRelationships() {
1975 $query = "SELECT id FROM civicrm_relationship WHERE is_active = 1 AND end_date < CURDATE()";
1977 $dao = CRM_Core_DAO
::executeQuery($query);
1978 while ($dao->fetch()) {
1979 $result = CRM_Contact_BAO_Relationship
::setIsActive($dao->id
, FALSE);
1980 // Result will be NULL if error occurred. We abort early if error detected.
1981 if ($result == NULL) {
1989 * Function filters the query by possible relationships for the membership type.
1991 * It is intended to be called when constructing queries for the api (reciprocal & non-reciprocal)
1992 * and to add clauses to limit the return to those relationships which COULD inherit a membership type
1993 * (as opposed to those who inherit a particular membership
1995 * @param array $params
1997 * @param null $direction
1999 * @return array|void
2001 public static function membershipTypeToRelationshipTypes(&$params, $direction = NULL) {
2002 $membershipType = civicrm_api3('membership_type', 'getsingle', array(
2003 'id' => $params['membership_type_id'],
2004 'return' => 'relationship_type_id, relationship_direction',
2006 $relationshipTypes = $membershipType['relationship_type_id'];
2007 if (empty($relationshipTypes)) {
2010 // if we don't have any contact data we can only filter on type
2011 if (empty($params['contact_id']) && empty($params['contact_id_a']) && empty($params['contact_id_a'])) {
2012 $params['relationship_type_id'] = array('IN' => $relationshipTypes);
2016 $relationshipDirections = (array) $membershipType['relationship_direction'];
2017 // if we have contact_id_a OR contact_id_b we can make a call here
2018 // if we have contact??
2019 foreach ($relationshipDirections as $index => $mtdirection) {
2020 if (isset($params['contact_id_a']) && $mtdirection == 'a_b' ||
$direction == 'a_b') {
2021 $types[] = $relationshipTypes[$index];
2023 if (isset($params['contact_id_b']) && $mtdirection == 'b_a' ||
$direction == 'b_a') {
2024 $types[] = $relationshipTypes[$index];
2027 if (!empty($types)) {
2028 $params['relationship_type_id'] = array('IN' => $types);
2030 elseif (!empty($clauses)) {
2031 return explode(' OR ', $clauses);
2034 // effectively setting it to return no results
2035 $params['relationship_type_id'] = 0;
2042 * Wrapper for contact relationship selector.
2044 * @param array $params
2045 * Associated array for params record id.
2048 * associated array of contact relationships
2050 public static function getContactRelationshipSelector(&$params) {
2051 // format the params
2052 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2053 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
2055 if ($params['context'] == 'past') {
2056 $relationshipStatus = CRM_Contact_BAO_Relationship
::INACTIVE
;
2058 elseif ($params['context'] == 'all') {
2059 $relationshipStatus = CRM_Contact_BAO_Relationship
::ALL
;
2062 $relationshipStatus = CRM_Contact_BAO_Relationship
::CURRENT
;
2065 // check logged in user for permission
2066 $page = new CRM_Core_Page();
2067 CRM_Contact_Page_View
::checkUserPermission($page, $params['contact_id']);
2068 $permissions = array($page->_permission
);
2069 if ($page->_permission
== CRM_Core_Permission
::EDIT
) {
2070 $permissions[] = CRM_Core_Permission
::DELETE
;
2072 $mask = CRM_Core_Action
::mask($permissions);
2074 $permissionedContacts = TRUE;
2075 if ($params['context'] != 'user') {
2076 $links = CRM_Contact_Page_View_Relationship
::links();
2079 $links = CRM_Contact_Page_View_UserDashBoard
::links();
2082 // get contact relationships
2083 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
2084 $relationshipStatus,
2085 $params['rp'], 0, 0,
2087 $permissionedContacts,
2091 $contactRelationships = array();
2092 $params['total'] = $relationships['total_relationships'];
2093 unset($relationships['total_relationships']);
2094 if (!empty($relationships)) {
2096 $displayName = CRM_Contact_BAO_Contact
::displayName($params['contact_id']);
2099 foreach ($relationships as $relationshipId => $values) {
2100 $relationship = array();
2102 $relationship['DT_RowId'] = $values['id'];
2103 $relationship['DT_RowClass'] = 'crm-entity';
2104 if ($values['is_active'] == 0) {
2105 $relationship['DT_RowClass'] .= ' disabled';
2108 $relationship['DT_RowAttr'] = array();
2109 $relationship['DT_RowAttr']['data-entity'] = 'relationship';
2110 $relationship['DT_RowAttr']['data-id'] = $values['id'];
2112 //Add image icon for related contacts: CRM-14919; CRM-19668
2113 $contactType = (!empty($values['contact_sub_type'])) ?
$values['contact_sub_type'] : $values['contact_type'];
2114 $icon = CRM_Contact_BAO_Contact_Utils
::getImage($contactType,
2118 $relationship['sort_name'] = $icon . ' ' . CRM_Utils_System
::href(
2120 'civicrm/contact/view',
2121 "reset=1&cid={$values['cid']}");
2123 $relationship['relation'] = CRM_Utils_System
::href(
2124 $values['relation'],
2125 'civicrm/contact/view/rel',
2126 "action=view&reset=1&cid={$values['cid']}&id={$values['id']}&rtype={$values['rtype']}");
2128 if (!empty($values['description'])) {
2129 $relationship['relation'] .= "<p class='description'>{$values['description']}</p>";
2132 if ($params['context'] == 'current') {
2133 $smarty = CRM_Core_Smarty
::singleton();
2137 'permContact' => $params['contact_id'],
2138 'permDisplayName' => $displayName,
2139 'otherContact' => $values['cid'],
2140 'otherDisplayName' => $values['display_name'],
2141 'columnKey' => 'sort_name',
2144 'permContact' => $values['cid'],
2145 'permDisplayName' => $values['display_name'],
2146 'otherContact' => $params['contact_id'],
2147 'otherDisplayName' => $displayName,
2148 'columnKey' => 'relation',
2152 foreach ($contactCombos as $combo) {
2153 foreach ([CRM_Contact_BAO_Relationship
::EDIT
, CRM_Contact_BAO_Relationship
::VIEW
] as $permType) {
2154 $smarty->assign('permType', $permType);
2155 if (($combo['permContact'] == $values['contact_id_a'] and $values['is_permission_a_b'] == $permType)
2156 ||
($combo['permContact'] == $values['contact_id_b'] and $values['is_permission_b_a'] == $permType)
2158 $smarty->assign('permDisplayName', $combo['permDisplayName']);
2159 $smarty->assign('otherDisplayName', $combo['otherDisplayName']);
2160 $relationship[$combo['columnKey']] .= $smarty->fetch('CRM/Contact/Page/View/RelationshipPerm.tpl');
2166 $relationship['start_date'] = CRM_Utils_Date
::customFormat($values['start_date']);
2167 $relationship['end_date'] = CRM_Utils_Date
::customFormat($values['end_date']);
2168 $relationship['city'] = $values['city'];
2169 $relationship['state'] = $values['state'];
2170 $relationship['email'] = $values['email'];
2171 $relationship['phone'] = $values['phone'];
2172 $relationship['links'] = $values['action'];
2174 array_push($contactRelationships, $relationship);
2178 $relationshipsDT = array();
2179 $relationshipsDT['data'] = $contactRelationships;
2180 $relationshipsDT['recordsTotal'] = $params['total'];
2181 $relationshipsDT['recordsFiltered'] = $params['total'];
2183 return $relationshipsDT;
2189 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2190 if ($fieldName === 'relationship_type_id') {
2191 return self
::buildRelationshipTypeOptions($props);
2194 return parent
::buildOptions($fieldName, $context, $props);
2198 * Builds a list of options available for relationship types
2200 * @param array $params
2201 * - contact_type: Limits by contact type on the "A" side
2202 * - relationship_id: Used to find the value for contact type for "B" side.
2203 * If contact_a matches provided contact_id then type of contact_b will
2204 * be used. Otherwise uses type of contact_a. Must be used with contact_id
2205 * - contact_id: Limits by contact types of this contact on the "A" side
2206 * - is_form: Returns array with keys indexed for use in a quickform
2207 * - relationship_direction: For relationship types with duplicate names
2208 * on both sides, defines which option should be returned, a_b or b_a
2212 public static function buildRelationshipTypeOptions($params = array()) {
2213 $contactId = CRM_Utils_Array
::value('contact_id', $params);
2214 $direction = CRM_Utils_Array
::value('relationship_direction', $params, 'a_b');
2215 $relationshipId = CRM_Utils_Array
::value('relationship_id', $params);
2216 $contactType = CRM_Utils_Array
::value('contact_type', $params);
2217 $isForm = CRM_Utils_Array
::value('is_form', $params);
2220 // getContactRelationshipType will return an empty set if these are not set
2221 if (!$contactId && !$relationshipId && !$contactType) {
2225 $labels = self
::getContactRelationshipType(
2238 $names = self
::getContactRelationshipType(
2247 // ensure $names contains only entries in $labels
2248 $names = array_intersect_key($names, $labels);
2250 $nameToLabels = array_combine($names, $labels);
2252 return $nameToLabels;
2256 * Process the params from api, form and check if current
2257 * employer should be set or unset.
2259 * @param array $params
2260 * @param int $relationshipId
2261 * @param int|NULL $updatedRelTypeID
2264 * TRUE if current employer needs to be cleared.
2266 public static function isCurrentEmployerNeedingToBeCleared($params, $relationshipId, $updatedRelTypeID = NULL) {
2267 $existingTypeID = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Relationship', $relationshipId, 'relationship_type_id');
2268 $existingTypeName = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType', $existingTypeID, 'name_b_a');
2269 $updatedRelTypeID = $updatedRelTypeID ?
$updatedRelTypeID : $existingTypeID;
2271 if ($existingTypeName !== 'Employer of') {
2274 //Clear employer if relationship is expired.
2275 if (!empty($params['end_date']) && strtotime($params['end_date']) < time()) {
2278 //current employer checkbox is disabled on the form.
2279 //inactive or relationship type(employer of) is updated.
2280 if ((isset($params['is_current_employer']) && empty($params['is_current_employer']))
2281 ||
((isset($params['is_active']) && empty($params['is_active'])))
2282 ||
$existingTypeID != $updatedRelTypeID) {