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