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