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