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 * Build the form object
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
));
103 $this->assign('caseID', CRM_Utils_Array
::first($this->_caseId
));
106 if (!$this->_caseId ||
107 (!$this->_activityId
&& !$this->_activityTypeId
)
109 CRM_Core_Error
::fatal('required params missing.');
112 //check for case activity access.
113 if (!CRM_Case_BAO_Case
::accessCiviCase()) {
114 CRM_Core_Error
::fatal(ts('You are not authorized to access this page.'));
117 if ($this->_caseId
&&
118 !CRM_Core_Permission
::check('access all cases and activities')
120 $session = CRM_Core_Session
::singleton();
121 $allCases = CRM_Case_BAO_Case
::getCases(TRUE, $session->get('userID'), 'any');
122 if (!array_key_exists($this->_caseId
, $allCases)) {
123 CRM_Core_Error
::fatal(ts('You are not authorized to access this page.'));
127 //validate case activity id.
128 if ($this->_activityId
&&
129 ($this->_action
& CRM_Core_Action
::UPDATE
)
131 $valid = CRM_Case_BAO_Case
::checkPermission($this->_activityId
, 'edit',
132 $this->_activityTypeId
135 CRM_Core_Error
::fatal(ts('You are not authorized to access this page.'));
139 foreach ($this->_caseId
as $casePos => $caseId) {
140 $this->_caseType
[$casePos] = CRM_Case_BAO_Case
::getCaseType($caseId, 'name');
142 $this->assign('caseType', $this->_caseType
);
144 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
145 $isMultiClient = $xmlProcessorProcess->getAllowMultipleCaseClients();
146 $this->assign('multiClient', $isMultiClient);
148 foreach ($this->_caseId
as $casePos => $caseId) {
149 $clients[] = CRM_Case_BAO_Case
::getContactNames($caseId);
151 $this->assign('client_names', $clients);
153 $caseIds = implode(',', $this->_caseId
);
154 // set context for pushUserContext and for statusBounce
155 if ($this->_context
== 'fulltext') {
156 if ($this->_action
== CRM_Core_Action
::UPDATE ||
$this->_action
== CRM_Core_Action
::DELETE
) {
157 $url = CRM_Utils_System
::url('civicrm/contact/view/case',
158 "reset=1&action=view&cid={$this->_currentlyViewedContactId}&id={$caseIds}&show=1&context={$this->_context}"
162 $url = CRM_Utils_System
::url('civicrm/contact/search/custom', 'force=1');
166 $url = CRM_Utils_System
::url('civicrm/contact/view/case',
167 "reset=1&action=view&cid={$this->_currentlyViewedContactId}&id={$caseIds}&show=1"
170 if (!$this->_activityId
) {
171 $caseTypes = CRM_Case_PseudoConstant
::caseType();
173 if (empty($caseTypes) && ($this->_activityTypeName
== 'Change Case Type') && !$this->_caseId
) {
174 $url = CRM_Utils_System
::url('civicrm/contact/view/case',
175 "reset=1&action=view&cid={$this->_currentlyViewedContactId}&id={$caseIds}&show=1"
177 $session = CRM_Core_Session
::singleton();
178 $session->pushUserContext($url);
179 CRM_Core_Error
::statusBounce(ts("You do not have any active Case Types"));
182 // check if activity count is within the limit
183 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
184 foreach ($this->_caseId
as $casePos => $caseId) {
185 $caseType = $this->_caseType
[$casePos];
186 $activityInst = $xmlProcessor->getMaxInstance($caseType);
188 // If not bounce back and also provide activity edit link
189 if (isset($activityInst[$this->_activityTypeName
])) {
190 $activityCount = CRM_Case_BAO_Case
::getCaseActivityCount($caseId, $this->_activityTypeId
);
191 if ($activityCount >= $activityInst[$this->_activityTypeName
]) {
192 if ($activityInst[$this->_activityTypeName
] == 1) {
193 $atArray = array('activity_type_id' => $this->_activityTypeId
);
194 $activities = CRM_Case_BAO_Case
::getCaseActivity($caseId,
196 $this->_currentUserId
198 $activities = array_keys($activities);
199 $activities = $activities[0];
200 $editUrl = CRM_Utils_System
::url('civicrm/case/activity',
201 "reset=1&cid={$this->_currentlyViewedContactId}&caseid={$caseId}&action=update&id={$activities}"
204 CRM_Core_Error
::statusBounce(ts("You can not add another '%1' activity to this case. %2",
206 1 => $this->_activityTypeName
,
207 2 => "Do you want to <a href='$editUrl'>edit the existing activity</a> ?"
217 $session = CRM_Core_Session
::singleton();
218 $session->pushUserContext($url);
222 * Set default values for the form. For edit/view mode
223 * the default values are retrieved from the database
229 function setDefaultValues() {
230 $this->_defaults
= parent
::setDefaultValues();
231 $targetContactValues = array();
232 foreach ($this->_caseId
as $key => $val) {
234 $clients = CRM_Case_BAO_Case
::getContactNames($val);
235 if (isset($this->_activityId
) && empty($_POST)) {
236 if (!CRM_Utils_Array
::crmIsEmptyArray($this->_defaults
['target_contact'])) {
237 $targetContactValues = array_combine(array_unique($this->_defaults
['target_contact']),
238 explode(';', trim($this->_defaults
['target_contact_value']))
240 //exclude all clients.
241 foreach ($clients as $clientId => $vals) {
242 if (array_key_exists($clientId, $targetContactValues)) {
243 unset($targetContactValues[$clientId]);
248 $this->assign('targetContactValues', empty($targetContactValues) ?
FALSE : $targetContactValues);
250 //return form for ajax
251 if ($this->_cdType
) {
252 return $this->_defaults
;
255 if (isset($this->_encounterMedium
)) {
256 $this->_defaults
['medium_id'] = $this->_encounterMedium
;
258 elseif (empty($this->_defaults
['medium_id'])) {
259 // set default encounter medium CRM-4816
260 $medium = CRM_Core_OptionGroup
::values('encounter_medium', FALSE, FALSE, FALSE, 'AND is_default = 1');
261 if (count($medium) == 1) {
262 $this->_defaults
['medium_id'] = key($medium);
266 return $this->_defaults
;
270 public function buildQuickForm() {
271 $this->_fields
['source_contact_id']['label'] = ts('Reported By');
272 unset($this->_fields
['status_id']['attributes']['required']);
274 if ($this->_caseType
) {
275 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
277 foreach ($this->_caseType
as $key => $val) {
278 $activityTypes = $xmlProcessor->get($val, 'ActivityTypes', TRUE);
279 $aTypes = $aTypes +
$activityTypes;
282 // remove Open Case activity type since we're inside an existing case
283 $openCaseID = CRM_Core_OptionGroup
::getValue('activity_type', 'Open Case', 'name');
284 unset($aTypes[$openCaseID]);
286 $this->_fields
['followup_activity_type_id']['attributes'] = array(
287 '' => '- select activity type -'
291 $result = parent
::buildQuickForm();
293 if ($this->_action
& (CRM_Core_Action
::DELETE | CRM_Core_Action
::DETACH | CRM_Core_Action
::RENEW
)) {
297 if ($this->_cdType
) {
301 $this->assign('urlPath', 'civicrm/case/activity');
303 $encounterMediums = CRM_Case_PseudoConstant
::encounterMedium();
304 // 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.
305 // Is that really a big problem?
306 if ($this->_activityTypeFile
== 'OpenCase') {
307 $this->_encounterMedium
= CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $this->_activityId
,
310 if (!array_key_exists($this->_encounterMedium
, $encounterMediums)) {
311 $encounterMediums[$this->_encounterMedium
] = CRM_Core_OptionGroup
::getLabel('encounter_medium',
312 $this->_encounterMedium
,
318 $this->add('select', 'medium_id', ts('Medium'), $encounterMediums, TRUE);
320 foreach ($this->_caseId
as $key => $val) {
321 $this->_relatedContacts
[] = $rgc = CRM_Case_BAO_Case
::getRelatedAndGlobalContacts($val);
322 $contName = CRM_Case_BAO_Case
::getContactNames($val);
323 foreach ($contName as $nkey => $nval) {
324 array_push($this->_relatedContacts
[$i][0] , $this->_relatedContacts
[$i][0]['managerOf']= $nval['display_name']);
329 //add case client in send a copy selector.CRM-4438.
330 foreach ($this->_caseId
as $key => $val) {
331 $relatedContacts[] = $relCon= CRM_Case_BAO_Case
::getContactNames($val);
334 if (!empty($relatedContacts)) {
335 foreach ($relatedContacts as $relatedContact) {
336 $this->_relatedContacts
[] = $relatedContact;
340 if (!empty($this->_relatedContacts
)) {
341 $checkBoxes = array();
342 foreach ($this->_relatedContacts
as $id => $row) {
343 $checkBoxes[$id] = $this->addElement('checkbox', $id, NULL, NULL, array('class' => 'select-row'));
346 $this->addGroup($checkBoxes, 'contact_check');
347 $this->addElement('checkbox', 'toggleSelect', NULL, NULL,
348 array('class' => 'select-rows')
350 $this->assign('searchRows', $this->_relatedContacts
);
352 $this->_relatedContacts
= $rgc +
$relCon;
354 $this->addFormRule(array('CRM_Case_Form_Activity', 'formRule'), $this);
360 * @param array $fields the input form values
361 * @param array $files the uploaded files if any
364 * @return true if no errors, else array of errors
368 static function formRule($fields, $files, $self) {
369 // skip form rule if deleting
370 if (CRM_Utils_Array
::value('_qf_Activity_next_', $fields) == 'Delete' || CRM_Utils_Array
::value('_qf_Activity_next_', $fields) == 'Restore') {
374 return parent
::formrule($fields, $files, $self);
378 * Process the form submission
382 * @param array $params
386 public function postProcess($params = NULL) {
387 $transaction = new CRM_Core_Transaction();
389 if ($this->_action
& CRM_Core_Action
::DELETE
) {
392 //block deleting activities which affects
393 //case attributes.CRM-4543
394 $activityCondition = " AND v.name IN ('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date')";
395 $caseAttributeActivities = CRM_Core_OptionGroup
::values('activity_type', FALSE, FALSE, FALSE, $activityCondition);
397 if (!array_key_exists($this->_activityTypeId
, $caseAttributeActivities)) {
398 $params = array('id' => $this->_activityId
);
399 $activityDelete = CRM_Activity_BAO_Activity
::deleteActivity($params, TRUE);
400 if ($activityDelete) {
401 $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 />');
405 $statusMsg = ts("Selected Activity cannot be deleted.");
409 'entity_table' => 'civicrm_activity',
410 'entity_id' => $this->_activityId
412 CRM_Core_BAO_EntityTag
::del($tagParams);
414 CRM_Core_Session
::setStatus('', $statusMsg, 'info');
418 if ($this->_action
& CRM_Core_Action
::RENEW
) {
420 $params = array('id' => $this->_activityId
);
421 $activityRestore = CRM_Activity_BAO_Activity
::restoreActivity($params);
422 if ($activityRestore) {
423 $statusMsg = ts('The selected activity has been restored.<br />');
425 CRM_Core_Session
::setStatus('', $statusMsg, 'info');
429 // store the submitted values in an array
430 $params = $this->controller
->exportValues($this->_name
);
432 //set parent id if its edit mode
433 if ($parentId = CRM_Utils_Array
::value('parent_id', $this->_defaults
)) {
434 $params['parent_id'] = $parentId;
437 // required for status msg
438 $recordStatus = 'created';
440 // store the dates with proper format
441 $params['activity_date_time'] = CRM_Utils_Date
::processDate($params['activity_date_time'], $params['activity_date_time_time']);
442 $params['activity_type_id'] = $this->_activityTypeId
;
444 // format with contact (target contact) values
445 if (isset($params['target_contact_id'])) {
446 $params['target_contact_id'] = explode(',', $params['target_contact_id']);
449 $params['target_contact_id'] = array();
452 // format activity custom data
453 if (!empty($params['hidden_custom'])) {
454 if ($this->_activityId
) {
455 // unset custom fields-id from params since we want custom
456 // fields to be saved for new activity.
457 foreach ($params as $key => $value) {
459 if (preg_match('/^(custom_\d+_)(\d+)$/', $key, $match)) {
460 $params[$match[1] . '-1'] = $params[$key];
462 // for autocomplete transfer hidden value instead of label
463 if ($params[$key] && isset($params[$key . '_id'])) {
464 $params[$match[1] . '-1_id'] = $params[$key . '_id'];
465 unset($params[$key . '_id']);
467 unset($params[$key]);
472 // build custom data getFields array
473 $customFields = CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE, $this->_activityTypeId
);
474 $customFields = CRM_Utils_Array
::crmArrayMerge($customFields,
475 CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE,
479 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($params,
486 // assigning formatted value
487 if (!empty($params['assignee_contact_id'])) {
488 $params['assignee_contact_id'] = explode(',', $params['assignee_contact_id']);
491 $params['assignee_contact_id'] = array();
494 if (isset($this->_activityId
)) {
495 // activity which hasn't been modified by a user yet
496 if ($this->_defaults
['is_auto'] == 1) {
497 $params['is_auto'] = 0;
500 // always create a revision of an case activity. CRM-4533
501 $newActParams = $params;
503 // add target contact values in update mode
504 if (empty($params['target_contact_id']) && !empty($this->_defaults
['target_contact'])) {
505 $newActParams['target_contact_id'] = $this->_defaults
['target_contact'];
508 // record status for status msg
509 $recordStatus = 'updated';
512 if (!isset($newActParams)) {
513 // add more attachments if needed for old activity
514 CRM_Core_BAO_File
::formatAttachment($params,
519 // call begin post process, before the activity is created/updated.
520 $this->beginPostProcess($params);
521 foreach ($this->_caseId
as $key => $val) {
522 $params['case_id'] = $val;
523 // activity create/update
524 $activity = CRM_Activity_BAO_Activity
::create($params);
525 $vvalue[] = array('case_id' => $val, 'actId' => $activity->id
);
526 // call end post process, after the activity has been created/updated.
527 $this->endPostProcess($params, $activity);
531 // since the params we need to set are very few, and we don't want rest of the
532 // work done by bao create method , lets use dao object to make the changes
533 $params = array('id' => $this->_activityId
);
534 $params['is_current_revision'] = 0;
535 $activity = new CRM_Activity_DAO_Activity();
536 $activity->copyValues($params);
540 // create a new version of activity if activity was found to
541 // have been modified/created by user
542 if (isset($newActParams)) {
543 // set proper original_id
544 if (!empty($this->_defaults
['original_id'])) {
545 $newActParams['original_id'] = $this->_defaults
['original_id'];
548 $newActParams['original_id'] = $activity->id
;
550 //is_current_revision will be set to 1 by default.
552 // add attachments if any
553 CRM_Core_BAO_File
::formatAttachment($newActParams,
558 // call begin post process, before the activity is created/updated.
559 $this->beginPostProcess($newActParams);
560 foreach ($this->_caseId
as $key => $val) {
561 $newActParams['case_id'] = $val;
562 $activity = CRM_Activity_BAO_Activity
::create($newActParams);
563 $vvalue[] = array('case_id'=> $val, 'actId'=> $activity->id
);
564 // call end post process, after the activity has been created/updated.
565 $this->endPostProcess($newActParams, $activity);
567 // copy files attached to old activity if any, to new one,
568 // as long as users have not selected the 'delete attachment' option.
569 if (empty($newActParams['is_delete_attachment'])) {
570 CRM_Core_BAO_File
::copyEntityFile('civicrm_activity', $this->_activityId
,
571 'civicrm_activity', $activity->id
575 // copy back params to original var
576 $params = $newActParams;
579 foreach ($vvalue as $vkey => $vval) {
580 if ($vval['actId']) {
581 // add tags if exists
582 $tagParams = array();
583 if (!empty($params['tag'])) {
584 foreach ($params['tag'] as $tag) {
585 $tagParams[$tag] = 1;
590 CRM_Core_BAO_EntityTag
::create($tagParams, 'civicrm_activity', $vval['actId']);
593 if (isset($params['taglist']) && !empty($params['taglist'])) {
594 CRM_Core_Form_Tag
::postProcess($params['taglist'], $vval['actId'], 'civicrm_activity', $this);
598 // update existing case record if needed
599 $caseParams = $params;
600 $caseParams['id'] = $vval['case_id'];
601 if (!empty($caseParams['case_status_id'])) {
602 $caseParams['status_id'] = $caseParams['case_status_id'];
605 // unset params intended for activities only
606 unset($caseParams['subject'], $caseParams['details'],
607 $caseParams['status_id'], $caseParams['custom']
609 $case = CRM_Case_BAO_Case
::create($caseParams);
610 // create case activity record
612 'activity_id' => $vval['actId'],
613 'case_id' => $vval['case_id'],
615 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
618 // Insert civicrm_log record for the activity (e.g. store the
619 // created / edited by contact id and date for the activity)
620 // Note - civicrm_log is already created by CRM_Activity_BAO_Activity::create()
622 // send copy to selected contacts.
624 $mailToContacts = array();
627 //check for notification settings for assignee contacts
628 $selectedContacts = array('contact_check');
629 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
630 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
631 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
632 'activity_assignee_notification'
635 $selectedContacts[] = 'assignee_contact_id';
638 foreach ($vvalue as $vkey => $vval) {
639 foreach ($selectedContacts as $dnt => $val) {
640 if (array_key_exists($val, $params) && !CRM_Utils_array
::crmIsEmptyArray($params[$val])) {
641 if ($val == 'contact_check') {
642 $mailStatus = ts("A copy of the activity has also been sent to selected contacts(s).");
645 $this->_relatedContacts
= CRM_Activity_BAO_ActivityAssignment
::getAssigneeNames(array($vval['actId']), TRUE, FALSE);
646 $mailStatus .= ' ' . ts("A copy of the activity has also been sent to assignee contacts(s).");
648 //build an associative array with unique email addresses.
649 foreach ($params[$val] as $key => $value) {
650 if ($val == 'contact_check') {
657 if (isset($id) && array_key_exists($id, $this->_relatedContacts
) && isset($this->_relatedContacts
[$id]['email'])) {
658 //if email already exists in array then append with ', ' another role only otherwise add it to array.
659 if ($contactDetails = CRM_Utils_Array
::value($this->_relatedContacts
[$id]['email'], $mailToContacts)) {
660 $caseRole = CRM_Utils_Array
::value('role', $this->_relatedContacts
[$id]);
661 $mailToContacts[$this->_relatedContacts
[$id]['email']]['role'] = $contactDetails['role'] . ', ' . $caseRole;
664 $mailToContacts[$this->_relatedContacts
[$id]['email']] = $this->_relatedContacts
[$id];
671 if (!CRM_Utils_array
::crmIsEmptyArray($mailToContacts)) {
672 //include attachments while sending a copy of activity.
673 $attachments = CRM_Core_BAO_File
::getEntityFile('civicrm_activity',
677 $ics = new CRM_Activity_BAO_ICalendar($activity);
678 $ics->addAttachment($attachments, $mailToContacts);
679 $result = CRM_Case_BAO_Case
::sendActivityCopy($this->_currentlyViewedContactId
,
680 $vval['actId'], $mailToContacts, $attachments, $vval['case_id']
683 if (empty($result)) {
691 // create follow up activity if needed
692 $followupStatus = '';
693 if (!empty($params['followup_activity_type_id'])) {
694 $followupActivity = CRM_Activity_BAO_Activity
::createFollowupActivity($vval['actId'], $params);
696 if ($followupActivity) {
698 'activity_id' => $followupActivity->id
,
699 'case_id' => $vval['case_id'],
701 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
702 $followupStatus = ts("A followup activity has been scheduled.");
706 CRM_Core_Session
::setStatus('', ts("'%1' activity has been %2. %3 %4",
708 1 => $this->_activityTypeName
,
710 3 => $followupStatus,