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
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);
71 * Takes an associative array and creates a relationship object
72 * @deprecated For single creates use the api instead (it's tested).
73 * For multiple a new variant of this function needs to be written and migrated to as this is a bit
76 * @param array $params
77 * (reference ) an assoc array of name/value pairs.
79 * The array that holds all the db ids.
80 * per http://wiki.civicrm.org/confluence/display/CRM/Database+layer
81 * "we are moving away from the $ids param "
83 * @return CRM_Contact_BAO_Relationship object
86 public static function createMultiple(&$params, $ids = array()) {
87 $valid = $invalid = $duplicate = $saved = 0;
88 $relationships = $relationshipIds = array();
89 $relationshipId = CRM_Utils_Array
::value('relationship', $ids, CRM_Utils_Array
::value('id', $params));
90 //CRM-9015 - the hooks are called here & in add (since add doesn't call create)
91 // but in future should be tidied per ticket
92 if(empty($relationshipId)){
94 $action = CRM_Core_Action
::ADD
;
98 $action = CRM_Core_Action
::UPDATE
;
101 CRM_Utils_Hook
::pre($hook, 'Relationship', $relationshipId, $params);
103 if (!$relationshipId) {
104 // creating a new relationship
105 $dataExists = self
::dataExists($params);
107 return array(FALSE, TRUE, FALSE, FALSE, NULL);
109 $relationshipIds = array();
110 foreach ($params['contact_check'] as $key => $value) {
112 // check if the relationship is valid between contacts.
113 // step 1: check if the relationship is valid if not valid skip and keep the count
114 // step 2: check the if two contacts already have a relationship if yes skip and keep the count
115 // step 3: if valid relationship then add the relation and keep the count
118 $errors = self
::checkValidRelationship($params, $ids, $key);
125 self
::checkDuplicateRelationship(
127 CRM_Utils_Array
::value('contact', $ids),
135 self
::setContactABFromIDs($params, $ids, $key);
136 $relationship = self
::add($params);
137 $relationshipIds[] = $relationship->id
;
138 $relationships[$relationship->id
] = $relationship;
141 // editing the relationship
144 // check for duplicate relationship
145 // @todo this code doesn't cope well with updates - causes e-Notices.
146 // API has a lot of code to work around
147 // this but should review this code & remove the extra handling from the api
148 // it seems doubtful any of this is relevant if the contact fields & relationship
149 // type fields are not set
151 self
::checkDuplicateRelationship(
153 CRM_Utils_Array
::value('contact', $ids),
154 $ids['contactTarget'],
159 return array($valid, $invalid, $duplicate, $saved, NULL);
162 $validContacts = TRUE;
163 //validate contacts in update mode also.
164 if (!empty($ids['contact']) && !empty($ids['contactTarget'])) {
165 if (self
::checkValidRelationship($params, $ids, $ids['contactTarget'])) {
166 $validContacts = FALSE;
170 if ($validContacts) {
171 // editing an existing relationship
172 $relationship = self
::add($params, $ids, $ids['contactTarget']);
173 $relationshipIds[] = $relationship->id
;
174 $relationships[$relationship->id
] = $relationship;
179 // do not add to recent items for import, CRM-4399
180 if (!(!empty($params['skipRecentView']) ||
$invalid ||
$duplicate)) {
181 self
::addRecent($params, $relationship);
184 return array($valid, $invalid, $duplicate, $saved, $relationshipIds, $relationships);
188 * This is the function that check/add if the relationship created is valid
190 * @param array $params
191 * (reference ) an assoc array of name/value pairs.
192 * @param int $contactId
193 * This is contact id for adding relationship.
195 * The array that holds all the db ids.
197 * @return CRM_Contact_BAO_Relationship
200 public static function add(&$params, $ids = array(), $contactId = NULL) {
202 CRM_Utils_Array
::value('relationship', $ids, CRM_Utils_Array
::value('id', $params));
205 if($relationshipId) {
208 //@todo hook are called from create and add - remove one
209 CRM_Utils_Hook
::pre($hook , 'Relationship', $relationshipId, $params);
211 self
::setContactABFromIDs($params);
212 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
214 // explode the string with _ to get the relationship type id
215 // and to know which contact has to be inserted in
216 // contact_id_a and which one in contact_id_b
217 list($type) = explode('_', $relationshipTypes);
219 // check if the relationship type is Head of Household then update the
220 // household's primary contact with this contact.
222 CRM_Contact_BAO_Household
::updatePrimaryContact($params['contact_id_b'], $params['contact_id_a']);
225 $relationship = new CRM_Contact_BAO_Relationship();
226 //@todo this code needs to be updated for the possibility that not all fields are set
228 $relationship->contact_id_b
= $params['contact_id_b'];
229 $relationship->contact_id_a
= $params['contact_id_a'];
230 $relationship->relationship_type_id
= $type;
231 $relationship->id
= $relationshipId;
233 $dateFields = array('end_date', 'start_date');
235 foreach (self
::getdefaults() as $defaultField => $defaultValue){
236 if(isset($params[$defaultField])){
237 if(in_array($defaultField, $dateFields)){
238 $relationship->$defaultField = CRM_Utils_Date
::format(CRM_Utils_Array
::value($defaultField, $params));
239 if(!$relationship->$defaultField){
240 $relationship->$defaultField = 'NULL';
244 $relationship->$defaultField = $params[$defaultField];
247 elseif(!$relationshipId){
248 $relationship->$defaultField = $defaultValue;
252 $relationship->save();
254 // add custom field values
255 if (!empty($params['custom'])) {
256 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_relationship', $relationship->id
);
259 $relationship->free();
261 CRM_Utils_Hook
::post($hook, 'Relationship', $relationship->id
, $relationship);
263 return $relationship;
267 * Add relationship to recent links
268 * @param array $params
269 * @param CRM_Contact_DAO_Relationship $relationship
271 public static function addRecent($params, $relationship) {
272 $url = CRM_Utils_System
::url('civicrm/contact/view/rel',
273 "action=view&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&context=home"
275 $session = CRM_Core_Session
::singleton();
276 $recentOther = array();
277 if (($session->get('userID') == $relationship->contact_id_a
) ||
278 CRM_Contact_BAO_Contact_Permission
::allow($relationship->contact_id_a
, CRM_Core_Permission
::EDIT
)
280 $rType = substr(CRM_Utils_Array
::value('relationship_type_id', $params), -3);
281 $recentOther = array(
282 'editUrl' => CRM_Utils_System
::url('civicrm/contact/view/rel',
283 "action=update&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
285 'deleteUrl' => CRM_Utils_System
::url('civicrm/contact/view/rel',
286 "action=delete&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
290 $title = CRM_Contact_BAO_Contact
::displayName($relationship->contact_id_a
) . ' (' . CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType',
291 $relationship->relationship_type_id
, 'label_a_b'
292 ) . ' ' . CRM_Contact_BAO_Contact
::displayName($relationship->contact_id_b
) . ')';
294 CRM_Utils_Recent
::add($title,
298 $relationship->contact_id_a
,
305 * Resolve passed in contact IDs to contact_id_a & contact_id_b
308 * @param null $contactID
309 * @throws \CRM_Core_Exception
311 public static function setContactABFromIDs(&$params, $ids = array(), $contactID = NULL) {
312 if (!empty($params['contact_id_a']) && !empty($params['contact_id_b'])) {
315 if (empty($ids['contact'])) {
316 if (!empty($params['id'])) {
317 //let's load the missing ids here since other things tend to rely on them.
318 $fieldsToFill = array('contact_id_a', 'contact_id_b', 'relationship_type_id');
319 $result = CRM_Core_DAO
::executeQuery("SELECT " . implode(',', $fieldsToFill) . " FROM civicrm_relationship WHERE id = %1", array(1 => array($params['id'], 'Integer')));
320 while ($result->fetch()) {
321 foreach ($fieldsToFill as $field) {
322 $params[$field] = !empty($params[$field]) ?
$params[$field] : $result->$field;
327 throw new CRM_Core_Exception('Cannot create relationship, insufficient contact IDs provided');
329 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
330 list($relationshipTypeID, $first, $second) = explode('_', $relationshipTypes);
331 if (empty($params['relationship_type_id'])) {
332 $params['relationship_type_id'] = $relationshipTypeID;
334 foreach (array('a', 'b') as $contactLetter) {
335 if (empty($params['contact_' . $contactLetter])) {
336 if ($first == $contactLetter) {
337 $params['contact_id_' . $contactLetter] = CRM_Utils_Array
::value('contact', $ids);
340 $params['contact_id_' . $contactLetter] = $contactID;
347 * Specifiy defaults for creating a relationship
349 * @return array $defaults array of defaults for creating relationship
352 public static function getdefaults() {
355 'is_permission_a_b' => 0,
356 'is_permission_b_a' => 0,
358 'start_date' => 'NULL',
360 'end_date' => 'NULL',
366 * Check if there is data to create the object
368 * @param array $params
369 * (reference ) an assoc array of name/value pairs.
374 public static function dataExists(&$params) {
375 // return if no data present
376 if (!is_array(CRM_Utils_Array
::value('contact_check', $params))) {
383 * Get get list of relationship type based on the contact type.
385 * @param int $contactId
386 * This is the contact id of the current contact.
387 * @param null $contactSuffix
388 * @param string $relationshipId
389 * The id of the existing relationship if any.
390 * @param string $contactType
393 * If true returns relationship types in both the direction.
394 * @param string $column
395 * Name/label that going to retrieve from db.
396 * @param bool $biDirectional
397 * @param string $contactSubType
398 * Includes relationshiptypes between this subtype.
399 * @param bool $onlySubTypeRelationTypes
400 * If set only subtype which is passed by $contactSubType.
401 * related relationshiptypes get return
405 * @return array - array reference of all relationship types with context to current contact.
407 static function getContactRelationshipType($contactId = NULL,
408 $contactSuffix = NULL,
409 $relationshipId = NULL,
413 $biDirectional = TRUE,
414 $contactSubType = NULL,
415 $onlySubTypeRelationTypes = FALSE
417 $allRelationshipType = array();
418 $relationshipType = array();
419 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType($column);
421 $otherContactType = NULL;
422 if ($relationshipId) {
423 $relationship = new CRM_Contact_DAO_Relationship();
424 $relationship->id
= $relationshipId;
425 if ($relationship->find(TRUE)) {
426 $contact = new CRM_Contact_DAO_Contact();
427 $contact->id
= ($relationship->contact_id_a
=== $contactId) ?
$relationship->contact_id_b
: $relationship->contact_id_a
;
429 if ($contact->find(TRUE)) {
430 $otherContactType = $contact->contact_type
;
431 //CRM-5125 for contact subtype specific relationshiptypes
432 if ($contact->contact_sub_type
) {
433 $otherContactSubType = $contact->contact_sub_type
;
439 $contactSubType = array();
441 $contactType = CRM_Contact_BAO_Contact
::getContactType($contactId);
442 $contactSubType = CRM_Contact_BAO_Contact
::getContactSubType($contactId);
445 foreach ($allRelationshipType as $key => $value) {
446 // the contact type is required or matches
447 if (((!$value['contact_type_a']) ||
448 $value['contact_type_a'] == $contactType
450 // the other contact type is required or present or matches
451 ((!$value['contact_type_b']) ||
452 (!$otherContactType) ||
453 $value['contact_type_b'] == $otherContactType
455 (in_array($value['contact_sub_type_a'], $contactSubType) ||
456 in_array($value['contact_sub_type_b'], $contactSubType) ||
457 (!$value['contact_sub_type_a'] && !$onlySubTypeRelationTypes)
460 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
463 if (((!$value['contact_type_b']) ||
464 $value['contact_type_b'] == $contactType
466 ((!$value['contact_type_a']) ||
467 (!$otherContactType) ||
468 $value['contact_type_a'] == $otherContactType
470 (in_array($value['contact_sub_type_b'], $contactSubType) ||
471 in_array($value['contact_sub_type_a'], $contactSubType) ||
472 (!$value['contact_sub_type_b'] && !$onlySubTypeRelationTypes)
475 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
479 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
480 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
484 if ($biDirectional) {
485 // lets clean up the data and eliminate all duplicate values
486 // (i.e. the relationship is bi-directional)
487 $relationshipType = array_unique($relationshipType);
490 // sort the relationshipType in ascending order CRM-7736
491 asort($relationshipType);
492 return $relationshipType;
499 * @return CRM_Contact_DAO_Relationship
501 public static function clearCurrentEmployer($id, $action) {
502 $relationship = new CRM_Contact_DAO_Relationship();
503 $relationship->id
= $id;
504 $relationship->find(TRUE);
506 //to delete relationship between household and individual \
507 //or between individual and orgnization
508 if (($action & CRM_Core_Action
::DISABLE
) ||
($action & CRM_Core_Action
::DELETE
)) {
509 $relTypes = CRM_Utils_Array
::index(array('name_a_b'), CRM_Core_PseudoConstant
::relationshipType('name'));
510 if ($relationship->relationship_type_id
== $relTypes['Employee of']['id'] ||
511 $relationship->relationship_type_id
== $relTypes['Household Member of']['id']) {
512 $sharedContact = new CRM_Contact_DAO_Contact();
513 $sharedContact->id
= $relationship->contact_id_a
;
514 $sharedContact->find(TRUE);
516 if ($relationship->relationship_type_id
== 4 && $relationship->contact_id_b
== $sharedContact->employer_id
) {
517 CRM_Contact_BAO_Contact_Utils
::clearCurrentEmployer($relationship->contact_id_a
);
521 return $relationship;
525 * Delete the relationship
534 public static function del($id) {
535 // delete from relationship table
536 CRM_Utils_Hook
::pre('delete', 'Relationship', $id, CRM_Core_DAO
::$_nullArray);
538 $relationship = self
::clearCurrentEmployer($id, CRM_Core_Action
::DELETE
);
539 if (CRM_Core_Permission
::access('CiviMember')) {
540 // create $params array which isrequired to delete memberships
541 // of the related contacts.
543 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
544 'contact_check' => array($relationship->contact_id_b
=> 1),
548 // calling relatedMemberships to delete the memberships of
550 self
::relatedMemberships($relationship->contact_id_a
,
553 CRM_Core_Action
::DELETE
,
558 $relationship->delete();
559 CRM_Core_Session
::setStatus(ts('Selected relationship has been deleted successfully.'), ts('Record Deleted'), 'success');
561 CRM_Utils_Hook
::post('delete', 'Relationship', $id, $relationship);
563 // delete the recently created Relationship
564 $relationshipRecent = array(
566 'type' => 'Relationship',
568 CRM_Utils_Recent
::del($relationshipRecent);
570 return $relationship;
574 * Disable/enable the relationship
584 public static function disableEnableRelationship($id, $action) {
585 $relationship = self
::clearCurrentEmployer($id, $action);
586 if (CRM_Core_Permission
::access('CiviMember')) {
587 // create $params array which isrequired to delete memberships
588 // of the related contacts.
590 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
591 'contact_check' => array($relationship->contact_id_b
=> 1),
595 // calling relatedMemberships to delete/add the memberships of
597 if ($action & CRM_Core_Action
::DISABLE
) {
598 CRM_Contact_BAO_Relationship
::relatedMemberships($relationship->contact_id_a
,
601 CRM_Core_Action
::DELETE
,
605 elseif ($action & CRM_Core_Action
::ENABLE
) {
606 $ids['contact'] = $relationship->contact_id_a
;
607 CRM_Contact_BAO_Relationship
::relatedMemberships($relationship->contact_id_a
,
610 CRM_Core_Action
::ADD
,
618 * Delete the object records that are associated with this contact
620 * @param int $contactId
621 * 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
649 public static function getContactIds($id) {
650 $relationship = new CRM_Contact_DAO_Relationship();
652 $relationship->id
= $id;
653 $relationship->selectAdd();
654 $relationship->selectAdd('contact_id_a, contact_id_b');
655 $relationship->find(TRUE);
657 return $relationship;
661 * Check if the relationship type selected between two contacts is correct
663 * @param int $contact_a
665 * @param int $contact_b
667 * @param int $relationshipTypeId
668 * Relationship type id.
670 * @return boolean true if it is valid relationship else false
673 public static function checkRelationshipType($contact_a, $contact_b, $relationshipTypeId) {
674 $relationshipType = new CRM_Contact_DAO_RelationshipType();
675 $relationshipType->id
= $relationshipTypeId;
676 $relationshipType->selectAdd();
677 $relationshipType->selectAdd('contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b');
678 if ($relationshipType->find(TRUE)) {
679 $contact_type_a = CRM_Contact_BAO_Contact
::getContactType($contact_a);
680 $contact_type_b = CRM_Contact_BAO_Contact
::getContactType($contact_b);
682 $contact_sub_type_a = CRM_Contact_BAO_Contact
::getContactSubType($contact_a);
683 $contact_sub_type_b = CRM_Contact_BAO_Contact
::getContactSubType($contact_b);
685 if (((!$relationshipType->contact_type_a
) ||
($relationshipType->contact_type_a
== $contact_type_a)) &&
686 ((!$relationshipType->contact_type_b
) ||
($relationshipType->contact_type_b
== $contact_type_b)) &&
687 ((!$relationshipType->contact_sub_type_a
) ||
(in_array($relationshipType->contact_sub_type_a
,
690 ((!$relationshipType->contact_sub_type_b
) ||
(in_array($relationshipType->contact_sub_type_b
,
704 * This function does the validtion for valid relationship
706 * @param array $params
707 * This array contains the values there are subitted by the form.
709 * The array that holds all the db ids.
710 * @param int $contactId
711 * This is contact id for adding relationship.
717 public static function checkValidRelationship($params, $ids, $contactId) {
719 self
::setContactABFromIDs($params, $ids, $contactId);
720 // get the string of relationship type
721 $relationshipTypes = CRM_Utils_Array
::value('relationship_type_id', $params);
722 list($type) = explode('_', $relationshipTypes);
723 // function to check if the relationship selected is correct
724 // i.e. employer relationship can exit between Individual and Organization (not between Individual and Individual)
725 if (!CRM_Contact_BAO_Relationship
::checkRelationshipType($params['contact_id_a'], $params['contact_id_b'], $type)) {
726 $errors = 'Please select valid relationship between these two contacts.';
732 * This function checks for duplicate relationship
734 * @param array $params
735 * (reference ) an assoc array of name/value pairs.
737 * This the id of the contact whom we are adding relationship.
738 * @param int $contactId
739 * This is contact id for adding relationship.
740 * @param int $relationshipId
741 * This is relationship id for the contact.
743 * @return boolean true if record exists else false
746 public static function checkDuplicateRelationship(&$params, $id, $contactId = 0, $relationshipId = 0) {
747 $relationshipTypeId = CRM_Utils_Array
::value('relationship_type_id', $params);
748 list($type) = explode('_', $relationshipTypeId);
752 FROM civicrm_relationship
753 WHERE relationship_type_id = " . CRM_Utils_Type
::escape($type, 'Integer');
756 * CRM-11792 - date fields from API are in ISO format, but this function
757 * supports date arrays BAO has increasingly standardised to ISO format
758 * so I believe this function should support ISO rather than make API
759 * format it - however, need to support array format for now to avoid breakage
760 * @ time of writing this function is called from Relationship::createMultiple (twice)
761 * CRM_BAO_Contact_Utils::clearCurrentEmployer (seemingly without dates)
762 * CRM_Contact_Form_Task_AddToOrganization::postProcess &
763 * CRM_Contact_Form_Task_AddToHousehold::postProcess
764 * (I don't think the last 2 support dates but not sure
767 $dateFields = array('end_date', 'start_date');
768 foreach ($dateFields as $dateField){
769 if(array_key_exists($dateField, $params)) {
770 if (empty($params[$dateField]) ||
$params[$dateField] == 'null'){
771 //this is most likely coming from an api call & probably loaded
772 // from the DB to deal with some of the
773 // other myriad of excessive checks still in place both in
774 // the api & the create functions
775 $queryString .= " AND $dateField IS NULL";
778 elseif (is_array($params[$dateField])){
779 $queryString .= " AND $dateField = " .
780 CRM_Utils_Type
::escape(CRM_Utils_Date
::format($params[$dateField]), 'Date');
783 $queryString .= " AND $dateField = " .
784 CRM_Utils_Type
::escape($params[$dateField], 'Date');
790 " AND ( ( contact_id_a = " . CRM_Utils_Type
::escape($id, 'Integer') .
791 " AND contact_id_b = " . CRM_Utils_Type
::escape($contactId, 'Integer') .
792 " ) OR ( contact_id_a = " . CRM_Utils_Type
::escape($contactId, 'Integer') .
793 " AND contact_id_b = " . CRM_Utils_Type
::escape($id, 'Integer') . " ) ) ";
795 //if caseId is provided, include it duplicate checking.
796 if ($caseId = CRM_Utils_Array
::value('case_id', $params)) {
797 $queryString .= " AND case_id = " . CRM_Utils_Type
::escape($caseId, 'Integer');
800 if ($relationshipId) {
801 $queryString .= " AND id !=" . CRM_Utils_Type
::escape($relationshipId, 'Integer');
804 $relationship = new CRM_Contact_BAO_Relationship();
805 $relationship->query($queryString);
806 $relationship->fetch();
807 $relationship->free();
808 return ($relationship->id
) ?
TRUE : FALSE;
812 * Update the is_active flag in the db
815 * Id of the database record.
816 * @param bool $is_active
817 * Value we want to set the is_active field.
819 * @throws CiviCRM_API3_Exception
820 * @return Object DAO object on success, null otherwise
823 public static function setIsActive($id, $is_active) {
824 // as both the create & add functions have a bunch of logic in them that
825 // doesn't seem to cope with a normal update we will call the api which
826 // has tested handling for this
827 // however, a longer term solution would be to simplify the add, create & api functions
828 // to be more standard. It is debatable @ that point whether it's better to call the BAO
829 // direct as the api is more tested.
830 $result = civicrm_api('relationship', 'create', array(
832 'is_active' => $is_active,
836 if (is_array($result) && !empty($result['is_error']) && $result['error_message'] != 'Relationship already exists') {
837 throw new CiviCRM_API3_Exception($result['error_message'], CRM_Utils_Array
::value('error_code', $result, 'undefined'), $result);
840 // call (undocumented possibly deprecated) hook
841 CRM_Utils_Hook
::enableDisable('CRM_Contact_BAO_Relationship', $id, $is_active);
847 * Given the list of params in the params array, fetch the object
848 * and store the values in the values array
850 * @param array $params
851 * Input parameters to find object.
852 * @param array $values
853 * Output values of the object.
855 * @return array (reference) the values that could be potentially assigned to smarty
858 public static function &getValues(&$params, &$values) {
859 if (empty($params)) {
864 // get the specific number of relationship or all relationships.
865 if (!empty($params['numRelationship'])) {
866 $v['data'] = &CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'], NULL, $params['numRelationship']);
869 $v['data'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id']);
872 // get the total count of relationships
873 $v['totalCount'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'], NULL, NULL, TRUE);
875 $values['relationship']['data'] = &$v['data'];
876 $values['relationship']['totalCount'] = &$v['totalCount'];
882 * Helper function to form the sql for relationship retrieval
884 * @param int $contactId
887 * (check const at top of file).
888 * @param int $numRelationship
889 * No of relationships to display (limit).
891 * Get the no of relationships.
892 * $param int $relationshipId relationship id
893 * @param int $relationshipId
894 * @param string $direction
895 * The direction we are interested in a_b or b_a.
896 * @param array $params
897 * Array of extra values including relationship_type_id per api spec.
899 * return string the query for this diretion
904 public static function makeURLClause($contactId, $status, $numRelationship, $count, $relationshipId, $direction, $params = array()) {
905 $select = $from = $where = '';
909 if ($direction == 'a_b') {
910 $select .= ' SELECT count(DISTINCT civicrm_relationship.id) as cnt1, 0 as cnt2 ';
913 $select .= ' SELECT 0 as cnt1, count(DISTINCT civicrm_relationship.id) as cnt2 ';
917 $select .= ' SELECT civicrm_relationship.id as civicrm_relationship_id,
918 civicrm_contact.sort_name as sort_name,
919 civicrm_contact.display_name as display_name,
920 civicrm_contact.job_title as job_title,
921 civicrm_contact.employer_id as employer_id,
922 civicrm_contact.organization_name as organization_name,
923 civicrm_address.street_address as street_address,
924 civicrm_address.city as city,
925 civicrm_address.postal_code as postal_code,
926 civicrm_state_province.abbreviation as state,
927 civicrm_country.name as country,
928 civicrm_email.email as email,
929 civicrm_contact.contact_type as contact_type,
930 civicrm_phone.phone as phone,
931 civicrm_contact.id as civicrm_contact_id,
932 civicrm_relationship.contact_id_b as contact_id_b,
933 civicrm_relationship.contact_id_a as contact_id_a,
934 civicrm_relationship_type.id as civicrm_relationship_type_id,
935 civicrm_relationship.start_date as start_date,
936 civicrm_relationship.end_date as end_date,
937 civicrm_relationship.description as description,
938 civicrm_relationship.is_active as is_active,
939 civicrm_relationship.is_permission_a_b as is_permission_a_b,
940 civicrm_relationship.is_permission_b_a as is_permission_b_a,
941 civicrm_relationship.case_id as case_id';
943 if ($direction == 'a_b') {
944 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
945 civicrm_relationship_type.label_b_a as relation ';
948 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
949 civicrm_relationship_type.label_a_b as relation ';
954 FROM civicrm_relationship
955 INNER JOIN civicrm_relationship_type ON ( civicrm_relationship.relationship_type_id = civicrm_relationship_type.id )
956 INNER JOIN civicrm_contact ";
957 if ($direction == 'a_b') {
958 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_a ) ';
961 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_b ) ';
964 LEFT JOIN civicrm_address ON (civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1)
965 LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
966 LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id AND civicrm_email.is_primary = 1)
967 LEFT JOIN civicrm_state_province ON (civicrm_address.state_province_id = civicrm_state_province.id)
968 LEFT JOIN civicrm_country ON (civicrm_address.country_id = civicrm_country.id)
970 $where = 'WHERE ( 1 )';
972 if ($direction == 'a_b') {
973 $where .= ' AND civicrm_relationship.contact_id_b = ' . CRM_Utils_Type
::escape($contactId, 'Positive');
976 $where .= ' AND civicrm_relationship.contact_id_a = ' . CRM_Utils_Type
::escape($contactId, 'Positive') . '
977 AND civicrm_relationship.contact_id_a != civicrm_relationship.contact_id_b ';
980 if ($relationshipId) {
981 $where .= ' AND civicrm_relationship.id = ' . CRM_Utils_Type
::escape($relationshipId, 'Positive');
984 $date = date('Y-m-d');
985 if ($status == self
::PAST
) {
986 //this case for showing past relationship
987 $where .= ' AND civicrm_relationship.is_active = 1 ';
988 $where .= " AND civicrm_relationship.end_date < '" . $date . "'";
990 elseif ($status == self
::DISABLED
) {
991 // this case for showing disabled relationship
992 $where .= ' AND civicrm_relationship.is_active = 0 ';
994 elseif ($status == self
::CURRENT
) {
995 //this case for showing current relationship
996 $where .= ' AND civicrm_relationship.is_active = 1 ';
997 $where .= " AND (civicrm_relationship.end_date >= '" . $date . "' OR civicrm_relationship.end_date IS NULL) ";
999 elseif ($status == self
::INACTIVE
) {
1000 //this case for showing inactive relationships
1001 $where .= " AND (civicrm_relationship.end_date < '" . $date . "'";
1002 $where .= ' OR civicrm_relationship.is_active = 0 )';
1006 $where .= ' AND civicrm_contact.is_deleted = 0';
1007 if(!empty($params['membership_type_id']) && empty($params['relationship_type_id'])) {
1008 $where .= self
::membershipTypeToRelationshipTypes($params, $direction);
1010 if(!empty($params['relationship_type_id'])) {
1011 if(is_array($params['relationship_type_id'])) {
1012 $where .= " AND " . CRM_Core_DAO
::createSQLFilter('relationship_type_id', $params['relationship_type_id'], 'Integer');
1015 $where .= ' AND relationship_type_id = ' . CRM_Utils_Type
::escape($params['relationship_type_id'], 'Positive');
1018 if ($direction == 'a_b') {
1019 $where .= ' ) UNION ';
1025 return array($select, $from, $where);
1029 * This is the function to get the list of relationships
1031 * @param int $contactId
1033 * @param int $status
1034 * 1: Past 2: Disabled 3: Current.
1035 * @param int $numRelationship
1036 * No of relationships to display (limit).
1038 * Get the no of relationships.
1039 * $param int $relationshipId relationship id
1040 * $param array $links the list of links to display
1041 * $param int $permissionMask the permission mask to be applied for the actions
1042 * $param boolean $permissionedContact to return only permissioned Contact
1043 * $param array $params array of variables consistent with filters supported by the api
1044 * return array $values relationship records
1045 * @param int $relationshipId
1046 * @param null $links
1047 * @param null $permissionMask
1048 * @param bool $permissionedContact
1049 * @param array $params
1054 static function getRelationship($contactId = NULL,
1055 $status = 0, $numRelationship = 0,
1056 $count = 0, $relationshipId = 0,
1057 $links = NULL, $permissionMask = NULL,
1058 $permissionedContact = FALSE,
1062 if (!$contactId && !$relationshipId) {
1066 list($select1, $from1, $where1) = self
::makeURLClause($contactId, $status, $numRelationship,
1067 $count, $relationshipId, 'a_b', $params
1069 list($select2, $from2, $where2) = self
::makeURLClause($contactId, $status, $numRelationship,
1070 $count, $relationshipId, 'b_a', $params
1073 $order = $limit = '';
1075 if (empty($params['sort'])) {
1076 $order = ' ORDER BY civicrm_relationship_type_id, sort_name ';
1079 $order = " ORDER BY {$params['sort']} ";
1083 if (!empty($params['offset']) && $params['offset'] > 0) {
1084 $offset = $params['offset'];
1087 if ($numRelationship) {
1088 $limit = " LIMIT {$offset}, $numRelationship";
1092 // building the query string
1093 $queryString = $select1 . $from1 . $where1 . $select2 . $from2 . $where2 . $order . $limit;
1095 $relationship = new CRM_Contact_DAO_Relationship();
1097 $relationship->query($queryString);
1100 $relationshipCount = 0;
1101 while ($relationship->fetch()) {
1102 $relationshipCount +
= $relationship->cnt1 +
$relationship->cnt2
;
1104 return $relationshipCount;
1109 if ($status != self
::INACTIVE
) {
1111 $mask = array_sum(array_keys($links));
1112 if ($mask & CRM_Core_Action
::DISABLE
) {
1113 $mask -= CRM_Core_Action
::DISABLE
;
1115 if ($mask & CRM_Core_Action
::ENABLE
) {
1116 $mask -= CRM_Core_Action
::ENABLE
;
1119 if ($status == self
::CURRENT
) {
1120 $mask |
= CRM_Core_Action
::DISABLE
;
1122 elseif ($status == self
::DISABLED
) {
1123 $mask |
= CRM_Core_Action
::ENABLE
;
1125 $mask = $mask & $permissionMask;
1128 while ($relationship->fetch()) {
1129 $rid = $relationship->civicrm_relationship_id
;
1130 $cid = $relationship->civicrm_contact_id
;
1131 if (($permissionedContact) &&
1132 (!CRM_Contact_BAO_Contact_Permission
::relationship($cid, $contactId))
1136 $values[$rid]['id'] = $rid;
1137 $values[$rid]['cid'] = $cid;
1138 $values[$rid]['contact_id_a'] = $relationship->contact_id_a
;
1139 $values[$rid]['contact_id_b'] = $relationship->contact_id_b
;
1140 $values[$rid]['contact_type'] = $relationship->contact_type
;
1141 $values[$rid]['relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1142 $values[$rid]['relation'] = $relationship->relation
;
1143 $values[$rid]['name'] = $relationship->sort_name
;
1144 $values[$rid]['display_name'] = $relationship->display_name
;
1145 $values[$rid]['job_title'] = $relationship->job_title
;
1146 $values[$rid]['email'] = $relationship->email
;
1147 $values[$rid]['phone'] = $relationship->phone
;
1148 $values[$rid]['employer_id'] = $relationship->employer_id
;
1149 $values[$rid]['organization_name'] = $relationship->organization_name
;
1150 $values[$rid]['country'] = $relationship->country
;
1151 $values[$rid]['city'] = $relationship->city
;
1152 $values[$rid]['state'] = $relationship->state
;
1153 $values[$rid]['start_date'] = $relationship->start_date
;
1154 $values[$rid]['end_date'] = $relationship->end_date
;
1155 $values[$rid]['description'] = $relationship->description
;
1156 $values[$rid]['is_active'] = $relationship->is_active
;
1157 $values[$rid]['is_permission_a_b'] = $relationship->is_permission_a_b
;
1158 $values[$rid]['is_permission_b_a'] = $relationship->is_permission_b_a
;
1159 $values[$rid]['case_id'] = $relationship->case_id
;
1162 $values[$rid]['status'] = $status;
1165 $values[$rid]['civicrm_relationship_type_id'] = $relationship->civicrm_relationship_type_id
;
1167 if ($relationship->contact_id_a
== $contactId) {
1168 $values[$rid]['rtype'] = 'a_b';
1171 $values[$rid]['rtype'] = 'b_a';
1177 'rtype' => $values[$rid]['rtype'],
1178 'cid' => $contactId,
1179 'cbid' => $values[$rid]['cid'],
1180 'caseid' => $values[$rid]['case_id'],
1181 'clientid' => $contactId,
1184 if ($status == self
::INACTIVE
) {
1185 // setting links for inactive relationships
1186 $mask = array_sum(array_keys($links));
1187 if (!$values[$rid]['is_active']) {
1188 $mask -= CRM_Core_Action
::DISABLE
;
1191 $mask -= CRM_Core_Action
::ENABLE
;
1192 $mask -= CRM_Core_Action
::DISABLE
;
1196 // Give access to manage case link by copying to MAX_ACTION index temporarily, depending on case permission of user.
1197 if ($values[$rid]['case_id']) {
1198 // Borrowed logic from CRM_Case_Page_Tab
1199 $hasCaseAccess = FALSE;
1200 if (CRM_Core_Permission
::check('access all cases and activities')) {
1201 $hasCaseAccess = TRUE;
1204 $userCases = CRM_Case_BAO_Case
::getCases(FALSE);
1205 if (array_key_exists($values[$rid]['case_id'], $userCases)) {
1206 $hasCaseAccess = TRUE;
1210 if ($hasCaseAccess) {
1211 // give access by copying to MAX_ACTION temporarily, otherwise leave at NONE which won't display
1212 $links[CRM_Core_Action
::MAX_ACTION
] = $links[CRM_Core_Action
::NONE
];
1213 $links[CRM_Core_Action
::MAX_ACTION
]['name'] = ts('Manage Case #%1', array(1 => $values[$rid]['case_id']));
1214 $links[CRM_Core_Action
::MAX_ACTION
]['class'] = 'no-popup';
1216 // Also make sure we have the right client cid since can get here from multiple relationship tabs.
1217 if ($values[$rid]['rtype'] == 'b_a') {
1218 $replace['clientid'] = $values[$rid]['cid'];
1223 $values[$rid]['action'] = CRM_Core_Action
::formLink(
1229 'relationship.selector.row',
1232 unset($links[CRM_Core_Action
::MAX_ACTION
]);
1236 $relationship->free();
1242 * Get get list of relationship type based on the target contact type.
1244 * @param string $targetContactType
1245 * It's valid contact tpye(may be Individual , Organization , Household).
1247 * @return array - array reference of all relationship types with context to current contact type .
1250 public function getRelationType($targetContactType) {
1251 $relationshipType = array();
1252 $allRelationshipType = CRM_Core_PseudoConstant
::relationshipType();
1254 foreach ($allRelationshipType as $key => $type) {
1255 if ($type['contact_type_b'] == $targetContactType) {
1256 $relationshipType[$key . '_a_b'] = $type['label_a_b'];
1260 return $relationshipType;
1264 * Create / update / delete membership for related contacts.
1266 * This function will create/update/delete membership for related
1267 * contact based on 1) contact have active membership 2) that
1268 * membership is is extedned by the same relationship type to that
1269 * of the existing relationship.
1274 * Array array of values submitted by POST.
1276 * Array array of ids.
1277 * @param \const|\which $action which action called this function
1279 * @param bool $active
1283 public static function relatedMemberships($contactId, &$params, $ids, $action = CRM_Core_Action
::ADD
, $active = TRUE) {
1284 // Check the end date and set the status of the relationship
1286 $status = self
::CURRENT
;
1288 if (!empty($params['end_date'])) {
1289 $endDate = CRM_Utils_Date
::setDateDefaults(CRM_Utils_Date
::format($params['end_date']), NULL, 'Ymd');
1290 $today = date('Ymd');
1292 if ($today > $endDate) {
1293 $status = self
::PAST
;
1297 if (($action & CRM_Core_Action
::ADD
) &&
1298 ($status & self
::PAST
)
1300 // if relationship is PAST and action is ADD, no qustion
1301 // of creating RELATED membership and return back to
1306 $rel = explode('_', $params['relationship_type_id']);
1308 $relTypeId = $rel[0];
1309 if (!empty($rel[1])) {
1310 $relDirection = "_{$rel[1]}_{$rel[2]}";
1313 // this call is coming from somewhere where the direction was resolved early on (e.g an api call)
1314 // so we can assume _a_b
1315 $relDirection = "_a_b";
1317 $targetContact = array();
1318 if (($action & CRM_Core_Action
::ADD
) ||
1319 ($action & CRM_Core_Action
::DELETE
)
1321 $contact = $contactId;
1322 $targetContact = CRM_Utils_Array
::value('contact_check', $params);
1324 elseif ($action & CRM_Core_Action
::UPDATE
) {
1325 $contact = $ids['contact'];
1326 $targetContact = array($ids['contactTarget'] => 1);
1329 // Build the 'values' array for
1332 // This will allow us to check if either of the contacts in
1333 // relationship have active memberships.
1338 $values[$contact] = array(
1339 'relatedContacts' => $targetContact,
1340 'relationshipTypeId' => $relTypeId,
1341 'relationshipTypeDirection' => $relDirection,
1344 if (!empty($targetContact)) {
1345 foreach ($targetContact as $cid => $donCare) {
1346 $values[$cid] = array(
1347 'relatedContacts' => array($contact => 1),
1348 'relationshipTypeId' => $relTypeId,
1351 $relTypeParams = array('id' => $relTypeId);
1352 $relTypeValues = array();
1353 CRM_Contact_BAO_RelationshipType
::retrieve($relTypeParams, $relTypeValues);
1355 if (CRM_Utils_Array
::value('name_a_b', $relTypeValues) == CRM_Utils_Array
::value('name_b_a', $relTypeValues)) {
1356 $values[$cid]['relationshipTypeDirection'] = '_a_b';
1359 $values[$cid]['relationshipTypeDirection'] = ($relDirection == '_a_b') ?
'_b_a' : '_a_b';
1364 // Now get the active memberships for all the contacts.
1365 // If contact have any valid membership(s), then add it to
1367 foreach ($values as $cid => $subValues) {
1368 $memParams = array('contact_id' => $cid);
1369 $memberships = array();
1371 CRM_Member_BAO_Membership
::getValues($memParams, $memberships, $active);
1373 if (empty($memberships)) {
1377 $values[$cid]['memberships'] = $memberships;
1379 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1381 // done with 'values' array.
1382 // Finally add / edit / delete memberships for the related contacts
1383 foreach ($values as $cid => $details) {
1384 if (!array_key_exists('memberships', $details)) {
1388 $mainRelatedContactId = key(CRM_Utils_Array
::value('relatedContacts', $details, array()));
1390 foreach ($details['memberships'] as $membershipId => $membershipValues) {
1391 $relTypeIds = array();
1392 if ($action & CRM_Core_Action
::DELETE
) {
1393 // Delete memberships of the related contacts only if relationship type exists for membership type
1395 SELECT relationship_type_id, relationship_direction
1396 FROM civicrm_membership_type
1397 WHERE id = {$membershipValues['membership_type_id']}";
1398 $dao = CRM_Core_DAO
::executeQuery($query);
1399 $relTypeDirs = array();
1400 while ($dao->fetch()) {
1401 $relTypeId = $dao->relationship_type_id
;
1402 $relDirection = $dao->relationship_direction
;
1404 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $relTypeId);
1405 if (in_array($values[$cid]['relationshipTypeId'], $relTypeIds)) {
1406 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $mainRelatedContactId);
1410 if (($action & CRM_Core_Action
::UPDATE
) &&
1411 ($status & self
::PAST
) &&
1412 ($membershipValues['owner_membership_id'])
1414 // If relationship is PAST and action is UPDATE
1415 // then delete the RELATED membership
1416 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipValues['owner_membership_id'],
1417 $membershipValues['membership_contact_id']
1422 // add / edit the memberships for related
1425 // Get the Membership Type Details.
1426 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipValues['membership_type_id']);
1427 // Check if contact's relationship type exists in membership type
1428 $relTypeDirs = array();
1429 if (!empty($membershipType['relationship_type_id'])) {
1430 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_type_id']);
1432 if (!empty($membershipType['relationship_direction'])) {
1433 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_direction']);
1435 foreach ($relTypeIds as $key => $value) {
1436 $relTypeDirs[] = $value . '_' . $relDirections[$key];
1438 $relTypeDir = $details['relationshipTypeId'] . $details['relationshipTypeDirection'];
1439 if (in_array($relTypeDir, $relTypeDirs)) {
1440 // Check if relationship being created/updated is
1441 // similar to that of membership type's
1444 $membershipValues['owner_membership_id'] = $membershipId;
1445 unset($membershipValues['id']);
1446 unset($membershipValues['membership_contact_id']);
1447 unset($membershipValues['contact_id']);
1448 unset($membershipValues['membership_id']);
1449 foreach ($details['relatedContacts'] as $relatedContactId => $donCare) {
1450 $membershipValues['contact_id'] = $relatedContactId;
1451 if ($deceasedStatusId &&
1452 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $relatedContactId, 'is_deceased')
1454 $membershipValues['status_id'] = $deceasedStatusId;
1455 $membershipValues['skipStatusCal'] = TRUE;
1458 'join_date', 'start_date', 'end_date') as $dateField) {
1459 if (!empty($membershipValues[$dateField])) {
1460 $membershipValues[$dateField] = CRM_Utils_Date
::processDate($membershipValues[$dateField]);
1464 if ($action & CRM_Core_Action
::UPDATE
) {
1465 //delete the membership record for related
1466 //contact before creating new membership record.
1467 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $relatedContactId);
1470 // check whether we have some related memberships still available
1473 FROM civicrm_membership
1474 LEFT JOIN civicrm_membership_status ON (civicrm_membership_status.id = civicrm_membership.status_id)
1475 WHERE membership_type_id = {$membershipValues['membership_type_id']} AND owner_membership_id = {$membershipValues['owner_membership_id']}
1476 AND is_current_member = 1";
1477 $result = CRM_Core_DAO
::singleValueQuery($query);
1478 if ($result < CRM_Utils_Array
::value('max_related', $membershipValues, PHP_INT_MAX
)) {
1479 CRM_Member_BAO_Membership
::create($membershipValues, CRM_Core_DAO
::$_nullArray);
1483 elseif ($action & CRM_Core_Action
::UPDATE
) {
1484 // if action is update and updated relationship do
1485 // not match with the existing
1486 // membership=>relationship then we need to
1487 // delete the membership record created for
1488 // previous relationship.
1490 if (self
::isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, CRM_Utils_Array
::value('relationship_ids', $params))) {
1491 CRM_Member_BAO_Membership
::deleteRelatedMemberships($membershipId, $mainRelatedContactId);
1499 * Helper function to check whether to delete the membership or
1505 public static function isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, $relIds) {
1506 if (in_array($relTypeId, $relTypeIds)) {
1510 if (empty($relIds)) {
1514 $relParamas = array(1 => array($contactId, 'Integer'),
1515 2 => array($mainRelatedContactId, 'Integer'),
1518 if ($contactId == $mainRelatedContactId) {
1519 $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);
1520 if ($recordsFound) {
1526 $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);
1528 if ($recordsFound) {
1536 * Get Current Employer for Contact
1538 * @param $contactIds
1541 * @return array $currentEmployer array of the current employer@static
1543 public static function getCurrentEmployer($contactIds) {
1544 $contacts = implode(',', $contactIds);
1547 SELECT organization_name, id, employer_id
1548 FROM civicrm_contact
1549 WHERE id IN ( {$contacts} )
1552 $dao = CRM_Core_DAO
::executeQuery($query, CRM_Core_DAO
::$_nullArray);
1553 $currentEmployer = array();
1554 while ($dao->fetch()) {
1555 $currentEmployer[$dao->id
]['org_id'] = $dao->employer_id
;
1556 $currentEmployer[$dao->id
]['org_name'] = $dao->organization_name
;
1559 return $currentEmployer;
1563 * Return list of permissioned employer for a given contact.
1566 * Int contact id whose employers.
1569 * String employers sort name.
1573 * @return array array of employers.
1576 public static function getPermissionedEmployer($contactID, $name = NULL) {
1577 //get the relationship id
1578 $relTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType',
1579 'Employee of', 'id', 'name_a_b'
1582 return self
::getPermissionedContacts($contactID, $relTypeId, $name);
1587 * Function to return list of permissioned contacts for a given contact and relationship type
1590 * Int contact id whose permissioned contacts are to be found.
1592 * String one or more relationship type id's.
1598 * @return array of contacts
1600 public static function getPermissionedContacts($contactID, $relTypeId, $name = NULL) {
1601 $contacts = array();
1605 SELECT cc.id as id, cc.sort_name as name
1606 FROM civicrm_relationship cr, civicrm_contact cc
1608 cr.contact_id_a = %1 AND
1609 cr.relationship_type_id IN (%2) AND
1610 cr.is_permission_a_b = 1 AND
1611 IF(cr.end_date IS NULL, 1, (DATEDIFF( CURDATE( ), cr.end_date ) <= 0)) AND
1612 cr.is_active = 1 AND
1613 cc.id = cr.contact_id_b AND
1616 if (!empty($name)) {
1617 $name = CRM_Utils_Type
::escape($name, 'String');
1619 AND cc.sort_name LIKE '%$name%'";
1622 $args = array(1 => array($contactID, 'Integer'), 2 => array($relTypeId, 'String'));
1623 $dao = CRM_Core_DAO
::executeQuery($query, $args);
1625 while ($dao->fetch()) {
1626 $contacts[$dao->id
] = array(
1627 'name' => $dao->name
,
1628 'value' => $dao->id
,
1636 * Merge relationships from otherContact to mainContact
1637 * Called during contact merge operation
1639 * @param int $mainId
1640 * Contact id of main contact record.
1641 * @param int $otherId
1642 * Contact id of record which is going to merge.
1643 * @param array $sqls
1644 * (reference) array of sql statements to append to.
1646 * @see CRM_Dedupe_Merger::cpTables()
1650 public static function mergeRelationships($mainId, $otherId, &$sqls) {
1651 // Delete circular relationships
1652 $sqls[] = "DELETE FROM civicrm_relationship
1653 WHERE (contact_id_a = $mainId AND contact_id_b = $otherId)
1654 OR (contact_id_b = $mainId AND contact_id_a = $otherId)";
1656 // Delete relationship from other contact if main contact already has that relationship
1657 $sqls[] = "DELETE r2
1658 FROM civicrm_relationship r1, civicrm_relationship r2
1659 WHERE r1.relationship_type_id = r2.relationship_type_id
1662 r1.contact_id_a = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_b = r2.contact_id_b
1663 OR r1.contact_id_b = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_a = r2.contact_id_a
1665 (r1.contact_id_a = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_b = r2.contact_id_a
1666 OR r1.contact_id_b = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_a = r2.contact_id_b)
1667 AND r1.relationship_type_id IN (SELECT id FROM civicrm_relationship_type WHERE name_b_a = name_a_b)
1671 // Move relationships
1672 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_a = $mainId WHERE contact_id_a = $otherId";
1673 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_b = $mainId WHERE contact_id_b = $otherId";
1675 // Move current employer id (name will get updated later)
1676 $sqls[] = "UPDATE civicrm_contact SET employer_id = $mainId WHERE employer_id = $otherId";
1680 * Set 'is_valid' field to false for all relationships whose end date is in the past, ie. are expired.
1682 * @return True on success, false if error is encountered.
1684 public static function disableExpiredRelationships() {
1685 $query = "SELECT id FROM civicrm_relationship WHERE is_active = 1 AND end_date < CURDATE()";
1687 $dao = CRM_Core_DAO
::executeQuery($query);
1688 while ($dao->fetch()) {
1689 $result = CRM_Contact_BAO_Relationship
::setIsActive($dao->id
, FALSE);
1690 // Result will be NULL if error occurred. We abort early if error detected.
1691 if ($result == NULL) {
1699 * Function filters the query by possible relationships for the membership type
1700 * It is intended to be called when constructing queries for the api (reciprocal & non-reciprocal)
1701 * and to add clauses to limit the return to those relationships which COULD inherit a membership type
1702 * (as opposed to those who inherit a particular membership
1704 * @param array $params
1706 * @param null $direction
1710 public static function membershipTypeToRelationshipTypes(&$params, $direction = NULL) {
1711 $membershipType = civicrm_api3('membership_type', 'getsingle', array('id' => $params['membership_type_id'], 'return' => 'relationship_type_id, relationship_direction'));
1712 $relationshipTypes = $membershipType['relationship_type_id'];
1713 if(empty($relationshipTypes)) {
1716 // if we don't have any contact data we can only filter on type
1717 if(empty($params['contact_id']) && empty($params['contact_id_a']) && empty($params['contact_id_a'])) {
1718 $params['relationship_type_id'] = array('IN' => $relationshipTypes);
1722 $relationshipDirections = (array) $membershipType['relationship_direction'];
1723 // if we have contact_id_a OR contact_id_b we can make a call here
1724 // if we have contact??
1725 foreach ($relationshipDirections as $index => $mtdirection) {
1726 if(isset($params['contact_id_a']) && $mtdirection == 'a_b' ||
$direction == 'a_b') {
1727 $types[] = $relationshipTypes[$index];
1729 if(isset($params['contact_id_b']) && $mtdirection == 'b_a' ||
$direction == 'b_a') {
1730 $types[] = $relationshipTypes[$index];
1733 if(!empty($types)) {
1734 $params['relationship_type_id'] = array('IN' => $types);
1736 elseif(!empty($clauses)) {
1737 return explode(' OR ', $clauses);
1740 // effectively setting it to return no results
1741 $params['relationship_type_id'] = 0;
1748 * This function is a wrapper for contact relationship selector
1750 * @param array $params
1751 * Associated array for params record id.
1753 * @return array $contactRelationships associated array of contact relationships
1755 public static function getContactRelationshipSelector(&$params) {
1756 // format the params
1757 $params['offset'] = ($params['page'] - 1) * $params['rp'];
1758 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
1760 if ($params['context'] == 'past') {
1761 $relationshipStatus = CRM_Contact_BAO_Relationship
::INACTIVE
;
1764 $relationshipStatus = CRM_Contact_BAO_Relationship
::CURRENT
;
1767 // check logged in user for permission
1768 $page = new CRM_Core_Page();
1769 CRM_Contact_Page_View
::checkUserPermission($page, $params['contact_id']);
1770 $permissions = array($page->_permission
);
1771 if ($page->_permission
== CRM_Core_Permission
::EDIT
) {
1772 $permissions[] = CRM_Core_Permission
::DELETE
;
1774 $mask = CRM_Core_Action
::mask($permissions);
1776 if ($params['context'] != 'user') {
1777 $links = CRM_Contact_Page_View_Relationship
::links();
1778 $permissionedContacts = FALSE;
1781 $links = CRM_Contact_Page_View_UserDashBoard
::links();
1782 $permissionedContacts = TRUE;
1785 // get contact relationships
1786 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1787 $relationshipStatus,
1788 $params['rp'], 0, 0,
1790 $permissionedContacts,
1794 $contactRelationships = array();
1795 $params['total'] = 0;
1796 if (!empty($relationships)) {
1797 // get the total relationships
1798 if ($params['context'] != 'user') {
1799 $params['total'] = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1800 $relationshipStatus, 0, 1, 0, NULL, NULL, $permissionedContacts);
1803 // FIX ME: we cannot directly determine total permissioned relationship, hence re-fire query
1804 $permissionedRelationships = CRM_Contact_BAO_Relationship
::getRelationship($params['contact_id'],
1805 $relationshipStatus,
1809 $params['total'] = count($permissionedRelationships);
1813 foreach ($relationships as $relationshipId => $values) {
1814 //Add image icon for related contacts: CRM-14919
1815 $icon = CRM_Contact_BAO_Contact_Utils
::getImage($values['contact_type'],
1819 $contactRelationships[$relationshipId]['name'] = $icon.' '.CRM_Utils_System
::href(
1821 'civicrm/contact/view',
1822 "reset=1&cid={$values['cid']}");
1824 $contactRelationships[$relationshipId]['relation'] = CRM_Utils_System
::href(
1825 $values['relation'],
1826 'civicrm/contact/view/rel',
1827 "action=view&reset=1&cid={$values['cid']}&id={$values['id']}&rtype={$values['rtype']}");
1829 if ($params['context'] == 'current') {
1830 if (($params['contact_id'] == $values['contact_id_a'] AND $values['is_permission_a_b'] == 1) OR
1831 ($params['contact_id'] == $values['contact_id_b'] AND $values['is_permission_b_a'] == 1)
1833 $contactRelationships[$relationshipId]['name'] .= '<span id="permission-a-b" class="crm-marker permission-relationship"> *</span>';
1836 if (($values['cid'] == $values['contact_id_a'] AND $values['is_permission_a_b'] == 1) OR
1837 ($values['cid'] == $values['contact_id_b'] AND $values['is_permission_b_a'] == 1)
1839 $contactRelationships[$relationshipId]['relation'] .= '<span id="permission-b-a" class="crm-marker permission-relationship"> *</span>';
1843 if (!empty($values['description'])) {
1844 $contactRelationships[$relationshipId]['relation'] .= "<p class='description'>{$values['description']}</p>";
1847 $contactRelationships[$relationshipId]['start_date'] = CRM_Utils_Date
::customFormat($values['start_date']);
1848 $contactRelationships[$relationshipId]['end_date'] = CRM_Utils_Date
::customFormat($values['end_date']);
1849 $contactRelationships[$relationshipId]['city'] = $values['city'];
1850 $contactRelationships[$relationshipId]['state'] = $values['state'];
1851 $contactRelationships[$relationshipId]['email'] = $values['email'];
1852 $contactRelationships[$relationshipId]['phone'] = $values['phone'];
1853 $contactRelationships[$relationshipId]['links'] = $values['action'];
1854 $contactRelationships[$relationshipId]['id'] = $values['id'];
1855 $contactRelationships[$relationshipId]['is_active'] = $values['is_active'];
1858 return $contactRelationships;