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