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