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