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 array of releted contact info.
61 public $_relatedContacts;
64 * Build the form object.
68 public function preProcess() {
69 $caseIds = CRM_Utils_Request
::retrieve('caseid', 'String', $this);
70 $this->_caseId
= explode(',', $caseIds);
71 $this->_context
= CRM_Utils_Request
::retrieve('context', 'String', $this);
72 if (!$this->_context
) {
73 $this->_context
= 'caseActivity';
75 $this->_crmDir
= 'Case';
76 $this->assign('context', $this->_context
);
78 $result = parent
::preProcess();
80 $scheduleStatusId = CRM_Core_OptionGroup
::getValue('activity_status', 'Scheduled', 'name');
81 $this->assign('scheduleStatusId', $scheduleStatusId);
83 if (!$this->_caseId
&& $this->_activityId
) {
84 $this->_caseId
= CRM_Core_DAO
::getFieldValue('CRM_Case_DAO_CaseActivity', $this->_activityId
,
85 'case_id', 'activity_id'
89 $this->assign('caseId', $this->_caseId
);
90 $this->assign('countId', count($this->_caseId
));
91 $this->assign('caseID', CRM_Utils_Array
::first($this->_caseId
));
94 if (!$this->_caseId ||
95 (!$this->_activityId
&& !$this->_activityTypeId
)
97 CRM_Core_Error
::fatal('required params missing.');
100 //check for case activity access.
101 if (!CRM_Case_BAO_Case
::accessCiviCase()) {
102 CRM_Core_Error
::fatal(ts('You are not authorized to access this page.'));
105 if ($this->_caseId
&&
106 !CRM_Core_Permission
::check('access all cases and activities')
108 $session = CRM_Core_Session
::singleton();
109 $allCases = CRM_Case_BAO_Case
::getCases(TRUE, $session->get('userID'), 'any');
110 if (!array_key_exists($this->_caseId
, $allCases)) {
111 CRM_Core_Error
::fatal(ts('You are not authorized to access this page.'));
115 //validate case activity id.
116 if ($this->_activityId
&&
117 ($this->_action
& CRM_Core_Action
::UPDATE
)
119 $valid = CRM_Case_BAO_Case
::checkPermission($this->_activityId
, 'edit',
120 $this->_activityTypeId
123 CRM_Core_Error
::fatal(ts('You are not authorized to access this page.'));
127 foreach ($this->_caseId
as $casePos => $caseId) {
128 $this->_caseType
[$casePos] = CRM_Case_BAO_Case
::getCaseType($caseId, 'name');
130 $this->assign('caseType', $this->_caseType
);
132 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
133 $isMultiClient = $xmlProcessorProcess->getAllowMultipleCaseClients();
134 $this->assign('multiClient', $isMultiClient);
136 foreach ($this->_caseId
as $casePos => $caseId) {
137 $clients[] = CRM_Case_BAO_Case
::getContactNames($caseId);
139 $this->assign('client_names', $clients);
141 $caseIds = implode(',', $this->_caseId
);
142 // set context for pushUserContext and for statusBounce
143 if ($this->_context
== 'fulltext') {
144 if ($this->_action
== CRM_Core_Action
::UPDATE ||
$this->_action
== CRM_Core_Action
::DELETE
) {
145 $url = CRM_Utils_System
::url('civicrm/contact/view/case',
146 "reset=1&action=view&cid={$this->_currentlyViewedContactId}&id={$caseIds}&show=1&context={$this->_context}"
150 $url = CRM_Utils_System
::url('civicrm/contact/search/custom', 'force=1');
154 $url = CRM_Utils_System
::url('civicrm/contact/view/case',
155 "reset=1&action=view&cid={$this->_currentlyViewedContactId}&id={$caseIds}&show=1"
158 if (!$this->_activityId
) {
159 $caseTypes = CRM_Case_PseudoConstant
::caseType();
161 if (empty($caseTypes) && ($this->_activityTypeName
== 'Change Case Type') && !$this->_caseId
) {
162 $url = CRM_Utils_System
::url('civicrm/contact/view/case',
163 "reset=1&action=view&cid={$this->_currentlyViewedContactId}&id={$caseIds}&show=1"
165 $session = CRM_Core_Session
::singleton();
166 $session->pushUserContext($url);
167 CRM_Core_Error
::statusBounce(ts("You do not have any active Case Types"));
170 // check if activity count is within the limit
171 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
172 foreach ($this->_caseId
as $casePos => $caseId) {
173 $caseType = $this->_caseType
[$casePos];
174 $activityInst = $xmlProcessor->getMaxInstance($caseType);
176 // If not bounce back and also provide activity edit link
177 if (isset($activityInst[$this->_activityTypeName
])) {
178 $activityCount = CRM_Case_BAO_Case
::getCaseActivityCount($caseId, $this->_activityTypeId
);
179 if ($activityCount >= $activityInst[$this->_activityTypeName
]) {
180 if ($activityInst[$this->_activityTypeName
] == 1) {
181 $atArray = array('activity_type_id' => $this->_activityTypeId
);
182 $activities = CRM_Case_BAO_Case
::getCaseActivity($caseId,
184 $this->_currentUserId
186 $activities = array_keys($activities);
187 $activities = $activities[0];
188 $editUrl = CRM_Utils_System
::url('civicrm/case/activity',
189 "reset=1&cid={$this->_currentlyViewedContactId}&caseid={$caseId}&action=update&id={$activities}"
192 CRM_Core_Error
::statusBounce(ts("You can not add another '%1' activity to this case. %2",
194 1 => $this->_activityTypeName
,
195 2 => ts("Do you want to <a %1>edit the existing activity</a>?", array(1 => "href='$editUrl'")),
205 $session = CRM_Core_Session
::singleton();
206 $session->pushUserContext($url);
210 * Set default values for the form. For edit/view mode
211 * the default values are retrieved from the database
216 public function setDefaultValues() {
217 $this->_defaults
= parent
::setDefaultValues();
218 $targetContactValues = array();
219 foreach ($this->_caseId
as $key => $val) {
221 $clients = CRM_Case_BAO_Case
::getContactNames($val);
222 if (isset($this->_activityId
) && empty($_POST)) {
223 if (!CRM_Utils_Array
::crmIsEmptyArray($this->_defaults
['target_contact'])) {
224 $targetContactValues = array_combine(array_unique($this->_defaults
['target_contact']),
225 explode(';', trim($this->_defaults
['target_contact_value']))
227 //exclude all clients.
228 foreach ($clients as $clientId => $vals) {
229 if (array_key_exists($clientId, $targetContactValues)) {
230 unset($targetContactValues[$clientId]);
235 $this->assign('targetContactValues', empty($targetContactValues) ?
FALSE : $targetContactValues);
237 if (isset($this->_encounterMedium
)) {
238 $this->_defaults
['medium_id'] = $this->_encounterMedium
;
240 elseif (empty($this->_defaults
['medium_id'])) {
241 // set default encounter medium CRM-4816
242 $medium = CRM_Core_OptionGroup
::values('encounter_medium', FALSE, FALSE, FALSE, 'AND is_default = 1');
243 if (count($medium) == 1) {
244 $this->_defaults
['medium_id'] = key($medium);
248 return $this->_defaults
;
252 public function buildQuickForm() {
253 $this->_fields
['source_contact_id']['label'] = ts('Reported By');
254 unset($this->_fields
['status_id']['attributes']['required']);
256 if ($this->_caseType
) {
257 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
259 foreach ($this->_caseType
as $key => $val) {
260 $activityTypes = $xmlProcessor->get($val, 'ActivityTypes', TRUE);
261 $aTypes = $aTypes +
$activityTypes;
264 // remove Open Case activity type since we're inside an existing case
265 $openCaseID = CRM_Core_OptionGroup
::getValue('activity_type', 'Open Case', 'name');
266 unset($aTypes[$openCaseID]);
268 $this->_fields
['followup_activity_type_id']['attributes'] = array('' => '- select activity type -') +
$aTypes;
271 $result = parent
::buildQuickForm();
273 if ($this->_action
& (CRM_Core_Action
::DELETE | CRM_Core_Action
::DETACH | CRM_Core_Action
::RENEW
)) {
277 $this->assign('urlPath', 'civicrm/case/activity');
279 $encounterMediums = CRM_Case_PseudoConstant
::encounterMedium();
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 if ($this->_activityTypeFile
== 'OpenCase') {
283 $this->_encounterMedium
= CRM_Core_DAO
::getFieldValue('CRM_Activity_DAO_Activity', $this->_activityId
,
286 if (!array_key_exists($this->_encounterMedium
, $encounterMediums)) {
287 $encounterMediums[$this->_encounterMedium
] = CRM_Core_OptionGroup
::getLabel('encounter_medium',
288 $this->_encounterMedium
,
294 $this->add('select', 'medium_id', ts('Medium'), $encounterMediums, TRUE);
296 foreach ($this->_caseId
as $key => $val) {
297 $this->_relatedContacts
[] = $rgc = CRM_Case_BAO_Case
::getRelatedAndGlobalContacts($val);
298 $contName = CRM_Case_BAO_Case
::getContactNames($val);
299 foreach ($contName as $nkey => $nval) {
300 array_push($this->_relatedContacts
[$i][0], $this->_relatedContacts
[$i][0]['managerOf'] = $nval['display_name']);
305 //add case client in send a copy selector.CRM-4438.
306 foreach ($this->_caseId
as $key => $val) {
307 $relatedContacts[] = $relCon = CRM_Case_BAO_Case
::getContactNames($val);
310 if (!empty($relatedContacts)) {
311 foreach ($relatedContacts as $relatedContact) {
312 $this->_relatedContacts
[] = $relatedContact;
316 if (!empty($this->_relatedContacts
)) {
317 $checkBoxes = array();
318 foreach ($this->_relatedContacts
as $id => $row) {
319 $checkBoxes[$id] = $this->addElement('checkbox', $id, NULL, NULL, array('class' => 'select-row'));
322 $this->addGroup($checkBoxes, 'contact_check');
323 $this->addElement('checkbox', 'toggleSelect', NULL, NULL,
324 array('class' => 'select-rows')
326 $this->assign('searchRows', $this->_relatedContacts
);
328 $this->_relatedContacts
= $rgc +
$relCon;
330 $this->addFormRule(array('CRM_Case_Form_Activity', 'formRule'), $this);
336 * @param array $fields
337 * The input form values.
338 * @param array $files
339 * The uploaded files if any.
343 * true if no errors, else array of errors
345 public static function formRule($fields, $files, $self) {
346 // skip form rule if deleting
347 if (CRM_Utils_Array
::value('_qf_Activity_next_', $fields) == 'Delete' || CRM_Utils_Array
::value('_qf_Activity_next_', $fields) == 'Restore') {
351 return parent
::formrule($fields, $files, $self);
355 * Process the form submission.
358 * @param array $params
362 public function postProcess($params = NULL) {
363 $transaction = new CRM_Core_Transaction();
365 if ($this->_action
& CRM_Core_Action
::DELETE
) {
368 //block deleting activities which affects
369 //case attributes.CRM-4543
370 $activityCondition = " AND v.name IN ('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date')";
371 $caseAttributeActivities = CRM_Core_OptionGroup
::values('activity_type', FALSE, FALSE, FALSE, $activityCondition);
373 if (!array_key_exists($this->_activityTypeId
, $caseAttributeActivities)) {
374 $params = array('id' => $this->_activityId
);
375 $activityDelete = CRM_Activity_BAO_Activity
::deleteActivity($params, TRUE);
376 if ($activityDelete) {
377 $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 />');
381 $statusMsg = ts("Selected Activity cannot be deleted.");
385 'entity_table' => 'civicrm_activity',
386 'entity_id' => $this->_activityId
,
388 CRM_Core_BAO_EntityTag
::del($tagParams);
390 CRM_Core_Session
::setStatus('', $statusMsg, 'info');
394 if ($this->_action
& CRM_Core_Action
::RENEW
) {
396 $params = array('id' => $this->_activityId
);
397 $activityRestore = CRM_Activity_BAO_Activity
::restoreActivity($params);
398 if ($activityRestore) {
399 $statusMsg = ts('The selected activity has been restored.<br />');
401 CRM_Core_Session
::setStatus('', $statusMsg, 'info');
405 // store the submitted values in an array
406 $params = $this->controller
->exportValues($this->_name
);
408 //set parent id if its edit mode
409 if ($parentId = CRM_Utils_Array
::value('parent_id', $this->_defaults
)) {
410 $params['parent_id'] = $parentId;
413 // store the dates with proper format
414 $params['activity_date_time'] = CRM_Utils_Date
::processDate($params['activity_date_time'], $params['activity_date_time_time']);
415 $params['activity_type_id'] = $this->_activityTypeId
;
417 // format with contact (target contact) values
418 if (isset($params['target_contact_id'])) {
419 $params['target_contact_id'] = explode(',', $params['target_contact_id']);
422 $params['target_contact_id'] = array();
425 // format activity custom data
426 if (!empty($params['hidden_custom'])) {
427 if ($this->_activityId
) {
428 // unset custom fields-id from params since we want custom
429 // fields to be saved for new activity.
430 foreach ($params as $key => $value) {
432 if (preg_match('/^(custom_\d+_)(\d+)$/', $key, $match)) {
433 $params[$match[1] . '-1'] = $params[$key];
435 // for autocomplete transfer hidden value instead of label
436 if ($params[$key] && isset($params[$key . '_id'])) {
437 $params[$match[1] . '-1_id'] = $params[$key . '_id'];
438 unset($params[$key . '_id']);
440 unset($params[$key]);
445 // build custom data getFields array
446 $customFields = CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE, $this->_activityTypeId
);
447 $customFields = CRM_Utils_Array
::crmArrayMerge($customFields,
448 CRM_Core_BAO_CustomField
::getFields('Activity', FALSE, FALSE,
452 $params['custom'] = CRM_Core_BAO_CustomField
::postProcess($params,
458 // assigning formatted value
459 if (!empty($params['assignee_contact_id'])) {
460 $params['assignee_contact_id'] = explode(',', $params['assignee_contact_id']);
463 $params['assignee_contact_id'] = array();
466 if (isset($this->_activityId
)) {
467 // activity which hasn't been modified by a user yet
468 if ($this->_defaults
['is_auto'] == 1) {
469 $params['is_auto'] = 0;
472 // always create a revision of an case activity. CRM-4533
473 $newActParams = $params;
475 // add target contact values in update mode
476 if (empty($params['target_contact_id']) && !empty($this->_defaults
['target_contact'])) {
477 $newActParams['target_contact_id'] = $this->_defaults
['target_contact'];
481 if (!isset($newActParams)) {
482 // add more attachments if needed for old activity
483 CRM_Core_BAO_File
::formatAttachment($params,
488 // call begin post process, before the activity is created/updated.
489 $this->beginPostProcess($params);
490 foreach ($this->_caseId
as $key => $val) {
491 $params['case_id'] = $val;
492 // activity create/update
493 $activity = CRM_Activity_BAO_Activity
::create($params);
494 $vvalue[] = array('case_id' => $val, 'actId' => $activity->id
);
495 // call end post process, after the activity has been created/updated.
496 $this->endPostProcess($params, $activity);
500 // since the params we need to set are very few, and we don't want rest of the
501 // work done by bao create method , lets use dao object to make the changes
502 $params = array('id' => $this->_activityId
);
503 $params['is_current_revision'] = 0;
504 $activity = new CRM_Activity_DAO_Activity();
505 $activity->copyValues($params);
509 // create a new version of activity if activity was found to
510 // have been modified/created by user
511 if (isset($newActParams)) {
512 // set proper original_id
513 if (!empty($this->_defaults
['original_id'])) {
514 $newActParams['original_id'] = $this->_defaults
['original_id'];
517 $newActParams['original_id'] = $activity->id
;
519 //is_current_revision will be set to 1 by default.
521 // add attachments if any
522 CRM_Core_BAO_File
::formatAttachment($newActParams,
527 // call begin post process, before the activity is created/updated.
528 $this->beginPostProcess($newActParams);
529 foreach ($this->_caseId
as $key => $val) {
530 $newActParams['case_id'] = $val;
531 $activity = CRM_Activity_BAO_Activity
::create($newActParams);
532 $vvalue[] = array('case_id' => $val, 'actId' => $activity->id
);
533 // call end post process, after the activity has been created/updated.
534 $this->endPostProcess($newActParams, $activity);
536 // copy files attached to old activity if any, to new one,
537 // as long as users have not selected the 'delete attachment' option.
538 if (empty($newActParams['is_delete_attachment'])) {
539 CRM_Core_BAO_File
::copyEntityFile('civicrm_activity', $this->_activityId
,
540 'civicrm_activity', $activity->id
544 // copy back params to original var
545 $params = $newActParams;
548 foreach ($vvalue as $vkey => $vval) {
549 if ($vval['actId']) {
550 // add tags if exists
551 $tagParams = array();
552 if (!empty($params['tag'])) {
553 foreach ($params['tag'] as $tag) {
554 $tagParams[$tag] = 1;
559 CRM_Core_BAO_EntityTag
::create($tagParams, 'civicrm_activity', $vval['actId']);
562 if (isset($params['taglist']) && !empty($params['taglist'])) {
563 CRM_Core_Form_Tag
::postProcess($params['taglist'], $vval['actId'], 'civicrm_activity', $this);
567 // update existing case record if needed
568 $caseParams = $params;
569 $caseParams['id'] = $vval['case_id'];
570 if (!empty($caseParams['case_status_id'])) {
571 $caseParams['status_id'] = $caseParams['case_status_id'];
574 // unset params intended for activities only
575 unset($caseParams['subject'], $caseParams['details'],
576 $caseParams['status_id'], $caseParams['custom']
578 $case = CRM_Case_BAO_Case
::create($caseParams);
579 // create case activity record
581 'activity_id' => $vval['actId'],
582 'case_id' => $vval['case_id'],
584 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
587 // Insert civicrm_log record for the activity (e.g. store the
588 // created / edited by contact id and date for the activity)
589 // Note - civicrm_log is already created by CRM_Activity_BAO_Activity::create()
591 // send copy to selected contacts.
593 $mailToContacts = array();
596 //check for notification settings for assignee contacts
597 $selectedContacts = array('contact_check');
598 $activityContacts = CRM_Core_OptionGroup
::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
599 $assigneeID = CRM_Utils_Array
::key('Activity Assignees', $activityContacts);
600 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
601 'activity_assignee_notification'
604 $selectedContacts[] = 'assignee_contact_id';
607 foreach ($vvalue as $vkey => $vval) {
608 foreach ($selectedContacts as $dnt => $val) {
609 if (array_key_exists($val, $params) && !CRM_Utils_array
::crmIsEmptyArray($params[$val])) {
610 if ($val == 'contact_check') {
611 $mailStatus = ts("A copy of the activity has also been sent to selected contacts(s).");
614 $this->_relatedContacts
= CRM_Activity_BAO_ActivityAssignment
::getAssigneeNames(array($vval['actId']), TRUE, FALSE);
615 $mailStatus .= ' ' . ts("A copy of the activity has also been sent to assignee contacts(s).");
617 //build an associative array with unique email addresses.
618 foreach ($params[$val] as $key => $value) {
619 if ($val == 'contact_check') {
626 if (isset($id) && array_key_exists($id, $this->_relatedContacts
) && isset($this->_relatedContacts
[$id]['email'])) {
627 //if email already exists in array then append with ', ' another role only otherwise add it to array.
628 if ($contactDetails = CRM_Utils_Array
::value($this->_relatedContacts
[$id]['email'], $mailToContacts)) {
629 $caseRole = CRM_Utils_Array
::value('role', $this->_relatedContacts
[$id]);
630 $mailToContacts[$this->_relatedContacts
[$id]['email']]['role'] = $contactDetails['role'] . ', ' . $caseRole;
633 $mailToContacts[$this->_relatedContacts
[$id]['email']] = $this->_relatedContacts
[$id];
640 $extraParams = array('case_id' => $vval['case_id'], 'client_id' => $this->_currentlyViewedContactId
);
641 $result = CRM_Activity_BAO_Activity
::sendToAssignee($activity, $mailToContacts, $extraParams);
642 if (empty($result)) {
646 // create follow up activity if needed
647 $followupStatus = '';
648 if (!empty($params['followup_activity_type_id'])) {
649 $followupActivity = CRM_Activity_BAO_Activity
::createFollowupActivity($vval['actId'], $params);
651 if ($followupActivity) {
653 'activity_id' => $followupActivity->id
,
654 'case_id' => $vval['case_id'],
656 CRM_Case_BAO_Case
::processCaseActivity($caseParams);
657 $followupStatus = ts("A followup activity has been scheduled.") . '<br /><br />';
660 $title = ts("%1 Saved", array(1 => $this->_activityTypeName
));
661 CRM_Core_Session
::setStatus($followupStatus . $mailStatus, $title, 'success');