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