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