Merge pull request #6538 from systopia/CRM-17047
[civicrm-core.git] / CRM / Contact / Form / Relationship.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 * This class generates form components for relationship.
30 */
31 class CRM_Contact_Form_Relationship extends CRM_Core_Form {
32
33 /**
34 * The relationship id, used when editing the relationship
35 *
36 * @var int
37 */
38 public $_relationshipId;
39
40 /**
41 * The contact id, used when add/edit relationship
42 *
43 * @var int
44 */
45 public $_contactId;
46
47 /**
48 * This is a string which is either a_b or b_a used to determine the relationship between to contacts
49 */
50 public $_rtype;
51
52 /**
53 * This is a string which is used to determine the relationship between to contacts
54 */
55 public $_rtypeId;
56
57 /**
58 * Display name of contact a
59 */
60 public $_display_name_a;
61
62 /**
63 * Display name of contact b
64 */
65 public $_display_name_b;
66
67 /**
68 * The relationship type id
69 *
70 * @var int
71 */
72 public $_relationshipTypeId;
73
74 /**
75 * An array of all relationship names
76 *
77 * @var array
78 */
79 public $_allRelationshipNames;
80
81 /**
82 * @var bool
83 */
84 public $_enabled;
85
86 /**
87 * @var bool
88 */
89 public $_isCurrentEmployer;
90
91 /**
92 * @var string
93 */
94 public $_contactType;
95
96 /**
97 * The relationship values if Updating relationship
98 */
99 public $_values;
100
101 /**
102 * Case id if it called from case context
103 */
104 public $_caseId;
105
106 /**
107 * Explicitly declare the form context.
108 */
109 public function getDefaultContext() {
110 return 'create';
111 }
112
113 /**
114 * Explicitly declare the entity api name.
115 */
116 public function getDefaultEntity() {
117 return 'Relationship';
118 }
119
120 public function preProcess() {
121 $this->_contactId = $this->get('contactId');
122
123 $this->_contactType = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'contact_type');
124
125 $this->_relationshipId = $this->get('id');
126
127 $this->_rtype = CRM_Utils_Request::retrieve('rtype', 'String', $this);
128
129 $this->_rtypeId = CRM_Utils_Request::retrieve('relTypeId', 'String', $this);
130
131 $this->_display_name_a = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'display_name');
132
133 $this->assign('display_name_a', $this->_display_name_a);
134
135 // Check for permissions
136 if (in_array($this->_action, array(CRM_Core_Action::ADD, CRM_Core_Action::UPDATE, CRM_Core_Action::DELETE))) {
137 if (!CRM_Contact_BAO_Contact_Permission::allow($this->_contactId, CRM_Core_Permission::EDIT)) {
138 CRM_Core_Error::statusBounce(ts('You do not have the necessary permission to edit this contact.'));
139 }
140 }
141
142 // Set page title based on action
143 switch ($this->_action) {
144 case CRM_Core_Action::VIEW:
145 CRM_Utils_System::setTitle(ts('View Relationship for %1', array(1 => $this->_display_name_a)));
146 break;
147
148 case CRM_Core_Action::ADD:
149 CRM_Utils_System::setTitle(ts('Add Relationship for %1', array(1 => $this->_display_name_a)));
150 break;
151
152 case CRM_Core_Action::UPDATE:
153 CRM_Utils_System::setTitle(ts('Edit Relationship for %1', array(1 => $this->_display_name_a)));
154 break;
155
156 case CRM_Core_Action::DELETE:
157 CRM_Utils_System::setTitle(ts('Delete Relationship for %1', array(1 => $this->_display_name_a)));
158 break;
159 }
160
161 $this->_caseId = CRM_Utils_Request::retrieve('caseID', 'Integer', $this);
162
163 //get the relationship values.
164 $this->_values = array();
165 if ($this->_relationshipId) {
166 $params = array('id' => $this->_relationshipId);
167 CRM_Core_DAO::commonRetrieve('CRM_Contact_DAO_Relationship', $params, $this->_values);
168 }
169
170 if (!$this->_rtypeId) {
171 $params = $this->controller->exportValues($this->_name);
172 if (isset($params['relationship_type_id'])) {
173 $this->_rtypeId = $params['relationship_type_id'];
174 }
175 elseif (!empty($this->_values)) {
176 $this->_rtypeId = $this->_values['relationship_type_id'] . '_' . $this->_rtype;
177 }
178 }
179
180 //get the relationship type id
181 $this->_relationshipTypeId = str_replace(array('_a_b', '_b_a'), array('', ''), $this->_rtypeId);
182
183 //get the relationship type
184 if (!$this->_rtype) {
185 $this->_rtype = str_replace($this->_relationshipTypeId . '_', '', $this->_rtypeId);
186 }
187
188 //need to assign custom data type and subtype to the template - FIXME: explain why
189 $this->assign('customDataType', 'Relationship');
190 $this->assign('customDataSubType', $this->_relationshipTypeId);
191 $this->assign('entityID', $this->_relationshipId);
192
193 //use name as it remain constant, CRM-3336
194 $this->_allRelationshipNames = CRM_Core_PseudoConstant::relationshipType('name');
195
196 // Current employer?
197 if ($this->_action & CRM_Core_Action::UPDATE) {
198 if ($this->_allRelationshipNames[$this->_relationshipTypeId]["name_a_b"] == 'Employee of') {
199 $this->_isCurrentEmployer = $this->_values['contact_id_b'] == CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_values['contact_id_a'], 'employer_id');
200 }
201 }
202
203 // when custom data is included in this page
204 if (!empty($_POST['hidden_custom'])) {
205 CRM_Custom_Form_CustomData::preProcess($this);
206 CRM_Custom_Form_CustomData::buildQuickForm($this);
207 CRM_Custom_Form_CustomData::setDefaultValues($this);
208 }
209 }
210
211 /**
212 * Set default values for the form.
213 */
214 public function setDefaultValues() {
215
216 $defaults = array();
217
218 if ($this->_action & CRM_Core_Action::UPDATE) {
219 if (!empty($this->_values)) {
220 $defaults['relationship_type_id'] = $this->_rtypeId;
221 if (!empty($this->_values['start_date'])) {
222 list($defaults['start_date']) = CRM_Utils_Date::setDateDefaults($this->_values['start_date']);
223 }
224 if (!empty($this->_values['end_date'])) {
225 list($defaults['end_date']) = CRM_Utils_Date::setDateDefaults($this->_values['end_date']);
226 }
227 $defaults['description'] = CRM_Utils_Array::value('description', $this->_values);
228 $defaults['is_active'] = CRM_Utils_Array::value('is_active', $this->_values);
229
230 // The javascript on the form will swap these fields if it is a b_a relationship, so we compensate here
231 $defaults['is_permission_a_b'] = CRM_Utils_Array::value('is_permission_' . $this->_rtype, $this->_values);
232 $defaults['is_permission_b_a'] = CRM_Utils_Array::value('is_permission_' . strrev($this->_rtype), $this->_values);
233
234 $defaults['is_current_employer'] = $this->_isCurrentEmployer;
235
236 // Load info about the related contact
237 $contact = new CRM_Contact_DAO_Contact();
238 if ($this->_rtype == 'a_b' && $this->_values['contact_id_a'] == $this->_contactId) {
239 $contact->id = $this->_values['contact_id_b'];
240 }
241 else {
242 $contact->id = $this->_values['contact_id_a'];
243 }
244 if ($contact->find(TRUE)) {
245 $defaults['related_contact_id'] = $contact->id;
246 $this->_display_name_b = $contact->display_name;
247 $this->assign('display_name_b', $this->_display_name_b);
248 }
249
250 $noteParams = array(
251 'entity_id' => $this->_relationshipId,
252 'entity_table' => 'civicrm_relationship',
253 'limit' => 1,
254 'version' => 3,
255 );
256 $note = civicrm_api('Note', 'getsingle', $noteParams);
257 $defaults['note'] = CRM_Utils_Array::value('note', $note);
258 }
259 }
260 else {
261 $defaults['is_active'] = $defaults['is_current_employer'] = 1;
262 $defaults['relationship_type_id'] = $this->_rtypeId;
263 }
264
265 $this->_enabled = $defaults['is_active'];
266 return $defaults;
267 }
268
269 /**
270 * Add the rules for form.
271 */
272 public function addRules() {
273
274 if (!($this->_action & CRM_Core_Action::DELETE)) {
275 $this->addFormRule(array('CRM_Contact_Form_Relationship', 'dateRule'));
276 }
277 }
278
279 /**
280 * Build the form object.
281 */
282 public function buildQuickForm() {
283 if ($this->_action & CRM_Core_Action::DELETE) {
284 $this->addButtons(array(
285 array(
286 'type' => 'next',
287 'name' => ts('Delete'),
288 'isDefault' => TRUE,
289 ),
290 array(
291 'type' => 'cancel',
292 'name' => ts('Cancel'),
293 ),
294 )
295 );
296 return;
297 }
298
299 // Select list
300 $relationshipList = CRM_Contact_BAO_Relationship::getContactRelationshipType($this->_contactId, $this->_rtype, $this->_relationshipId);
301
302 // Metadata needed on clientside
303 $contactTypes = CRM_Contact_BAO_ContactType::contactTypeInfo(TRUE);
304 $jsData = array();
305 // Get just what we need to keep the dom small
306 $whatWeWant = array_flip(array('contact_type_a', 'contact_type_b', 'contact_sub_type_a', 'contact_sub_type_b'));
307 foreach ($this->_allRelationshipNames as $id => $vals) {
308 if ($vals['name_a_b'] === 'Employee of') {
309 $this->assign('employmentRelationship', $id);
310 }
311 if (isset($relationshipList["{$id}_a_b"]) || isset($relationshipList["{$id}_b_a"])) {
312 $jsData[$id] = array_filter(array_intersect_key($this->_allRelationshipNames[$id], $whatWeWant));
313 // Add user-friendly placeholder
314 foreach (array('a', 'b') as $x) {
315 $type = !empty($jsData[$id]["contact_sub_type_$x"]) ? $jsData[$id]["contact_sub_type_$x"] : CRM_Utils_Array::value("contact_type_$x", $jsData[$id]);
316 $jsData[$id]["placeholder_$x"] = $type ? ts('- select %1 -', array(strtolower($contactTypes[$type]['label']))) : ts('- select contact -');
317 }
318 }
319 }
320 $this->assign('relationshipData', $jsData);
321
322 $this->addField('relationship_type_id', array('options' => array('' => ts('- select -')) + $relationshipList, 'class' => 'huge', 'placeholder' => '- select -'), TRUE);
323
324 $label = $this->_action & CRM_Core_Action::ADD ? ts('Contact(s)') : ts('Contact');
325 $contactField = $this->addField('related_contact_id', array('label' => $label, 'name' => 'contact_id_b', 'multiple' => TRUE, 'create' => TRUE), TRUE);
326 // This field cannot be updated
327 if ($this->_action & CRM_Core_Action::UPDATE) {
328 $contactField->freeze();
329 }
330
331 $this->add('advcheckbox', 'is_current_employer', $this->_contactType == 'Organization' ? ts('Current Employee') : ts('Current Employer'));
332
333 $this->addField('start_date', array('label' => ts('Start Date'), 'formatType' => 'searchDate'));
334 $this->addField('end_date', array('label' => ts('End Date'), 'formatType' => 'searchDate'));
335
336 $this->addField('is_active', array('label' => ts('Enabled?')));
337
338 $this->addField('is_permission_a_b');
339 $this->addField('is_permission_b_a');
340
341 $this->addField('description', array('label' => ts('Description')));
342
343 CRM_Contact_Form_Edit_Notes::buildQuickForm($this);
344
345 if ($this->_action & CRM_Core_Action::VIEW) {
346 $this->addButtons(array(
347 array(
348 'type' => 'cancel',
349 'name' => ts('Done'),
350 ),
351 ));
352 }
353 else {
354 // make this form an upload since we don't know if the custom data injected dynamically is of type file etc.
355 $this->addButtons(array(
356 array(
357 'type' => 'upload',
358 'name' => ts('Save Relationship'),
359 'isDefault' => TRUE,
360 ),
361 array(
362 'type' => 'cancel',
363 'name' => ts('Cancel'),
364 ),
365 ));
366 }
367 }
368
369 /**
370 * This function is called when the form is submitted.
371 */
372 public function postProcess() {
373 // Store the submitted values in an array.
374 $params = $this->controller->exportValues($this->_name);
375
376 // CRM-14612 - Don't use adv-checkbox as it interferes with the form js
377 $params['is_permission_a_b'] = CRM_Utils_Array::value('is_permission_a_b', $params, 0);
378 $params['is_permission_b_a'] = CRM_Utils_Array::value('is_permission_b_a', $params, 0);
379
380 // action is taken depending upon the mode
381 if ($this->_action & CRM_Core_Action::DELETE) {
382 CRM_Contact_BAO_Relationship::del($this->_relationshipId);
383
384 // CRM-15881 UPDATES
385 // Since the line above nullifies the organization_name and employer_id fiels in the contact record, we need to reload all blocks to reflect this chage on the user interface.
386 $this->ajaxResponse['reloadBlocks'] = array('#crm-contactinfo-content');
387
388 return;
389 }
390
391 $relationshipTypeParts = explode('_', $params['relationship_type_id']);
392 $params['relationship_type_id'] = $relationshipTypeParts[0];
393 if (!$this->_rtype) {
394 // Do we need to wrap this in an if - when is rtype used & is relationship_type_id always set then?
395 $this->_rtype = $params['relationship_type_id'];
396 }
397 $params['contact_id_' . $relationshipTypeParts[1]] = $this->_contactId;
398
399 // Update mode (always single)
400 if ($this->_action & CRM_Core_Action::UPDATE) {
401 $update = TRUE;
402 $params['id'] = $this->_relationshipId;
403 $ids['relationship'] = $this->_relationshipId;
404 $relation = CRM_Contact_BAO_Relationship::getRelationshipByID($this->_relationshipId);
405 if ($relation->contact_id_a == $this->_contactId) {
406 // I couldn't replicate this path in testing. See below.
407 $params['contact_id_a'] = $this->_contactId;
408 $params['contact_id_b'] = array($params['related_contact_id']);
409 $outcome = CRM_Contact_BAO_Relationship::createMultiple($params, $relationshipTypeParts[1]);
410 $relationshipIds = $outcome['relationship_ids'];
411 }
412 else {
413 // The only reason we have changed this to use the api & not the above is that this was broken.
414 // Recommend extracting all of update into a function that uses the api
415 // and ensuring api / bao take care of 'other stuff' in this form
416 // the contact_id_a & b can't be changed on this form so don't really need setting.
417 $params['contact_id_b'] = $this->_contactId;
418 $params['contact_id_a'] = $params['related_contact_id'];
419 $result = civicrm_api3('relationship', 'create', $params);
420 $relationshipIds = array($result['id']);
421 }
422 $ids['contactTarget'] = ($relation->contact_id_a == $this->_contactId) ? $relation->contact_id_b : $relation->contact_id_a;
423
424 // @todo this belongs in the BAO.
425 if ($this->_isCurrentEmployer) {
426 // if relationship type changes, relationship is disabled, or "current employer" is unchecked,
427 // clear the current employer. CRM-3235.
428 $relChanged = $params['relationship_type_id'] != $this->_values['relationship_type_id'];
429 if (!$params['is_active'] || !$params['is_current_employer'] || $relChanged) {
430
431 // CRM-15881 UPDATES
432 // If not is_active then is_current_employer needs to be set false as well! Logically a contact cannot be a current employee of a disabled employer relationship.
433 // If this is not done, then the below process will go ahead and disable the organization_name and employer_id fields in the contact record (which is what is wanted) but then further down will be re-enabled becuase is_current_employer is not false, therefore undoing what was done correctly.
434 if (!$params['is_active']) {
435 $params['is_current_employer'] = FALSE;
436 }
437
438 CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($this->_values['contact_id_a']);
439 // Refresh contact summary if in ajax mode
440 $this->ajaxResponse['reloadBlocks'] = array('#crm-contactinfo-content');
441 }
442 }
443 if (empty($outcome['saved']) && !empty($update)) {
444 $outcome['saved'] = $update;
445 }
446 $this->setMessage($outcome);
447 }
448 // Create mode (could be 1 or more relationships)
449 else {
450 $params['contact_id_' . $relationshipTypeParts[2]] = explode(',', $params['related_contact_id']);
451 $outcome = CRM_Contact_BAO_Relationship::createMultiple($params, $relationshipTypeParts[1]);
452 $relationshipIds = $outcome['relationship_ids'];
453 if (empty($outcome['saved']) && !empty($update)) {
454 $outcome['saved'] = $update;
455 }
456 $this->setMessage($outcome);
457 }
458
459 // if this is called from case view,
460 //create an activity for case role removal.CRM-4480
461 // @todo this belongs in the BAO.
462 if ($this->_caseId) {
463 CRM_Case_BAO_Case::createCaseRoleActivity($this->_caseId, $relationshipIds, $params['contact_check'], $this->_contactId);
464 }
465
466 // Save notes
467 // @todo this belongs in the BAO.
468 if ($this->_action & CRM_Core_Action::UPDATE || $params['note']) {
469 foreach ($relationshipIds as $id) {
470 $noteParams = array(
471 'entity_id' => $id,
472 'entity_table' => 'civicrm_relationship',
473 );
474 $existing = civicrm_api3('note', 'get', $noteParams);
475 if (!empty($existing['id'])) {
476 $noteParams['id'] = $existing['id'];
477 }
478 $noteParams['note'] = $params['note'];
479 $noteParams['contact_id'] = $this->_contactId;
480 if (!empty($existing['id']) || $params['note']) {
481 $action = $params['note'] ? 'create' : 'delete';
482 civicrm_api3('note', $action, $noteParams);
483 }
484 }
485 }
486
487 $params['relationship_ids'] = $relationshipIds;
488
489 // Refresh contact tabs which might have been affected
490 $this->ajaxResponse['updateTabs'] = array(
491 '#tab_member' => CRM_Contact_BAO_Contact::getCountComponent('membership', $this->_contactId),
492 '#tab_contribute' => CRM_Contact_BAO_Contact::getCountComponent('contribution', $this->_contactId),
493 );
494
495 // Set current employee/employer relationship, CRM-3532
496 if ($params['is_current_employer'] && $this->_allRelationshipNames[$params['relationship_type_id']]["name_a_b"] ==
497 'Employee of') {
498 $employerParams = array();
499 foreach ($relationshipIds as $id) {
500 // Fixme this is dumb why do we have to look this up again?
501 $rel = CRM_Contact_BAO_Relationship::getRelationshipByID($id);
502 $employerParams[$rel->contact_id_a] = $rel->contact_id_b;
503 }
504 // @todo this belongs in the BAO.
505 CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($employerParams);
506 // Refresh contact summary if in ajax mode
507 $this->ajaxResponse['reloadBlocks'] = array('#crm-contactinfo-content');
508 }
509 }
510
511 /**
512 * Date validation.
513 *
514 * @param array $params
515 * (reference ) an assoc array of name/value pairs.
516 *
517 * @return bool|array
518 * mixed true or array of errors
519 */
520 public static function dateRule($params) {
521 $errors = array();
522
523 // check start and end date
524 if (!empty($params['start_date']) && !empty($params['end_date'])) {
525 $start_date = CRM_Utils_Date::format(CRM_Utils_Array::value('start_date', $params));
526 $end_date = CRM_Utils_Date::format(CRM_Utils_Array::value('end_date', $params));
527 if ($start_date && $end_date && (int ) $end_date < (int ) $start_date) {
528 $errors['end_date'] = ts('The relationship end date cannot be prior to the start date.');
529 }
530 }
531
532 return empty($errors) ? TRUE : $errors;
533 }
534
535 /**
536 * Set Status message to reflect outcome of the update action.
537 *
538 * @param array $outcome
539 * Outcome of save action - including
540 * - 'valid' : Number of valid relationships attempted.
541 * - 'invalid' : Number of invalid relationships attempted.
542 * - 'duplicate' : Number of duplicate relationships attempted.
543 * - 'saved' : boolean of whether save was successful
544 */
545 protected function setMessage($outcome) {
546 if (!empty($outcome['valid']) && empty($outcome['saved'])) {
547 CRM_Core_Session::setStatus(ts('Relationship created.', array(
548 'count' => $outcome['valid'],
549 'plural' => '%count relationships created.',
550 )), ts('Saved'), 'success');
551 }
552 if (!empty($outcome['invalid'])) {
553 CRM_Core_Session::setStatus(ts('%count relationship record was not created due to an invalid contact type.', array(
554 'count' => $outcome['invalid'],
555 'plural' => '%count relationship records were not created due to invalid contact types.',
556 )), ts('%count invalid relationship record', array(
557 'count' => $outcome['invalid'],
558 'plural' => '%count invalid relationship records',
559 )));
560 }
561 if (!empty($outcome['duplicate'])) {
562 CRM_Core_Session::setStatus(ts('One relationship was not created because it already exists.', array(
563 'count' => $outcome['duplicate'],
564 'plural' => '%count relationships were not created because they already exist.',
565 )), ts('%count duplicate relationship', array(
566 'count' => $outcome['duplicate'],
567 'plural' => '%count duplicate relationships',
568 )));
569 }
570 if (!empty($outcome['saved'])) {
571 CRM_Core_Session::setStatus(ts('Relationship record has been updated.'), ts('Saved'), 'success');
572 }
573 }
574
575 }