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