3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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 * Function to build the form
76 function preProcess() {
77 $caseIds = CRM_Utils_Request
::retrieve('caseid', 'String', $this);
78 $this->_caseId
= explode(',', $caseIds);
79 $this->_context
= CRM_Utils_Request
::retrieve('context', 'String', $this);
80 if (!$this->_context
) {
81 $this->_context
= 'caseActivity';
83 $this->_crmDir
= 'Case';
84 $this->assign('context', $this->_context
);
86 $result = parent
::preProcess();
88 $scheduleStatusId = CRM_Core_OptionGroup
::getValue('activity_status', 'Scheduled', 'name');
89 $this->assign('scheduleStatusId', $scheduleStatusId);
95 if (!$this->_caseId
&& $this->_activityId
) {
96 $this->_caseId
= CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_CaseActivity', $this->_activityId
,
97 'case_id', 'activity_id'
100 if ($this->_caseId
) {
101 $this->assign('caseId', $this->_caseId
);
102 $this->assign('countId', count($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 $key => $val) {
139 $this->_caseType
[] = CRM_Case_BAO_Case
::getCaseType($val, '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 $key => $val) {
148 $clients[] = CRM_Case_BAO_Case
::getContactNames($val);
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->_caseType
as $key => $val) {
184 $activityInst = $xmlProcessor->getMaxInstance($val);
186 // If not bounce back and also provide activity edit link
187 if (isset($activityInst[$this->_activityTypeName
])) {
188 $activityCount = CRM_Case_BAO_Case
::getCaseActivityCount($val, $this->_activityTypeId
);
189 if ($activityCount >= $activityInst[$this->_activityTypeName
]) {
190 if ($activityInst[$this->_activityTypeName
] == 1) {
191 $atArray = array('activity_type_id' => $this->_activityTypeId
);
192 $activities = CRM_Case_BAO_Case
::getCaseActivity($val,
194 $this->_currentUserId
196 $activities = array_keys($activities);
197 $activities = $activities[0];
198 $editUrl = CRM_Utils_System
::url('civicrm/case/activity',
199 "reset=1&cid={$this->_currentlyViewedContactId}&caseid={$val}&action=update&id={$activities}"
202 CRM_Core_Error
::statusBounce(ts("You can not add another '%1' activity to this case. %2",
204 1 => $this->_activityTypeName
,
205 2 => "Do you want to <a href='$editUrl'>edit the existing activity</a> ?"
215 $session = CRM_Core_Session
::singleton();
216 $session->pushUserContext($url);
220 * This function sets the default values for the form. For edit/view mode
221 * the default values are retrieved from the database
227 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(
285 '' => '- select activity type -'
289 $result = parent
::buildQuickForm();
291 if ($this->_action
& (CRM_Core_Action
::DELETE | CRM_Core_Action
::DETACH | CRM_Core_Action
::RENEW
)) {
295 if ($this->_cdType
) {
299 $this->assign('urlPath', 'civicrm/case/activity');
301 $encounterMediums = CRM_Case_PseudoConstant
::encounterMedium();
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 if ($this->_activityTypeFile
== 'OpenCase') {
305 $this->_encounterMedium
= CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $this->_activityId
,
308 if (!array_key_exists($this->_encounterMedium
, $encounterMediums)) {
309 $encounterMediums[$this->_encounterMedium
] = CRM_Core_OptionGroup
::getLabel('encounter_medium',
310 $this->_encounterMedium
,
316 $this->add('select', 'medium_id', ts('Medium'), $encounterMediums, TRUE);
318 foreach ($this->_caseId
as $key => $val) {
319 $this->_relatedContacts
[] = CRM_Case_BAO_Case
::getRelatedAndGlobalContacts($val);
320 $contName = CRM_Case_BAO_Case
::getContactNames($val);
321 foreach ($contName as $nkey => $nval) {
322 array_push($this->_relatedContacts
[$i][0] , $this->_relatedContacts
[$i][0]['managerOf']= $nval['display_name']);
327 //add case client in send a copy selector.CRM-4438.
328 foreach ($this->_caseId
as $key => $val) {
329 $relatedContacts[] = CRM_Case_BAO_Case
::getContactNames($val);
332 if (!empty($relatedContacts)) {
333 foreach ($relatedContacts as $relatedContact) {
334 $this->_relatedContacts
[] = $relatedContact;
338 if (!empty($this->_relatedContacts
)) {
339 $checkBoxes = array();
340 foreach ($this->_relatedContacts
as $id => $row) {
341 $checkBoxes[$id] = $this->addElement('checkbox', $id, NULL, NULL, array('class' => 'select-row'));
344 $this->addGroup($checkBoxes, 'contact_check');
345 $this->addElement('checkbox', 'toggleSelect', NULL, NULL,
346 array('class' => 'select-rows')
348 $this->assign('searchRows', $this->_relatedContacts
);
351 $this->addFormRule(array('CRM_Case_Form_Activity', 'formRule'), $this);
357 * @param array $fields the input form values
358 * @param array $files the uploaded files if any
361 * @internal param array $options additional user data
363 * @return true if no errors, else array of errors
367 static function formRule($fields, $files, $self) {
368 // skip form rule if deleting
369 if (CRM_Utils_Array
::value('_qf_Activity_next_', $fields) == 'Delete' || CRM_Utils_Array
::value('_qf_Activity_next_', $fields) == 'Restore') {
373 return parent
::formrule($fields, $files, $self);
377 * Function to process the form
381 * @param null $params
385 public function postProcess($params = NULL) {
386 $transaction = new CRM_Core_Transaction();
388 if ($this->_action
& CRM_Core_Action
::DELETE
) {
391 //block deleting activities which affects
392 //case attributes.CRM-4543
393 $activityCondition = " AND v.name IN ('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date')";
394 $caseAttributeActivities = CRM_Core_OptionGroup
::values('activity_type', FALSE, FALSE, FALSE, $activityCondition);
396 if (!array_key_exists($this->_activityTypeId
, $caseAttributeActivities)) {
397 $params = array('id' => $this->_activityId
);
398 $activityDelete = CRM_Activity_BAO_Activity
::deleteActivity($params, TRUE);
399 if ($activityDelete) {
400 $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 />');
404 $statusMsg = ts("Selected Activity cannot be deleted.");
408 'entity_table' => 'civicrm_activity',
409 'entity_id' => $this->_activityId
411 CRM_Core_BAO_EntityTag
::del($tagParams);
413 CRM_Core_Session
::setStatus('', $statusMsg, 'info');
417 if ($this->_action
& CRM_Core_Action
::RENEW
) {
419 $params = array('id' => $this->_activityId
);
420 $activityRestore = CRM_Activity_BAO_Activity
::restoreActivity($params);
421 if ($activityRestore) {
422 $statusMsg = ts('The selected activity has been restored.<br />');
424 CRM_Core_Session
::setStatus('', $statusMsg, 'info');
428 // store the submitted values in an array
429 $params = $this->controller
->exportValues($this->_name
);
431 //set parent id if its edit mode
432 if ($parentId = CRM_Utils_Array
::value('parent_id', $this->_defaults
)) {
433 $params['parent_id'] = $parentId;
436 // required for status msg
437 $recordStatus = 'created';
439 // store the dates with proper format
440 $params['activity_date_time'] = CRM_Utils_Date
::processDate($params['activity_date_time'], $params['activity_date_time_time']);
441 $params['activity_type_id'] = $this->_activityTypeId
;
443 // format with contact (target contact) values
444 if (isset($params['contact'][1])) {
445 $params['target_contact_id'] = explode(',', $params['contact'][1]);
448 $params['target_contact_id'] = array();
451 // format activity custom data
452 if (!empty($params['hidden_custom'])) {
453 if ($this->_activityId
) {
454 // unset custom fields-id from params since we want custom
455 // fields to be saved for new activity.
456 foreach ($params as $key => $value) {
458 if (preg_match('/^(custom_\d+_)(\d+)$/', $key, $match)) {
459 $params[$match[1] . '-1'] = $params[$key];
461 // for autocomplete transfer hidden value instead of label
462 if ($params[$key] && isset($params[$key . '_id'])) {
463 $params[$match[1] . '-1_id'] = $params[$key . '_id'];
464 unset($params[$key . '_id']);
466 unset($params[$key]);
471 // build custom data getFields array
472 $customFields = CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE, $this->_activityTypeId
);
473 $customFields = CRM_Utils_Array
::crmArrayMerge($customFields,
474 CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE,
478 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($params,
485 // assigning formatted value
486 if (!empty($params['assignee_contact_id'])) {
487 $params['assignee_contact_id'] = explode(',', $params['assignee_contact_id']);
490 $params['assignee_contact_id'] = array();
493 if (isset($this->_activityId
)) {
494 // activity which hasn't been modified by a user yet
495 if ($this->_defaults
['is_auto'] == 1) {
496 $params['is_auto'] = 0;
499 // always create a revision of an case activity. CRM-4533
500 $newActParams = $params;
502 // add target contact values in update mode
503 if (empty($params['target_contact_id']) && !empty($this->_defaults
['target_contact'])) {
504 $newActParams['target_contact_id'] = $this->_defaults
['target_contact'];
507 // record status for status msg
508 $recordStatus = 'updated';
511 if (!isset($newActParams)) {
512 // add more attachments if needed for old activity
513 CRM_Core_BAO_File
::formatAttachment($params,
518 // call begin post process, before the activity is created/updated.
519 $this->beginPostProcess($params);
520 foreach ($this->_caseId
as $key => $val) {
521 $params['case_id'] = $val;
522 // activity create/update
523 $activity = CRM_Activity_BAO_Activity
::create($params);
524 $vvalue[] = array('case_id' => $val, 'actId' => $activity->id
);
525 // call end post process, after the activity has been created/updated.
526 $this->endPostProcess($params, $activity);
530 // since the params we need to set are very few, and we don't want rest of the
531 // work done by bao create method , lets use dao object to make the changes
532 $params = array('id' => $this->_activityId
);
533 $params['is_current_revision'] = 0;
534 $activity = new CRM_Activity_DAO_Activity();
535 $activity->copyValues($params);
539 // create a new version of activity if activity was found to
540 // have been modified/created by user
541 if (isset($newActParams)) {
542 // set proper original_id
543 if (!empty($this->_defaults
['original_id'])) {
544 $newActParams['original_id'] = $this->_defaults
['original_id'];
547 $newActParams['original_id'] = $activity->id
;
549 //is_current_revision will be set to 1 by default.
551 // add attachments if any
552 CRM_Core_BAO_File
::formatAttachment($newActParams,
557 // call begin post process, before the activity is created/updated.
558 $this->beginPostProcess($newActParams);
559 foreach ($this->_caseId
as $key => $val) {
560 $newActParams['case_id'] = $val;
561 $activity = CRM_Activity_BAO_Activity
::create($newActParams);
562 $vvalue[] = array('case_id'=> $val, 'actId'=> $activity->id
);
563 // call end post process, after the activity has been created/updated.
564 $this->endPostProcess($newActParams, $activity);
566 // copy files attached to old activity if any, to new one,
567 // as long as users have not selected the 'delete attachment' option.
568 if (empty($newActParams['is_delete_attachment'])) {
569 CRM_Core_BAO_File
::copyEntityFile('civicrm_activity', $this->_activityId
,
570 'civicrm_activity', $activity->id
574 // copy back params to original var
575 $params = $newActParams;
578 foreach ($vvalue as $vkey => $vval) {
579 if ($vval['actId']) {
580 // add tags if exists
581 $tagParams = array();
582 if (!empty($params['tag'])) {
583 foreach ($params['tag'] as $tag) {
584 $tagParams[$tag] = 1;
589 CRM_Core_BAO_EntityTag
::create($tagParams, 'civicrm_activity', $vval['actId']);
592 if (isset($params['taglist']) && !empty($params['taglist'])) {
593 CRM_Core_Form_Tag
::postProcess($params['taglist'], $vval['actId'], 'civicrm_activity', $this);
597 // update existing case record if needed
598 $caseParams = $params;
599 $caseParams['id'] = $vval['case_id'];
600 if (!empty($caseParams['case_type_id'])) {
601 $caseParams['case_type_id'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $caseParams['case_type_id'] . CRM_Core_DAO
::VALUE_SEPARATOR
;
603 if (!empty($caseParams['case_status_id'])) {
604 $caseParams['status_id'] = $caseParams['case_status_id'];
607 // unset params intended for activities only
608 unset($caseParams['subject'], $caseParams['details'],
609 $caseParams['status_id'], $caseParams['custom']
611 $case = CRM_Case_BAO_Case
::create($caseParams);
612 // create case activity record
614 'activity_id' => $vval['actId'],
615 'case_id' => $vval['case_id'],
617 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
620 // Insert civicrm_log record for the activity (e.g. store the
621 // created / edited by contact id and date for the activity)
622 // Note - civicrm_log is already created by CRM_Activity_BAO_Activity::create()
624 // send copy to selected contacts.
626 $mailToContacts = array();
629 //check for notification settings for assignee contacts
630 $selectedContacts = array('contact_check');
631 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
632 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
633 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
634 'activity_assignee_notification'
637 $selectedContacts[] = 'assignee_contact_id';
640 foreach ($vvalue as $vkey => $vval) {
641 foreach ($selectedContacts as $dnt => $val) {
642 if (array_key_exists($val, $params) && !CRM_Utils_array
::crmIsEmptyArray($params[$val])) {
643 if ($val == 'contact_check') {
644 $mailStatus = ts("A copy of the activity has also been sent to selected contacts(s).");
647 $this->_relatedContacts
= CRM_Activity_BAO_ActivityAssignment
::getAssigneeNames(array($vval['actId']), TRUE, FALSE);
648 $mailStatus .= ' ' . ts("A copy of the activity has also been sent to assignee contacts(s).");
650 //build an associative array with unique email addresses.
651 foreach ($params[$val] as $key => $value) {
652 if ($val == 'contact_check') {
659 if (isset($id) && array_key_exists($id, $this->_relatedContacts
) && isset($this->_relatedContacts
[$id]['email'])) {
660 //if email already exists in array then append with ', ' another role only otherwise add it to array.
661 if ($contactDetails = CRM_Utils_Array
::value($this->_relatedContacts
[$id]['email'], $mailToContacts)) {
662 $caseRole = CRM_Utils_Array
::value('role', $this->_relatedContacts
[$id]);
663 $mailToContacts[$this->_relatedContacts
[$id]['email']]['role'] = $contactDetails['role'] . ', ' . $caseRole;
666 $mailToContacts[$this->_relatedContacts
[$id]['email']] = $this->_relatedContacts
[$id];
673 if (!CRM_Utils_array
::crmIsEmptyArray($mailToContacts)) {
674 //include attachments while sending a copy of activity.
675 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_activity',
679 $ics = new CRM_Activity_BAO_ICalendar($activity);
680 $ics->addAttachment($attachments, $mailToContacts);
681 $result = CRM_Case_BAO_Case
::sendActivityCopy($this->_currentlyViewedContactId
,
682 $vval['actId'], $mailToContacts, $attachments, $vval['case_id']
685 if (empty($result)) {
693 // create follow up activity if needed
694 $followupStatus = '';
695 if (!empty($params['followup_activity_type_id'])) {
696 $followupActivity = CRM_Activity_BAO_Activity
::createFollowupActivity($vval['actId'], $params);
698 if ($followupActivity) {
700 'activity_id' => $followupActivity->id
,
701 'case_id' => $vval['case_id'],
703 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
704 $followupStatus = ts("A followup activity has been scheduled.");
708 CRM_Core_Session
::setStatus('', ts("'%1' activity has been %2. %3 %4",
710 1 => $this->_activityTypeName
,
712 3 => $followupStatus,