3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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', 'String', $this);
67 if (!$this->_context
) {
68 $this->_context
= 'caseActivity';
70 $this->_crmDir
= 'Case';
71 $this->assign('context', $this->_context
);
73 $result = parent
::preProcess();
75 $scheduleStatusId = CRM_Core_OptionGroup
::getValue('activity_status', 'Scheduled', 'name');
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 $session = CRM_Core_Session
::singleton();
104 $allCases = CRM_Case_BAO_Case
::getCases(TRUE, $session->get('userID'), 'any');
105 if (!array_key_exists($this->_caseId
, $allCases)) {
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 $activities = array_keys($activities);
182 $activities = $activities[0];
183 $editUrl = CRM_Utils_System
::url('civicrm/case/activity',
184 "reset=1&cid={$this->_currentlyViewedContactId}&caseid={$caseId}&action=update&id={$activities}"
187 CRM_Core_Error
::statusBounce(ts("You can not add another '%1' activity to this case. %2",
189 1 => $this->_activityTypeName
,
190 2 => ts("Do you want to <a %1>edit the existing activity</a>?", array(1 => "href='$editUrl'")),
200 $session = CRM_Core_Session
::singleton();
201 $session->pushUserContext($url);
205 * Set default values for the form.
207 public function setDefaultValues() {
208 $this->_defaults
= parent
::setDefaultValues();
209 $targetContactValues = array();
210 foreach ($this->_caseId
as $key => $val) {
212 $clients = CRM_Case_BAO_Case
::getContactNames($val);
213 if (isset($this->_activityId
) && empty($_POST)) {
214 if (!CRM_Utils_Array
::crmIsEmptyArray($this->_defaults
['target_contact'])) {
215 $targetContactValues = array_combine(array_unique($this->_defaults
['target_contact']),
216 explode(';', trim($this->_defaults
['target_contact_value']))
218 //exclude all clients.
219 foreach ($clients as $clientId => $vals) {
220 if (array_key_exists($clientId, $targetContactValues)) {
221 unset($targetContactValues[$clientId]);
226 $this->assign('targetContactValues', empty($targetContactValues) ?
FALSE : $targetContactValues);
228 if (isset($this->_encounterMedium
)) {
229 $this->_defaults
['medium_id'] = $this->_encounterMedium
;
231 elseif (empty($this->_defaults
['medium_id'])) {
232 // set default encounter medium CRM-4816
233 $medium = CRM_Core_OptionGroup
::values('encounter_medium', FALSE, FALSE, FALSE, 'AND is_default = 1');
234 if (count($medium) == 1) {
235 $this->_defaults
['medium_id'] = key($medium);
239 return $this->_defaults
;
243 public function buildQuickForm() {
244 $this->_fields
['source_contact_id']['label'] = ts('Reported By');
245 unset($this->_fields
['status_id']['attributes']['required']);
247 if ($this->_caseType
) {
248 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
250 foreach ($this->_caseType
as $key => $val) {
251 $activityTypes = $xmlProcessor->get($val, 'ActivityTypes', TRUE);
252 $aTypes = $aTypes +
$activityTypes;
255 // remove Open Case activity type since we're inside an existing case
256 $openCaseID = CRM_Core_OptionGroup
::getValue('activity_type', 'Open Case', 'name');
257 unset($aTypes[$openCaseID]);
259 $this->_fields
['followup_activity_type_id']['attributes'] = array('' => '- select activity type -') +
$aTypes;
262 $result = parent
::buildQuickForm();
264 if ($this->_action
& (CRM_Core_Action
::DELETE | CRM_Core_Action
::DETACH | CRM_Core_Action
::RENEW
)) {
268 $this->assign('urlPath', 'civicrm/case/activity');
270 $encounterMediums = CRM_Case_PseudoConstant
::encounterMedium();
271 // 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.
272 // Is that really a big problem?
273 if ($this->_activityTypeFile
== 'OpenCase') {
274 $this->_encounterMedium
= CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $this->_activityId
,
277 if (!array_key_exists($this->_encounterMedium
, $encounterMediums)) {
278 $encounterMediums[$this->_encounterMedium
] = CRM_Core_OptionGroup
::getLabel('encounter_medium',
279 $this->_encounterMedium
,
285 $this->add('select', 'medium_id', ts('Medium'), $encounterMediums, TRUE);
287 foreach ($this->_caseId
as $key => $val) {
288 $this->_relatedContacts
[] = $rgc = CRM_Case_BAO_Case
::getRelatedAndGlobalContacts($val);
289 $contName = CRM_Case_BAO_Case
::getContactNames($val);
290 foreach ($contName as $nkey => $nval) {
291 array_push($this->_relatedContacts
[$i][0], $this->_relatedContacts
[$i][0]['managerOf'] = $nval['display_name']);
296 //add case client in send a copy selector.CRM-4438.
297 foreach ($this->_caseId
as $key => $val) {
298 $relatedContacts[] = $relCon = CRM_Case_BAO_Case
::getContactNames($val);
301 if (!empty($relatedContacts)) {
302 foreach ($relatedContacts as $relatedContact) {
303 $this->_relatedContacts
[] = $relatedContact;
307 if (!empty($this->_relatedContacts
)) {
308 $checkBoxes = array();
309 foreach ($this->_relatedContacts
as $id => $row) {
310 $checkBoxes[$id] = $this->addElement('checkbox', $id, NULL, NULL, array('class' => 'select-row'));
313 $this->addGroup($checkBoxes, 'contact_check');
314 $this->addElement('checkbox', 'toggleSelect', NULL, NULL,
315 array('class' => 'select-rows')
317 $this->assign('searchRows', $this->_relatedContacts
);
319 $this->_relatedContacts
= $rgc +
$relCon;
321 $this->addFormRule(array('CRM_Case_Form_Activity', 'formRule'), $this);
327 * @param array $fields
328 * The input form values.
329 * @param array $files
330 * The uploaded files if any.
334 * true if no errors, else array of errors
336 public static function formRule($fields, $files, $self) {
337 // skip form rule if deleting
338 if (CRM_Utils_Array
::value('_qf_Activity_next_', $fields) == 'Delete' || CRM_Utils_Array
::value('_qf_Activity_next_', $fields) == 'Restore') {
342 return parent
::formrule($fields, $files, $self);
346 * Process the form submission.
348 * @param array $params
350 public function postProcess($params = NULL) {
351 $transaction = new CRM_Core_Transaction();
353 if ($this->_action
& CRM_Core_Action
::DELETE
) {
356 //block deleting activities which affects
357 //case attributes.CRM-4543
358 $activityCondition = " AND v.name IN ('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date')";
359 $caseAttributeActivities = CRM_Core_OptionGroup
::values('activity_type', FALSE, FALSE, FALSE, $activityCondition);
361 if (!array_key_exists($this->_activityTypeId
, $caseAttributeActivities)) {
362 $params = array('id' => $this->_activityId
);
363 $activityDelete = CRM_Activity_BAO_Activity
::deleteActivity($params, TRUE);
364 if ($activityDelete) {
365 $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 />');
369 $statusMsg = ts("Selected Activity cannot be deleted.");
373 'entity_table' => 'civicrm_activity',
374 'entity_id' => $this->_activityId
,
376 CRM_Core_BAO_EntityTag
::del($tagParams);
378 CRM_Core_Session
::setStatus('', $statusMsg, 'info');
382 if ($this->_action
& CRM_Core_Action
::RENEW
) {
384 $params = array('id' => $this->_activityId
);
385 $activityRestore = CRM_Activity_BAO_Activity
::restoreActivity($params);
386 if ($activityRestore) {
387 $statusMsg = ts('The selected activity has been restored.<br />');
389 CRM_Core_Session
::setStatus('', $statusMsg, 'info');
393 // store the submitted values in an array
394 $params = $this->controller
->exportValues($this->_name
);
396 //set parent id if its edit mode
397 if ($parentId = CRM_Utils_Array
::value('parent_id', $this->_defaults
)) {
398 $params['parent_id'] = $parentId;
401 // store the dates with proper format
402 $params['activity_date_time'] = CRM_Utils_Date
::processDate($params['activity_date_time'], $params['activity_date_time_time']);
403 $params['activity_type_id'] = $this->_activityTypeId
;
405 // format with contact (target contact) values
406 if (isset($params['target_contact_id'])) {
407 $params['target_contact_id'] = explode(',', $params['target_contact_id']);
410 $params['target_contact_id'] = array();
413 // format activity custom data
414 if (!empty($params['hidden_custom'])) {
415 if ($this->_activityId
) {
416 // unset custom fields-id from params since we want custom
417 // fields to be saved for new activity.
418 foreach ($params as $key => $value) {
420 if (preg_match('/^(custom_\d+_)(\d+)$/', $key, $match)) {
421 $params[$match[1] . '-1'] = $params[$key];
423 // for autocomplete transfer hidden value instead of label
424 if ($params[$key] && isset($params[$key . '_id'])) {
425 $params[$match[1] . '-1_id'] = $params[$key . '_id'];
426 unset($params[$key . '_id']);
428 unset($params[$key]);
433 // build custom data getFields array
434 $customFields = CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE, $this->_activityTypeId
);
435 $customFields = CRM_Utils_Array
::crmArrayMerge($customFields,
436 CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE,
440 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($params,
446 // assigning formatted value
447 if (!empty($params['assignee_contact_id'])) {
448 $params['assignee_contact_id'] = explode(',', $params['assignee_contact_id']);
451 $params['assignee_contact_id'] = array();
454 if (isset($this->_activityId
)) {
455 // activity which hasn't been modified by a user yet
456 if ($this->_defaults
['is_auto'] == 1) {
457 $params['is_auto'] = 0;
460 // always create a revision of an case activity. CRM-4533
461 $newActParams = $params;
463 // add target contact values in update mode
464 if (empty($params['target_contact_id']) && !empty($this->_defaults
['target_contact'])) {
465 $newActParams['target_contact_id'] = $this->_defaults
['target_contact'];
469 if (!isset($newActParams)) {
470 // add more attachments if needed for old activity
471 CRM_Core_BAO_File
::formatAttachment($params,
476 // call begin post process, before the activity is created/updated.
477 $this->beginPostProcess($params);
478 foreach ($this->_caseId
as $key => $val) {
479 $params['case_id'] = $val;
480 // activity create/update
481 $activity = CRM_Activity_BAO_Activity
::create($params);
482 $vvalue[] = array('case_id' => $val, 'actId' => $activity->id
);
483 // call end post process, after the activity has been created/updated.
484 $this->endPostProcess($params, $activity);
488 // since the params we need to set are very few, and we don't want rest of the
489 // work done by bao create method , lets use dao object to make the changes
490 $params = array('id' => $this->_activityId
);
491 $params['is_current_revision'] = 0;
492 $activity = new CRM_Activity_DAO_Activity();
493 $activity->copyValues($params);
497 // create a new version of activity if activity was found to
498 // have been modified/created by user
499 if (isset($newActParams)) {
500 // set proper original_id
501 if (!empty($this->_defaults
['original_id'])) {
502 $newActParams['original_id'] = $this->_defaults
['original_id'];
505 $newActParams['original_id'] = $activity->id
;
507 //is_current_revision will be set to 1 by default.
509 // add attachments if any
510 CRM_Core_BAO_File
::formatAttachment($newActParams,
515 // call begin post process, before the activity is created/updated.
516 $this->beginPostProcess($newActParams);
517 foreach ($this->_caseId
as $key => $val) {
518 $newActParams['case_id'] = $val;
519 $activity = CRM_Activity_BAO_Activity
::create($newActParams);
520 $vvalue[] = array('case_id' => $val, 'actId' => $activity->id
);
521 // call end post process, after the activity has been created/updated.
522 $this->endPostProcess($newActParams, $activity);
524 // copy files attached to old activity if any, to new one,
525 // as long as users have not selected the 'delete attachment' option.
526 if (empty($newActParams['is_delete_attachment'])) {
527 CRM_Core_BAO_File
::copyEntityFile('civicrm_activity', $this->_activityId
,
528 'civicrm_activity', $activity->id
532 // copy back params to original var
533 $params = $newActParams;
536 foreach ($vvalue as $vkey => $vval) {
537 if ($vval['actId']) {
538 // add tags if exists
539 $tagParams = array();
540 if (!empty($params['tag'])) {
541 foreach ($params['tag'] as $tag) {
542 $tagParams[$tag] = 1;
547 CRM_Core_BAO_EntityTag
::create($tagParams, 'civicrm_activity', $vval['actId']);
550 if (isset($params['taglist']) && !empty($params['taglist'])) {
551 CRM_Core_Form_Tag
::postProcess($params['taglist'], $vval['actId'], 'civicrm_activity', $this);
555 // update existing case record if needed
556 $caseParams = $params;
557 $caseParams['id'] = $vval['case_id'];
558 if (!empty($caseParams['case_status_id'])) {
559 $caseParams['status_id'] = $caseParams['case_status_id'];
562 // unset params intended for activities only
563 unset($caseParams['subject'], $caseParams['details'],
564 $caseParams['status_id'], $caseParams['custom']
566 $case = CRM_Case_BAO_Case
::create($caseParams);
567 // create case activity record
569 'activity_id' => $vval['actId'],
570 'case_id' => $vval['case_id'],
572 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
575 // Insert civicrm_log record for the activity (e.g. store the
576 // created / edited by contact id and date for the activity)
577 // Note - civicrm_log is already created by CRM_Activity_BAO_Activity::create()
579 // send copy to selected contacts.
581 $mailToContacts = array();
584 //check for notification settings for assignee contacts
585 $selectedContacts = array('contact_check');
586 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
587 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
588 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
589 'activity_assignee_notification'
592 $selectedContacts[] = 'assignee_contact_id';
595 foreach ($vvalue as $vkey => $vval) {
596 foreach ($selectedContacts as $dnt => $val) {
597 if (array_key_exists($val, $params) && !CRM_Utils_array
::crmIsEmptyArray($params[$val])) {
598 if ($val == 'contact_check') {
599 $mailStatus = ts("A copy of the activity has also been sent to selected contacts(s).");
602 $this->_relatedContacts
= CRM_Activity_BAO_ActivityAssignment
::getAssigneeNames(array($vval['actId']), TRUE, FALSE);
603 $mailStatus .= ' ' . ts("A copy of the activity has also been sent to assignee contacts(s).");
605 //build an associative array with unique email addresses.
606 foreach ($params[$val] as $key => $value) {
607 if ($val == 'contact_check') {
614 if (isset($id) && array_key_exists($id, $this->_relatedContacts
) && isset($this->_relatedContacts
[$id]['email'])) {
615 //if email already exists in array then append with ', ' another role only otherwise add it to array.
616 if ($contactDetails = CRM_Utils_Array
::value($this->_relatedContacts
[$id]['email'], $mailToContacts)) {
617 $caseRole = CRM_Utils_Array
::value('role', $this->_relatedContacts
[$id]);
618 $mailToContacts[$this->_relatedContacts
[$id]['email']]['role'] = $contactDetails['role'] . ', ' . $caseRole;
621 $mailToContacts[$this->_relatedContacts
[$id]['email']] = $this->_relatedContacts
[$id];
628 $extraParams = array('case_id' => $vval['case_id'], 'client_id' => $this->_currentlyViewedContactId
);
629 $result = CRM_Activity_BAO_Activity
::sendToAssignee($activity, $mailToContacts, $extraParams);
630 if (empty($result)) {
634 // create follow up activity if needed
635 $followupStatus = '';
636 if (!empty($params['followup_activity_type_id'])) {
637 $followupActivity = CRM_Activity_BAO_Activity
::createFollowupActivity($vval['actId'], $params);
639 if ($followupActivity) {
641 'activity_id' => $followupActivity->id
,
642 'case_id' => $vval['case_id'],
644 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
645 $followupStatus = ts("A followup activity has been scheduled.") . '<br /><br />';
648 $title = ts("%1 Saved", array(1 => $this->_activityTypeName
));
649 CRM_Core_Session
::setStatus($followupStatus . $mailStatus, $title, 'success');