Merge pull request #1885 from ar-jan/CRM-13687
[civicrm-core.git] / CRM / Contact / BAO / Relationship.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
232624b1 4 | CiviCRM version 4.4 |
6a488035
TO
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26*/
27
28/**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2013
32 * $Id$
33 *
34 */
35class CRM_Contact_BAO_Relationship extends CRM_Contact_DAO_Relationship {
36
37 /**
38 * various constants to indicate different type of relationships
39 *
40 * @var int
41 */
42 CONST PAST = 1, DISABLED = 2, CURRENT = 4, INACTIVE = 8;
43
44 /**
45 * takes an associative array and creates a relationship object
46 *
47 *
48 * @param array $params (reference ) an assoc array of name/value pairs
49 * @param array $ids the array that holds all the db ids
26dcc9eb 50 * per http://wiki.civicrm.org/confluence/display/CRM/Database+layer
51 * "we are moving away from the $ids param "
6a488035
TO
52 *
53 * @return object CRM_Contact_BAO_Relationship object
54 * @access public
55 * @static
56 */
26dcc9eb 57 static function create(&$params, $ids = array()) {
6a488035 58 $valid = $invalid = $duplicate = $saved = 0;
26dcc9eb 59 $relationships = array();
60 $relationshipId = CRM_Utils_Array::value('relationship', $ids, CRM_Utils_Array::value('id', $params));
6a488035
TO
61 //CRM-9015 - the hooks are called here & in add (since add doesn't call create)
62 // but in future should be tidied per ticket
26dcc9eb 63 if(empty($relationshipId)){
64 $hook = 'create';
65 $action = CRM_Core_Action::ADD;
6a488035 66 }
26dcc9eb 67 else{
68 $hook = 'edit';
69 $action = CRM_Core_Action::UPDATE;
6a488035 70 }
26dcc9eb 71
72 CRM_Utils_Hook::pre($hook, 'Relationship', $relationshipId, $params);
73
6a488035
TO
74 if (!$relationshipId) {
75 // creating a new relationship
76 $dataExists = self::dataExists($params);
77 if (!$dataExists) {
43291913 78 return array(FALSE, TRUE, FALSE, FALSE, NULL);
6a488035
TO
79 }
80 $relationshipIds = array();
81 foreach ($params['contact_check'] as $key => $value) {
82 $errors = '';
83 // check if the relationship is valid between contacts.
84 // step 1: check if the relationship is valid if not valid skip and keep the count
85 // step 2: check the if two contacts already have a relationship if yes skip and keep the count
86 // step 3: if valid relationship then add the relation and keep the count
87
88 // step 1
89 $errors = self::checkValidRelationship($params, $ids, $key);
90 if ($errors) {
91 $invalid++;
92 continue;
93 }
94
95 if (
96 self::checkDuplicateRelationship(
97 $params,
98 CRM_Utils_Array::value('contact', $ids),
99 // step 2
100 $key
101 )
102 ) {
103 $duplicate++;
104 continue;
105 }
106
107 $relationship = self::add($params, $ids, $key);
108 $relationshipIds[] = $relationship->id;
26dcc9eb 109 $relationships[$relationship->id] = $relationship;
6a488035
TO
110 $valid++;
111 }
112 // editing the relationship
113 }
114 else {
115 // check for duplicate relationship
49f8272d
E
116 //@todo this code doesn't cope well with updates - causes e-Notices. API has a lot of code to work around
117 // this but should review this code & remove the extra handling from the api
118 // it seems doubtful any of this is relevant if the contact fields & relationship type fields are not set
6a488035
TO
119 if (
120 self::checkDuplicateRelationship(
121 $params,
122 CRM_Utils_Array::value('contact', $ids),
123 $ids['contactTarget'],
124 $relationshipId
125 )
126 ) {
127 $duplicate++;
43291913 128 return array($valid, $invalid, $duplicate, $saved, NULL);
6a488035
TO
129 }
130
131 $validContacts = TRUE;
132 //validate contacts in update mode also.
133 if (CRM_Utils_Array::value('contact', $ids) &&
134 CRM_Utils_Array::value('contactTarget', $ids)
135 ) {
136 if (self::checkValidRelationship($params, $ids, $ids['contactTarget'])) {
137 $validContacts = FALSE;
138 $invalid++;
139 }
140 }
141 if ($validContacts) {
142 // editing an existing relationship
143 $relationship = self::add($params, $ids, $ids['contactTarget']);
144 $relationshipIds[] = $relationship->id;
26dcc9eb 145 $relationships[$relationship->id] = $relationship;
6a488035
TO
146 $saved++;
147 }
148 }
149
150 // do not add to recent items for import, CRM-4399
151 if (!(CRM_Utils_Array::value('skipRecentView', $params) || $invalid || $duplicate)) {
152 $url = CRM_Utils_System::url('civicrm/contact/view/rel',
153 "action=view&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&context=home"
154 );
155
156
157 $session = CRM_Core_Session::singleton();
158 $recentOther = array();
159 if (($session->get('userID') == $relationship->contact_id_a) ||
160 CRM_Contact_BAO_Contact_Permission::allow($relationship->contact_id_a, CRM_Core_Permission::EDIT)
161 ) {
162 $rType = substr(CRM_Utils_Array::value('relationship_type_id', $params), -3);
163 $recentOther = array(
164 'editUrl' => CRM_Utils_System::url('civicrm/contact/view/rel',
165 "action=update&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
166 ),
167 'deleteUrl' => CRM_Utils_System::url('civicrm/contact/view/rel',
168 "action=delete&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
169 ),
170 );
171 }
172
173 $title = CRM_Contact_BAO_Contact::displayName($relationship->contact_id_a) . ' (' . CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType',
174 $relationship->relationship_type_id, 'label_a_b'
175 ) . ' ' . CRM_Contact_BAO_Contact::displayName($relationship->contact_id_b) . ')';
6a488035
TO
176 // add the recently created Relationship
177 CRM_Utils_Recent::add($title,
178 $url,
179 $relationship->id,
180 'Relationship',
181 $relationship->contact_id_a,
182 NULL,
183 $recentOther
184 );
185 }
186
26dcc9eb 187 return array($valid, $invalid, $duplicate, $saved, $relationshipIds, $relationships);
6a488035
TO
188 }
189
190 /**
191 * This is the function that check/add if the relationship created is valid
192 *
193 * @param array $params (reference ) an assoc array of name/value pairs
194 * @param integer $contactId this is contact id for adding relationship
195 * @param array $ids the array that holds all the db ids
196 *
197 * @return object CRM_Contact_BAO_Relationship
198 * @access public
199 * @static
200 */
49f8272d
E
201 static function add(&$params, $ids = array(), $contactId = NULL) {
202 $relationshipId = CRM_Utils_Array::value('relationship', $ids, CRM_Utils_Array::value('id', $params));
203 $hook = 'create';
204 if($relationshipId) {
205 $hook = 'edit';
6a488035 206 }
49f8272d
E
207 //@todo hook are called from create and add - remove one
208 CRM_Utils_Hook::pre($hook , 'Relationship', $relationshipId, $params);
6a488035
TO
209
210 $relationshipTypes = CRM_Utils_Array::value('relationship_type_id', $params);
211
212 // expolode the string with _ to get the relationship type id and to know which contact has to be inserted in
213 // contact_id_a and which one in contact_id_b
214 list($type, $first, $second) = explode('_', $relationshipTypes);
215
216 ${'contact_' . $first} = CRM_Utils_Array::value('contact', $ids);
217 ${'contact_' . $second} = $contactId;
218
219 //check if the relationship type is Head of Household then update the household's primary contact with this contact.
220 if ($type == 6) {
221 CRM_Contact_BAO_Household::updatePrimaryContact($contact_b, $contact_a);
222 }
223
224 $relationship = new CRM_Contact_BAO_Relationship();
49f8272d
E
225 //@todo this code needs to be updated for the possibility that not all fields are set
226 // (update)
6a488035
TO
227 $relationship->contact_id_b = $contact_b;
228 $relationship->contact_id_a = $contact_a;
229 $relationship->relationship_type_id = $type;
49f8272d 230 $relationship->id = $relationshipId;
6a488035
TO
231
232 $dateFields = array('end_date', 'start_date');
233
234 foreach (self::getdefaults() as $defaultField => $defaultValue){
235 if(isset($params[$defaultField])){
236 if(in_array($defaultField, $dateFields)){
237 $relationship->$defaultField = CRM_Utils_Date::format(CRM_Utils_Array::value($defaultField, $params));
238 if(!$relationship->$defaultField){
239 $relationship->$defaultField = 'NULL';
240 }
241 }
242 else{
243 $relationship->$defaultField = $params[$defaultField];
244 }
245 }
49f8272d 246 elseif(!$relationshipId){
6a488035
TO
247 $relationship->$defaultField = $defaultValue;
248 }
249 }
250
251 $relationship->save();
252
253 // add custom field values
254 if (CRM_Utils_Array::value('custom', $params)) {
255 CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_relationship', $relationship->id);
256 }
257
258 $relationship->free();
259
49f8272d 260 CRM_Utils_Hook::post($hook, 'Relationship', $relationshipId, $relationship);
6a488035
TO
261
262 return $relationship;
263 }
264 /**
265 * Specifiy defaults for creating a relationship
266 *
267 * @return array $defaults array of defaults for creating relationship
268 * @access public
269 * @static
270 */
271 static function getdefaults() {
272 return array(
273 'is_active' => 0,
274 'is_permission_a_b' => 0,
275 'is_permission_b_a' => 0,
276 'description' => '',
277 'start_date' => 'NULL',
278 'case_id' => NULL,
279 'end_date' => 'NULL',
280 );
281 }
282
283
284 /**
285 * Check if there is data to create the object
286 *
287 * @param array $params (reference ) an assoc array of name/value pairs
288 *
289 * @return boolean
290 * @access public
291 * @static
292 */
293 static function dataExists(&$params) {
294 // return if no data present
295 if (!is_array(CRM_Utils_Array::value('contact_check', $params))) {
296 return FALSE;
297 }
298 return TRUE;
299 }
300
301 /**
302 * Function to get get list of relationship type based on the contact type.
303 *
304 * @param int $contactId this is the contact id of the current contact.
305 * @param string $strContact this value is currently ignored, keeping it there for legacy reasons
306 * @param string $relationshipId the id of the existing relationship if any
307 * @param string $contactType contact type
308 * @param boolean $all if true returns relationship types in both the direction
309 * @param string $column name/label that going to retrieve from db.
310 *
311 *
312 * @param string $contactSubType includes relationshiptypes between this subtype
313 *
314 * @param boolean $onlySubTypeRelationTypes if set only subtype which is passed by $contactSubType
315 * related relationshiptypes get return
316 * @access public
317 * @static
318 *
319 * @return array - array reference of all relationship types with context to current contact.
320 */
321 static function getContactRelationshipType($contactId = NULL,
322 $contactSuffix = NULL,
323 $relationshipId = NULL,
324 $contactType = NULL,
325 $all = FALSE,
326 $column = 'label',
327 $biDirectional = TRUE,
328 $contactSubType = NULL,
329 $onlySubTypeRelationTypes = FALSE
330 ) {
331 $allRelationshipType = array();
332 $relationshipType = array();
333 $allRelationshipType = CRM_Core_PseudoConstant::relationshipType($column);
334
335 $otherContactType = NULL;
336 if ($relationshipId) {
337 $relationship = new CRM_Contact_DAO_Relationship();
338 $relationship->id = $relationshipId;
339 if ($relationship->find(TRUE)) {
340 $contact = new CRM_Contact_DAO_Contact();
341 $contact->id = ($relationship->contact_id_a === $contactId) ? $relationship->contact_id_b : $relationship->contact_id_a;
342
343 if ($contact->find(TRUE)) {
344 $otherContactType = $contact->contact_type;
345 //CRM-5125 for contact subtype specific relationshiptypes
346 if ($contact->contact_sub_type) {
347 $otherContactSubType = $contact->contact_sub_type;
348 }
349 }
350 }
351 }
352
353 $contactSubType = array();
354 if ($contactId) {
355 $contactType = CRM_Contact_BAO_Contact::getContactType($contactId);
356 $contactSubType = CRM_Contact_BAO_Contact::getContactSubType($contactId);
357 }
358
359 foreach ($allRelationshipType as $key => $value) {
360 // the contact type is required or matches
361 if (((!$value['contact_type_a']) ||
362 $value['contact_type_a'] == $contactType
363 ) &&
364 // the other contact type is required or present or matches
365 ((!$value['contact_type_b']) ||
366 (!$otherContactType) ||
367 $value['contact_type_b'] == $otherContactType
368 ) &&
369 (!$contactSubType ||
370 (in_array($value['contact_sub_type_a'], $contactSubType) ||
371 ((!$value['contact_sub_type_b'] &&
372 !$value['contact_sub_type_a']
373 ) &&
374 !$onlySubTypeRelationTypes
375 )
376 )
377 )
378 ) {
379 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
380 }
381 elseif (empty($value['contact_type_b'])) {
382 // case contact_type_b is "all contacts", CRM-9877
383 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
384 }
385
386 if (((!$value['contact_type_b']) ||
387 $value['contact_type_b'] == $contactType
388 ) &&
389 ((!$value['contact_type_a']) ||
390 (!$otherContactType) ||
391 $value['contact_type_a'] == $otherContactType
392 ) &&
393 (!$contactSubType ||
394 (in_array($value['contact_sub_type_b'], $contactSubType) ||
395 ((!$value['contact_sub_type_a'] &&
396 !$value['contact_sub_type_b']
397 ) &&
398 !$onlySubTypeRelationTypes
399 )
400 )
401 )
402 ) {
403 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
404 }
405 elseif (empty($value['contact_type_a'])) {
406 // case contact_type_a is "all contacts", CRM-9877
407 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
408 }
409
410 if ($all) {
411 $relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
412 $relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
413 }
414 }
415
416 if ($biDirectional) {
417 // lets clean up the data and eliminate all duplicate values
418 // (i.e. the relationship is bi-directional)
419 $relationshipType = array_unique($relationshipType);
420 }
421
422 // sort the relationshipType in ascending order CRM-7736
423 asort($relationshipType);
424 return $relationshipType;
425 }
426
427 static function clearCurrentEmployer($id, $action) {
428 $relationship = new CRM_Contact_DAO_Relationship();
429 $relationship->id = $id;
430 $relationship->find(TRUE);
431
432 //to delete relationship between household and individual \
433 //or between individual and orgnization
434 if (($action & CRM_Core_Action::DISABLE) || ($action & CRM_Core_Action::DELETE)) {
05802b8e
DG
435 $relTypes = CRM_Utils_Array::index(array('name_a_b'), CRM_Core_PseudoConstant::relationshipType('name'));
436 if ($relationship->relationship_type_id == $relTypes['Employee of']['id'] ||
437 $relationship->relationship_type_id == $relTypes['Household Member of']['id']) {
438 $sharedContact = new CRM_Contact_DAO_Contact();
439 $sharedContact->id = $relationship->contact_id_a;
440 $sharedContact->find(TRUE);
441
442 if ($relationship->relationship_type_id == 4 && $relationship->contact_id_b == $sharedContact->employer_id) {
443 CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($relationship->contact_id_a);
444 }
6a488035
TO
445 }
446 }
6a488035
TO
447 return $relationship;
448 }
449
450 /**
451 * Function to delete the relationship
452 *
453 * @param int $id relationship id
454 *
455 * @return null
456 * @access public
457 *
458 * @static
459 */
460 static function del($id) {
461 // delete from relationship table
462 CRM_Utils_Hook::pre('delete', 'Relationship', $id, CRM_Core_DAO::$_nullArray);
463
464 $relationship = self::clearCurrentEmployer($id, CRM_Core_Action::DELETE);
465 if (CRM_Core_Permission::access('CiviMember')) {
466 // create $params array which isrequired to delete memberships
467 // of the related contacts.
468 $params = array(
469 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
470 'contact_check' => array($relationship->contact_id_b => 1),
471 );
472
473 $ids = array();
474 // calling relatedMemberships to delete the memberships of
475 // related contacts.
476 self::relatedMemberships($relationship->contact_id_a,
477 $params,
478 $ids,
479 CRM_Core_Action::DELETE,
480 FALSE
481 );
482 }
483
484 $relationship->delete();
485 CRM_Core_Session::setStatus(ts('Selected relationship has been deleted successfully.'), ts('Record Deleted'), 'success');
486
487 CRM_Utils_Hook::post('delete', 'Relationship', $relationship->id, $relationship);
488
489 // delete the recently created Relationship
490 $relationshipRecent = array(
491 'id' => $id,
492 'type' => 'Relationship',
493 );
494 CRM_Utils_Recent::del($relationshipRecent);
495
496 return $relationship;
497 }
498
499 /**
500 * Function to disable/enable the relationship
501 *
502 * @param int $id relationship id
503 *
504 * @return null
505 * @access public
506
507 * @static
508 */
509 static function disableEnableRelationship($id, $action) {
510 $relationship = self::clearCurrentEmployer($id, $action);
511 if (CRM_Core_Permission::access('CiviMember')) {
512 // create $params array which isrequired to delete memberships
513 // of the related contacts.
514 $params = array(
515 'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
516 'contact_check' => array($relationship->contact_id_b => 1),
517 );
518
519 $ids = array();
520 // calling relatedMemberships to delete/add the memberships of
521 // related contacts.
522 if ($action & CRM_Core_Action::DISABLE) {
523 CRM_Contact_BAO_Relationship::relatedMemberships($relationship->contact_id_a,
524 $params,
525 $ids,
526 CRM_Core_Action::DELETE,
527 FALSE
528 );
529 }
530 elseif ($action & CRM_Core_Action::ENABLE) {
531 $ids['contact'] = $relationship->contact_id_a;
532 CRM_Contact_BAO_Relationship::relatedMemberships($relationship->contact_id_a,
533 $params,
534 $ids,
535 CRM_Core_Action::ADD,
536 FALSE
537 );
538 }
539 }
540 }
541
542 /**
543 * Delete the object records that are associated with this contact
544 *
545 * @param int $contactId id of the contact to delete
546 *
547 * @return void
548 * @access public
549 * @static
550 */
551 static function deleteContact($contactId) {
552 $relationship = new CRM_Contact_DAO_Relationship();
553 $relationship->contact_id_a = $contactId;
554 $relationship->delete();
555
556 $relationship = new CRM_Contact_DAO_Relationship();
557 $relationship->contact_id_b = $contactId;
558 $relationship->delete();
559
560 CRM_Contact_BAO_Household::updatePrimaryContact(NULL, $contactId);
561 }
562
563 /**
564 * Function to get the other contact in a relationship
565 *
566 * @param int $id relationship id
567 *
568 * $returns returns the contact ids in the realtionship
569 * @access public
570 * @static
571 */
572 static function getContactIds($id) {
573 $relationship = new CRM_Contact_DAO_Relationship();
574
575 $relationship->id = $id;
576 $relationship->selectAdd();
577 $relationship->selectAdd('contact_id_a, contact_id_b');
578 $relationship->find(TRUE);
579
580 return $relationship;
581 }
582
583 /**
584 * Function to check if the relationship type selected between two contacts is correct
585 *
586 * @param int $contact_a 1st contact id
587 * @param int $contact_b 2nd contact id
588 * @param int $relationshipTypeId relationship type id
589 *
590 * @return boolean true if it is valid relationship else false
591 * @access public
592 * @static
593 */
594 static function checkRelationshipType($contact_a, $contact_b, $relationshipTypeId) {
595 $relationshipType = new CRM_Contact_DAO_RelationshipType();
596 $relationshipType->id = $relationshipTypeId;
597 $relationshipType->selectAdd();
598 $relationshipType->selectAdd('contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b');
599 if ($relationshipType->find(TRUE)) {
600 $contact_type_a = CRM_Contact_BAO_Contact::getContactType($contact_a);
601 $contact_type_b = CRM_Contact_BAO_Contact::getContactType($contact_b);
602
603 $contact_sub_type_a = CRM_Contact_BAO_Contact::getContactSubType($contact_a);
604 $contact_sub_type_b = CRM_Contact_BAO_Contact::getContactSubType($contact_b);
605
606 if (((!$relationshipType->contact_type_a) || ($relationshipType->contact_type_a == $contact_type_a)) &&
607 ((!$relationshipType->contact_type_b) || ($relationshipType->contact_type_b == $contact_type_b)) &&
608 ((!$relationshipType->contact_sub_type_a) || (in_array($relationshipType->contact_sub_type_a,
609 $contact_sub_type_a
610 ))) &&
611 ((!$relationshipType->contact_sub_type_b) || (in_array($relationshipType->contact_sub_type_b,
612 $contact_sub_type_b
613 )))
614 ) {
615 return TRUE;
616 }
617 else {
618 return FALSE;
619 }
620 }
621 return FALSE;
622 }
623
624 /**
625 * this function does the validtion for valid relationship
626 *
627 * @param array $params this array contains the values there are subitted by the form
628 * @param array $ids the array that holds all the db ids
629 * @param integer $contactId this is contact id for adding relationship
630 *
631 * @return
632 * @access public
633 * @static
634 */
635 static function checkValidRelationship(&$params, &$ids, $contactId) {
636 $errors = '';
637
638 // get the string of relationship type
639 $relationshipTypes = CRM_Utils_Array::value('relationship_type_id', $params);
640 list($type, $first, $second) = explode('_', $relationshipTypes);
641 ${'contact_' . $first} = CRM_Utils_Array::value('contact', $ids);
642 ${'contact_' . $second} = $contactId;
643 // function to check if the relationship selected is correct
644 // i.e. employer relationship can exit between Individual and Organization (not between Individual and Individual)
645 if (!CRM_Contact_BAO_Relationship::checkRelationshipType($contact_a, $contact_b, $type)) {
646 $errors = 'Please select valid relationship between these two contacts.';
647 }
648 return $errors;
649 }
650
651 /**
652 * this function checks for duplicate relationship
653 *
654 * @param array $params (reference ) an assoc array of name/value pairs
655 * @param integer $id this the id of the contact whom we are adding relationship
656 * @param integer $contactId this is contact id for adding relationship
657 * @param integer $relationshipId this is relationship id for the contact
658 *
659 * @return boolean true if record exists else false
660 * @access public
661 * @static
662 */
663 static function checkDuplicateRelationship(&$params, $id, $contactId = 0, $relationshipId = 0) {
664 $relationshipTypeId = CRM_Utils_Array::value('relationship_type_id', $params);
665 list($type, $first, $second) = explode('_', $relationshipTypeId);
666
667 $queryString = " SELECT id
668 FROM civicrm_relationship
669 WHERE relationship_type_id = " . CRM_Utils_Type::escape($type, 'Integer');
670
671 /*
672 * CRM-11792 - date fields from API are in ISO format, but this function supports date arrays
673 * BAO has increasingly standardised to ISO format so I believe this function should support
674 * ISO rather than make API format it - however, need to support array format for now to avoid breakage
675 * @ time of writing this function is called from Relationship::create (twice)
676 * CRM_BAO_Contact_Utils::clearCurrentEmployer (seemingly without dates)
677 * CRM_Contact_Form_Task_AddToOrganization::postProcess &
678 * CRM_Contact_Form_Task_AddToHousehold::postProcess
679 * (I don't think the last 2 support dates but not sure
680 */
681
682 $dateFields = array('end_date', 'start_date');
683 foreach ($dateFields as $dateField){
684 if(array_key_exists($dateField, $params)) {
685 if (empty($params[$dateField]) || $params[$dateField] == 'null'){
686 //this is most likely coming from an api call & probably loaded from the DB to deal with some of the
687 //other myriad of excessive checks still in place both in the api & the create functions
688 $queryString .= " AND $dateField IS NULL";
689 continue;
690 }
691 elseif (is_array($params[$dateField])){
692 $queryString .= " AND $dateField = " . CRM_Utils_Type::escape(CRM_Utils_Date::format($params[$dateField]), 'Date');
693 }
694 else{
695 $queryString .= " AND $dateField = " . CRM_Utils_Type::escape($params[$dateField], 'Date');
696 }
697 }
698 }
699
700 $queryString .=
701 " AND ( ( contact_id_a = " . CRM_Utils_Type::escape($id, 'Integer') .
702 " AND contact_id_b = " . CRM_Utils_Type::escape($contactId, 'Integer') .
703 " ) OR ( contact_id_a = " . CRM_Utils_Type::escape($contactId, 'Integer') .
704 " AND contact_id_b = " . CRM_Utils_Type::escape($id, 'Integer') . " ) ) ";
705
706 //if caseId is provided, include it duplicate checking.
707 if ($caseId = CRM_Utils_Array::value('case_id', $params)) {
708 $queryString .= " AND case_id = " . CRM_Utils_Type::escape($caseId, 'Integer');
709 }
710
711 if ($relationshipId) {
712 $queryString .= " AND id !=" . CRM_Utils_Type::escape($relationshipId, 'Integer');
713 }
714
715 $relationship = new CRM_Contact_BAO_Relationship();
716 $relationship->query($queryString);
717 $relationship->fetch();
718 $relationship->free();
719 return ($relationship->id) ? TRUE : FALSE;
720 }
721
722 /**
723 * update the is_active flag in the db
724 *
725 * @param int $id id of the database record
726 * @param boolean $is_active value we want to set the is_active field
727 *
728 * @return Object DAO object on success, null otherwise
729 * @static
730 */
731 static function setIsActive($id, $is_active) {
49f8272d
E
732 // as both the create & add functions have a bunch of logic in them that
733 // doesn't seem to cope with a normal update we will call the api which
734 // has tested handling for this
735 // however, a longer term solution would be to simplify the add, create & api functions
736 // to be more standard. It is debatable @ that point whether it's better to call the BAO
737 // direct as the api is more tested.
738 civicrm_api3('relationship', 'create', array('id' => $id, 'is_active' => $is_active));
739
740 // call (undocumented possibly deprecated) hook
6a488035
TO
741 CRM_Utils_Hook::enableDisable('CRM_Contact_BAO_Relationship', $id, $is_active);
742
743 return TRUE;
744 }
745
746 /**
747 * Given the list of params in the params array, fetch the object
748 * and store the values in the values array
749 *
750 * @param array $params input parameters to find object
751 * @param array $values output values of the object
752 * @param array $ids the array that holds all the db ids
753 *
754 * @return array (reference) the values that could be potentially assigned to smarty
755 * @access public
756 * @static
757 */
758 static function &getValues(&$params, &$values) {
759 if (empty($params)) {
760 return NULL;
761 }
762 $v = array();
763
764 // get the specific number of relationship or all relationships.
765 if (CRM_Utils_Array::value('numRelationship', $params)) {
766 $v['data'] = &CRM_Contact_BAO_Relationship::getRelationship($params['contact_id'], NULL, $params['numRelationship']);
767 }
768 else {
769 $v['data'] = CRM_Contact_BAO_Relationship::getRelationship($params['contact_id']);
770 }
771
772 // get the total count of relationships
773 $v['totalCount'] = CRM_Contact_BAO_Relationship::getRelationship($params['contact_id'], NULL, NULL, TRUE);
774
775 $values['relationship']['data'] = &$v['data'];
776 $values['relationship']['totalCount'] = &$v['totalCount'];
777
778 return $v;
779 }
780
781 /**
782 * helper function to form the sql for relationship retrieval
783 *
784 * @param int $contactId contact id
785 * @param int $status (check const at top of file)
786 * @param int $numRelationship no of relationships to display (limit)
787 * @param int $count get the no of relationships
788 * $param int $relationshipId relationship id
789 * @param string $direction the direction we are interested in a_b or b_a
75638074 790 * @param array $params array of extra values including relationship_type_id per api spec
6a488035
TO
791 *
792 * return string the query for this diretion
793 * @static
794 * @access public
795 */
75638074 796 static function makeURLClause($contactId, $status, $numRelationship, $count, $relationshipId, $direction, $params = array()) {
6a488035
TO
797 $select = $from = $where = '';
798
799 $select = '( ';
800 if ($count) {
801 if ($direction == 'a_b') {
802 $select .= ' SELECT count(DISTINCT civicrm_relationship.id) as cnt1, 0 as cnt2 ';
803 }
804 else {
805 $select .= ' SELECT 0 as cnt1, count(DISTINCT civicrm_relationship.id) as cnt2 ';
806 }
807 }
808 else {
809 $select .= ' SELECT civicrm_relationship.id as civicrm_relationship_id,
810 civicrm_contact.sort_name as sort_name,
811 civicrm_contact.display_name as display_name,
812 civicrm_contact.job_title as job_title,
813 civicrm_contact.employer_id as employer_id,
814 civicrm_contact.organization_name as organization_name,
815 civicrm_address.street_address as street_address,
816 civicrm_address.city as city,
817 civicrm_address.postal_code as postal_code,
818 civicrm_state_province.abbreviation as state,
819 civicrm_country.name as country,
820 civicrm_email.email as email,
821 civicrm_phone.phone as phone,
822 civicrm_contact.id as civicrm_contact_id,
823 civicrm_contact.contact_type as contact_type,
824 civicrm_relationship.contact_id_b as contact_id_b,
825 civicrm_relationship.contact_id_a as contact_id_a,
826 civicrm_relationship_type.id as civicrm_relationship_type_id,
827 civicrm_relationship.start_date as start_date,
828 civicrm_relationship.end_date as end_date,
829 civicrm_relationship.description as description,
830 civicrm_relationship.is_active as is_active,
831 civicrm_relationship.is_permission_a_b as is_permission_a_b,
832 civicrm_relationship.is_permission_b_a as is_permission_b_a,
833 civicrm_relationship.case_id as case_id';
834
835 if ($direction == 'a_b') {
836 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
837 civicrm_relationship_type.label_b_a as relation ';
838 }
839 else {
840 $select .= ', civicrm_relationship_type.label_a_b as label_a_b,
841 civicrm_relationship_type.label_a_b as relation ';
842 }
843 }
844
845 $from = "
846 FROM civicrm_relationship
847INNER JOIN civicrm_relationship_type ON ( civicrm_relationship.relationship_type_id = civicrm_relationship_type.id )
848INNER JOIN civicrm_contact ";
849 if ($direction == 'a_b') {
850 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_a ) ';
851 }
852 else {
853 $from .= 'ON ( civicrm_contact.id = civicrm_relationship.contact_id_b ) ';
854 }
855 $from .= "
856LEFT JOIN civicrm_address ON (civicrm_address.contact_id = civicrm_contact.id AND civicrm_address.is_primary = 1)
857LEFT JOIN civicrm_phone ON (civicrm_phone.contact_id = civicrm_contact.id AND civicrm_phone.is_primary = 1)
858LEFT JOIN civicrm_email ON (civicrm_email.contact_id = civicrm_contact.id AND civicrm_email.is_primary = 1)
859LEFT JOIN civicrm_state_province ON (civicrm_address.state_province_id = civicrm_state_province.id)
860LEFT JOIN civicrm_country ON (civicrm_address.country_id = civicrm_country.id)
861";
862 $where = 'WHERE ( 1 )';
863 if ($contactId) {
864 if ($direction == 'a_b') {
865 $where .= ' AND civicrm_relationship.contact_id_b = ' . CRM_Utils_Type::escape($contactId, 'Positive');
866 }
867 else {
868 $where .= ' AND civicrm_relationship.contact_id_a = ' . CRM_Utils_Type::escape($contactId, 'Positive');
869 }
870 }
871 if ($relationshipId) {
872 $where .= ' AND civicrm_relationship.id = ' . CRM_Utils_Type::escape($relationshipId, 'Positive');
873 }
874
875 $date = date('Y-m-d');
876 if ($status == self::PAST) {
877 //this case for showing past relationship
878 $where .= ' AND civicrm_relationship.is_active = 1 ';
879 $where .= " AND civicrm_relationship.end_date < '" . $date . "'";
880 }
881 elseif ($status == self::DISABLED) {
882 // this case for showing disabled relationship
883 $where .= ' AND civicrm_relationship.is_active = 0 ';
884 }
885 elseif ($status == self::CURRENT) {
886 //this case for showing current relationship
887 $where .= ' AND civicrm_relationship.is_active = 1 ';
888 $where .= " AND (civicrm_relationship.end_date >= '" . $date . "' OR civicrm_relationship.end_date IS NULL) ";
889 }
890 elseif ($status == self::INACTIVE) {
891 //this case for showing inactive relationships
892 $where .= " AND (civicrm_relationship.end_date < '" . $date . "'";
893 $where .= ' OR civicrm_relationship.is_active = 0 )';
894 }
895
896 // CRM-6181
897 $where .= ' AND civicrm_contact.is_deleted = 0';
c9c41397 898 if(!empty($params['membership_type_id']) && empty($params['relationship_type_id'])) {
899 $where .= self::membershipTypeToRelationshipTypes($params, $direction);
900 }
75638074 901 if(!empty($params['relationship_type_id'])) {
902 if(is_array($params['relationship_type_id'])) {
faf8c53b 903 $where .= " AND " . CRM_Core_DAO::createSQLFilter('relationship_type_id', $params['relationship_type_id'], 'Integer');
75638074 904 }
905 else {
906 $where .= ' AND relationship_type_id = ' . CRM_Utils_Type::escape($params['relationship_type_id'], 'Positive');
907 }
908 }
6a488035
TO
909 if ($direction == 'a_b') {
910 $where .= ' ) UNION ';
911 }
912 else {
913 $where .= ' ) ';
914 }
915
916 return array($select, $from, $where);
917 }
918
919 /**
920 * This is the function to get the list of relationships
921 *
922 * @param int $contactId contact id
923 * @param int $status 1: Past 2: Disabled 3: Current
924 * @param int $numRelationship no of relationships to display (limit)
925 * @param int $count get the no of relationships
926 * $param int $relationshipId relationship id
927 * $param array $links the list of links to display
928 * $param int $permissionMask the permission mask to be applied for the actions
929 * $param boolean $permissionedContact to return only permissioned Contact
75638074 930 * $param array $params array of variables consistent with filters supported by the api
6a488035
TO
931 * return array $values relationship records
932 * @static
933 * @access public
934 */
935 static function getRelationship($contactId = NULL,
936 $status = 0, $numRelationship = 0,
937 $count = 0, $relationshipId = 0,
938 $links = NULL, $permissionMask = NULL,
75638074 939 $permissionedContact = FALSE,
940 $params = array()
6a488035
TO
941 ) {
942 $values = array();
943 if (!$contactId && !$relationshipId) {
944 return $values;
945 }
946
947 list($select1, $from1, $where1) = self::makeURLClause($contactId, $status, $numRelationship,
75638074 948 $count, $relationshipId, 'a_b', $params
6a488035
TO
949 );
950 list($select2, $from2, $where2) = self::makeURLClause($contactId, $status, $numRelationship,
75638074 951 $count, $relationshipId, 'b_a', $params
6a488035
TO
952 );
953
954 $order = $limit = '';
955 if (!$count) {
956 $order = ' ORDER BY civicrm_relationship_type_id, sort_name ';
957
958 if ($numRelationship) {
959 $limit = " LIMIT 0, $numRelationship";
960 }
961 }
962
963 // building the query string
964 $queryString = '';
965 $queryString = $select1 . $from1 . $where1 . $select2 . $from2 . $where2 . $order . $limit;
966
967 $relationship = new CRM_Contact_DAO_Relationship();
968
969 $relationship->query($queryString);
970 $row = array();
971 if ($count) {
972 $relationshipCount = 0;
973 while ($relationship->fetch()) {
974 $relationshipCount += $relationship->cnt1 + $relationship->cnt2;
975 }
976 return $relationshipCount;
977 }
978 else {
979
980 $mask = NULL;
981 if ($status != self::INACTIVE) {
982 if ($links) {
983 $mask = array_sum(array_keys($links));
984 if ($mask & CRM_Core_Action::DISABLE) {
985 $mask -= CRM_Core_Action::DISABLE;
986 }
987 if ($mask & CRM_Core_Action::ENABLE) {
988 $mask -= CRM_Core_Action::ENABLE;
989 }
990
991 if ($status == self::CURRENT) {
992 $mask |= CRM_Core_Action::DISABLE;
993 }
994 elseif ($status == self::DISABLED) {
995 $mask |= CRM_Core_Action::ENABLE;
996 }
997 $mask = $mask & $permissionMask;
998 }
999 }
1000 while ($relationship->fetch()) {
1001 $rid = $relationship->civicrm_relationship_id;
1002 $cid = $relationship->civicrm_contact_id;
1003 if (($permissionedContact) &&
1004 (!CRM_Contact_BAO_Contact_Permission::relationship($cid, $contactId))
1005 ) {
1006 continue;
1007 }
1008 $values[$rid]['id'] = $rid;
1009 $values[$rid]['cid'] = $cid;
1010 $values[$rid]['contact_id_a'] = $relationship->contact_id_a;
1011 $values[$rid]['contact_id_b'] = $relationship->contact_id_b;
1012 $values[$rid]['relationship_type_id'] = $relationship->civicrm_relationship_type_id;
1013 $values[$rid]['relation'] = $relationship->relation;
1014 $values[$rid]['name'] = $relationship->sort_name;
1015 $values[$rid]['display_name'] = $relationship->display_name;
1016 $values[$rid]['job_title'] = $relationship->job_title;
1017 $values[$rid]['email'] = $relationship->email;
1018 $values[$rid]['phone'] = $relationship->phone;
1019 $values[$rid]['employer_id'] = $relationship->employer_id;
1020 $values[$rid]['organization_name'] = $relationship->organization_name;
1021 $values[$rid]['country'] = $relationship->country;
1022 $values[$rid]['city'] = $relationship->city;
1023 $values[$rid]['state'] = $relationship->state;
1024 $values[$rid]['start_date'] = $relationship->start_date;
1025 $values[$rid]['end_date'] = $relationship->end_date;
1026 $values[$rid]['description'] = $relationship->description;
1027 $values[$rid]['is_active'] = $relationship->is_active;
1028 $values[$rid]['is_permission_a_b'] = $relationship->is_permission_a_b;
1029 $values[$rid]['is_permission_b_a'] = $relationship->is_permission_b_a;
1030 $values[$rid]['case_id'] = $relationship->case_id;
1031
1032 if ($status) {
1033 $values[$rid]['status'] = $status;
1034 }
1035
1036 $values[$rid]['civicrm_relationship_type_id'] = $relationship->civicrm_relationship_type_id;
1037
1038 if ($relationship->contact_id_a == $contactId) {
1039 $values[$rid]['rtype'] = 'a_b';
1040 }
1041 else {
1042 $values[$rid]['rtype'] = 'b_a';
1043 }
1044
1045 if ($links) {
1046 $replace = array(
1047 'id' => $rid,
1048 'rtype' => $values[$rid]['rtype'],
1049 'cid' => $contactId,
1050 'cbid' => $values[$rid]['cid'],
1051 'caseid' => $values[$rid]['case_id'],
1052 'clientid' => $contactId,
1053 );
1054
1055 if ($status == self::INACTIVE) {
1056 // setting links for inactive relationships
1057 $mask = array_sum(array_keys($links));
1058 if (!$values[$rid]['is_active']) {
1059 $mask -= CRM_Core_Action::DISABLE;
1060 }
1061 else {
1062 $mask -= CRM_Core_Action::ENABLE;
1063 $mask -= CRM_Core_Action::DISABLE;
1064 }
1065 }
1066
1067 // Give access to manage case link by copying to MAX_ACTION index temporarily, depending on case permission of user.
1068 if ($values[$rid]['case_id']) {
1069 // Borrowed logic from CRM_Case_Page_Tab
1070 $hasCaseAccess = FALSE;
1071 if (CRM_Core_Permission::check('access all cases and activities')) {
1072 $hasCaseAccess = TRUE;
1073 }
1074 else {
1075 $userCases = CRM_Case_BAO_Case::getCases(FALSE);
1076 if (array_key_exists($values[$rid]['case_id'], $userCases)) {
1077 $hasCaseAccess = TRUE;
1078 }
1079 }
1080
1081 if ($hasCaseAccess) {
1082 // give access by copying to MAX_ACTION temporarily, otherwise leave at NONE which won't display
1083 $links[CRM_Core_Action::MAX_ACTION] = $links[CRM_Core_Action::NONE];
1084 $links[CRM_Core_Action::MAX_ACTION]['name'] = ts('Manage Case #%1', array(1 => $values[$rid]['case_id']));
1085
1086 // Also make sure we have the right client cid since can get here from multiple relationship tabs.
1087 if ($values[$rid]['rtype'] == 'b_a') {
1088 $replace['clientid'] = $values[$rid]['cid'];
1089 }
1090 }
1091 }
1092
1093 $values[$rid]['action'] = CRM_Core_Action::formLink($links, $mask, $replace);
1094 unset($links[CRM_Core_Action::MAX_ACTION]);
1095 }
1096 }
1097
1098 $relationship->free();
1099 return $values;
1100 }
1101 }
1102
1103 /**
1104 * Function to get get list of relationship type based on the target contact type.
1105 *
1106 * @param string $targetContactType it's valid contact tpye(may be Individual , Organization , Household)
1107 *
1108 * @return array - array reference of all relationship types with context to current contact type .
1109 *
1110 */
1111 function getRelationType($targetContactType) {
1112 $relationshipType = array();
1113 $allRelationshipType = CRM_Core_PseudoConstant::relationshipType();
1114
1115 foreach ($allRelationshipType as $key => $type) {
1116 if ($type['contact_type_b'] == $targetContactType) {
1117 $relationshipType[$key . '_a_b'] = $type['label_a_b'];
1118 }
1119 }
1120
1121 return $relationshipType;
1122 }
1123
1124 /**
1125 * Function to create / update / delete membership for related contacts.
1126 *
1127 * This function will create/update/delete membership for related
1128 * contact based on 1) contact have active membership 2) that
1129 * membership is is extedned by the same relationship type to that
1130 * of the existing relationship.
1131 *
1132 * @param $contactId Int contact id
1133 * @param $params array array of values submitted by POST
1134 * @param $ids array array of ids
1135 * @param $action which action called this function
1136 *
1137 * @static
1138 *
1139 */
1140 static function relatedMemberships($contactId, &$params, $ids, $action = CRM_Core_Action::ADD, $active = TRUE) {
1141 // Check the end date and set the status of the relationship
1142 // accrodingly.
1143 $status = self::CURRENT;
1144
1145 if (!empty($params['end_date'])) {
1146 $endDate = CRM_Utils_Date::setDateDefaults(CRM_Utils_Date::format($params['end_date']), NULL, 'Ymd');
1147 $today = date('Ymd');
1148
1149 if ($today > $endDate) {
1150 $status = self::PAST;
1151 }
1152 }
1153
1154 if (($action & CRM_Core_Action::ADD) &&
1155 ($status & self::PAST)
1156 ) {
1157 // if relationship is PAST and action is ADD, no qustion
1158 // of creating RELATED membership and return back to
1159 // calling method
1160 return;
1161 }
1162
1163 $rel = explode('_', $params['relationship_type_id']);
1164
1165 $relTypeId = $rel[0];
1166 $relDirection = "_{$rel[1]}_{$rel[2]}";
1167 $targetContact = array();
1168 if (($action & CRM_Core_Action::ADD) ||
1169 ($action & CRM_Core_Action::DELETE)
1170 ) {
1171 $contact = $contactId;
1172 $targetContact = CRM_Utils_Array::value('contact_check', $params);
1173 }
1174 elseif ($action & CRM_Core_Action::UPDATE) {
1175 $contact = $ids['contact'];
1176 $targetContact = array($ids['contactTarget'] => 1);
1177 }
1178
1179 // Build the 'values' array for
1180 // 1. ContactA
1181 // 2. ContactB
1182 // This will allow us to check if either of the contacts in
1183 // relationship have active memberships.
1184
1185 $values = array();
1186
1187 // 1. ContactA
1188 $values[$contact] = array(
1189 'relatedContacts' => $targetContact,
1190 'relationshipTypeId' => $relTypeId,
1191 'relationshipTypeDirection' => $relDirection,
1192 );
1193 // 2. ContactB
1194 if (!empty($targetContact)) {
1195 foreach ($targetContact as $cid => $donCare) {
1196 $values[$cid] = array(
1197 'relatedContacts' => array($contact => 1),
1198 'relationshipTypeId' => $relTypeId,
1199 );
1200
1201 $relTypeParams = array('id' => $relTypeId);
1202 $relTypeValues = array();
1203 CRM_Contact_BAO_RelationshipType::retrieve($relTypeParams, $relTypeValues);
1204
1205 if (CRM_Utils_Array::value('name_a_b', $relTypeValues) == CRM_Utils_Array::value('name_b_a', $relTypeValues)) {
1206 $values[$cid]['relationshipTypeDirection'] = '_a_b';
1207 }
1208 else {
1209 $values[$cid]['relationshipTypeDirection'] = ($relDirection == '_a_b') ? '_b_a' : '_a_b';
1210 }
1211 }
1212 }
1213
1214 // Now get the active memberships for all the contacts.
1215 // If contact have any valid membership(s), then add it to
1216 // 'values' array.
1217 foreach ($values as $cid => $subValues) {
1218 $memParams = array('contact_id' => $cid);
1219 $memberships = array();
1220
1221 CRM_Member_BAO_Membership::getValues($memParams, $memberships, $active);
1222
1223 if (empty($memberships)) {
1224 continue;
1225 }
1226
1227 $values[$cid]['memberships'] = $memberships;
1228 }
1229 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant::membershipStatus());
1230
1231 // done with 'values' array.
1232 // Finally add / edit / delete memberships for the related contacts
1233 foreach ($values as $cid => $details) {
1234 if (!array_key_exists('memberships', $details)) {
1235 continue;
1236 }
1237
1238 $mainRelatedContactId = key(CRM_Utils_Array::value('relatedContacts', $details, array()));
1239
1240 foreach ($details['memberships'] as $membershipId => $membershipValues) {
1241 $relTypeIds = array();
1242 if ($action & CRM_Core_Action::DELETE) {
1243 // Delete memberships of the related contacts only if relationship type exists for membership type
1244 $query = "
1245SELECT relationship_type_id, relationship_direction
1246 FROM civicrm_membership_type
1247 WHERE id = {$membershipValues['membership_type_id']}";
1248 $dao = CRM_Core_DAO::executeQuery($query);
1249 $relTypeDirs = array();
1250 while ($dao->fetch()) {
1251 $relTypeId = $dao->relationship_type_id;
1252 $relDirection = $dao->relationship_direction;
1253 }
1254 $relTypeIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $relTypeId);
1255 if (in_array($values[$cid]['relationshipTypeId'], $relTypeIds)) {
1256 CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipId, $mainRelatedContactId);
1257 }
1258 continue;
1259 }
1260 if (($action & CRM_Core_Action::UPDATE) &&
1261 ($status & self::PAST) &&
1262 ($membershipValues['owner_membership_id'])
1263 ) {
1264 // If relationship is PAST and action is UPDATE
1265 // then delete the RELATED membership
1266 CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipValues['owner_membership_id'],
1267 $membershipValues['membership_contact_id']
1268 );
1269 continue;
1270 }
1271
1272 // add / edit the memberships for related
1273 // contacts.
1274
1275 // Get the Membership Type Details.
1276 $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($membershipValues['membership_type_id']);
1277 // Check if contact's relationship type exists in membership type
1278 $relTypeDirs = array();
1279 if (CRM_Utils_Array::value('relationship_type_id', $membershipType)) {
1280 $relTypeIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_type_id']);
1281 }
1282 if (CRM_Utils_Array::value('relationship_direction', $membershipType)) {
1283 $relDirections = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_direction']);
1284 }
1285 foreach ($relTypeIds as $key => $value) {
1286 $relTypeDirs[] = $value . '_' . $relDirections[$key];
1287 }
1288 $relTypeDir = $details['relationshipTypeId'] . $details['relationshipTypeDirection'];
1289 if (in_array($relTypeDir, $relTypeDirs)) {
1290 // Check if relationship being created/updated is
1291 // similar to that of membership type's
1292 // relationship.
1293
1294 $membershipValues['owner_membership_id'] = $membershipId;
1295 unset($membershipValues['id']);
1296 unset($membershipValues['membership_contact_id']);
1297 unset($membershipValues['contact_id']);
1298 unset($membershipValues['membership_id']);
1299 foreach ($details['relatedContacts'] as $relatedContactId => $donCare) {
1300 $membershipValues['contact_id'] = $relatedContactId;
1301 if ($deceasedStatusId &&
1302 CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $relatedContactId, 'is_deceased')
1303 ) {
1304 $membershipValues['status_id'] = $deceasedStatusId;
1305 $membershipValues['skipStatusCal'] = TRUE;
1306 }
1307 foreach (array(
1308 'join_date', 'start_date', 'end_date') as $dateField) {
1309 if (CRM_Utils_Array::value($dateField, $membershipValues)) {
1310 $membershipValues[$dateField] = CRM_Utils_Date::processDate($membershipValues[$dateField]);
1311 }
1312 }
1313
1314 if ($action & CRM_Core_Action::UPDATE) {
1315 //delete the membership record for related
1316 //contact before creating new membership record.
1317 CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipId, $relatedContactId);
1318 }
1319
1320 // check whether we have some related memberships still available
1321 $query = "
1322SELECT count(*)
1323 FROM civicrm_membership
1324 LEFT JOIN civicrm_membership_status ON (civicrm_membership_status.id = civicrm_membership.status_id)
1325 WHERE membership_type_id = {$membershipValues['membership_type_id']} AND owner_membership_id = {$membershipValues['owner_membership_id']}
1326 AND is_current_member = 1";
1327 $result = CRM_Core_DAO::singleValueQuery($query);
1328 if ($result < CRM_Utils_Array::value('max_related', $membershipValues, PHP_INT_MAX)) {
43291913 1329 CRM_Member_BAO_Membership::create($membershipValues, CRM_Core_DAO::$_nullArray);
6a488035
TO
1330 }
1331 }
1332 }
1333 elseif ($action & CRM_Core_Action::UPDATE) {
1334 // if action is update and updated relationship do
1335 // not match with the existing
1336 // membership=>relationship then we need to
1337 // delete the membership record created for
1338 // previous relationship.
1339
1340 if (self::isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, CRM_Utils_Array::value('relationship_ids', $params))) {
1341 CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipId, $mainRelatedContactId);
1342 }
1343 }
1344 }
1345 }
1346 }
1347
1348 /**
1349 * Helper function to check whether to delete the membership or
1350 * not.
1351 *
e9dfde0c
DG
1352 * @static
1353 *
6a488035 1354 */
e9dfde0c 1355 static function isDeleteRelatedMembership($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, $relIds) {
6a488035
TO
1356 if (in_array($relTypeId, $relTypeIds)) {
1357 return TRUE;
1358 }
1359
1360 if (empty($relIds)) {
1361 return FALSE;
1362 }
1363
1364 $relParamas = array(1 => array($contactId, 'Integer'),
1365 2 => array($mainRelatedContactId, 'Integer'),
1366 );
1367
1368 if ($contactId == $mainRelatedContactId) {
1369 $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);
1370 if ($recordsFound) {
1371 return FALSE;
1372 }
1373 return TRUE;
1374 }
1375
1376 $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);
1377
1378 if ($recordsFound) {
1379 return FALSE;
1380 }
1381
1382 return TRUE;
1383 }
1384
1385 /**
1386 * Function to get Current Employer for Contact
1387 *
1388 * @param $contactIds Contact Ids
1389 *
1390 * @return $currentEmployer array of the current employer
1391 *
1392 * @static
1393 *
1394 */
1395 static function getCurrentEmployer($contactIds) {
1396 $contacts = implode(',', $contactIds);
1397
1398 $query = "
1399SELECT organization_name, id, employer_id
1400FROM civicrm_contact
1401WHERE id IN ( {$contacts} )
1402";
1403
1404 $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
1405 $currentEmployer = array();
1406 while ($dao->fetch()) {
1407 $currentEmployer[$dao->id]['org_id'] = $dao->employer_id;
1408 $currentEmployer[$dao->id]['org_name'] = $dao->organization_name;
1409 }
1410
1411 return $currentEmployer;
1412 }
1413
1414 /**
1415 * Function to return list of permissioned employer for a given contact.
1416 *
1417 * @param $contactID int contact id whose employers
1418 * are to be found.
1419 * @param $name string employers sort name
1420 *
1421 * @static
1422 *
1423 * @return array array of employers.
1424 *
1425 */
51e89def 1426 static function getPermissionedEmployer($contactID, $name = NULL) {
6a488035
TO
1427 //get the relationship id
1428 $relTypeId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType',
1429 'Employee of', 'id', 'name_a_b'
1430 );
1431
51e89def
DS
1432 return self::getPermissionedContacts($contactID, $relTypeId, $name);
1433 }
1434
1435
1436 /**
1437 * Function to return list of permissioned contacts for a given contact and relationship type
1438 *
1439 * @param $contactID int contact id whose permissioned contacts are to be found.
1440 * @param $relTypeId relationship type id
1441 * @param $name string
1442 *
1443 * @static
1444 *
1445 * @return array of contacts
1446 */
1447 static function getPermissionedContacts($contactID, $relTypeId, $name = NULL) {
1448 $contacts = array();
1449
6a488035
TO
1450 if ($relTypeId) {
1451 $query = "
1452SELECT cc.id as id, cc.sort_name as name
1453FROM civicrm_relationship cr, civicrm_contact cc
49f8272d 1454WHERE
51e89def
DS
1455cr.contact_id_a = %1 AND
1456cr.relationship_type_id = %2 AND
1457cr.is_permission_a_b = 1 AND
6a488035
TO
1458IF(cr.end_date IS NULL, 1, (DATEDIFF( CURDATE( ), cr.end_date ) <= 0)) AND
1459cr.is_active = 1 AND
51e89def
DS
1460cc.id = cr.contact_id_b";
1461
1462 if (!empty($name)) {
1463 $name = CRM_Utils_Type::escape($name, 'String');
1464 $query .= "
49f8272d 1465AND cc.sort_name LIKE '%$name%'";
51e89def 1466 }
6a488035 1467
51e89def
DS
1468 $args = array(1 => array($contactID, 'Integer'), 2 => array($relTypeId, 'Integer'));
1469 $dao = CRM_Core_DAO::executeQuery($query, $args);
6a488035
TO
1470
1471 while ($dao->fetch()) {
51e89def 1472 $contacts[$dao->id] = array(
6a488035
TO
1473 'name' => $dao->name,
1474 'value' => $dao->id,
1475 );
1476 }
1477 }
51e89def 1478 return $contacts;
6a488035
TO
1479 }
1480
1481 static function getValidContactTypeList($relType) {
1482 // string looks like 4_a_b
1483 $rel_parts = explode('_', $relType);
1484 $allRelationshipType = CRM_Core_PseudoConstant::relationshipType('label');
1485 $contactProfiles = CRM_Core_BAO_UFGroup::getReservedProfiles('Contact', NULL);
1486
1487 if ($rel_parts[1] == 'a') {
1488 $leftType = $allRelationshipType[$rel_parts[0]]['contact_type_b'];
1489 }
1490 else {
1491 $leftType = $allRelationshipType[$rel_parts[0]]['contact_type_a'];
1492 }
1493
1494 // Handle 'All Contacts' contact type for left side of relationship ($leftType is empty in this case)
1495 // In this case all reserved profiles are available
1496 if ($leftType == '') {
1497 $contactTypes = $contactProfiles;
1498 } else {
1499 $contactTypes = array();
1500 foreach ($contactProfiles as $key => $value) {
1501 if (strpos($value, $leftType) !== FALSE) {
1502 $contactTypes = array($key => $value);
1503 }
1504 }
1505 }
1506
1507 return $contactTypes;
1508 }
1509
1510 /**
1511 * Merge relationships from otherContact to mainContact
1512 * Called during contact merge operation
1513 *
1514 * @param int $mainId contact id of main contact record.
1515 * @param int $otherId contact id of record which is going to merge.
1516 * @param array $sqls (reference) array of sql statements to append to.
1517 *
1518 * @see CRM_Dedupe_Merger::cpTables()
1519 *
1520 * @static
1521 */
1522 static function mergeRelationships($mainId, $otherId, &$sqls) {
1523 // Delete circular relationships
1524 $sqls[] = "DELETE FROM civicrm_relationship
1525 WHERE (contact_id_a = $mainId AND contact_id_b = $otherId)
1526 OR (contact_id_b = $mainId AND contact_id_a = $otherId)";
1527
1528 // Delete relationship from other contact if main contact already has that relationship
1529 $sqls[] = "DELETE r2
1530 FROM civicrm_relationship r1, civicrm_relationship r2
1531 WHERE r1.relationship_type_id = r2.relationship_type_id
1532 AND r1.id <> r2.id
1533 AND (
1534 r1.contact_id_a = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_b = r2.contact_id_b
1535 OR r1.contact_id_b = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_a = r2.contact_id_a
1536 OR (
1537 (r1.contact_id_a = $mainId AND r2.contact_id_b = $otherId AND r1.contact_id_b = r2.contact_id_a
1538 OR r1.contact_id_b = $mainId AND r2.contact_id_a = $otherId AND r1.contact_id_a = r2.contact_id_b)
1539 AND r1.relationship_type_id IN (SELECT id FROM civicrm_relationship_type WHERE name_b_a = name_a_b)
1540 )
1541 )";
1542
1543 // Move relationships
1544 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_a = $mainId WHERE contact_id_a = $otherId";
1545 $sqls[] = "UPDATE IGNORE civicrm_relationship SET contact_id_b = $mainId WHERE contact_id_b = $otherId";
1546
1547 // Move current employer id (name will get updated later)
1548 $sqls[] = "UPDATE civicrm_contact SET employer_id = $mainId WHERE employer_id = $otherId";
1549 }
1550
1551 /**
1552 * Set 'is_valid' field to false for all relationships whose end date is in the past, ie. are expired.
1553 *
1554 * @return True on success, false if error is encountered.
1555 */
1556 static function disableExpiredRelationships() {
1557 $query = "SELECT id FROM civicrm_relationship WHERE is_active = 1 AND end_date < CURDATE()";
1558
1559 $dao = CRM_Core_DAO::executeQuery($query);
1560 while ($dao->fetch()) {
1561 $result = CRM_Contact_BAO_Relationship::setIsActive($dao->id, FALSE);
1562 // Result will be NULL if error occurred. We abort early if error detected.
1563 if ($result == NULL) {
1564 return FALSE;
1565 }
1566 }
1567 return TRUE;
1568 }
c9c41397 1569
1570 /**
1571 * Function filters the query by possible relationships for the membership type
1572 * It is intended to be called when constructing queries for the api (reciprocal & non-reciprocal)
1573 * and to add clauses to limit the return to those relationships which COULD inherit a membership type
1574 * (as opposed to those who inherit a particular membership
1575 *
1576 * @param array $params api input array
1577 */
1578 static function membershipTypeToRelationshipTypes(&$params, $direction = NULL) {
1579 $membershipType = civicrm_api3('membership_type', 'getsingle', array('id' => $params['membership_type_id'], 'return' => 'relationship_type_id, relationship_direction'));
1580 $relationshipTypes = $membershipType['relationship_type_id'];
f201289d 1581 if(empty($relationshipTypes)) {
1582 return;
1583 }
c9c41397 1584 // if we don't have any contact data we can only filter on type
1585 if(empty($params['contact_id']) && empty($params['contact_id_a']) && empty($params['contact_id_a'])) {
1586 $params['relationship_type_id'] = array('IN' => $relationshipTypes);
1587 return;
1588 }
1589 else {
1a9b2ee8 1590 $relationshipDirections = (array) $membershipType['relationship_direction'];
c9c41397 1591 // if we have contact_id_a OR contact_id_b we can make a call here
1592 // if we have contact??
1593 foreach ($relationshipDirections as $index => $mtdirection) {
1594 if(isset($params['contact_id_a']) && $mtdirection == 'a_b' || $direction == 'a_b') {
1595 $types[] = $relationshipTypes[$index];
1596 }
1597 if(isset($params['contact_id_b']) && $mtdirection == 'b_a' || $direction == 'b_a') {
1598 $types[] = $relationshipTypes[$index];
1599 }
1600 }
1601 if(!empty($types)) {
1602 $params['relationship_type_id'] = array('IN' => $types);
1603 }
1604 elseif(!empty($clauses)) {
1605 return explode(' OR ', $clauses);
1606 }
1607 else{
1608 // effectively setting it to return no results
1609 $params['relationship_type_id'] = 0;
1610 }
1611 }
1612 }
6a488035
TO
1613}
1614