3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
35 * This class create activities for a case.
37 class CRM_Case_Form_Activity
extends CRM_Activity_Form_Activity
{
40 * The default variable defined.
47 * The default case type variable defined.
54 * The array of releted contact info.
58 public $_relatedContacts;
61 * Build the form object.
63 public function preProcess() {
64 $caseIds = CRM_Utils_Request
::retrieve('caseid', 'String', $this);
65 $this->_caseId
= explode(',', $caseIds);
66 $this->_context
= CRM_Utils_Request
::retrieve('context', 'Alphanumeric', $this);
67 if (!$this->_context
) {
68 $this->_context
= 'caseActivity';
70 $this->_crmDir
= 'Case';
71 $this->assign('context', $this->_context
);
75 $scheduleStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Scheduled');
76 $this->assign('scheduleStatusId', $scheduleStatusId);
78 if (!$this->_caseId
&& $this->_activityId
) {
79 $this->_caseId
= CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_CaseActivity', $this->_activityId
,
80 'case_id', 'activity_id'
84 $this->assign('caseId', $this->_caseId
);
85 $this->assign('countId', count($this->_caseId
));
86 $this->assign('caseID', CRM_Utils_Array
::first($this->_caseId
));
89 if (!$this->_caseId ||
90 (!$this->_activityId
&& !$this->_activityTypeId
)
92 CRM_Core_Error
::fatal('required params missing.');
95 //check for case activity access.
96 if (!CRM_Case_BAO_Case
::accessCiviCase()) {
97 CRM_Core_Error
::fatal(ts('You are not authorized to access this page.'));
100 if ($this->_caseId
&&
101 !CRM_Core_Permission
::check('access all cases and activities')
103 $params = array('type' => 'any');
104 $allCases = CRM_Case_BAO_Case
::getCases(TRUE, $params);
105 if (count(array_intersect($this->_caseId
, array_keys($allCases))) == 0) {
106 CRM_Core_Error
::fatal(ts('You are not authorized to access this page.'));
110 //validate case activity id.
111 if ($this->_activityId
&&
112 ($this->_action
& CRM_Core_Action
::UPDATE
)
114 $valid = CRM_Case_BAO_Case
::checkPermission($this->_activityId
, 'edit',
115 $this->_activityTypeId
118 CRM_Core_Error
::fatal(ts('You are not authorized to access this page.'));
122 foreach ($this->_caseId
as $casePos => $caseId) {
123 $this->_caseType
[$casePos] = CRM_Case_BAO_Case
::getCaseType($caseId, 'name');
125 $this->assign('caseType', $this->_caseType
);
127 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
128 $isMultiClient = $xmlProcessorProcess->getAllowMultipleCaseClients();
129 $this->assign('multiClient', $isMultiClient);
131 foreach ($this->_caseId
as $casePos => $caseId) {
132 $clients[] = CRM_Case_BAO_Case
::getContactNames($caseId);
134 $this->assign('client_names', $clients);
136 $caseIds = implode(',', $this->_caseId
);
137 // set context for pushUserContext and for statusBounce
138 if ($this->_context
== 'fulltext') {
139 if ($this->_action
== CRM_Core_Action
::UPDATE ||
$this->_action
== CRM_Core_Action
::DELETE
) {
140 $url = CRM_Utils_System
::url('civicrm/contact/view/case',
141 "reset=1&action=view&cid={$this->_currentlyViewedContactId}&id={$caseIds}&show=1&context={$this->_context}"
145 $url = CRM_Utils_System
::url('civicrm/contact/search/custom', 'force=1');
149 $url = CRM_Utils_System
::url('civicrm/contact/view/case',
150 "reset=1&action=view&cid={$this->_currentlyViewedContactId}&id={$caseIds}&show=1"
153 if (!$this->_activityId
) {
154 $caseTypes = CRM_Case_PseudoConstant
::caseType();
156 if (empty($caseTypes) && ($this->_activityTypeName
== 'Change Case Type') && !$this->_caseId
) {
157 $url = CRM_Utils_System
::url('civicrm/contact/view/case',
158 "reset=1&action=view&cid={$this->_currentlyViewedContactId}&id={$caseIds}&show=1"
160 $session = CRM_Core_Session
::singleton();
161 $session->pushUserContext($url);
162 CRM_Core_Error
::statusBounce(ts("You do not have any active Case Types"));
165 // check if activity count is within the limit
166 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
167 foreach ($this->_caseId
as $casePos => $caseId) {
168 $caseType = $this->_caseType
[$casePos];
169 $activityInst = $xmlProcessor->getMaxInstance($caseType);
171 // If not bounce back and also provide activity edit link
172 if (isset($activityInst[$this->_activityTypeName
])) {
173 $activityCount = CRM_Case_BAO_Case
::getCaseActivityCount($caseId, $this->_activityTypeId
);
174 if ($activityCount >= $activityInst[$this->_activityTypeName
]) {
175 if ($activityInst[$this->_activityTypeName
] == 1) {
176 $atArray = array('activity_type_id' => $this->_activityTypeId
);
177 $activities = CRM_Case_BAO_Case
::getCaseActivity($caseId,
179 $this->_currentUserId
181 $activityId = CRM_Utils_Array
::first(array_keys($activities['data']));
182 $editUrl = CRM_Utils_System
::url('civicrm/case/activity',
183 "reset=1&cid={$this->_currentlyViewedContactId}&caseid={$caseId}&action=update&id={$activityId}"
186 CRM_Core_Error
::statusBounce(ts("You can not add another '%1' activity to this case. %2",
188 1 => $this->_activityTypeName
,
189 2 => ts("Do you want to <a %1>edit the existing activity</a>?", array(1 => "href='$editUrl'")),
199 // Turn off the prompt which asks the user if they want to create separate
200 // activities when specifying multiple contacts "with" a new activity.
201 // Instead, always create one activity with all contacts together.
202 $this->supportsActivitySeparation
= FALSE;
204 $session = CRM_Core_Session
::singleton();
205 $session->pushUserContext($url);
209 * Set default values for the form.
211 public function setDefaultValues() {
212 $this->_defaults
= parent
::setDefaultValues();
213 $targetContactValues = array();
214 foreach ($this->_caseId
as $key => $val) {
216 $clients = CRM_Case_BAO_Case
::getContactNames($val);
217 if (isset($this->_activityId
) && empty($_POST)) {
218 if (!CRM_Utils_Array
::crmIsEmptyArray($this->_defaults
['target_contact'])) {
219 $targetContactValues = array_combine(array_unique($this->_defaults
['target_contact']),
220 explode(';', trim($this->_defaults
['target_contact_value']))
222 //exclude all clients.
223 foreach ($clients as $clientId => $vals) {
224 if (array_key_exists($clientId, $targetContactValues)) {
225 unset($targetContactValues[$clientId]);
230 $this->assign('targetContactValues', empty($targetContactValues) ?
FALSE : $targetContactValues);
232 if (isset($this->_encounterMedium
)) {
233 $this->_defaults
['medium_id'] = $this->_encounterMedium
;
235 elseif (empty($this->_defaults
['medium_id'])) {
236 // set default encounter medium CRM-4816
237 $medium = CRM_Core_OptionGroup
::values('encounter_medium', FALSE, FALSE, FALSE, 'AND is_default = 1');
238 if (count($medium) == 1) {
239 $this->_defaults
['medium_id'] = key($medium);
243 return $this->_defaults
;
247 public function buildQuickForm() {
248 $this->_fields
['source_contact_id']['label'] = ts('Reported By');
249 unset($this->_fields
['status_id']['attributes']['required']);
251 if ($this->_caseType
) {
252 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
254 foreach ($this->_caseType
as $key => $val) {
255 $activityTypes = $xmlProcessor->get($val, 'ActivityTypes', TRUE);
256 $aTypes = $aTypes +
$activityTypes;
259 // remove Open Case activity type since we're inside an existing case
260 $openCaseID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Open Case');
261 unset($aTypes[$openCaseID]);
263 $this->_fields
['followup_activity_type_id']['attributes'] = array('' => '- select activity type -') +
$aTypes;
266 parent
::buildQuickForm();
268 if ($this->_action
& (CRM_Core_Action
::DELETE | CRM_Core_Action
::DETACH | CRM_Core_Action
::RENEW
)) {
272 $this->assign('urlPath', 'civicrm/case/activity');
274 $encounterMediums = CRM_Case_PseudoConstant
::encounterMedium();
276 if ($this->_activityTypeFile
== 'OpenCase' && $this->_action
== CRM_Core_Action
::UPDATE
) {
277 $this->getElement('activity_date_time')->freeze();
279 if ($this->_activityId
) {
280 // 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.
281 // Is that really a big problem?
282 $this->_encounterMedium
= CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $this->_activityId
, 'medium_id');
283 if (!array_key_exists($this->_encounterMedium
, $encounterMediums)) {
284 $encounterMediums[$this->_encounterMedium
] = CRM_Core_PseudoConstant
::getLabel('CRM_Activity_BAO_Activity', 'medium_id', $this->_encounterMedium
);
289 $this->add('select', 'medium_id', ts('Medium'), $encounterMediums, TRUE);
291 foreach ($this->_caseId
as $key => $val) {
292 $this->_relatedContacts
[] = $rgc = CRM_Case_BAO_Case
::getRelatedAndGlobalContacts($val);
293 $contName = CRM_Case_BAO_Case
::getContactNames($val);
294 foreach ($contName as $nkey => $nval) {
295 array_push($this->_relatedContacts
[$i][0], $this->_relatedContacts
[$i][0]['managerOf'] = $nval['display_name']);
300 //add case client in send a copy selector.CRM-4438.
301 foreach ($this->_caseId
as $key => $val) {
302 $relatedContacts[] = $relCon = CRM_Case_BAO_Case
::getContactNames($val);
305 if (!empty($relatedContacts)) {
306 foreach ($relatedContacts as $relatedContact) {
307 $this->_relatedContacts
[] = $relatedContact;
311 if (!empty($this->_relatedContacts
)) {
312 $checkBoxes = array();
313 foreach ($this->_relatedContacts
as $id => $row) {
314 foreach ($row as $key => $value) {
315 $checkBoxes[$key] = $this->addElement('checkbox', $key, NULL, NULL, array('class' => 'select-row'));
319 $this->addGroup($checkBoxes, 'contact_check');
320 $this->addElement('checkbox', 'toggleSelect', NULL, NULL,
321 array('class' => 'select-rows')
323 $this->assign('searchRows', $this->_relatedContacts
);
325 $this->_relatedContacts
= $rgc +
$relCon;
327 $this->addFormRule(array('CRM_Case_Form_Activity', 'formRule'), $this);
333 * @param array $fields
334 * The input form values.
335 * @param array $files
336 * The uploaded files if any.
340 * true if no errors, else array of errors
342 public static function formRule($fields, $files, $self) {
343 // skip form rule if deleting
344 if (CRM_Utils_Array
::value('_qf_Activity_next_', $fields) == 'Delete' || CRM_Utils_Array
::value('_qf_Activity_next_', $fields) == 'Restore') {
348 return parent
::formRule($fields, $files, $self);
352 * Process the form submission.
354 * @param array $params
356 public function postProcess($params = NULL) {
357 $transaction = new CRM_Core_Transaction();
359 if ($this->_action
& CRM_Core_Action
::DELETE
) {
362 //block deleting activities which affects
363 //case attributes.CRM-4543
364 $activityCondition = " AND v.name IN ('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date')";
365 $caseAttributeActivities = CRM_Core_OptionGroup
::values('activity_type', FALSE, FALSE, FALSE, $activityCondition);
367 if (!array_key_exists($this->_activityTypeId
, $caseAttributeActivities)) {
368 $params = array('id' => $this->_activityId
);
369 $activityDelete = CRM_Activity_BAO_Activity
::deleteActivity($params, TRUE);
370 if ($activityDelete) {
371 $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 />');
375 $statusMsg = ts("Selected Activity cannot be deleted.");
379 'entity_table' => 'civicrm_activity',
380 'entity_id' => $this->_activityId
,
382 CRM_Core_BAO_EntityTag
::del($tagParams);
384 CRM_Core_Session
::setStatus('', $statusMsg, 'info');
388 if ($this->_action
& CRM_Core_Action
::RENEW
) {
390 $params = array('id' => $this->_activityId
);
391 $activityRestore = CRM_Activity_BAO_Activity
::restoreActivity($params);
392 if ($activityRestore) {
393 $statusMsg = ts('The selected activity has been restored.<br />');
395 CRM_Core_Session
::setStatus('', $statusMsg, 'info');
399 // store the submitted values in an array
400 $params = $this->controller
->exportValues($this->_name
);
402 //set parent id if its edit mode
403 if ($parentId = CRM_Utils_Array
::value('parent_id', $this->_defaults
)) {
404 $params['parent_id'] = $parentId;
407 $params['activity_type_id'] = $this->_activityTypeId
;
409 // format with contact (target contact) values
410 if (isset($params['target_contact_id'])) {
411 $params['target_contact_id'] = explode(',', $params['target_contact_id']);
414 $params['target_contact_id'] = array();
417 // format activity custom data
418 if (!empty($params['hidden_custom'])) {
419 if ($this->_activityId
) {
420 // retrieve and include the custom data of old Activity
421 $oldActivity = civicrm_api3('Activity', 'getsingle', array('id' => $this->_activityId
));
422 $params = array_merge($oldActivity, $params);
424 // unset custom fields-id from params since we want custom
425 // fields to be saved for new activity.
426 foreach ($params as $key => $value) {
428 if (preg_match('/^(custom_\d+_)(\d+)$/', $key, $match)) {
429 $params[$match[1] . '-1'] = $params[$key];
431 // for autocomplete transfer hidden value instead of label
432 if ($params[$key] && isset($params[$key . '_id'])) {
433 $params[$match[1] . '-1_id'] = $params[$key . '_id'];
434 unset($params[$key . '_id']);
436 unset($params[$key]);
441 // build custom data getFields array
442 $customFields = CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE, $this->_activityTypeId
);
443 $customFields = CRM_Utils_Array
::crmArrayMerge($customFields,
444 CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE,
448 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($params,
454 // assigning formatted value
455 if (!empty($params['assignee_contact_id'])) {
456 $params['assignee_contact_id'] = explode(',', $params['assignee_contact_id']);
459 $params['assignee_contact_id'] = array();
462 if (isset($this->_activityId
)) {
463 // activity which hasn't been modified by a user yet
464 if ($this->_defaults
['is_auto'] == 1) {
465 $params['is_auto'] = 0;
468 // always create a revision of an case activity. CRM-4533
469 $newActParams = $params;
471 // add target contact values in update mode
472 if (empty($params['target_contact_id']) && !empty($this->_defaults
['target_contact'])) {
473 $newActParams['target_contact_id'] = $this->_defaults
['target_contact'];
477 if (!isset($newActParams)) {
478 // add more attachments if needed for old activity
479 CRM_Core_BAO_File
::formatAttachment($params,
484 // call begin post process, before the activity is created/updated.
485 $this->beginPostProcess($params);
486 foreach ($this->_caseId
as $key => $val) {
487 $params['case_id'] = $val;
488 // activity create/update
489 $activity = CRM_Activity_BAO_Activity
::create($params);
490 $vvalue[] = array('case_id' => $val, 'actId' => $activity->id
);
491 // call end post process, after the activity has been created/updated.
492 $this->endPostProcess($params, $activity);
496 // since the params we need to set are very few, and we don't want rest of the
497 // work done by bao create method , lets use dao object to make the changes
498 $params = array('id' => $this->_activityId
);
499 $params['is_current_revision'] = 0;
500 $activity = new CRM_Activity_DAO_Activity();
501 $activity->copyValues($params);
505 // create a new version of activity if activity was found to
506 // have been modified/created by user
507 if (isset($newActParams)) {
508 // set proper original_id
509 if (!empty($this->_defaults
['original_id'])) {
510 $newActParams['original_id'] = $this->_defaults
['original_id'];
513 $newActParams['original_id'] = $activity->id
;
516 //is_current_revision will be set to 1 by default.
517 // add attachments if any
518 CRM_Core_BAO_File
::formatAttachment($newActParams,
523 // call begin post process, before the activity is created/updated.
524 $this->beginPostProcess($newActParams);
525 foreach ($this->_caseId
as $key => $val) {
526 $newActParams['case_id'] = $val;
527 $activity = CRM_Activity_BAO_Activity
::create($newActParams);
528 $vvalue[] = array('case_id' => $val, 'actId' => $activity->id
);
529 // call end post process, after the activity has been created/updated.
530 $this->endPostProcess($newActParams, $activity);
532 // copy files attached to old activity if any, to new one,
533 // as long as users have not selected the 'delete attachment' option.
534 if (empty($newActParams['is_delete_attachment']) && ($this->_activityId
!= $activity->id
)) {
535 CRM_Core_BAO_File
::copyEntityFile('civicrm_activity', $this->_activityId
,
536 'civicrm_activity', $activity->id
540 // copy back params to original var
541 $params = $newActParams;
544 foreach ($vvalue as $vkey => $vval) {
545 if ($vval['actId']) {
546 // add tags if exists
547 $tagParams = array();
548 if (!empty($params['tag'])) {
549 if (!is_array($params['tag'])) {
550 $params['tag'] = explode(',', $params['tag']);
553 $tagParams = array_fill_keys($params['tag'], 1);
557 CRM_Core_BAO_EntityTag
::create($tagParams, 'civicrm_activity', $vval['actId']);
560 if (isset($params['taglist']) && !empty($params['taglist'])) {
561 CRM_Core_Form_Tag
::postProcess($params['taglist'], $vval['actId'], 'civicrm_activity', $this);
565 // update existing case record if needed
566 $caseParams = $params;
567 $caseParams['id'] = $vval['case_id'];
568 if (!empty($caseParams['case_status_id'])) {
569 $caseParams['status_id'] = $caseParams['case_status_id'];
572 // unset params intended for activities only
573 unset($caseParams['subject'], $caseParams['details'],
574 $caseParams['status_id'], $caseParams['custom']
576 CRM_Case_BAO_Case
::create($caseParams);
577 // create case activity record
579 'activity_id' => $vval['actId'],
580 'case_id' => $vval['case_id'],
582 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
585 // send copy to selected contacts.
587 $mailToContacts = array();
590 //check for notification settings for assignee contacts
591 $selectedContacts = array('contact_check');
592 if (Civi
::settings()->get('activity_assignee_notification')) {
593 $selectedContacts[] = 'assignee_contact_id';
596 foreach ($vvalue as $vkey => $vval) {
597 foreach ($selectedContacts as $dnt => $val) {
598 if (array_key_exists($val, $params) && !CRM_Utils_Array
::crmIsEmptyArray($params[$val])) {
599 if ($val == 'contact_check') {
600 $mailStatus = ts("A copy of the activity has also been sent to selected contacts(s).");
603 $this->_relatedContacts
= CRM_Activity_BAO_ActivityAssignment
::getAssigneeNames(array($vval['actId']), TRUE, FALSE);
604 $mailStatus .= ' ' . ts("A copy of the activity has also been sent to assignee contacts(s).");
606 //build an associative array with unique email addresses.
607 foreach ($params[$val] as $key => $value) {
608 if ($val == 'contact_check') {
615 if (isset($id) && array_key_exists($id, $this->_relatedContacts
) && isset($this->_relatedContacts
[$id]['email'])) {
616 //if email already exists in array then append with ', ' another role only otherwise add it to array.
617 if ($contactDetails = CRM_Utils_Array
::value($this->_relatedContacts
[$id]['email'], $mailToContacts)) {
618 $caseRole = CRM_Utils_Array
::value('role', $this->_relatedContacts
[$id]);
619 $mailToContacts[$this->_relatedContacts
[$id]['email']]['role'] = $contactDetails['role'] . ', ' . $caseRole;
622 $mailToContacts[$this->_relatedContacts
[$id]['email']] = $this->_relatedContacts
[$id];
629 $extraParams = array('case_id' => $vval['case_id'], 'client_id' => $this->_currentlyViewedContactId
);
630 $result = CRM_Activity_BAO_Activity
::sendToAssignee($activity, $mailToContacts, $extraParams);
631 if (empty($result)) {
635 // create follow up activity if needed
636 $followupStatus = '';
637 if (!empty($params['followup_activity_type_id'])) {
638 $followupActivity = CRM_Activity_BAO_Activity
::createFollowupActivity($vval['actId'], $params);
640 if ($followupActivity) {
642 'activity_id' => $followupActivity->id
,
643 'case_id' => $vval['case_id'],
645 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
646 $followupStatus = ts("A followup activity has been scheduled.") . '<br /><br />';
649 $title = ts("%1 Saved", array(1 => $this->_activityTypeName
));
650 CRM_Core_Session
::setStatus($followupStatus . $mailStatus, $title, 'success');