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