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