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