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