3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
35 class CRM_Contact_BAO_Relationship
extends CRM_Contact_DAO_Relationship
{
38 * Various constants to indicate different type of relationships
42 const PAST
= 1, DISABLED
= 2, CURRENT
= 4, INACTIVE
= 8;
45 * Create function. (Use the API instead)
46 * Note that the previous create function has been renamed 'createMultiple'
47 * and this is new in 4.6
48 * All existing calls have been changed to createMultiple except the api call - however, it is recommended
49 * that you call that as the end to end testing here is based on the api & refactoring may still be done
50 * @param array $params
51 * @return \CRM_Contact_BAO_Relationship
52 * @throws \CRM_Core_Exception
54 public static function create(&$params) {
55 self
::setContactABFromIDs($params);
56 if (self
::checkDuplicateRelationship($params, $params['contact_id_a'], $params['contact_id_b'], CRM_Utils_Array
::value('id', $params, 0))) {
57 throw new CRM_Core_Exception('Duplicate Relationship');
59 if (self
::checkValidRelationship($params, $params, 0)) {
60 throw new CRM_Core_Exception('Invalid Relationship');
62 $relationship = self
::add($params);
63 if (!empty($params['contact_id_a'])) {
64 $ids = array('contactTarget' => $relationship->contact_id_b
, 'contact' => $params['contact_id_a']);
65 CRM_Contact_BAO_Relationship
::relatedMemberships($params['contact_id_a'], $values, $ids, (empty($params['id']) ? CRM_Core_Action
::ADD
: CRM_Core_Action
::UPDATE
));
67 self
::addRecent($params, $relationship);
72 * Takes an associative array and creates a relationship object
73 * @deprecated For single creates use the api instead (it's tested).
74 * For multiple a new variant of this function needs to be written and migrated to as this is a bit
77 * @param array $params
78 * (reference ) an assoc array of name/value pairs.
80 * The array that holds all the db ids.
81 * per http://wiki.civicrm.org/confluence/display/CRM/Database+layer
82 * "we are moving away from the $ids param "
84 * @return CRM_Contact_BAO_Relationship
86 public static function createMultiple(&$params, $ids = array()) {
87 $valid = $invalid = $duplicate = $saved = 0;
88 $relationships = $relationshipIds = array();
89 $relationshipId = CRM_Utils_Array
::value('relationship', $ids, CRM_Utils_Array
::value('id', $params));
90 //CRM-9015 - the hooks are called here & in add (since add doesn't call create)
91 // but in future should be tidied per ticket
92 if (empty($relationshipId)) {
94 $action = CRM_Core_Action
::ADD
;
98 $action = CRM_Core_Action
::UPDATE
;
101 CRM_Utils_Hook
::pre($hook, 'Relationship', $relationshipId, $params);
103 if (!$relationshipId) {
104 // creating a new relationship
105 $dataExists = self
::dataExists($params);
107 return array(FALSE, TRUE, FALSE, FALSE, NULL);
109 $relationshipIds = array();
110 foreach ($params['contact_check'] as $key => $value) {
112 // check if the relationship is valid between contacts.
113 // step 1: check if the relationship is valid if not valid skip and keep the count
114 // step 2: check the if two contacts already have a relationship if yes skip and keep the count
115 // step 3: if valid relationship then add the relation and keep the count
118 $errors = self
::checkValidRelationship($params, $ids, $key);
125 self
::checkDuplicateRelationship(
127 CRM_Utils_Array
::value('contact', $ids),
135 self
::setContactABFromIDs($params, $ids, $key);
136 $relationship = self
::add($params);
137 $relationshipIds[] = $relationship->id
;
138 $relationships[$relationship->id
] = $relationship;
141 // editing the relationship
144 // check for duplicate relationship
145 // @todo this code doesn't cope well with updates - causes e-Notices.
146 // API has a lot of code to work around
147 // this but should review this code & remove the extra handling from the api
148 // it seems doubtful any of this is relevant if the contact fields & relationship
149 // type fields are not set
151 self
::checkDuplicateRelationship(
153 CRM_Utils_Array
::value('contact', $ids),
154 $ids['contactTarget'],
159 return array($valid, $invalid, $duplicate, $saved, NULL);
162 $validContacts = TRUE;
163 //validate contacts in update mode also.
164 if (!empty($ids['contact']) && !empty($ids['contactTarget'])) {
165 if (self
::checkValidRelationship($params, $ids, $ids['contactTarget'])) {
166 $validContacts = FALSE;
170 if ($validContacts) {
171 // editing an existing relationship
172 $relationship = self
::add($params, $ids, $ids['contactTarget']);
173 $relationshipIds[] = $relationship->id
;
174 $relationships[$relationship->id
] = $relationship;
179 // do not add to recent items for import, CRM-4399
180 if (!(!empty($params['skipRecentView']) ||
$invalid ||
$duplicate)) {
181 self
::addRecent($params, $relationship);
184 return array($valid, $invalid, $duplicate, $saved, $relationshipIds, $relationships);
188 * This is the function that check/add if the relationship created is valid
190 * @param array $params
191 * (reference ) an assoc array of name/value pairs.
193 * The array that holds all the db ids.
194 * @param int $contactId
195 * This is contact id for adding relationship.
197 * @return CRM_Contact_BAO_Relationship
199 public static function add(&$params, $ids = array(), $contactId = NULL) {
200 $relationshipId = CRM_Utils_Array
::value('relationship', $ids, CRM_Utils_Array
::value('id', $params));
203 if ($relationshipId) {
206 //@todo hook are called from create and add - remove one
207 CRM_Utils_Hook
::pre($hook, 'Relationship', $relationshipId, $params);
209 self
::setContactABFromIDs($params);
210 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
212 // explode the string with _ to get the relationship type id
213 // and to know which contact has to be inserted in
214 // contact_id_a and which one in contact_id_b
215 list($type) = explode('_', $relationshipTypes);
217 // check if the relationship type is Head of Household then update the
218 // household's primary contact with this contact.
220 CRM_Contact_BAO_Household
::updatePrimaryContact($params['contact_id_b'], $params['contact_id_a']);
223 $relationship = new CRM_Contact_BAO_Relationship();
224 //@todo this code needs to be updated for the possibility that not all fields are set
226 $relationship->contact_id_b
= $params['contact_id_b'];
227 $relationship->contact_id_a
= $params['contact_id_a'];
228 $relationship->relationship_type_id
= $type;
229 $relationship->id
= $relationshipId;
231 $dateFields = array('end_date', 'start_date');
233 foreach (self
::getdefaults() as $defaultField => $defaultValue) {
234 if (isset($params[$defaultField])) {
235 if (in_array($defaultField, $dateFields)) {
236 $relationship->$defaultField = CRM_Utils_Date
::format(CRM_Utils_Array
::value($defaultField, $params));
237 if (!$relationship->$defaultField) {
238 $relationship->$defaultField = 'NULL';
242 $relationship->$defaultField = $params[$defaultField];
245 elseif (!$relationshipId) {
246 $relationship->$defaultField = $defaultValue;
250 $relationship->save();
252 // add custom field values
253 if (!empty($params['custom'])) {
254 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_relationship', $relationship->id
);
257 $relationship->free();
259 CRM_Utils_Hook
::post($hook, 'Relationship', $relationship->id
, $relationship);
261 return $relationship;
265 * Add relationship to recent links
266 * @param array $params
267 * @param CRM_Contact_DAO_Relationship $relationship
269 public static function addRecent($params, $relationship) {
270 $url = CRM_Utils_System
::url('civicrm/contact/view/rel',
271 "action=view&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&context=home"
273 $session = CRM_Core_Session
::singleton();
274 $recentOther = array();
275 if (($session->get('userID') == $relationship->contact_id_a
) ||
276 CRM_Contact_BAO_Contact_Permission
::allow($relationship->contact_id_a
, CRM_Core_Permission
::EDIT
)
278 $rType = substr(CRM_Utils_Array
::value('relationship_type_id', $params), -3);
279 $recentOther = array(
280 'editUrl' => CRM_Utils_System
::url('civicrm/contact/view/rel',
281 "action=update&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
283 'deleteUrl' => CRM_Utils_System
::url('civicrm/contact/view/rel',
284 "action=delete&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
288 $title = CRM_Contact_BAO_Contact
::displayName($relationship->contact_id_a
) . ' (' . CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType',
289 $relationship->relationship_type_id
, 'label_a_b'
290 ) . ' ' . CRM_Contact_BAO_Contact
::displayName($relationship->contact_id_b
) . ')';
292 CRM_Utils_Recent
::add($title,
296 $relationship->contact_id_a
,
303 * Resolve passed in contact IDs to contact_id_a & contact_id_b
304 * @param array $params
306 * @param null $contactID
307 * @throws \CRM_Core_Exception
309 public static function setContactABFromIDs(&$params, $ids = array(), $contactID = NULL) {
310 if (!empty($params['contact_id_a']) && !empty($params['contact_id_b'])) {
313 if (empty($ids['contact'])) {
314 if (!empty($params['id'])) {
315 //let's load the missing ids here since other things tend to rely on them.
316 $fieldsToFill = array('contact_id_a', 'contact_id_b', 'relationship_type_id');
317 $result = CRM_Core_DAO
::executeQuery("SELECT " . implode(',', $fieldsToFill) . " FROM civicrm_relationship WHERE id = %1", array(
323 while ($result->fetch()) {
324 foreach ($fieldsToFill as $field) {
325 $params[$field] = !empty($params[$field]) ?
$params[$field] : $result->$field;
330 throw new CRM_Core_Exception('Cannot create relationship, insufficient contact IDs provided');
332 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
333 list($relationshipTypeID, $first, $second) = explode('_', $relationshipTypes);
334 if (empty($params['relationship_type_id'])) {
335 $params['relationship_type_id'] = $relationshipTypeID;
337 foreach (array('a', 'b') as $contactLetter) {
338 if (empty($params['contact_' . $contactLetter])) {
339 if ($first == $contactLetter) {
340 $params['contact_id_' . $contactLetter] = CRM_Utils_Array
::value('contact', $ids);
343 $params['contact_id_' . $contactLetter] = $contactID;
350 * Specifiy defaults for creating a relationship
353 * array of defaults for creating relationship
355 public static function getdefaults() {
358 'is_permission_a_b' => 0,
359 'is_permission_b_a' => 0,
361 'start_date' => 'NULL',
363 'end_date' => 'NULL',
369 * Check if there is data to create the object
371 * @param array $params
372 * (reference ) an assoc array of name/value pairs.
376 public static function dataExists(&$params) {
377 // return if no data present
378 if (!is_array(CRM_Utils_Array
::value('contact_check', $params))) {
385 * Get get list of relationship type based on the contact type.
387 * @param int $contactId
388 * This is the contact id of the current contact.
389 * @param null $contactSuffix
390 * @param string $relationshipId
391 * The id of the existing relationship if any.
392 * @param string $contactType
395 * If true returns relationship types in both the direction.
396 * @param string $column
397 * Name/label that going to retrieve from db.
398 * @param bool $biDirectional
399 * @param string $contactSubType
400 * Includes relationshiptypes between this subtype.
401 * @param bool $onlySubTypeRelationTypes
402 * If set only subtype which is passed by $contactSubType.
403 * related relationshiptypes get return
407 * array reference of all relationship types with context to current contact.
409 public static function getContactRelationshipType(
411 $contactSuffix = NULL,
412 $relationshipId = NULL,
416 $biDirectional = TRUE,
417 $contactSubType = NULL,
418 $onlySubTypeRelationTypes = FALSE
420 $allRelationshipType = array();
421 $relationshipType = array();
422 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType($column);
424 $otherContactType = NULL;
425 if ($relationshipId) {
426 $relationship = new CRM_Contact_DAO_Relationship();
427 $relationship->id
= $relationshipId;
428 if ($relationship->find(TRUE)) {
429 $contact = new CRM_Contact_DAO_Contact();
430 $contact->id
= ($relationship->contact_id_a
=== $contactId) ?
$relationship->contact_id_b
: $relationship->contact_id_a
;
432 if ($contact->find(TRUE)) {
433 $otherContactType = $contact->contact_type
;
434 //CRM-5125 for contact subtype specific relationshiptypes
435 if ($contact->contact_sub_type
) {
436 $otherContactSubType = $contact->contact_sub_type
;
442 $contactSubType = array();
444 $contactType = CRM_Contact_BAO_Contact
::getContactType($contactId);
445 $contactSubType = CRM_Contact_BAO_Contact
::getContactSubType($contactId);
448 foreach ($allRelationshipType as $key => $value) {
449 // the contact type is required or matches
450 if (((!$value['contact_type_a']) ||
451 $value['contact_type_a'] == $contactType
453 // the other contact type is required or present or matches
454 ((!$value['contact_type_b']) ||
455 (!$otherContactType) ||
456 $value['contact_type_b'] == $otherContactType
458 (in_array($value['contact_sub_type_a'], $contactSubType) ||
459 in_array($value['contact_sub_type_b'], $contactSubType) ||
460 (!$value['contact_sub_type_a'] && !$onlySubTypeRelationTypes)
463 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
466 if (((!$value['contact_type_b']) ||
467 $value['contact_type_b'] == $contactType
469 ((!$value['contact_type_a']) ||
470 (!$otherContactType) ||
471 $value['contact_type_a'] == $otherContactType
473 (in_array($value['contact_sub_type_b'], $contactSubType) ||
474 in_array($value['contact_sub_type_a'], $contactSubType) ||
475 (!$value['contact_sub_type_b'] && !$onlySubTypeRelationTypes)
478 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
482 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
483 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
487 if ($biDirectional) {
488 // lets clean up the data and eliminate all duplicate values
489 // (i.e. the relationship is bi-directional)
490 $relationshipType = array_unique($relationshipType);
493 // sort the relationshipType in ascending order CRM-7736
494 asort($relationshipType);
495 return $relationshipType;
502 * @return CRM_Contact_DAO_Relationship
504 public static function clearCurrentEmployer($id, $action) {
505 $relationship = new CRM_Contact_DAO_Relationship();
506 $relationship->id
= $id;
507 $relationship->find(TRUE);
509 //to delete relationship between household and individual \
510 //or between individual and orgnization
511 if (($action & CRM_Core_Action
::DISABLE
) ||
($action & CRM_Core_Action
::DELETE
)) {
512 $relTypes = CRM_Utils_Array
::index(array('name_a_b'), CRM_Core_PseudoConstant
::relationshipType('name'));
513 if ($relationship->relationship_type_id
== $relTypes['Employee of']['id'] ||
514 $relationship->relationship_type_id
== $relTypes['Household Member of']['id']
516 $sharedContact = new CRM_Contact_DAO_Contact();
517 $sharedContact->id
= $relationship->contact_id_a
;
518 $sharedContact->find(TRUE);
520 if ($relationship->relationship_type_id
== 4 && $relationship->contact_id_b
== $sharedContact->employer_id
) {
521 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($relationship->contact_id_a
);
525 return $relationship;
529 * Delete the relationship
537 public static function del($id) {
538 // delete from relationship table
539 CRM_Utils_Hook
::pre('delete', 'Relationship', $id, CRM_Core_DAO
::$_nullArray);
541 $relationship = self
::clearCurrentEmployer($id, CRM_Core_Action
::DELETE
);
542 if (CRM_Core_Permission
::access('CiviMember')) {
543 // create $params array which isrequired to delete memberships
544 // of the related contacts.
546 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
547 'contact_check' => array($relationship->contact_id_b
=> 1),
551 // calling relatedMemberships to delete the memberships of
553 self
::relatedMemberships($relationship->contact_id_a
,
556 CRM_Core_Action
::DELETE
,
561 $relationship->delete();
562 CRM_Core_Session
::setStatus(ts('Selected relationship has been deleted successfully.'), ts('Record Deleted'), 'success');
564 CRM_Utils_Hook
::post('delete', 'Relationship', $id, $relationship);
566 // delete the recently created Relationship
567 $relationshipRecent = array(
569 'type' => 'Relationship',
571 CRM_Utils_Recent
::del($relationshipRecent);
573 return $relationship;
577 * Disable/enable the relationship
585 public static function disableEnableRelationship($id, $action) {
586 $relationship = self
::clearCurrentEmployer($id, $action);
587 if (CRM_Core_Permission
::access('CiviMember')) {
588 // create $params array which isrequired to delete memberships
589 // of the related contacts.
591 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
592 'contact_check' => array($relationship->contact_id_b
=> 1),
596 // calling relatedMemberships to delete/add the memberships of
598 if ($action & CRM_Core_Action
::DISABLE
) {
599 CRM_Contact_BAO_Relationship
::relatedMemberships($relationship->contact_id_a
,
602 CRM_Core_Action
::DELETE
,
606 elseif ($action & CRM_Core_Action
::ENABLE
) {
607 $ids['contact'] = $relationship->contact_id_a
;
608 CRM_Contact_BAO_Relationship
::relatedMemberships($relationship->contact_id_a
,
611 CRM_Core_Action
::ADD
,
619 * Delete the object records that are associated with this contact
621 * @param int $contactId
622 * Id of the contact to delete.
626 public static function deleteContact($contactId) {
627 $relationship = new CRM_Contact_DAO_Relationship();
628 $relationship->contact_id_a
= $contactId;
629 $relationship->delete();
631 $relationship = new CRM_Contact_DAO_Relationship();
632 $relationship->contact_id_b
= $contactId;
633 $relationship->delete();
635 CRM_Contact_BAO_Household
::updatePrimaryContact(NULL, $contactId);
639 * Get the other contact in a relationship
644 * $returns returns the contact ids in the realtionship
646 * @return \CRM_Contact_DAO_Relationship
648 public static function getContactIds($id) {
649 $relationship = new CRM_Contact_DAO_Relationship();
651 $relationship->id
= $id;
652 $relationship->selectAdd();
653 $relationship->selectAdd('contact_id_a, contact_id_b');
654 $relationship->find(TRUE);
656 return $relationship;
660 * Check if the relationship type selected between two contacts is correct
662 * @param int $contact_a
664 * @param int $contact_b
666 * @param int $relationshipTypeId
667 * Relationship type id.
670 * true if it is valid relationship else false
672 public static function checkRelationshipType($contact_a, $contact_b, $relationshipTypeId) {
673 $relationshipType = new CRM_Contact_DAO_RelationshipType();
674 $relationshipType->id
= $relationshipTypeId;
675 $relationshipType->selectAdd();
676 $relationshipType->selectAdd('contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b');
677 if ($relationshipType->find(TRUE)) {
678 $contact_type_a = CRM_Contact_BAO_Contact
::getContactType($contact_a);
679 $contact_type_b = CRM_Contact_BAO_Contact
::getContactType($contact_b);
681 $contact_sub_type_a = CRM_Contact_BAO_Contact
::getContactSubType($contact_a);
682 $contact_sub_type_b = CRM_Contact_BAO_Contact
::getContactSubType($contact_b);
684 if (((!$relationshipType->contact_type_a
) ||
($relationshipType->contact_type_a
== $contact_type_a)) &&
685 ((!$relationshipType->contact_type_b
) ||
($relationshipType->contact_type_b
== $contact_type_b)) &&
686 ((!$relationshipType->contact_sub_type_a
) ||
(in_array($relationshipType->contact_sub_type_a
,
689 ((!$relationshipType->contact_sub_type_b
) ||
(in_array($relationshipType->contact_sub_type_b
,
703 * This function does the validtion for valid relationship
705 * @param array $params
706 * This array contains the values there are subitted by the form.
708 * The array that holds all the db ids.
709 * @param int $contactId
710 * This is contact id for adding relationship.
714 public static function checkValidRelationship($params, $ids, $contactId) {
716 self
::setContactABFromIDs($params, $ids, $contactId);
717 // get the string of relationship type
718 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
719 list($type) = explode('_', $relationshipTypes);
720 // function to check if the relationship selected is correct
721 // i.e. employer relationship can exit between Individual and Organization (not between Individual and Individual)
722 if (!CRM_Contact_BAO_Relationship
::checkRelationshipType($params['contact_id_a'], $params['contact_id_b'], $type)) {
723 $errors = 'Please select valid relationship between these two contacts.';
729 * This function checks for duplicate relationship
731 * @param array $params
732 * (reference ) an assoc array of name/value pairs.
734 * This the id of the contact whom we are adding relationship.
735 * @param int $contactId
736 * This is contact id for adding relationship.
737 * @param int $relationshipId
738 * This is relationship id for the contact.
741 * true if record exists else false
743 public static function checkDuplicateRelationship(&$params, $id, $contactId = 0, $relationshipId = 0) {
744 $relationshipTypeId = CRM_Utils_Array
::value('relationship_type_id', $params);
745 list($type) = explode('_', $relationshipTypeId);
749 FROM civicrm_relationship
750 WHERE relationship_type_id = " . CRM_Utils_Type
::escape($type, 'Integer');
753 * CRM-11792 - date fields from API are in ISO format, but this function
754 * supports date arrays BAO has increasingly standardised to ISO format
755 * so I believe this function should support ISO rather than make API
756 * format it - however, need to support array format for now to avoid breakage
757 * @ time of writing this function is called from Relationship::createMultiple (twice)
758 * CRM_BAO_Contact_Utils::clearCurrentEmployer (seemingly without dates)
759 * CRM_Contact_Form_Task_AddToOrganization::postProcess &
760 * CRM_Contact_Form_Task_AddToHousehold::postProcess
761 * (I don't think the last 2 support dates but not sure
764 $dateFields = array('end_date', 'start_date');
765 foreach ($dateFields as $dateField) {
766 if (array_key_exists($dateField, $params)) {
767 if (empty($params[$dateField]) ||
$params[$dateField] == 'null') {
768 //this is most likely coming from an api call & probably loaded
769 // from the DB to deal with some of the
770 // other myriad of excessive checks still in place both in
771 // the api & the create functions
772 $queryString .= " AND $dateField IS NULL";
775 elseif (is_array($params[$dateField])) {
776 $queryString .= " AND $dateField = " .
777 CRM_Utils_Type
::escape(CRM_Utils_Date
::format($params[$dateField]), 'Date');
780 $queryString .= " AND $dateField = " .
781 CRM_Utils_Type
::escape($params[$dateField], 'Date');
787 " AND ( ( contact_id_a = " . CRM_Utils_Type
::escape($id, 'Integer') .
788 " AND contact_id_b = " . CRM_Utils_Type
::escape($contactId, 'Integer') .
789 " ) OR ( contact_id_a = " . CRM_Utils_Type
::escape($contactId, 'Integer') .
790 " AND contact_id_b = " . CRM_Utils_Type
::escape($id, 'Integer') . " ) ) ";
792 //if caseId is provided, include it duplicate checking.
793 if ($caseId = CRM_Utils_Array
::value('case_id', $params)) {
794 $queryString .= " AND case_id = " . CRM_Utils_Type
::escape($caseId, 'Integer');
797 if ($relationshipId) {
798 $queryString .= " AND id !=" . CRM_Utils_Type
::escape($relationshipId, 'Integer');
801 $relationship = new CRM_Contact_BAO_Relationship();
802 $relationship->query($queryString);
803 $relationship->fetch();
804 $relationship->free();
805 return ($relationship->id
) ?
TRUE : FALSE;
809 * Update the is_active flag in the db
812 * Id of the database record.
813 * @param bool $is_active
814 * Value we want to set the is_active field.
816 * @throws CiviCRM_API3_Exception
818 * DAO object on success, null otherwise
820 public static function setIsActive($id, $is_active) {
821 // as both the create & add functions have a bunch of logic in them that
822 // doesn't seem to cope with a normal update we will call the api which
823 // has tested handling for this
824 // however, a longer term solution would be to simplify the add, create & api functions
825 // to be more standard. It is debatable @ that point whether it's better to call the BAO
826 // direct as the api is more tested.
827 $result = civicrm_api('relationship', 'create', array(
829 'is_active' => $is_active,
833 if (is_array($result) && !empty($result['is_error']) && $result['error_message'] != 'Relationship already exists') {
834 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array
::value('error_code', $result, 'undefined'), $result);
837 // call (undocumented possibly deprecated) hook
838 CRM_Utils_Hook
::enableDisable('CRM_Contact_BAO_Relationship', $id, $is_active);
844 * Given the list of params in the params array, fetch the object
845 * and store the values in the values array
847 * @param array $params
848 * Input parameters to find object.
849 * @param array $values
850 * Output values of the object.
853 * (reference) the values that could be potentially assigned to smarty
855 public static function &getValues(&$params, &$values) {
856 if (empty($params)) {
861 // get the specific number of relationship or all relationships.
862 if (!empty($params['numRelationship'])) {
863 $v['data'] = &CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'], NULL, $params['numRelationship']);
866 $v['data'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id']);
869 // get the total count of relationships
870 $v['totalCount'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'], NULL, NULL, TRUE);
872 $values['relationship']['data'] = &$v['data'];
873 $values['relationship']['totalCount'] = &$v['totalCount'];
879 * Helper function to form the sql for relationship retrieval
881 * @param int $contactId
884 * (check const at top of file).
885 * @param int $numRelationship
886 * No of relationships to display (limit).
888 * Get the no of relationships.
889 * $param int $relationshipId relationship id
890 * @param int $relationshipId
891 * @param string $direction
892 * The direction we are interested in a_b or b_a.
893 * @param array $params
894 * Array of extra values including relationship_type_id per api spec.
897 * [select, from, where]
899 public static function makeURLClause($contactId, $status, $numRelationship, $count, $relationshipId, $direction, $params = array()) {
900 $select = $from = $where = '';
904 if ($direction == 'a_b') {
905 $select .= ' SELECT count(DISTINCT civicrm_relationship.id) as cnt1, 0 as cnt2 ';
908 $select .= ' SELECT 0 as cnt1, count(DISTINCT civicrm_relationship.id) as cnt2 ';
912 $select .= ' SELECT civicrm_relationship.id as civicrm_relationship_id,
913 civicrm_contact.sort_name as sort_name,
914 civicrm_contact.display_name as display_name,
915 civicrm_contact.job_title as job_title,
916 civicrm_contact.employer_id as employer_id,
917 civicrm_contact.organization_name as organization_name,
918 civicrm_address.street_address as street_address,
919 civicrm_address.city as city,
920 civicrm_address.postal_code as postal_code,
921 civicrm_state_province.abbreviation as state,
922 civicrm_country.name as country,
923 civicrm_email.email as email,
924 civicrm_contact.contact_type as contact_type,
925 civicrm_phone.phone as phone,
926 civicrm_contact.id as civicrm_contact_id,
927 civicrm_relationship.contact_id_b as contact_id_b,
928 civicrm_relationship.contact_id_a as contact_id_a,
929 civicrm_relationship_type.id as civicrm_relationship_type_id,
930 civicrm_relationship.start_date as start_date,
931 civicrm_relationship.end_date as end_date,
932 civicrm_relationship.description as description,
933 civicrm_relationship.is_active as is_active,
934 civicrm_relationship.is_permission_a_b as is_permission_a_b,
935 civicrm_relationship.is_permission_b_a as is_permission_b_a,
936 civicrm_relationship.case_id as case_id';
938 if ($direction == 'a_b') {
939 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
940 civicrm_relationship_type.label_b_a as relation ';
943 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
944 civicrm_relationship_type.label_a_b as relation ';
949 FROM civicrm_relationship
950 INNER JOIN civicrm_relationship_type ON ( civicrm_relationship.relationship_type_id = civicrm_relationship_type.id )
951 INNER JOIN civicrm_contact ";
952 if ($direction == 'a_b') {
953 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_a ) ';
956 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_b ) ';
959 LEFT JOIN civicrm_address ON (civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1)
960 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
961 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id AND civicrm_email.is_primary = 1)
962 LEFT JOIN civicrm_state_province ON (civicrm_address.state_province_id = civicrm_state_province.id)
963 LEFT JOIN civicrm_country ON (civicrm_address.country_id = civicrm_country.id)
965 $where = 'WHERE ( 1 )';
967 if ($direction == 'a_b') {
968 $where .= ' AND civicrm_relationship.contact_id_b = ' . CRM_Utils_Type
::escape($contactId, 'Positive');
971 $where .= ' AND civicrm_relationship.contact_id_a = ' . CRM_Utils_Type
::escape($contactId, 'Positive') . '
972 AND civicrm_relationship.contact_id_a != civicrm_relationship.contact_id_b ';
975 if ($relationshipId) {
976 $where .= ' AND civicrm_relationship.id = ' . CRM_Utils_Type
::escape($relationshipId, 'Positive');
979 $date = date('Y-m-d');
980 if ($status == self
::PAST
) {
981 //this case for showing past relationship
982 $where .= ' AND civicrm_relationship.is_active = 1 ';
983 $where .= " AND civicrm_relationship.end_date < '" . $date . "'";
985 elseif ($status == self
::DISABLED
) {
986 // this case for showing disabled relationship
987 $where .= ' AND civicrm_relationship.is_active = 0 ';
989 elseif ($status == self
::CURRENT
) {
990 //this case for showing current relationship
991 $where .= ' AND civicrm_relationship.is_active = 1 ';
992 $where .= " AND (civicrm_relationship.end_date >= '" . $date . "' OR civicrm_relationship.end_date IS NULL) ";
994 elseif ($status == self
::INACTIVE
) {
995 //this case for showing inactive relationships
996 $where .= " AND (civicrm_relationship.end_date < '" . $date . "'";
997 $where .= ' OR civicrm_relationship.is_active = 0 )';
1001 $where .= ' AND civicrm_contact.is_deleted = 0';
1002 if (!empty($params['membership_type_id']) && empty($params['relationship_type_id'])) {
1003 $where .= self
::membershipTypeToRelationshipTypes($params, $direction);
1005 if (!empty($params['relationship_type_id'])) {
1006 if (is_array($params['relationship_type_id'])) {
1007 $where .= " AND " . CRM_Core_DAO
::createSQLFilter('relationship_type_id', $params['relationship_type_id'], 'Integer');
1010 $where .= ' AND relationship_type_id = ' . CRM_Utils_Type
::escape($params['relationship_type_id'], 'Positive');
1013 if ($direction == 'a_b') {
1014 $where .= ' ) UNION ';
1020 return array($select, $from, $where);
1024 * Get a list of relationships
1026 * @param int $contactId
1028 * @param int $status
1029 * 1: Past 2: Disabled 3: Current.
1030 * @param int $numRelationship
1031 * No of relationships to display (limit).
1033 * Get the no of relationships.
1034 * @param int $relationshipId
1035 * @param array $links
1036 * the list of links to display
1037 * @param int $permissionMask
1038 * the permission mask to be applied for the actions
1039 * @param bool $permissionedContact
1040 * to return only permissioned Contact
1041 * @param array $params
1044 * relationship records
1046 public static function getRelationship(
1048 $status = 0, $numRelationship = 0,
1049 $count = 0, $relationshipId = 0,
1050 $links = NULL, $permissionMask = NULL,
1051 $permissionedContact = FALSE,
1055 if (!$contactId && !$relationshipId) {
1059 list($select1, $from1, $where1) = self
::makeURLClause($contactId, $status, $numRelationship,
1060 $count, $relationshipId, 'a_b', $params
1062 list($select2, $from2, $where2) = self
::makeURLClause($contactId, $status, $numRelationship,
1063 $count, $relationshipId, 'b_a', $params
1066 $order = $limit = '';
1068 if (empty($params['sort'])) {
1069 $order = ' ORDER BY civicrm_relationship_type_id, sort_name ';
1072 $order = " ORDER BY {$params['sort']} ";
1076 if (!empty($params['offset']) && $params['offset'] > 0) {
1077 $offset = $params['offset'];
1080 if ($numRelationship) {
1081 $limit = " LIMIT {$offset}, $numRelationship";
1085 // building the query string
1086 $queryString = $select1 . $from1 . $where1 . $select2 . $from2 . $where2 . $order . $limit;
1088 $relationship = new CRM_Contact_DAO_Relationship();
1090 $relationship->query($queryString);
1093 $relationshipCount = 0;
1094 while ($relationship->fetch()) {
1095 $relationshipCount +
= $relationship->cnt1 +
$relationship->cnt2
;
1097 return $relationshipCount;
1102 if ($status != self
::INACTIVE
) {
1104 $mask = array_sum(array_keys($links));
1105 if ($mask & CRM_Core_Action
::DISABLE
) {
1106 $mask -= CRM_Core_Action
::DISABLE
;
1108 if ($mask & CRM_Core_Action
::ENABLE
) {
1109 $mask -= CRM_Core_Action
::ENABLE
;
1112 if ($status == self
::CURRENT
) {
1113 $mask |
= CRM_Core_Action
::DISABLE
;
1115 elseif ($status == self
::DISABLED
) {
1116 $mask |
= CRM_Core_Action
::ENABLE
;
1118 $mask = $mask & $permissionMask;
1121 while ($relationship->fetch()) {
1122 $rid = $relationship->civicrm_relationship_id
;
1123 $cid = $relationship->civicrm_contact_id
;
1124 if (($permissionedContact) &&
1125 (!CRM_Contact_BAO_Contact_Permission
::relationship($cid, $contactId))
1129 $values[$rid]['id'] = $rid;
1130 $values[$rid]['cid'] = $cid;
1131 $values[$rid]['contact_id_a'] = $relationship->contact_id_a
;
1132 $values[$rid]['contact_id_b'] = $relationship->contact_id_b
;
1133 $values[$rid]['contact_type'] = $relationship->contact_type
;
1134 $values[$rid]['relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1135 $values[$rid]['relation'] = $relationship->relation
;
1136 $values[$rid]['name'] = $relationship->sort_name
;
1137 $values[$rid]['display_name'] = $relationship->display_name
;
1138 $values[$rid]['job_title'] = $relationship->job_title
;
1139 $values[$rid]['email'] = $relationship->email
;
1140 $values[$rid]['phone'] = $relationship->phone
;
1141 $values[$rid]['employer_id'] = $relationship->employer_id
;
1142 $values[$rid]['organization_name'] = $relationship->organization_name
;
1143 $values[$rid]['country'] = $relationship->country
;
1144 $values[$rid]['city'] = $relationship->city
;
1145 $values[$rid]['state'] = $relationship->state
;
1146 $values[$rid]['start_date'] = $relationship->start_date
;
1147 $values[$rid]['end_date'] = $relationship->end_date
;
1148 $values[$rid]['description'] = $relationship->description
;
1149 $values[$rid]['is_active'] = $relationship->is_active
;
1150 $values[$rid]['is_permission_a_b'] = $relationship->is_permission_a_b
;
1151 $values[$rid]['is_permission_b_a'] = $relationship->is_permission_b_a
;
1152 $values[$rid]['case_id'] = $relationship->case_id
;
1155 $values[$rid]['status'] = $status;
1158 $values[$rid]['civicrm_relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1160 if ($relationship->contact_id_a
== $contactId) {
1161 $values[$rid]['rtype'] = 'a_b';
1164 $values[$rid]['rtype'] = 'b_a';
1170 'rtype' => $values[$rid]['rtype'],
1171 'cid' => $contactId,
1172 'cbid' => $values[$rid]['cid'],
1173 'caseid' => $values[$rid]['case_id'],
1174 'clientid' => $contactId,
1177 if ($status == self
::INACTIVE
) {
1178 // setting links for inactive relationships
1179 $mask = array_sum(array_keys($links));
1180 if (!$values[$rid]['is_active']) {
1181 $mask -= CRM_Core_Action
::DISABLE
;
1184 $mask -= CRM_Core_Action
::ENABLE
;
1185 $mask -= CRM_Core_Action
::DISABLE
;
1189 // Give access to manage case link by copying to MAX_ACTION index temporarily, depending on case permission of user.
1190 if ($values[$rid]['case_id']) {
1191 // Borrowed logic from CRM_Case_Page_Tab
1192 $hasCaseAccess = FALSE;
1193 if (CRM_Core_Permission
::check('access all cases and activities')) {
1194 $hasCaseAccess = TRUE;
1197 $userCases = CRM_Case_BAO_Case
::getCases(FALSE);
1198 if (array_key_exists($values[$rid]['case_id'], $userCases)) {
1199 $hasCaseAccess = TRUE;
1203 if ($hasCaseAccess) {
1204 // give access by copying to MAX_ACTION temporarily, otherwise leave at NONE which won't display
1205 $links[CRM_Core_Action
::MAX_ACTION
] = $links[CRM_Core_Action
::NONE
];
1206 $links[CRM_Core_Action
::MAX_ACTION
]['name'] = ts('Manage Case #%1', array(1 => $values[$rid]['case_id']));
1207 $links[CRM_Core_Action
::MAX_ACTION
]['class'] = 'no-popup';
1209 // Also make sure we have the right client cid since can get here from multiple relationship tabs.
1210 if ($values[$rid]['rtype'] == 'b_a') {
1211 $replace['clientid'] = $values[$rid]['cid'];
1216 $values[$rid]['action'] = CRM_Core_Action
::formLink(
1222 'relationship.selector.row',
1225 unset($links[CRM_Core_Action
::MAX_ACTION
]);
1229 $relationship->free();
1235 * Get get list of relationship type based on the target contact type.
1237 * @param string $targetContactType
1238 * It's valid contact tpye(may be Individual , Organization , Household).
1241 * array reference of all relationship types with context to current contact type .
1243 public function getRelationType($targetContactType) {
1244 $relationshipType = array();
1245 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType();
1247 foreach ($allRelationshipType as $key => $type) {
1248 if ($type['contact_type_b'] == $targetContactType) {
1249 $relationshipType[$key . '_a_b'] = $type['label_a_b'];
1253 return $relationshipType;
1257 * Create / update / delete membership for related contacts.
1259 * This function will create/update/delete membership for related
1260 * contact based on 1) contact have active membership 2) that
1261 * membership is is extedned by the same relationship type to that
1262 * of the existing relationship.
1264 * @param int $contactId
1266 * @param array $params
1267 * array of values submitted by POST.
1270 * @param \const|\which $action which action called this function
1272 * @param bool $active
1275 public static function relatedMemberships($contactId, &$params, $ids, $action = CRM_Core_Action
::ADD
, $active = TRUE) {
1276 // Check the end date and set the status of the relationship
1278 $status = self
::CURRENT
;
1280 if (!empty($params['end_date'])) {
1281 $endDate = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Date
::format($params['end_date']), NULL, 'Ymd');
1282 $today = date('Ymd');
1284 if ($today > $endDate) {
1285 $status = self
::PAST
;
1289 if (($action & CRM_Core_Action
::ADD
) &&
1290 ($status & self
::PAST
)
1292 // if relationship is PAST and action is ADD, no qustion
1293 // of creating RELATED membership and return back to
1298 $rel = explode('_', $params['relationship_type_id']);
1300 $relTypeId = $rel[0];
1301 if (!empty($rel[1])) {
1302 $relDirection = "_{$rel[1]}_{$rel[2]}";
1305 // this call is coming from somewhere where the direction was resolved early on (e.g an api call)
1306 // so we can assume _a_b
1307 $relDirection = "_a_b";
1309 $targetContact = array();
1310 if (($action & CRM_Core_Action
::ADD
) ||
1311 ($action & CRM_Core_Action
::DELETE
)
1313 $contact = $contactId;
1314 $targetContact = CRM_Utils_Array
::value('contact_check', $params);
1316 elseif ($action & CRM_Core_Action
::UPDATE
) {
1317 $contact = $ids['contact'];
1318 $targetContact = array($ids['contactTarget'] => 1);
1321 // Build the 'values' array for
1324 // This will allow us to check if either of the contacts in
1325 // relationship have active memberships.
1330 $values[$contact] = array(
1331 'relatedContacts' => $targetContact,
1332 'relationshipTypeId' => $relTypeId,
1333 'relationshipTypeDirection' => $relDirection,
1336 if (!empty($targetContact)) {
1337 foreach ($targetContact as $cid => $donCare) {
1338 $values[$cid] = array(
1339 'relatedContacts' => array($contact => 1),
1340 'relationshipTypeId' => $relTypeId,
1343 $relTypeParams = array('id' => $relTypeId);
1344 $relTypeValues = array();
1345 CRM_Contact_BAO_RelationshipType
::retrieve($relTypeParams, $relTypeValues);
1347 if (CRM_Utils_Array
::value('name_a_b', $relTypeValues) == CRM_Utils_Array
::value('name_b_a', $relTypeValues)) {
1348 $values[$cid]['relationshipTypeDirection'] = '_a_b';
1351 $values[$cid]['relationshipTypeDirection'] = ($relDirection == '_a_b') ?
'_b_a' : '_a_b';
1356 // Now get the active memberships for all the contacts.
1357 // If contact have any valid membership(s), then add it to
1359 foreach ($values as $cid => $subValues) {
1360 $memParams = array('contact_id' => $cid);
1361 $memberships = array();
1363 CRM_Member_BAO_Membership
::getValues($memParams, $memberships, $active);
1365 if (empty($memberships)) {
1369 $values[$cid]['memberships'] = $memberships;
1371 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1373 // done with 'values' array.
1374 // Finally add / edit / delete memberships for the related contacts
1375 foreach ($values as $cid => $details) {
1376 if (!array_key_exists('memberships', $details)) {
1380 $mainRelatedContactId = key(CRM_Utils_Array
::value('relatedContacts', $details, array()));
1382 foreach ($details['memberships'] as $membershipId => $membershipValues) {
1383 $relTypeIds = array();
1384 if ($action & CRM_Core_Action
::DELETE
) {
1385 // Delete memberships of the related contacts only if relationship type exists for membership type
1387 SELECT relationship_type_id, relationship_direction
1388 FROM civicrm_membership_type
1389 WHERE id = {$membershipValues['membership_type_id']}";
1390 $dao = CRM_Core_DAO
::executeQuery($query);
1391 $relTypeDirs = array();
1392 while ($dao->fetch()) {
1393 $relTypeId = $dao->relationship_type_id
;
1394 $relDirection = $dao->relationship_direction
;
1396 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $relTypeId);
1397 if (in_array($values[$cid]['relationshipTypeId'], $relTypeIds)) {
1398 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $mainRelatedContactId);
1402 if (($action & CRM_Core_Action
::UPDATE
) &&
1403 ($status & self
::PAST
) &&
1404 ($membershipValues['owner_membership_id'])
1406 // If relationship is PAST and action is UPDATE
1407 // then delete the RELATED membership
1408 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipValues['owner_membership_id'],
1409 $membershipValues['membership_contact_id']
1414 // add / edit the memberships for related
1417 // Get the Membership Type Details.
1418 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipValues['membership_type_id']);
1419 // Check if contact's relationship type exists in membership type
1420 $relTypeDirs = array();
1421 if (!empty($membershipType['relationship_type_id'])) {
1422 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_type_id']);
1424 if (!empty($membershipType['relationship_direction'])) {
1425 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_direction']);
1427 foreach ($relTypeIds as $key => $value) {
1428 $relTypeDirs[] = $value . '_' . $relDirections[$key];
1430 $relTypeDir = $details['relationshipTypeId'] . $details['relationshipTypeDirection'];
1431 if (in_array($relTypeDir, $relTypeDirs)) {
1432 // Check if relationship being created/updated is
1433 // similar to that of membership type's
1436 $membershipValues['owner_membership_id'] = $membershipId;
1437 unset($membershipValues['id']);
1438 unset($membershipValues['membership_contact_id']);
1439 unset($membershipValues['contact_id']);
1440 unset($membershipValues['membership_id']);
1441 foreach ($details['relatedContacts'] as $relatedContactId => $donCare) {
1442 $membershipValues['contact_id'] = $relatedContactId;
1443 if ($deceasedStatusId &&
1444 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $relatedContactId, 'is_deceased')
1446 $membershipValues['status_id'] = $deceasedStatusId;
1447 $membershipValues['skipStatusCal'] = TRUE;
1454 if (!empty($membershipValues[$dateField])) {
1455 $membershipValues[$dateField] = CRM_Utils_Date
::processDate($membershipValues[$dateField]);
1459 if ($action & CRM_Core_Action
::UPDATE
) {
1460 //delete the membership record for related
1461 //contact before creating new membership record.
1462 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $relatedContactId);
1465 // check whether we have some related memberships still available
1468 FROM civicrm_membership
1469 LEFT JOIN civicrm_membership_status ON (civicrm_membership_status.id = civicrm_membership.status_id)
1470 WHERE membership_type_id = {$membershipValues['membership_type_id']} AND owner_membership_id = {$membershipValues['owner_membership_id']}
1471 AND is_current_member = 1";
1472 $result = CRM_Core_DAO
::singleValueQuery($query);
1473 if ($result < CRM_Utils_Array
::value('max_related', $membershipValues, PHP_INT_MAX
)) {
1474 CRM_Member_BAO_Membership
::create($membershipValues, CRM_Core_DAO
::$_nullArray);
1478 elseif ($action & CRM_Core_Action
::UPDATE
) {
1479 // if action is update and updated relationship do
1480 // not match with the existing
1481 // membership=>relationship then we need to
1482 // delete the membership record created for
1483 // previous relationship.
1485 if (self
::isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, CRM_Utils_Array
::value('relationship_ids', $params))) {
1486 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $mainRelatedContactId);
1494 * Helper function to check whether to delete the membership or
1498 public static function isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, $relIds) {
1499 if (in_array($relTypeId, $relTypeIds)) {
1503 if (empty($relIds)) {
1507 $relParamas = array(
1508 1 => array($contactId, 'Integer'),
1509 2 => array($mainRelatedContactId, 'Integer'),
1512 if ($contactId == $mainRelatedContactId) {
1513 $recordsFound = (int) CRM_Core_DAO
::singleValueQuery("SELECT COUNT(*) FROM civicrm_relationship WHERE relationship_type_id IN ( " . implode(',', $relTypeIds) . " ) AND contact_id_a IN ( %1 ) OR contact_id_b IN ( %1 ) AND id IN (" . implode(',', $relIds) . ")", $relParamas);
1514 if ($recordsFound) {
1520 $recordsFound = (int) CRM_Core_DAO
::singleValueQuery("SELECT COUNT(*) FROM civicrm_relationship WHERE relationship_type_id IN ( " . implode(',', $relTypeIds) . " ) AND contact_id_a IN ( %1, %2 ) AND contact_id_b IN ( %1, %2 ) AND id NOT IN (" . implode(',', $relIds) . ")", $relParamas);
1522 if ($recordsFound) {
1530 * Get Current Employer for Contact
1532 * @param $contactIds
1536 * array of the current employer
1538 public static function getCurrentEmployer($contactIds) {
1539 $contacts = implode(',', $contactIds);
1542 SELECT organization_name, id, employer_id
1543 FROM civicrm_contact
1544 WHERE id IN ( {$contacts} )
1547 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1548 $currentEmployer = array();
1549 while ($dao->fetch()) {
1550 $currentEmployer[$dao->id
]['org_id'] = $dao->employer_id
;
1551 $currentEmployer[$dao->id
]['org_name'] = $dao->organization_name
;
1554 return $currentEmployer;
1558 * Return list of permissioned employer for a given contact.
1560 * @param int $contactID
1561 * contact id whose employers.
1563 * @param string $name
1564 * employers sort name.
1568 * array of employers.
1570 public static function getPermissionedEmployer($contactID, $name = NULL) {
1571 //get the relationship id
1572 $relTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType',
1573 'Employee of', 'id', 'name_a_b'
1576 return self
::getPermissionedContacts($contactID, $relTypeId, $name);
1581 * Function to return list of permissioned contacts for a given contact and relationship type
1583 * @param int $contactID
1584 * contact id whose permissioned contacts are to be found.
1585 * @param string $relTypeId
1586 * one or more relationship type id's.
1587 * @param string $name
1593 public static function getPermissionedContacts($contactID, $relTypeId, $name = NULL) {
1594 $contacts = array();
1598 SELECT cc.id as id, cc.sort_name as name
1599 FROM civicrm_relationship cr, civicrm_contact cc
1601 cr.contact_id_a = %1 AND
1602 cr.relationship_type_id IN (%2) AND
1603 cr.is_permission_a_b = 1 AND
1604 IF(cr.end_date IS NULL, 1, (DATEDIFF( CURDATE( ), cr.end_date ) <= 0)) AND
1605 cr.is_active = 1 AND
1606 cc.id = cr.contact_id_b AND
1609 if (!empty($name)) {
1610 $name = CRM_Utils_Type
::escape($name, 'String');
1612 AND cc.sort_name LIKE '%$name%'";
1615 $args = array(1 => array($contactID, 'Integer'), 2 => array($relTypeId, 'String'));
1616 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1618 while ($dao->fetch()) {
1619 $contacts[$dao->id
] = array(
1620 'name' => $dao->name
,
1621 'value' => $dao->id
,
1629 * Merge relationships from otherContact to mainContact
1630 * Called during contact merge operation
1632 * @param int $mainId
1633 * Contact id of main contact record.
1634 * @param int $otherId
1635 * Contact id of record which is going to merge.
1636 * @param array $sqls
1637 * (reference) array of sql statements to append to.
1639 * @see CRM_Dedupe_Merger::cpTables()
1642 public static function mergeRelationships($mainId, $otherId, &$sqls) {
1643 // Delete circular relationships
1644 $sqls[] = "DELETE FROM civicrm_relationship
1645 WHERE (contact_id_a = $mainId AND contact_id_b = $otherId)
1646 OR (contact_id_b = $mainId AND contact_id_a = $otherId)";
1648 // Delete relationship from other contact if main contact already has that relationship
1649 $sqls[] = "DELETE r2
1650 FROM civicrm_relationship r1, civicrm_relationship r2
1651 WHERE r1.relationship_type_id = r2.relationship_type_id
1654 r1.contact_id_a = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_b = r2.contact_id_b
1655 OR r1.contact_id_b = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_a = r2.contact_id_a
1657 (r1.contact_id_a = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_b = r2.contact_id_a
1658 OR r1.contact_id_b = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_a = r2.contact_id_b)
1659 AND r1.relationship_type_id IN (SELECT id FROM civicrm_relationship_type WHERE name_b_a = name_a_b)
1663 // Move relationships
1664 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_a = $mainId WHERE contact_id_a = $otherId";
1665 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_b = $mainId WHERE contact_id_b = $otherId";
1667 // Move current employer id (name will get updated later)
1668 $sqls[] = "UPDATE civicrm_contact SET employer_id = $mainId WHERE employer_id = $otherId";
1672 * Set 'is_valid' field to false for all relationships whose end date is in the past, ie. are expired.
1675 * True on success, false if error is encountered.
1677 public static function disableExpiredRelationships() {
1678 $query = "SELECT id FROM civicrm_relationship WHERE is_active = 1 AND end_date < CURDATE()";
1680 $dao = CRM_Core_DAO
::executeQuery($query);
1681 while ($dao->fetch()) {
1682 $result = CRM_Contact_BAO_Relationship
::setIsActive($dao->id
, FALSE);
1683 // Result will be NULL if error occurred. We abort early if error detected.
1684 if ($result == NULL) {
1692 * Function filters the query by possible relationships for the membership type
1693 * It is intended to be called when constructing queries for the api (reciprocal & non-reciprocal)
1694 * and to add clauses to limit the return to those relationships which COULD inherit a membership type
1695 * (as opposed to those who inherit a particular membership
1697 * @param array $params
1699 * @param null $direction
1701 * @return array|void
1703 public static function membershipTypeToRelationshipTypes(&$params, $direction = NULL) {
1704 $membershipType = civicrm_api3('membership_type', 'getsingle', array(
1705 'id' => $params['membership_type_id'],
1706 'return' => 'relationship_type_id, relationship_direction',
1708 $relationshipTypes = $membershipType['relationship_type_id'];
1709 if (empty($relationshipTypes)) {
1712 // if we don't have any contact data we can only filter on type
1713 if (empty($params['contact_id']) && empty($params['contact_id_a']) && empty($params['contact_id_a'])) {
1714 $params['relationship_type_id'] = array('IN' => $relationshipTypes);
1718 $relationshipDirections = (array) $membershipType['relationship_direction'];
1719 // if we have contact_id_a OR contact_id_b we can make a call here
1720 // if we have contact??
1721 foreach ($relationshipDirections as $index => $mtdirection) {
1722 if (isset($params['contact_id_a']) && $mtdirection == 'a_b' ||
$direction == 'a_b') {
1723 $types[] = $relationshipTypes[$index];
1725 if (isset($params['contact_id_b']) && $mtdirection == 'b_a' ||
$direction == 'b_a') {
1726 $types[] = $relationshipTypes[$index];
1729 if (!empty($types)) {
1730 $params['relationship_type_id'] = array('IN' => $types);
1732 elseif (!empty($clauses)) {
1733 return explode(' OR ', $clauses);
1736 // effectively setting it to return no results
1737 $params['relationship_type_id'] = 0;
1744 * wrapper for contact relationship selector
1746 * @param array $params
1747 * Associated array for params record id.
1750 * associated array of contact relationships
1752 public static function getContactRelationshipSelector(&$params) {
1753 // format the params
1754 $params['offset'] = ($params['page'] - 1) * $params['rp'];
1755 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
1757 if ($params['context'] == 'past') {
1758 $relationshipStatus = CRM_Contact_BAO_Relationship
::INACTIVE
;
1761 $relationshipStatus = CRM_Contact_BAO_Relationship
::CURRENT
;
1764 // check logged in user for permission
1765 $page = new CRM_Core_Page();
1766 CRM_Contact_Page_View
::checkUserPermission($page, $params['contact_id']);
1767 $permissions = array($page->_permission
);
1768 if ($page->_permission
== CRM_Core_Permission
::EDIT
) {
1769 $permissions[] = CRM_Core_Permission
::DELETE
;
1771 $mask = CRM_Core_Action
::mask($permissions);
1773 if ($params['context'] != 'user') {
1774 $links = CRM_Contact_Page_View_Relationship
::links();
1775 $permissionedContacts = FALSE;
1778 $links = CRM_Contact_Page_View_UserDashBoard
::links();
1779 $permissionedContacts = TRUE;
1782 // get contact relationships
1783 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1784 $relationshipStatus,
1785 $params['rp'], 0, 0,
1787 $permissionedContacts,
1791 $contactRelationships = array();
1792 $params['total'] = 0;
1793 if (!empty($relationships)) {
1794 // get the total relationships
1795 if ($params['context'] != 'user') {
1796 $params['total'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1797 $relationshipStatus, 0, 1, 0, NULL, NULL, $permissionedContacts);
1800 // FIX ME: we cannot directly determine total permissioned relationship, hence re-fire query
1801 $permissionedRelationships = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1802 $relationshipStatus,
1806 $params['total'] = count($permissionedRelationships);
1810 foreach ($relationships as $relationshipId => $values) {
1811 //Add image icon for related contacts: CRM-14919
1812 $icon = CRM_Contact_BAO_Contact_Utils
::getImage($values['contact_type'],
1816 $contactRelationships[$relationshipId]['name'] = $icon . ' ' . CRM_Utils_System
::href(
1818 'civicrm/contact/view',
1819 "reset=1&cid={$values['cid']}");
1821 $contactRelationships[$relationshipId]['relation'] = CRM_Utils_System
::href(
1822 $values['relation'],
1823 'civicrm/contact/view/rel',
1824 "action=view&reset=1&cid={$values['cid']}&id={$values['id']}&rtype={$values['rtype']}");
1826 if ($params['context'] == 'current') {
1827 if (($params['contact_id'] == $values['contact_id_a'] AND $values['is_permission_a_b'] == 1) OR
1828 ($params['contact_id'] == $values['contact_id_b'] AND $values['is_permission_b_a'] == 1)
1830 $contactRelationships[$relationshipId]['name'] .= '<span id="permission-a-b" class="crm-marker permission-relationship"> *</span>';
1833 if (($values['cid'] == $values['contact_id_a'] AND $values['is_permission_a_b'] == 1) OR
1834 ($values['cid'] == $values['contact_id_b'] AND $values['is_permission_b_a'] == 1)
1836 $contactRelationships[$relationshipId]['relation'] .= '<span id="permission-b-a" class="crm-marker permission-relationship"> *</span>';
1840 if (!empty($values['description'])) {
1841 $contactRelationships[$relationshipId]['relation'] .= "<p class='description'>{$values['description']}</p>";
1844 $contactRelationships[$relationshipId]['start_date'] = CRM_Utils_Date
::customFormat($values['start_date']);
1845 $contactRelationships[$relationshipId]['end_date'] = CRM_Utils_Date
::customFormat($values['end_date']);
1846 $contactRelationships[$relationshipId]['city'] = $values['city'];
1847 $contactRelationships[$relationshipId]['state'] = $values['state'];
1848 $contactRelationships[$relationshipId]['email'] = $values['email'];
1849 $contactRelationships[$relationshipId]['phone'] = $values['phone'];
1850 $contactRelationships[$relationshipId]['links'] = $values['action'];
1851 $contactRelationships[$relationshipId]['id'] = $values['id'];
1852 $contactRelationships[$relationshipId]['is_active'] = $values['is_active'];
1855 return $contactRelationships;