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