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