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