Merge pull request #6517 from kurund/version-fixes
[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 // Set page title based on action
136 switch ($this->_action) {
137 case CRM_Core_Action::VIEW:
138 CRM_Utils_System::setTitle(ts('View Relationship for %1', array(1 => $this->_display_name_a)));
139 break;
140
141 case CRM_Core_Action::ADD:
142 CRM_Utils_System::setTitle(ts('Add Relationship for %1', array(1 => $this->_display_name_a)));
143 break;
144
145 case CRM_Core_Action::UPDATE:
146 CRM_Utils_System::setTitle(ts('Edit Relationship for %1', array(1 => $this->_display_name_a)));
147 break;
148
149 case CRM_Core_Action::DELETE:
150 CRM_Utils_System::setTitle(ts('Delete Relationship for %1', array(1 => $this->_display_name_a)));
151 break;
152 }
153
154 $this->_caseId = CRM_Utils_Request::retrieve('caseID', 'Integer', $this);
155
156 //get the relationship values.
157 $this->_values = array();
158 if ($this->_relationshipId) {
159 $params = array('id' => $this->_relationshipId);
160 CRM_Core_DAO::commonRetrieve('CRM_Contact_DAO_Relationship', $params, $this->_values);
161 }
162
163 if (!$this->_rtypeId) {
164 $params = $this->controller->exportValues($this->_name);
165 if (isset($params['relationship_type_id'])) {
166 $this->_rtypeId = $params['relationship_type_id'];
167 }
168 elseif (!empty($this->_values)) {
169 $this->_rtypeId = $this->_values['relationship_type_id'] . '_' . $this->_rtype;
170 }
171 }
172
173 //get the relationship type id
174 $this->_relationshipTypeId = str_replace(array('_a_b', '_b_a'), array('', ''), $this->_rtypeId);
175
176 //get the relationship type
177 if (!$this->_rtype) {
178 $this->_rtype = str_replace($this->_relationshipTypeId . '_', '', $this->_rtypeId);
179 }
180
181 //need to assign custom data type and subtype to the template - FIXME: explain why
182 $this->assign('customDataType', 'Relationship');
183 $this->assign('customDataSubType', $this->_relationshipTypeId);
184 $this->assign('entityID', $this->_relationshipId);
185
186 //use name as it remain constant, CRM-3336
187 $this->_allRelationshipNames = CRM_Core_PseudoConstant::relationshipType('name');
188
189 // Current employer?
190 if ($this->_action & CRM_Core_Action::UPDATE) {
191 if ($this->_allRelationshipNames[$this->_relationshipTypeId]["name_a_b"] == 'Employee of') {
192 $this->_isCurrentEmployer = $this->_values['contact_id_b'] == CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_values['contact_id_a'], 'employer_id');
193 }
194 }
195
196 // when custom data is included in this page
197 if (!empty($_POST['hidden_custom'])) {
198 CRM_Custom_Form_CustomData::preProcess($this);
199 CRM_Custom_Form_CustomData::buildQuickForm($this);
200 CRM_Custom_Form_CustomData::setDefaultValues($this);
201 }
202 }
203
204 /**
205 * Set default values for the form.
206 */
207 public function setDefaultValues() {
208
209 $defaults = array();
210
211 if ($this->_action & CRM_Core_Action::UPDATE) {
212 if (!empty($this->_values)) {
213 $defaults['relationship_type_id'] = $this->_rtypeId;
214 if (!empty($this->_values['start_date'])) {
215 list($defaults['start_date']) = CRM_Utils_Date::setDateDefaults($this->_values['start_date']);
216 }
217 if (!empty($this->_values['end_date'])) {
218 list($defaults['end_date']) = CRM_Utils_Date::setDateDefaults($this->_values['end_date']);
219 }
220 $defaults['description'] = CRM_Utils_Array::value('description', $this->_values);
221 $defaults['is_active'] = CRM_Utils_Array::value('is_active', $this->_values);
222
223 // The javascript on the form will swap these fields if it is a b_a relationship, so we compensate here
224 $defaults['is_permission_a_b'] = CRM_Utils_Array::value('is_permission_' . $this->_rtype, $this->_values);
225 $defaults['is_permission_b_a'] = CRM_Utils_Array::value('is_permission_' . strrev($this->_rtype), $this->_values);
226
227 $defaults['is_current_employer'] = $this->_isCurrentEmployer;
228
229 // Load info about the related contact
230 $contact = new CRM_Contact_DAO_Contact();
231 if ($this->_rtype == 'a_b' && $this->_values['contact_id_a'] == $this->_contactId) {
232 $contact->id = $this->_values['contact_id_b'];
233 }
234 else {
235 $contact->id = $this->_values['contact_id_a'];
236 }
237 if ($contact->find(TRUE)) {
238 $defaults['related_contact_id'] = $contact->id;
239 $this->_display_name_b = $contact->display_name;
240 $this->assign('display_name_b', $this->_display_name_b);
241 }
242
243 $noteParams = array(
244 'entity_id' => $this->_relationshipId,
245 'entity_table' => 'civicrm_relationship',
246 'limit' => 1,
247 'version' => 3,
248 );
249 $note = civicrm_api('Note', 'getsingle', $noteParams);
250 $defaults['note'] = CRM_Utils_Array::value('note', $note);
251 }
252 }
253 else {
254 $defaults['is_active'] = $defaults['is_current_employer'] = 1;
255 $defaults['relationship_type_id'] = $this->_rtypeId;
256 }
257
258 $this->_enabled = $defaults['is_active'];
259 return $defaults;
260 }
261
262 /**
263 * Add the rules for form.
264 */
265 public function addRules() {
266
267 if (!($this->_action & CRM_Core_Action::DELETE)) {
268 $this->addFormRule(array('CRM_Contact_Form_Relationship', 'dateRule'));
269 }
270 }
271
272 /**
273 * Build the form object.
274 */
275 public function buildQuickForm() {
276 if ($this->_action & CRM_Core_Action::DELETE) {
277 $this->addButtons(array(
278 array(
279 'type' => 'next',
280 'name' => ts('Delete'),
281 'isDefault' => TRUE,
282 ),
283 array(
284 'type' => 'cancel',
285 'name' => ts('Cancel'),
286 ),
287 )
288 );
289 return;
290 }
291
292 // Select list
293 $relationshipList = CRM_Contact_BAO_Relationship::getContactRelationshipType($this->_contactId, $this->_rtype, $this->_relationshipId);
294
295 // Metadata needed on clientside
296 $contactTypes = CRM_Contact_BAO_ContactType::contactTypeInfo(TRUE);
297 $jsData = array();
298 // Get just what we need to keep the dom small
299 $whatWeWant = array_flip(array('contact_type_a', 'contact_type_b', 'contact_sub_type_a', 'contact_sub_type_b'));
300 foreach ($this->_allRelationshipNames as $id => $vals) {
301 if ($vals['name_a_b'] === 'Employee of') {
302 $this->assign('employmentRelationship', $id);
303 }
304 if (isset($relationshipList["{$id}_a_b"]) || isset($relationshipList["{$id}_b_a"])) {
305 $jsData[$id] = array_filter(array_intersect_key($this->_allRelationshipNames[$id], $whatWeWant));
306 // Add user-friendly placeholder
307 foreach (array('a', 'b') as $x) {
308 $type = !empty($jsData[$id]["contact_sub_type_$x"]) ? $jsData[$id]["contact_sub_type_$x"] : CRM_Utils_Array::value("contact_type_$x", $jsData[$id]);
309 $jsData[$id]["placeholder_$x"] = $type ? ts('- select %1 -', array(strtolower($contactTypes[$type]['label']))) : ts('- select contact -');
310 }
311 }
312 }
313 $this->assign('relationshipData', $jsData);
314
315 $this->addField('relationship_type_id', array('options' => array('' => ts('- select -')) + $relationshipList, 'class' => 'huge', 'placeholder' => '- select -'), TRUE);
316
317 $label = $this->_action & CRM_Core_Action::ADD ? ts('Contact(s)') : ts('Contact');
318 $contactField = $this->addField('related_contact_id', array('label' => $label, 'name' => 'contact_id_b', 'multiple' => TRUE, 'create' => TRUE), TRUE);
319 // This field cannot be updated
320 if ($this->_action & CRM_Core_Action::UPDATE) {
321 $contactField->freeze();
322 }
323
324 $this->add('advcheckbox', 'is_current_employer', $this->_contactType == 'Organization' ? ts('Current Employee') : ts('Current Employer'));
325
326 $this->addField('start_date', array('label' => ts('Start Date'), 'formatType' => 'searchDate'));
327 $this->addField('end_date', array('label' => ts('End Date'), 'formatType' => 'searchDate'));
328
329 $this->addField('is_active', array('label' => ts('Enabled?')));
330
331 $this->addField('is_permission_a_b');
332 $this->addField('is_permission_b_a');
333
334 $this->addField('description', array('label' => ts('Description')));
335
336 CRM_Contact_Form_Edit_Notes::buildQuickForm($this);
337
338 if ($this->_action & CRM_Core_Action::VIEW) {
339 $this->addButtons(array(
340 array(
341 'type' => 'cancel',
342 'name' => ts('Done'),
343 ),
344 ));
345 }
346 else {
347 // make this form an upload since we don't know if the custom data injected dynamically is of type file etc.
348 $this->addButtons(array(
349 array(
350 'type' => 'upload',
351 'name' => ts('Save Relationship'),
352 'isDefault' => TRUE,
353 ),
354 array(
355 'type' => 'cancel',
356 'name' => ts('Cancel'),
357 ),
358 ));
359 }
360 }
361
362 /**
363 * This function is called when the form is submitted.
364 */
365 public function postProcess() {
366 // Store the submitted values in an array.
367 $params = $this->controller->exportValues($this->_name);
368
369 // CRM-14612 - Don't use adv-checkbox as it interferes with the form js
370 $params['is_permission_a_b'] = CRM_Utils_Array::value('is_permission_a_b', $params, 0);
371 $params['is_permission_b_a'] = CRM_Utils_Array::value('is_permission_b_a', $params, 0);
372
373 // action is taken depending upon the mode
374 if ($this->_action & CRM_Core_Action::DELETE) {
375 CRM_Contact_BAO_Relationship::del($this->_relationshipId);
376
377 // CRM-15881 UPDATES
378 // 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.
379 $this->ajaxResponse['reloadBlocks'] = array('#crm-contactinfo-content');
380
381 return;
382 }
383
384 $relationshipTypeParts = explode('_', $params['relationship_type_id']);
385 $params['relationship_type_id'] = $relationshipTypeParts[0];
386 if (!$this->_rtype) {
387 // Do we need to wrap this in an if - when is rtype used & is relationship_type_id always set then?
388 $this->_rtype = $params['relationship_type_id'];
389 }
390 $params['contact_id_' . $relationshipTypeParts[1]] = $this->_contactId;
391
392 // Update mode (always single)
393 if ($this->_action & CRM_Core_Action::UPDATE) {
394 $update = TRUE;
395 $params['id'] = $this->_relationshipId;
396 $ids['relationship'] = $this->_relationshipId;
397 $relation = CRM_Contact_BAO_Relationship::getRelationshipByID($this->_relationshipId);
398 if ($relation->contact_id_a == $this->_contactId) {
399 // I couldn't replicate this path in testing. See below.
400 $params['contact_id_a'] = $this->_contactId;
401 $params['contact_id_b'] = array($params['related_contact_id']);
402 $outcome = CRM_Contact_BAO_Relationship::createMultiple($params, $relationshipTypeParts[1]);
403 $relationshipIds = $outcome['relationship_ids'];
404 }
405 else {
406 // The only reason we have changed this to use the api & not the above is that this was broken.
407 // Recommend extracting all of update into a function that uses the api
408 // and ensuring api / bao take care of 'other stuff' in this form
409 // the contact_id_a & b can't be changed on this form so don't really need setting.
410 $params['contact_id_b'] = $this->_contactId;
411 $params['contact_id_a'] = $params['related_contact_id'];
412 $result = civicrm_api3('relationship', 'create', $params);
413 $relationshipIds = array($result['id']);
414 }
415 $ids['contactTarget'] = ($relation->contact_id_a == $this->_contactId) ? $relation->contact_id_b : $relation->contact_id_a;
416
417 // @todo this belongs in the BAO.
418 if ($this->_isCurrentEmployer) {
419 // if relationship type changes, relationship is disabled, or "current employer" is unchecked,
420 // clear the current employer. CRM-3235.
421 $relChanged = $params['relationship_type_id'] != $this->_values['relationship_type_id'];
422 if (!$params['is_active'] || !$params['is_current_employer'] || $relChanged) {
423
424 // CRM-15881 UPDATES
425 // 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.
426 // 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.
427 if (!$params['is_active']) {
428 $params['is_current_employer'] = FALSE;
429 }
430
431 CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($this->_values['contact_id_a']);
432 // Refresh contact summary if in ajax mode
433 $this->ajaxResponse['reloadBlocks'] = array('#crm-contactinfo-content');
434 }
435 }
436 if (empty($outcome['saved']) && !empty($update)) {
437 $outcome['saved'] = $update;
438 }
439 $this->setMessage($outcome);
440 }
441 // Create mode (could be 1 or more relationships)
442 else {
443 $params['contact_id_' . $relationshipTypeParts[2]] = explode(',', $params['related_contact_id']);
444 $outcome = CRM_Contact_BAO_Relationship::createMultiple($params, $relationshipTypeParts[1]);
445 $relationshipIds = $outcome['relationship_ids'];
446 if (empty($outcome['saved']) && !empty($update)) {
447 $outcome['saved'] = $update;
448 }
449 $this->setMessage($outcome);
450 }
451
452 // if this is called from case view,
453 //create an activity for case role removal.CRM-4480
454 // @todo this belongs in the BAO.
455 if ($this->_caseId) {
456 CRM_Case_BAO_Case::createCaseRoleActivity($this->_caseId, $relationshipIds, $params['contact_check'], $this->_contactId);
457 }
458
459 // Save notes
460 // @todo this belongs in the BAO.
461 if ($this->_action & CRM_Core_Action::UPDATE || $params['note']) {
462 foreach ($relationshipIds as $id) {
463 $noteParams = array(
464 'entity_id' => $id,
465 'entity_table' => 'civicrm_relationship',
466 );
467 $existing = civicrm_api3('note', 'get', $noteParams);
468 if (!empty($existing['id'])) {
469 $noteParams['id'] = $existing['id'];
470 }
471 $noteParams['note'] = $params['note'];
472 $noteParams['contact_id'] = $this->_contactId;
473 if (!empty($existing['id']) || $params['note']) {
474 $action = $params['note'] ? 'create' : 'delete';
475 civicrm_api3('note', $action, $noteParams);
476 }
477 }
478 }
479
480 $params['relationship_ids'] = $relationshipIds;
481
482 // Refresh contact tabs which might have been affected
483 $this->ajaxResponse['updateTabs'] = array(
484 '#tab_member' => CRM_Contact_BAO_Contact::getCountComponent('membership', $this->_contactId),
485 '#tab_contribute' => CRM_Contact_BAO_Contact::getCountComponent('contribution', $this->_contactId),
486 );
487
488 // Set current employee/employer relationship, CRM-3532
489 if ($params['is_current_employer'] && $this->_allRelationshipNames[$params['relationship_type_id']]["name_a_b"] ==
490 'Employee of') {
491 $employerParams = array();
492 foreach ($relationshipIds as $id) {
493 // Fixme this is dumb why do we have to look this up again?
494 $rel = CRM_Contact_BAO_Relationship::getRelationshipByID($id);
495 $employerParams[$rel->contact_id_a] = $rel->contact_id_b;
496 }
497 // @todo this belongs in the BAO.
498 CRM_Contact_BAO_Contact_Utils::setCurrentEmployer($employerParams);
499 // Refresh contact summary if in ajax mode
500 $this->ajaxResponse['reloadBlocks'] = array('#crm-contactinfo-content');
501 }
502 }
503
504 /**
505 * Date validation.
506 *
507 * @param array $params
508 * (reference ) an assoc array of name/value pairs.
509 *
510 * @return bool|array
511 * mixed true or array of errors
512 */
513 public static function dateRule($params) {
514 $errors = array();
515
516 // check start and end date
517 if (!empty($params['start_date']) && !empty($params['end_date'])) {
518 $start_date = CRM_Utils_Date::format(CRM_Utils_Array::value('start_date', $params));
519 $end_date = CRM_Utils_Date::format(CRM_Utils_Array::value('end_date', $params));
520 if ($start_date && $end_date && (int ) $end_date < (int ) $start_date) {
521 $errors['end_date'] = ts('The relationship end date cannot be prior to the start date.');
522 }
523 }
524
525 return empty($errors) ? TRUE : $errors;
526 }
527
528 /**
529 * Set Status message to reflect outcome of the update action.
530 *
531 * @param array $outcome
532 * Outcome of save action - including
533 * - 'valid' : Number of valid relationships attempted.
534 * - 'invalid' : Number of invalid relationships attempted.
535 * - 'duplicate' : Number of duplicate relationships attempted.
536 * - 'saved' : boolean of whether save was successful
537 */
538 protected function setMessage($outcome) {
539 if (!empty($outcome['valid']) && empty($outcome['saved'])) {
540 CRM_Core_Session::setStatus(ts('Relationship created.', array(
541 'count' => $outcome['valid'],
542 'plural' => '%count relationships created.',
543 )), ts('Saved'), 'success');
544 }
545 if (!empty($outcome['invalid'])) {
546 CRM_Core_Session::setStatus(ts('%count relationship record was not created due to an invalid contact type.', array(
547 'count' => $outcome['invalid'],
548 'plural' => '%count relationship records were not created due to invalid contact types.',
549 )), ts('%count invalid relationship record', array(
550 'count' => $outcome['invalid'],
551 'plural' => '%count invalid relationship records',
552 )));
553 }
554 if (!empty($outcome['duplicate'])) {
555 CRM_Core_Session::setStatus(ts('One relationship was not created because it already exists.', array(
556 'count' => $outcome['duplicate'],
557 'plural' => '%count relationships were not created because they already exist.',
558 )), ts('%count duplicate relationship', array(
559 'count' => $outcome['duplicate'],
560 'plural' => '%count duplicate relationships',
561 )));
562 }
563 if (!empty($outcome['saved'])) {
564 CRM_Core_Session::setStatus(ts('Relationship record has been updated.'), ts('Saved'), 'success');
565 }
566 }
567
568 }