Merge pull request #15833 from yashodha/participant_edit
[civicrm-core.git] / CRM / Case / Form / Activity.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2020 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2020
32 */
33
34 /**
35 * This class create activities for a case.
36 */
37 class CRM_Case_Form_Activity extends CRM_Activity_Form_Activity {
38
39 /**
40 * Cases this activity belongs to.
41 *
42 * @var []int
43 */
44 public $_caseId;
45
46 /**
47 * The default case type variable defined.
48 *
49 * @var []int
50 */
51 public $_caseType;
52
53 /**
54 * The array of releted contact info.
55 *
56 * @var array
57 */
58 public $_relatedContacts;
59
60 /**
61 * The case type definition column info
62 * for the caseId;
63 *
64 * @var array
65 */
66 public $_caseTypeDefinition;
67
68 /**
69 * Build the form object.
70 */
71 public function preProcess() {
72 $caseIds = CRM_Utils_Request::retrieve('caseid', 'CommaSeparatedIntegers', $this);
73 $this->_caseId = $caseIds ? explode(',', $caseIds) : [];
74 $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
75 if (!$this->_context) {
76 $this->_context = 'caseActivity';
77 }
78 $this->_crmDir = 'Case';
79 $this->assign('context', $this->_context);
80
81 parent::preProcess();
82
83 $scheduleStatusId = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Scheduled');
84 $this->assign('scheduleStatusId', $scheduleStatusId);
85
86 if (!$this->_caseId && $this->_activityId) {
87 $this->_caseId = (array) CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseActivity', $this->_activityId,
88 'case_id', 'activity_id'
89 );
90 }
91 if ($this->_caseId) {
92 $this->assign('caseId', $this->_caseId);
93 $this->assign('countId', count($this->_caseId));
94 $this->assign('caseID', CRM_Utils_Array::first($this->_caseId));
95 }
96
97 if (!$this->_caseId ||
98 (!$this->_activityId && !$this->_activityTypeId)
99 ) {
100 CRM_Core_Error::statusBounce(ts('required params missing.'));
101 }
102
103 //check for case activity access.
104 if (!CRM_Case_BAO_Case::accessCiviCase()) {
105 CRM_Core_Error::statusBounce(ts('You are not authorized to access this page.'));
106 }
107 //validate case id.
108 if ($this->_caseId &&
109 !CRM_Core_Permission::check('access all cases and activities')
110 ) {
111 $params = ['type' => 'any'];
112 $allCases = CRM_Case_BAO_Case::getCases(TRUE, $params);
113 if (count(array_intersect($this->_caseId, array_keys($allCases))) == 0) {
114 CRM_Core_Error::statusBounce(ts('You are not authorized to access this page.'));
115 }
116 }
117
118 //validate case activity id.
119 if ($this->_activityId &&
120 ($this->_action & CRM_Core_Action::UPDATE)
121 ) {
122 $valid = CRM_Case_BAO_Case::checkPermission($this->_activityId, 'edit',
123 $this->_activityTypeId
124 );
125 if (!$valid) {
126 CRM_Core_Error::statusBounce(ts('You are not authorized to access this page.'));
127 }
128 }
129
130 foreach ($this->_caseId as $casePos => $caseId) {
131 $this->_caseType[$casePos] = CRM_Case_BAO_Case::getCaseType($caseId, 'name');
132 }
133 $this->assign('caseType', $this->_caseType);
134
135 $this->_caseTypeDefinition = $this->getCaseTypeDefinition();
136
137 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
138 $isMultiClient = $xmlProcessorProcess->getAllowMultipleCaseClients();
139 $this->assign('multiClient', $isMultiClient);
140
141 foreach ($this->_caseId as $casePos => $caseId) {
142 $clients[] = CRM_Case_BAO_Case::getContactNames($caseId);
143 }
144 $this->assign('client_names', $clients);
145
146 $caseIds = implode(',', $this->_caseId);
147 // set context for pushUserContext and for statusBounce
148 if ($this->_context == 'fulltext') {
149 if ($this->_action == CRM_Core_Action::UPDATE || $this->_action == CRM_Core_Action::DELETE) {
150 $url = CRM_Utils_System::url('civicrm/contact/view/case',
151 "reset=1&action=view&cid={$this->_currentlyViewedContactId}&id={$caseIds}&show=1&context={$this->_context}"
152 );
153 }
154 else {
155 $url = CRM_Utils_System::url('civicrm/contact/search/custom', 'force=1');
156 }
157 }
158 else {
159 $url = CRM_Utils_System::url('civicrm/contact/view/case',
160 "reset=1&action=view&cid={$this->_currentlyViewedContactId}&id={$caseIds}&show=1"
161 );
162 }
163 if (!$this->_activityId) {
164 $caseTypes = CRM_Case_PseudoConstant::caseType();
165
166 if (empty($caseTypes) && ($this->_activityTypeName == 'Change Case Type') && !$this->_caseId) {
167 $url = CRM_Utils_System::url('civicrm/contact/view/case',
168 "reset=1&action=view&cid={$this->_currentlyViewedContactId}&id={$caseIds}&show=1"
169 );
170 $session = CRM_Core_Session::singleton();
171 $session->pushUserContext($url);
172 CRM_Core_Error::statusBounce(ts("You do not have any active Case Types"));
173 }
174
175 // check if activity count is within the limit
176 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
177 foreach ($this->_caseId as $casePos => $caseId) {
178 $caseType = $this->_caseType[$casePos];
179 $activityInst = $xmlProcessor->getMaxInstance($caseType);
180
181 // If not bounce back and also provide activity edit link if only one existing activity
182 if (isset($activityInst[$this->_activityTypeName])) {
183 $activityCount = CRM_Case_BAO_Case::getCaseActivityCount($caseId, $this->_activityTypeId);
184 $editUrl = self::checkMaxInstances(
185 $caseId,
186 $this->_activityTypeId,
187 $activityInst[$this->_activityTypeName],
188 $this->_currentUserId,
189 $this->_currentlyViewedContactId,
190 $activityCount
191 );
192 $bounceMessage = self::getMaxInstancesBounceMessage($editUrl, $this->_activityTypeName, $activityInst[$this->_activityTypeName], $activityCount);
193 if ($bounceMessage) {
194 CRM_Core_Error::statusBounce($bounceMessage, $url);
195 }
196 }
197 }
198 }
199
200 // Turn off the prompt which asks the user if they want to create separate
201 // activities when specifying multiple contacts "with" a new activity.
202 // Instead, always create one activity with all contacts together.
203 $this->supportsActivitySeparation = FALSE;
204
205 $session = CRM_Core_Session::singleton();
206 $session->pushUserContext($url);
207 }
208
209 /**
210 * Set default values for the form.
211 */
212 public function setDefaultValues() {
213 $this->_defaults = parent::setDefaultValues();
214 $targetContactValues = [];
215 foreach ($this->_caseId as $key => $val) {
216 //get all clients.
217 $clients = CRM_Case_BAO_Case::getContactNames($val);
218 if (isset($this->_activityId) && empty($_POST)) {
219 if (!CRM_Utils_Array::crmIsEmptyArray($this->_defaults['target_contact'])) {
220 $targetContactValues = array_combine(array_unique($this->_defaults['target_contact']),
221 explode(';', trim($this->_defaults['target_contact_value']))
222 );
223 //exclude all clients.
224 foreach ($clients as $clientId => $vals) {
225 if (array_key_exists($clientId, $targetContactValues)) {
226 unset($targetContactValues[$clientId]);
227 }
228 }
229 }
230 }
231 $this->assign('targetContactValues', empty($targetContactValues) ? FALSE : $targetContactValues);
232
233 if (isset($this->_encounterMedium)) {
234 $this->_defaults['medium_id'] = $this->_encounterMedium;
235 }
236 elseif (empty($this->_defaults['medium_id'])) {
237 // set default encounter medium CRM-4816
238 $medium = CRM_Core_OptionGroup::values('encounter_medium', FALSE, FALSE, FALSE, 'AND is_default = 1');
239 if (count($medium) == 1) {
240 $this->_defaults['medium_id'] = key($medium);
241 }
242 }
243
244 return $this->_defaults;
245 }
246 }
247
248 public function buildQuickForm() {
249 $this->_fields['source_contact_id']['label'] = ts('Reported By');
250 unset($this->_fields['status_id']['attributes']['required']);
251
252 if ($this->restrictAssignmentByUserAccount()) {
253 $assigneeParameters['uf_user'] = 1;
254 }
255
256 $activityAssignmentGroups = $this->getActivityAssignmentGroups();
257 if (!empty($activityAssignmentGroups)) {
258 $assigneeParameters['group'] = ['IN' => $activityAssignmentGroups];
259 }
260
261 if (!empty($assigneeParameters)) {
262 $this->_fields['assignee_contact_id']['attributes']['api']['params']
263 = array_merge($this->_fields['assignee_contact_id']['attributes']['api']['params'], $assigneeParameters);
264
265 $this->_fields['followup_assignee_contact_id']['attributes']['api']['params']
266 = array_merge($this->_fields['followup_assignee_contact_id']['attributes']['api']['params'], $assigneeParameters);
267
268 //Disallow creating a contact from the assignee field UI.
269 $this->_fields['assignee_contact_id']['attributes']['create'] = FALSE;
270 $this->_fields['followup_assignee_contact_id']['attributes']['create'] = FALSE;
271 }
272
273 if ($this->_caseType) {
274 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
275 $aTypes = [];
276 foreach (array_unique($this->_caseType) as $val) {
277 $activityTypes = $xmlProcessor->get($val, 'ActivityTypes', TRUE);
278 $aTypes = $aTypes + $activityTypes;
279 }
280
281 // remove Open Case activity type since we're inside an existing case
282 $openCaseID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Open Case');
283 unset($aTypes[$openCaseID]);
284 asort($aTypes);
285 $this->_fields['followup_activity_type_id']['attributes'] = ['' => '- select activity type -'] + $aTypes;
286 }
287
288 parent::buildQuickForm();
289
290 if ($this->_action & (CRM_Core_Action::DELETE | CRM_Core_Action::DETACH | CRM_Core_Action::RENEW)) {
291 return;
292 }
293
294 $this->assign('urlPath', 'civicrm/case/activity');
295
296 $encounterMediums = CRM_Case_PseudoConstant::encounterMedium();
297
298 if ($this->_activityTypeFile == 'OpenCase' && $this->_action == CRM_Core_Action::UPDATE) {
299 $this->getElement('activity_date_time')->freeze();
300
301 if ($this->_activityId) {
302 // Fixme: what's the justification for this? It seems like it is just re-adding an option in case it is the default and disabled.
303 // Is that really a big problem?
304 $this->_encounterMedium = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $this->_activityId, 'medium_id');
305 if (!array_key_exists($this->_encounterMedium, $encounterMediums)) {
306 $encounterMediums[$this->_encounterMedium] = CRM_Core_PseudoConstant::getLabel('CRM_Activity_BAO_Activity', 'medium_id', $this->_encounterMedium);
307 }
308 }
309 }
310
311 $this->add('select', 'medium_id', ts('Medium'), $encounterMediums, TRUE);
312 $i = 0;
313 foreach ($this->_caseId as $key => $val) {
314 $this->_relatedContacts[] = $rgc = CRM_Case_BAO_Case::getRelatedAndGlobalContacts($val);
315 $contName = CRM_Case_BAO_Case::getContactNames($val);
316 foreach ($contName as $nkey => $nval) {
317 array_push($this->_relatedContacts[$i][0], $this->_relatedContacts[$i][0]['managerOf'] = $nval['display_name']);
318 }
319 $i++;
320 }
321
322 //add case client in send a copy selector.CRM-4438.
323 foreach ($this->_caseId as $key => $val) {
324 $relatedContacts[] = $relCon = CRM_Case_BAO_Case::getContactNames($val);
325 }
326
327 if (!empty($relatedContacts)) {
328 foreach ($relatedContacts as $relatedContact) {
329 $this->_relatedContacts[] = $relatedContact;
330 }
331 }
332
333 if (!empty($this->_relatedContacts)) {
334 $checkBoxes = [];
335 foreach ($this->_relatedContacts as $id => $row) {
336 foreach ($row as $key => $value) {
337 $checkBoxes[$key] = $this->addElement('checkbox', $key, NULL, NULL, ['class' => 'select-row']);
338 }
339 }
340
341 $this->addGroup($checkBoxes, 'contact_check');
342 $this->addElement('checkbox', 'toggleSelect', NULL, NULL,
343 ['class' => 'select-rows']
344 );
345 $this->assign('searchRows', $this->_relatedContacts);
346 }
347 $this->_relatedContacts = $rgc + $relCon;
348
349 $this->addFormRule(['CRM_Case_Form_Activity', 'formRule'], $this);
350 }
351
352 /**
353 * Global form rule.
354 *
355 * @param array $fields
356 * The input form values.
357 * @param array $files
358 * The uploaded files if any.
359 * @param $self
360 *
361 * @return bool|array
362 * true if no errors, else array of errors
363 */
364 public static function formRule($fields, $files, $self) {
365 // skip form rule if deleting
366 if (CRM_Utils_Array::value('_qf_Activity_next_', $fields) == 'Delete' || CRM_Utils_Array::value('_qf_Activity_next_', $fields) == 'Restore') {
367 return TRUE;
368 }
369
370 return parent::formRule($fields, $files, $self);
371 }
372
373 /**
374 * Process the form submission.
375 *
376 * @param array $params
377 */
378 public function postProcess($params = NULL) {
379 $transaction = new CRM_Core_Transaction();
380
381 if ($this->_action & CRM_Core_Action::DELETE) {
382 $statusMsg = NULL;
383
384 //block deleting activities which affects
385 //case attributes.CRM-4543
386 $activityCondition = " AND v.name IN ('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date')";
387 $caseAttributeActivities = CRM_Core_OptionGroup::values('activity_type', FALSE, FALSE, FALSE, $activityCondition);
388
389 if (!array_key_exists($this->_activityTypeId, $caseAttributeActivities)) {
390 $params = ['id' => $this->_activityId];
391 $activityDelete = CRM_Activity_BAO_Activity::deleteActivity($params, TRUE);
392 if ($activityDelete) {
393 $statusMsg = ts('The selected activity has been moved to the Trash. You can view and / or restore deleted activities by checking "Deleted Activities" from the Case Activities search filter (under Manage Case).<br />');
394 }
395 }
396 else {
397 $statusMsg = ts("Selected Activity cannot be deleted.");
398 }
399
400 $tagParams = [
401 'entity_table' => 'civicrm_activity',
402 'entity_id' => $this->_activityId,
403 ];
404 CRM_Core_BAO_EntityTag::del($tagParams);
405
406 CRM_Core_Session::setStatus('', $statusMsg, 'info');
407 return;
408 }
409
410 if ($this->_action & CRM_Core_Action::RENEW) {
411 $statusMsg = NULL;
412 $params = ['id' => $this->_activityId];
413 $activityRestore = CRM_Activity_BAO_Activity::restoreActivity($params);
414 if ($activityRestore) {
415 $statusMsg = ts('The selected activity has been restored.<br />');
416 }
417 CRM_Core_Session::setStatus('', $statusMsg, 'info');
418 return;
419 }
420
421 // store the submitted values in an array
422 // Explanation for why we only check the is_unittest element: Prior to adding that check, there was no check and so any $params passed in would have been overwritten. Just in case somebody is passing in some non-null params and that broken code would have inadvertently been working, we can maintain backwards compatibility by only checking for the is_unittest parameter, and so that broken code will still work. At the same time this allows unit tests to pass in a $params without it getting overwritten. See also PR #2077 for some discussion of when the $params parameter was added as a passed in variable.
423 if (empty($params['is_unittest'])) {
424 $params = $this->controller->exportValues($this->_name);
425 }
426
427 //set parent id if its edit mode
428 if ($parentId = CRM_Utils_Array::value('parent_id', $this->_defaults)) {
429 $params['parent_id'] = $parentId;
430 }
431
432 $params['activity_type_id'] = $this->_activityTypeId;
433
434 // format with contact (target contact) values
435 if (isset($params['target_contact_id'])) {
436 $params['target_contact_id'] = explode(',', $params['target_contact_id']);
437 }
438 else {
439 $params['target_contact_id'] = [];
440 }
441
442 // format activity custom data
443 if (!empty($params['hidden_custom'])) {
444 if ($this->_activityId) {
445 // retrieve and include the custom data of old Activity
446 $oldActivity = civicrm_api3('Activity', 'getsingle', ['id' => $this->_activityId]);
447 $params = array_merge($oldActivity, $params);
448
449 // unset custom fields-id from params since we want custom
450 // fields to be saved for new activity.
451 foreach ($params as $key => $value) {
452 $match = [];
453 if (preg_match('/^(custom_\d+_)(\d+)$/', $key, $match)) {
454 $params[$match[1] . '-1'] = $params[$key];
455
456 // for autocomplete transfer hidden value instead of label
457 if ($params[$key] && isset($params[$key . '_id'])) {
458 $params[$match[1] . '-1_id'] = $params[$key . '_id'];
459 unset($params[$key . '_id']);
460 }
461 unset($params[$key]);
462 }
463 }
464 }
465
466 // build custom data getFields array
467 $customFields = CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, $this->_activityTypeId);
468 $customFields = CRM_Utils_Array::crmArrayMerge($customFields,
469 CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE,
470 NULL, NULL, TRUE
471 )
472 );
473 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
474 $this->_activityId,
475 'Activity'
476 );
477 }
478
479 // assigning formatted value
480 if (!empty($params['assignee_contact_id'])) {
481 $params['assignee_contact_id'] = explode(',', $params['assignee_contact_id']);
482 }
483 else {
484 $params['assignee_contact_id'] = [];
485 }
486
487 if (isset($this->_activityId)) {
488 // activity which hasn't been modified by a user yet
489 if ($this->_defaults['is_auto'] == 1) {
490 $params['is_auto'] = 0;
491 }
492
493 // always create a revision of an case activity. CRM-4533
494 $newActParams = $params;
495
496 // add target contact values in update mode
497 if (empty($params['target_contact_id']) && !empty($this->_defaults['target_contact'])) {
498 $newActParams['target_contact_id'] = $this->_defaults['target_contact'];
499 }
500 }
501
502 if (!isset($newActParams)) {
503 // add more attachments if needed for old activity
504 CRM_Core_BAO_File::formatAttachment($params,
505 $params,
506 'civicrm_activity'
507 );
508
509 // call begin post process, before the activity is created/updated.
510 $this->beginPostProcess($params);
511 foreach ($this->_caseId as $key => $val) {
512 $params['case_id'] = $val;
513 // activity create/update
514 $activity = CRM_Activity_BAO_Activity::create($params);
515 $vvalue[] = ['case_id' => $val, 'actId' => $activity->id];
516 // call end post process, after the activity has been created/updated.
517 $this->endPostProcess($params, $activity);
518 }
519 }
520 else {
521 // since the params we need to set are very few, and we don't want rest of the
522 // work done by bao create method , lets use dao object to make the changes
523 $params = ['id' => $this->_activityId];
524 $params['is_current_revision'] = 0;
525 $activity = new CRM_Activity_DAO_Activity();
526 $activity->copyValues($params);
527 $activity->save();
528 }
529
530 // create a new version of activity if activity was found to
531 // have been modified/created by user
532 if (isset($newActParams)) {
533 // set proper original_id
534 if (!empty($this->_defaults['original_id'])) {
535 $newActParams['original_id'] = $this->_defaults['original_id'];
536 }
537 else {
538 $newActParams['original_id'] = $activity->id;
539 }
540
541 //is_current_revision will be set to 1 by default.
542 // add attachments if any
543 CRM_Core_BAO_File::formatAttachment($newActParams,
544 $newActParams,
545 'civicrm_activity'
546 );
547
548 // call begin post process, before the activity is created/updated.
549 $this->beginPostProcess($newActParams);
550 foreach ($this->_caseId as $key => $val) {
551 $newActParams['case_id'] = $val;
552 $activity = CRM_Activity_BAO_Activity::create($newActParams);
553 $vvalue[] = ['case_id' => $val, 'actId' => $activity->id];
554 // call end post process, after the activity has been created/updated.
555 $this->endPostProcess($newActParams, $activity);
556 }
557 // copy files attached to old activity if any, to new one,
558 // as long as users have not selected the 'delete attachment' option.
559 if (empty($newActParams['is_delete_attachment']) && ($this->_activityId != $activity->id)) {
560 CRM_Core_BAO_File::copyEntityFile('civicrm_activity', $this->_activityId,
561 'civicrm_activity', $activity->id
562 );
563 }
564
565 // copy back params to original var
566 $params = $newActParams;
567 }
568
569 foreach ($vvalue as $vkey => $vval) {
570 if ($vval['actId']) {
571 // add tags if exists
572 $tagParams = [];
573 if (!empty($params['tag'])) {
574 if (!is_array($params['tag'])) {
575 $params['tag'] = explode(',', $params['tag']);
576 }
577
578 $tagParams = array_fill_keys($params['tag'], 1);
579 }
580
581 //save static tags
582 CRM_Core_BAO_EntityTag::create($tagParams, 'civicrm_activity', $vval['actId']);
583
584 //save free tags
585 if (isset($params['taglist']) && !empty($params['taglist'])) {
586 CRM_Core_Form_Tag::postProcess($params['taglist'], $vval['actId'], 'civicrm_activity', $this);
587 }
588 }
589
590 // update existing case record if needed
591 $caseParams = $params;
592 $caseParams['id'] = $vval['case_id'];
593 if (!empty($caseParams['case_status_id'])) {
594 $caseParams['status_id'] = $caseParams['case_status_id'];
595 }
596
597 // unset params intended for activities only
598 unset($caseParams['subject'], $caseParams['details'],
599 $caseParams['status_id'], $caseParams['custom']
600 );
601 CRM_Case_BAO_Case::create($caseParams);
602 // create case activity record
603 $caseParams = [
604 'activity_id' => $vval['actId'],
605 'case_id' => $vval['case_id'],
606 ];
607 CRM_Case_BAO_Case::processCaseActivity($caseParams);
608 }
609
610 // send copy to selected contacts.
611 $mailStatus = '';
612 $mailToContacts = [];
613
614 //CRM-5695
615 //check for notification settings for assignee contacts
616 $selectedContacts = ['contact_check'];
617 if (Civi::settings()->get('activity_assignee_notification')) {
618 $selectedContacts[] = 'assignee_contact_id';
619 }
620
621 foreach ($vvalue as $vkey => $vval) {
622 foreach ($selectedContacts as $dnt => $val) {
623 if (array_key_exists($val, $params) && !CRM_Utils_Array::crmIsEmptyArray($params[$val])) {
624 if ($val == 'contact_check') {
625 $mailStatus = ts("A copy of the activity has also been sent to selected contacts(s).");
626 }
627 else {
628 $this->_relatedContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames([$vval['actId']], TRUE, FALSE);
629 $mailStatus .= ' ' . ts("A copy of the activity has also been sent to assignee contacts(s).");
630 }
631 //build an associative array with unique email addresses.
632 foreach ($params[$val] as $key => $value) {
633 if ($val == 'contact_check') {
634 $id = $key;
635 }
636 else {
637 $id = $value;
638 }
639
640 if (isset($id) && array_key_exists($id, $this->_relatedContacts) && isset($this->_relatedContacts[$id]['email'])) {
641 //if email already exists in array then append with ', ' another role only otherwise add it to array.
642 if ($contactDetails = CRM_Utils_Array::value($this->_relatedContacts[$id]['email'], $mailToContacts)) {
643 $caseRole = CRM_Utils_Array::value('role', $this->_relatedContacts[$id]);
644 $mailToContacts[$this->_relatedContacts[$id]['email']]['role'] = $contactDetails['role'] . ', ' . $caseRole;
645 }
646 else {
647 $mailToContacts[$this->_relatedContacts[$id]['email']] = $this->_relatedContacts[$id];
648 }
649 }
650 }
651 }
652 }
653
654 $extraParams = ['case_id' => $vval['case_id'], 'client_id' => $this->_currentlyViewedContactId];
655 $result = CRM_Activity_BAO_Activity::sendToAssignee($activity, $mailToContacts, $extraParams);
656 if (empty($result)) {
657 $mailStatus = '';
658 }
659
660 // create follow up activity if needed
661 $followupStatus = '';
662 if (!empty($params['followup_activity_type_id'])) {
663 $followupActivity = CRM_Activity_BAO_Activity::createFollowupActivity($vval['actId'], $params);
664
665 if ($followupActivity) {
666 $caseParams = [
667 'activity_id' => $followupActivity->id,
668 'case_id' => $vval['case_id'],
669 ];
670 CRM_Case_BAO_Case::processCaseActivity($caseParams);
671 $followupStatus = ts("A followup activity has been scheduled.") . '<br /><br />';
672 }
673 }
674 $title = ts("%1 Saved", [1 => $this->_activityTypeName]);
675 CRM_Core_Session::setStatus($followupStatus . $mailStatus, $title, 'success');
676 }
677 }
678
679 /**
680 * Returns the groups that contacts must belong to in order to be assigned
681 * an activity for this case. It returns an empty array if no groups are found for
682 * the case type linked to the caseId.
683 *
684 * @return array
685 */
686 private function getActivityAssignmentGroups() {
687 if (!$this->_caseTypeDefinition) {
688 return [];
689 }
690
691 $assignmentGroups = [];
692 foreach ($this->_caseTypeDefinition as $caseId => $definition) {
693 if (!empty($definition['activityAsgmtGrps'])) {
694 $assignmentGroups = array_merge($assignmentGroups, $definition['activityAsgmtGrps']);
695 }
696 }
697
698 return $assignmentGroups;
699 }
700
701 /**
702 * Returns whether contacts must have a user account in order to be
703 * assigned an activity for this case.
704 *
705 * @return bool
706 */
707 private function restrictAssignmentByUserAccount() {
708 if (!$this->_caseTypeDefinition) {
709 return FALSE;
710 }
711
712 foreach ($this->_caseTypeDefinition as $caseId => $definition) {
713 if (!empty($definition['restrictActivityAsgmtToCmsUser'])) {
714 return TRUE;
715 }
716 }
717
718 return FALSE;
719 }
720
721 /**
722 * Returns the case type definition column value for the case type linked to the caseId.
723 *
724 * @return array
725 */
726 private function getCaseTypeDefinition() {
727 if (!$this->_caseId) {
728 return [];
729 }
730
731 $definitions = civicrm_api3('CaseType', 'get', [
732 'return' => ['name', 'definition'],
733 'name' => ['IN' => array_unique($this->_caseType)],
734 ]);
735
736 return array_column($definitions['values'], 'definition', 'name');
737 }
738
739 /**
740 * Get the edit link for a case activity
741 *
742 * This isn't here for reusability - it was a pull out
743 * from preProcess to make it easier to test.
744 * There is CRM_Case_Selector_Search::addCaseActivityLinks but it would
745 * need some rejigging, and there's also a FIXME note there already.
746 *
747 * @param int $caseId
748 * @param int $activityTypeId
749 * @param int $currentUserId
750 * @param int $currentlyViewedContactId
751 *
752 * @return string
753 */
754 public static function getCaseActivityEditLink($caseId, $activityTypeId, $currentUserId, $currentlyViewedContactId) {
755 $atArray = ['activity_type_id' => $activityTypeId];
756 $activities = CRM_Case_BAO_Case::getCaseActivity($caseId,
757 $atArray,
758 $currentUserId
759 );
760 $firstActivity = CRM_Utils_Array::first($activities['data']);
761 $activityId = empty($firstActivity['DT_RowId']) ? 0 : $firstActivity['DT_RowId'];
762 return CRM_Utils_System::url('civicrm/case/activity',
763 "reset=1&cid={$currentlyViewedContactId}&caseid={$caseId}&action=update&id={$activityId}"
764 );
765 }
766
767 /**
768 * Check the current activity count against max instances for a given case id and activity type.
769 *
770 * This isn't here for reusability - it was a pull out
771 * from preProcess to make it easier to test.
772 *
773 * @param int $caseId
774 * @param int $activityTypeId
775 * @param int $maxInstances
776 * @param int $currentUserId
777 * @param int $currentlyViewedContactId
778 * @param int $activityCount
779 *
780 * @return string
781 * If there is more than one existing activity of the given type then it's not clear which url to return so return null for the url.
782 */
783 public static function checkMaxInstances($caseId, $activityTypeId, $maxInstances, $currentUserId, $currentlyViewedContactId, $activityCount) {
784 $editUrl = NULL;
785 if ($activityCount >= $maxInstances) {
786 if ($maxInstances == 1) {
787 $editUrl = self::getCaseActivityEditLink($caseId, $activityTypeId, $currentUserId, $currentlyViewedContactId);
788 }
789 }
790 return $editUrl;
791 }
792
793 /**
794 * Compute the message text for the bounce message when max_instances is reached, depending on whether it's one or more than one.
795 *
796 * @param string $editUrl
797 * @param string $activityTypeName
798 * This is actually label!! But we do want label though in this function.
799 * @param int $maxInstances
800 * @param int $activityCount
801 * Count of existing activities of the given type on the case
802 *
803 * @return string
804 */
805 public static function getMaxInstancesBounceMessage($editUrl, $activityTypeName, $maxInstances, $activityCount) {
806 $bounceMessage = NULL;
807 if ($activityCount >= $maxInstances) {
808 if ($maxInstances == 1) {
809 $bounceMessage = ts("You can not add another '%1' activity to this case. %2",
810 [
811 1 => $activityTypeName,
812 2 => ts("Do you want to <a %1>edit the existing activity</a>?", [1 => "href='$editUrl'"]),
813 ]
814 );
815 }
816 else {
817 // More than one instance, so don't provide a link. What would it be a link to anyway?
818 $bounceMessage = ts("You can not add another '%1' activity to this case.",
819 [
820 1 => $activityTypeName,
821 ]
822 );
823 }
824 }
825 return $bounceMessage;
826 }
827
828 }