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