3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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
37 * This class create activities for a case
40 class CRM_Case_Form_Activity
extends CRM_Activity_Form_Activity
{
43 * The default variable defined.
50 * The default case type variable defined.
57 * The default values of an activity.
61 public $_defaults = array();
64 * The array of releted contact info.
68 public $_relatedContacts;
71 * Build the form object.
75 public function preProcess() {
76 $caseIds = CRM_Utils_Request
::retrieve('caseid', 'String', $this);
77 $this->_caseId
= explode(',', $caseIds);
78 $this->_context
= CRM_Utils_Request
::retrieve('context', 'String', $this);
79 if (!$this->_context
) {
80 $this->_context
= 'caseActivity';
82 $this->_crmDir
= 'Case';
83 $this->assign('context', $this->_context
);
85 $result = parent
::preProcess();
87 $scheduleStatusId = CRM_Core_OptionGroup
::getValue('activity_status', 'Scheduled', 'name');
88 $this->assign('scheduleStatusId', $scheduleStatusId);
94 if (!$this->_caseId
&& $this->_activityId
) {
95 $this->_caseId
= CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_CaseActivity', $this->_activityId
,
96 'case_id', 'activity_id'
100 $this->assign('caseId', $this->_caseId
);
101 $this->assign('countId', count($this->_caseId
));
102 $this->assign('caseID', CRM_Utils_Array
::first($this->_caseId
));
105 if (!$this->_caseId ||
106 (!$this->_activityId
&& !$this->_activityTypeId
)
108 CRM_Core_Error
::fatal('required params missing.');
111 //check for case activity access.
112 if (!CRM_Case_BAO_Case
::accessCiviCase()) {
113 CRM_Core_Error
::fatal(ts('You are not authorized to access this page.'));
116 if ($this->_caseId
&&
117 !CRM_Core_Permission
::check('access all cases and activities')
119 $session = CRM_Core_Session
::singleton();
120 $allCases = CRM_Case_BAO_Case
::getCases(TRUE, $session->get('userID'), 'any');
121 if (!array_key_exists($this->_caseId
, $allCases)) {
122 CRM_Core_Error
::fatal(ts('You are not authorized to access this page.'));
126 //validate case activity id.
127 if ($this->_activityId
&&
128 ($this->_action
& CRM_Core_Action
::UPDATE
)
130 $valid = CRM_Case_BAO_Case
::checkPermission($this->_activityId
, 'edit',
131 $this->_activityTypeId
134 CRM_Core_Error
::fatal(ts('You are not authorized to access this page.'));
138 foreach ($this->_caseId
as $casePos => $caseId) {
139 $this->_caseType
[$casePos] = CRM_Case_BAO_Case
::getCaseType($caseId, 'name');
141 $this->assign('caseType', $this->_caseType
);
143 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
144 $isMultiClient = $xmlProcessorProcess->getAllowMultipleCaseClients();
145 $this->assign('multiClient', $isMultiClient);
147 foreach ($this->_caseId
as $casePos => $caseId) {
148 $clients[] = CRM_Case_BAO_Case
::getContactNames($caseId);
150 $this->assign('client_names', $clients);
152 $caseIds = implode(',', $this->_caseId
);
153 // set context for pushUserContext and for statusBounce
154 if ($this->_context
== 'fulltext') {
155 if ($this->_action
== CRM_Core_Action
::UPDATE ||
$this->_action
== CRM_Core_Action
::DELETE
) {
156 $url = CRM_Utils_System
::url('civicrm/contact/view/case',
157 "reset=1&action=view&cid={$this->_currentlyViewedContactId}&id={$caseIds}&show=1&context={$this->_context}"
161 $url = CRM_Utils_System
::url('civicrm/contact/search/custom', 'force=1');
165 $url = CRM_Utils_System
::url('civicrm/contact/view/case',
166 "reset=1&action=view&cid={$this->_currentlyViewedContactId}&id={$caseIds}&show=1"
169 if (!$this->_activityId
) {
170 $caseTypes = CRM_Case_PseudoConstant
::caseType();
172 if (empty($caseTypes) && ($this->_activityTypeName
== 'Change Case Type') && !$this->_caseId
) {
173 $url = CRM_Utils_System
::url('civicrm/contact/view/case',
174 "reset=1&action=view&cid={$this->_currentlyViewedContactId}&id={$caseIds}&show=1"
176 $session = CRM_Core_Session
::singleton();
177 $session->pushUserContext($url);
178 CRM_Core_Error
::statusBounce(ts("You do not have any active Case Types"));
181 // check if activity count is within the limit
182 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
183 foreach ($this->_caseId
as $casePos => $caseId) {
184 $caseType = $this->_caseType
[$casePos];
185 $activityInst = $xmlProcessor->getMaxInstance($caseType);
187 // If not bounce back and also provide activity edit link
188 if (isset($activityInst[$this->_activityTypeName
])) {
189 $activityCount = CRM_Case_BAO_Case
::getCaseActivityCount($caseId, $this->_activityTypeId
);
190 if ($activityCount >= $activityInst[$this->_activityTypeName
]) {
191 if ($activityInst[$this->_activityTypeName
] == 1) {
192 $atArray = array('activity_type_id' => $this->_activityTypeId
);
193 $activities = CRM_Case_BAO_Case
::getCaseActivity($caseId,
195 $this->_currentUserId
197 $activities = array_keys($activities);
198 $activities = $activities[0];
199 $editUrl = CRM_Utils_System
::url('civicrm/case/activity',
200 "reset=1&cid={$this->_currentlyViewedContactId}&caseid={$caseId}&action=update&id={$activities}"
203 CRM_Core_Error
::statusBounce(ts("You can not add another '%1' activity to this case. %2",
205 1 => $this->_activityTypeName
,
206 2 => ts("Do you want to <a %1>edit the existing activity</a>?", array(1 => "href='$editUrl'")),
216 $session = CRM_Core_Session
::singleton();
217 $session->pushUserContext($url);
221 * Set default values for the form. For edit/view mode
222 * the default values are retrieved from the database
227 public function setDefaultValues() {
228 $this->_defaults
= parent
::setDefaultValues();
229 $targetContactValues = array();
230 foreach ($this->_caseId
as $key => $val) {
232 $clients = CRM_Case_BAO_Case
::getContactNames($val);
233 if (isset($this->_activityId
) && empty($_POST)) {
234 if (!CRM_Utils_Array
::crmIsEmptyArray($this->_defaults
['target_contact'])) {
235 $targetContactValues = array_combine(array_unique($this->_defaults
['target_contact']),
236 explode(';', trim($this->_defaults
['target_contact_value']))
238 //exclude all clients.
239 foreach ($clients as $clientId => $vals) {
240 if (array_key_exists($clientId, $targetContactValues)) {
241 unset($targetContactValues[$clientId]);
246 $this->assign('targetContactValues', empty($targetContactValues) ?
FALSE : $targetContactValues);
248 //return form for ajax
249 if ($this->_cdType
) {
250 return $this->_defaults
;
253 if (isset($this->_encounterMedium
)) {
254 $this->_defaults
['medium_id'] = $this->_encounterMedium
;
256 elseif (empty($this->_defaults
['medium_id'])) {
257 // set default encounter medium CRM-4816
258 $medium = CRM_Core_OptionGroup
::values('encounter_medium', FALSE, FALSE, FALSE, 'AND is_default = 1');
259 if (count($medium) == 1) {
260 $this->_defaults
['medium_id'] = key($medium);
264 return $this->_defaults
;
268 public function buildQuickForm() {
269 $this->_fields
['source_contact_id']['label'] = ts('Reported By');
270 unset($this->_fields
['status_id']['attributes']['required']);
272 if ($this->_caseType
) {
273 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
275 foreach ($this->_caseType
as $key => $val) {
276 $activityTypes = $xmlProcessor->get($val, 'ActivityTypes', TRUE);
277 $aTypes = $aTypes +
$activityTypes;
280 // remove Open Case activity type since we're inside an existing case
281 $openCaseID = CRM_Core_OptionGroup
::getValue('activity_type', 'Open Case', 'name');
282 unset($aTypes[$openCaseID]);
284 $this->_fields
['followup_activity_type_id']['attributes'] = array('' => '- select activity type -') +
$aTypes;
287 $result = parent
::buildQuickForm();
289 if ($this->_action
& (CRM_Core_Action
::DELETE | CRM_Core_Action
::DETACH | CRM_Core_Action
::RENEW
)) {
293 if ($this->_cdType
) {
297 $this->assign('urlPath', 'civicrm/case/activity');
299 $encounterMediums = CRM_Case_PseudoConstant
::encounterMedium();
300 // 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.
301 // Is that really a big problem?
302 if ($this->_activityTypeFile
== 'OpenCase') {
303 $this->_encounterMedium
= CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $this->_activityId
,
306 if (!array_key_exists($this->_encounterMedium
, $encounterMediums)) {
307 $encounterMediums[$this->_encounterMedium
] = CRM_Core_OptionGroup
::getLabel('encounter_medium',
308 $this->_encounterMedium
,
314 $this->add('select', 'medium_id', ts('Medium'), $encounterMediums, TRUE);
316 foreach ($this->_caseId
as $key => $val) {
317 $this->_relatedContacts
[] = $rgc = CRM_Case_BAO_Case
::getRelatedAndGlobalContacts($val);
318 $contName = CRM_Case_BAO_Case
::getContactNames($val);
319 foreach ($contName as $nkey => $nval) {
320 array_push($this->_relatedContacts
[$i][0], $this->_relatedContacts
[$i][0]['managerOf'] = $nval['display_name']);
325 //add case client in send a copy selector.CRM-4438.
326 foreach ($this->_caseId
as $key => $val) {
327 $relatedContacts[] = $relCon = CRM_Case_BAO_Case
::getContactNames($val);
330 if (!empty($relatedContacts)) {
331 foreach ($relatedContacts as $relatedContact) {
332 $this->_relatedContacts
[] = $relatedContact;
336 if (!empty($this->_relatedContacts
)) {
337 $checkBoxes = array();
338 foreach ($this->_relatedContacts
as $id => $row) {
339 $checkBoxes[$id] = $this->addElement('checkbox', $id, NULL, NULL, array('class' => 'select-row'));
342 $this->addGroup($checkBoxes, 'contact_check');
343 $this->addElement('checkbox', 'toggleSelect', NULL, NULL,
344 array('class' => 'select-rows')
346 $this->assign('searchRows', $this->_relatedContacts
);
348 $this->_relatedContacts
= $rgc +
$relCon;
350 $this->addFormRule(array('CRM_Case_Form_Activity', 'formRule'), $this);
356 * @param array $fields
357 * The input form values.
358 * @param array $files
359 * The uploaded files if any.
363 * true if no errors, else array of errors
365 public static function formRule($fields, $files, $self) {
366 // skip form rule if deleting
367 if (CRM_Utils_Array
::value('_qf_Activity_next_', $fields) == 'Delete' || CRM_Utils_Array
::value('_qf_Activity_next_', $fields) == 'Restore') {
371 return parent
::formrule($fields, $files, $self);
375 * Process the form submission.
378 * @param array $params
382 public function postProcess($params = NULL) {
383 $transaction = new CRM_Core_Transaction();
385 if ($this->_action
& CRM_Core_Action
::DELETE
) {
388 //block deleting activities which affects
389 //case attributes.CRM-4543
390 $activityCondition = " AND v.name IN ('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date')";
391 $caseAttributeActivities = CRM_Core_OptionGroup
::values('activity_type', FALSE, FALSE, FALSE, $activityCondition);
393 if (!array_key_exists($this->_activityTypeId
, $caseAttributeActivities)) {
394 $params = array('id' => $this->_activityId
);
395 $activityDelete = CRM_Activity_BAO_Activity
::deleteActivity($params, TRUE);
396 if ($activityDelete) {
397 $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 />');
401 $statusMsg = ts("Selected Activity cannot be deleted.");
405 'entity_table' => 'civicrm_activity',
406 'entity_id' => $this->_activityId
,
408 CRM_Core_BAO_EntityTag
::del($tagParams);
410 CRM_Core_Session
::setStatus('', $statusMsg, 'info');
414 if ($this->_action
& CRM_Core_Action
::RENEW
) {
416 $params = array('id' => $this->_activityId
);
417 $activityRestore = CRM_Activity_BAO_Activity
::restoreActivity($params);
418 if ($activityRestore) {
419 $statusMsg = ts('The selected activity has been restored.<br />');
421 CRM_Core_Session
::setStatus('', $statusMsg, 'info');
425 // store the submitted values in an array
426 $params = $this->controller
->exportValues($this->_name
);
428 //set parent id if its edit mode
429 if ($parentId = CRM_Utils_Array
::value('parent_id', $this->_defaults
)) {
430 $params['parent_id'] = $parentId;
433 // required for status msg
434 $recordStatus = ts("The '%1' activity has been created.", array(1 => $this->_activityTypeName
));
436 // store the dates with proper format
437 $params['activity_date_time'] = CRM_Utils_Date
::processDate($params['activity_date_time'], $params['activity_date_time_time']);
438 $params['activity_type_id'] = $this->_activityTypeId
;
440 // format with contact (target contact) values
441 if (isset($params['target_contact_id'])) {
442 $params['target_contact_id'] = explode(',', $params['target_contact_id']);
445 $params['target_contact_id'] = array();
448 // format activity custom data
449 if (!empty($params['hidden_custom'])) {
450 if ($this->_activityId
) {
451 // unset custom fields-id from params since we want custom
452 // fields to be saved for new activity.
453 foreach ($params as $key => $value) {
455 if (preg_match('/^(custom_\d+_)(\d+)$/', $key, $match)) {
456 $params[$match[1] . '-1'] = $params[$key];
458 // for autocomplete transfer hidden value instead of label
459 if ($params[$key] && isset($params[$key . '_id'])) {
460 $params[$match[1] . '-1_id'] = $params[$key . '_id'];
461 unset($params[$key . '_id']);
463 unset($params[$key]);
468 // build custom data getFields array
469 $customFields = CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE, $this->_activityTypeId
);
470 $customFields = CRM_Utils_Array
::crmArrayMerge($customFields,
471 CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE,
475 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($params,
482 // assigning formatted value
483 if (!empty($params['assignee_contact_id'])) {
484 $params['assignee_contact_id'] = explode(',', $params['assignee_contact_id']);
487 $params['assignee_contact_id'] = array();
490 if (isset($this->_activityId
)) {
491 // activity which hasn't been modified by a user yet
492 if ($this->_defaults
['is_auto'] == 1) {
493 $params['is_auto'] = 0;
496 // always create a revision of an case activity. CRM-4533
497 $newActParams = $params;
499 // add target contact values in update mode
500 if (empty($params['target_contact_id']) && !empty($this->_defaults
['target_contact'])) {
501 $newActParams['target_contact_id'] = $this->_defaults
['target_contact'];
504 // record status for status msg
505 $recordStatus = ts("The '%1' activity has been updated.", array(1 => $this->_activityTypeName
));
508 if (!isset($newActParams)) {
509 // add more attachments if needed for old activity
510 CRM_Core_BAO_File
::formatAttachment($params,
515 // call begin post process, before the activity is created/updated.
516 $this->beginPostProcess($params);
517 foreach ($this->_caseId
as $key => $val) {
518 $params['case_id'] = $val;
519 // activity create/update
520 $activity = CRM_Activity_BAO_Activity
::create($params);
521 $vvalue[] = array('case_id' => $val, 'actId' => $activity->id
);
522 // call end post process, after the activity has been created/updated.
523 $this->endPostProcess($params, $activity);
527 // since the params we need to set are very few, and we don't want rest of the
528 // work done by bao create method , lets use dao object to make the changes
529 $params = array('id' => $this->_activityId
);
530 $params['is_current_revision'] = 0;
531 $activity = new CRM_Activity_DAO_Activity();
532 $activity->copyValues($params);
536 // create a new version of activity if activity was found to
537 // have been modified/created by user
538 if (isset($newActParams)) {
539 // set proper original_id
540 if (!empty($this->_defaults
['original_id'])) {
541 $newActParams['original_id'] = $this->_defaults
['original_id'];
544 $newActParams['original_id'] = $activity->id
;
546 //is_current_revision will be set to 1 by default.
548 // add attachments if any
549 CRM_Core_BAO_File
::formatAttachment($newActParams,
554 // call begin post process, before the activity is created/updated.
555 $this->beginPostProcess($newActParams);
556 foreach ($this->_caseId
as $key => $val) {
557 $newActParams['case_id'] = $val;
558 $activity = CRM_Activity_BAO_Activity
::create($newActParams);
559 $vvalue[] = array('case_id' => $val, 'actId' => $activity->id
);
560 // call end post process, after the activity has been created/updated.
561 $this->endPostProcess($newActParams, $activity);
563 // copy files attached to old activity if any, to new one,
564 // as long as users have not selected the 'delete attachment' option.
565 if (empty($newActParams['is_delete_attachment'])) {
566 CRM_Core_BAO_File
::copyEntityFile('civicrm_activity', $this->_activityId
,
567 'civicrm_activity', $activity->id
571 // copy back params to original var
572 $params = $newActParams;
575 foreach ($vvalue as $vkey => $vval) {
576 if ($vval['actId']) {
577 // add tags if exists
578 $tagParams = array();
579 if (!empty($params['tag'])) {
580 foreach ($params['tag'] as $tag) {
581 $tagParams[$tag] = 1;
586 CRM_Core_BAO_EntityTag
::create($tagParams, 'civicrm_activity', $vval['actId']);
589 if (isset($params['taglist']) && !empty($params['taglist'])) {
590 CRM_Core_Form_Tag
::postProcess($params['taglist'], $vval['actId'], 'civicrm_activity', $this);
594 // update existing case record if needed
595 $caseParams = $params;
596 $caseParams['id'] = $vval['case_id'];
597 if (!empty($caseParams['case_status_id'])) {
598 $caseParams['status_id'] = $caseParams['case_status_id'];
601 // unset params intended for activities only
602 unset($caseParams['subject'], $caseParams['details'],
603 $caseParams['status_id'], $caseParams['custom']
605 $case = CRM_Case_BAO_Case
::create($caseParams);
606 // create case activity record
608 'activity_id' => $vval['actId'],
609 'case_id' => $vval['case_id'],
611 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
614 // Insert civicrm_log record for the activity (e.g. store the
615 // created / edited by contact id and date for the activity)
616 // Note - civicrm_log is already created by CRM_Activity_BAO_Activity::create()
618 // send copy to selected contacts.
620 $mailToContacts = array();
623 //check for notification settings for assignee contacts
624 $selectedContacts = array('contact_check');
625 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
626 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
627 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
628 'activity_assignee_notification'
631 $selectedContacts[] = 'assignee_contact_id';
634 foreach ($vvalue as $vkey => $vval) {
635 foreach ($selectedContacts as $dnt => $val) {
636 if (array_key_exists($val, $params) && !CRM_Utils_array
::crmIsEmptyArray($params[$val])) {
637 if ($val == 'contact_check') {
638 $mailStatus = ts("A copy of the activity has also been sent to selected contacts(s).");
641 $this->_relatedContacts
= CRM_Activity_BAO_ActivityAssignment
::getAssigneeNames(array($vval['actId']), TRUE, FALSE);
642 $mailStatus .= ' ' . ts("A copy of the activity has also been sent to assignee contacts(s).");
644 //build an associative array with unique email addresses.
645 foreach ($params[$val] as $key => $value) {
646 if ($val == 'contact_check') {
653 if (isset($id) && array_key_exists($id, $this->_relatedContacts
) && isset($this->_relatedContacts
[$id]['email'])) {
654 //if email already exists in array then append with ', ' another role only otherwise add it to array.
655 if ($contactDetails = CRM_Utils_Array
::value($this->_relatedContacts
[$id]['email'], $mailToContacts)) {
656 $caseRole = CRM_Utils_Array
::value('role', $this->_relatedContacts
[$id]);
657 $mailToContacts[$this->_relatedContacts
[$id]['email']]['role'] = $contactDetails['role'] . ', ' . $caseRole;
660 $mailToContacts[$this->_relatedContacts
[$id]['email']] = $this->_relatedContacts
[$id];
667 if (!CRM_Utils_array
::crmIsEmptyArray($mailToContacts)) {
668 //include attachments while sending a copy of activity.
669 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_activity',
673 $ics = new CRM_Activity_BAO_ICalendar($activity);
674 $ics->addAttachment($attachments, $mailToContacts);
675 $result = CRM_Case_BAO_Case
::sendActivityCopy($this->_currentlyViewedContactId
,
676 $vval['actId'], $mailToContacts, $attachments, $vval['case_id']
679 if (empty($result)) {
687 // create follow up activity if needed
688 $followupStatus = '';
689 if (!empty($params['followup_activity_type_id'])) {
690 $followupActivity = CRM_Activity_BAO_Activity
::createFollowupActivity($vval['actId'], $params);
692 if ($followupActivity) {
694 'activity_id' => $followupActivity->id
,
695 'case_id' => $vval['case_id'],
697 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
698 $followupStatus = ts("A followup activity has been scheduled.");
702 CRM_Core_Session
::setStatus('', $recordStatus . ' ' . $followupStatus . ' ' . $mailStatus, 'info');