CRM-21507 Fix error when creating case activities
[civicrm-core.git] / CRM / Case / Form / Activity.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
0f03f337 6 | Copyright CiviCRM LLC (c) 2004-2017 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
0f03f337 31 * @copyright CiviCRM LLC (c) 2004-2017
6a488035
TO
32 */
33
34/**
3819f101 35 * This class create activities for a case.
6a488035
TO
36 */
37class CRM_Case_Form_Activity extends CRM_Activity_Form_Activity {
77b97be7 38
6a488035 39 /**
d2e5d2ce 40 * The default variable defined.
6a488035
TO
41 *
42 * @var int
43 */
44 public $_caseId;
45
46 /**
d2e5d2ce 47 * The default case type variable defined.
6a488035
TO
48 *
49 * @var int
50 */
51 public $_caseType;
52
6a488035 53 /**
d2e5d2ce 54 * The array of releted contact info.
6a488035
TO
55 *
56 * @var array
57 */
58 public $_relatedContacts;
59
60 /**
d2e5d2ce 61 * Build the form object.
6a488035 62 */
00be9182 63 public function preProcess() {
725fd9d9
N
64 $caseIds = CRM_Utils_Request::retrieve('caseid', 'String', $this);
65 $this->_caseId = explode(',', $caseIds);
6a488035
TO
66 $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
67 if (!$this->_context) {
68 $this->_context = 'caseActivity';
69 }
70 $this->_crmDir = 'Case';
71 $this->assign('context', $this->_context);
72
73 $result = parent::preProcess();
74
75 $scheduleStatusId = CRM_Core_OptionGroup::getValue('activity_status', 'Scheduled', 'name');
76 $this->assign('scheduleStatusId', $scheduleStatusId);
77
6a488035
TO
78 if (!$this->_caseId && $this->_activityId) {
79 $this->_caseId = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_CaseActivity', $this->_activityId,
80 'case_id', 'activity_id'
81 );
82 }
83 if ($this->_caseId) {
84 $this->assign('caseId', $this->_caseId);
725fd9d9 85 $this->assign('countId', count($this->_caseId));
ad32fddf 86 $this->assign('caseID', CRM_Utils_Array::first($this->_caseId));
6a488035
TO
87 }
88
89 if (!$this->_caseId ||
90 (!$this->_activityId && !$this->_activityTypeId)
91 ) {
92 CRM_Core_Error::fatal('required params missing.');
93 }
94
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.'));
98 }
99 //validate case id.
100 if ($this->_caseId &&
101 !CRM_Core_Permission::check('access all cases and activities')
102 ) {
103 $session = CRM_Core_Session::singleton();
ef0ae32d 104 $allCases = CRM_Case_BAO_Case::getCases(TRUE, $session->get('userID'), 'any');
7fa5bb16 105 if (count(array_intersect($this->_caseId, array_keys($allCases))) == 0) {
6a488035
TO
106 CRM_Core_Error::fatal(ts('You are not authorized to access this page.'));
107 }
108 }
109
110 //validate case activity id.
111 if ($this->_activityId &&
112 ($this->_action & CRM_Core_Action::UPDATE)
113 ) {
114 $valid = CRM_Case_BAO_Case::checkPermission($this->_activityId, 'edit',
115 $this->_activityTypeId
116 );
117 if (!$valid) {
118 CRM_Core_Error::fatal(ts('You are not authorized to access this page.'));
119 }
120 }
121
cc30482e
TO
122 foreach ($this->_caseId as $casePos => $caseId) {
123 $this->_caseType[$casePos] = CRM_Case_BAO_Case::getCaseType($caseId, 'name');
725fd9d9 124 }
6a488035
TO
125 $this->assign('caseType', $this->_caseType);
126
127 $xmlProcessorProcess = new CRM_Case_XMLProcessor_Process();
128 $isMultiClient = $xmlProcessorProcess->getAllowMultipleCaseClients();
129 $this->assign('multiClient', $isMultiClient);
130
cc30482e
TO
131 foreach ($this->_caseId as $casePos => $caseId) {
132 $clients[] = CRM_Case_BAO_Case::getContactNames($caseId);
725fd9d9 133 }
6a488035
TO
134 $this->assign('client_names', $clients);
135
725fd9d9 136 $caseIds = implode(',', $this->_caseId);
6a488035
TO
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',
725fd9d9 141 "reset=1&action=view&cid={$this->_currentlyViewedContactId}&id={$caseIds}&show=1&context={$this->_context}"
6a488035
TO
142 );
143 }
144 else {
145 $url = CRM_Utils_System::url('civicrm/contact/search/custom', 'force=1');
146 }
147 }
148 else {
149 $url = CRM_Utils_System::url('civicrm/contact/view/case',
725fd9d9 150 "reset=1&action=view&cid={$this->_currentlyViewedContactId}&id={$caseIds}&show=1"
6a488035
TO
151 );
152 }
153 if (!$this->_activityId) {
154 $caseTypes = CRM_Case_PseudoConstant::caseType();
155
156 if (empty($caseTypes) && ($this->_activityTypeName == 'Change Case Type') && !$this->_caseId) {
157 $url = CRM_Utils_System::url('civicrm/contact/view/case',
725fd9d9 158 "reset=1&action=view&cid={$this->_currentlyViewedContactId}&id={$caseIds}&show=1"
6a488035
TO
159 );
160 $session = CRM_Core_Session::singleton();
161 $session->pushUserContext($url);
162 CRM_Core_Error::statusBounce(ts("You do not have any active Case Types"));
163 }
164
165 // check if activity count is within the limit
166 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
cc30482e
TO
167 foreach ($this->_caseId as $casePos => $caseId) {
168 $caseType = $this->_caseType[$casePos];
169 $activityInst = $xmlProcessor->getMaxInstance($caseType);
6a488035 170
cc30482e 171 // If not bounce back and also provide activity edit link
725fd9d9 172 if (isset($activityInst[$this->_activityTypeName])) {
cc30482e 173 $activityCount = CRM_Case_BAO_Case::getCaseActivityCount($caseId, $this->_activityTypeId);
725fd9d9
N
174 if ($activityCount >= $activityInst[$this->_activityTypeName]) {
175 if ($activityInst[$this->_activityTypeName] == 1) {
176 $atArray = array('activity_type_id' => $this->_activityTypeId);
cc30482e 177 $activities = CRM_Case_BAO_Case::getCaseActivity($caseId,
353ffa53
TO
178 $atArray,
179 $this->_currentUserId
725fd9d9
N
180 );
181 $activities = array_keys($activities);
182 $activities = $activities[0];
183 $editUrl = CRM_Utils_System::url('civicrm/case/activity',
cc30482e 184 "reset=1&cid={$this->_currentlyViewedContactId}&caseid={$caseId}&action=update&id={$activities}"
725fd9d9
N
185 );
186 }
187 CRM_Core_Error::statusBounce(ts("You can not add another '%1' activity to this case. %2",
188 array(
189 1 => $this->_activityTypeName,
e303faaf 190 2 => ts("Do you want to <a %1>edit the existing activity</a>?", array(1 => "href='$editUrl'")),
725fd9d9
N
191 )
192 ),
193 $url
6a488035
TO
194 );
195 }
6a488035
TO
196 }
197 }
198 }
199
53c79877
SM
200 // Turn off the prompt which asks the user if they want to create separate
201 // activities when specifying multiple contacts "with" a new activity.
202 // Instead, always create one activity with all contacts together.
203 $this->supportsActivitySeparation = FALSE;
204
6a488035
TO
205 $session = CRM_Core_Session::singleton();
206 $session->pushUserContext($url);
207 }
208
209 /**
3819f101 210 * Set default values for the form.
6a488035 211 */
00be9182 212 public function setDefaultValues() {
6a488035
TO
213 $this->_defaults = parent::setDefaultValues();
214 $targetContactValues = array();
725fd9d9
N
215 foreach ($this->_caseId as $key => $val) {
216 //get all clients.
217 $clients = CRM_Case_BAO_Case::getContactNames($val);
218 if (isset($this->_activityId) && empty($_POST)) {
219 if (!CRM_Utils_Array::crmIsEmptyArray($this->_defaults['target_contact'])) {
220 $targetContactValues = array_combine(array_unique($this->_defaults['target_contact']),
221 explode(';', trim($this->_defaults['target_contact_value']))
222 );
223 //exclude all clients.
224 foreach ($clients as $clientId => $vals) {
225 if (array_key_exists($clientId, $targetContactValues)) {
226 unset($targetContactValues[$clientId]);
227 }
6a488035
TO
228 }
229 }
230 }
725fd9d9 231 $this->assign('targetContactValues', empty($targetContactValues) ? FALSE : $targetContactValues);
6a488035 232
725fd9d9
N
233 if (isset($this->_encounterMedium)) {
234 $this->_defaults['medium_id'] = $this->_encounterMedium;
235 }
236 elseif (empty($this->_defaults['medium_id'])) {
237 // set default encounter medium CRM-4816
238 $medium = CRM_Core_OptionGroup::values('encounter_medium', FALSE, FALSE, FALSE, 'AND is_default = 1');
239 if (count($medium) == 1) {
240 $this->_defaults['medium_id'] = key($medium);
241 }
6a488035 242 }
6a488035 243
725fd9d9
N
244 return $this->_defaults;
245 }
6a488035
TO
246 }
247
248 public function buildQuickForm() {
249 $this->_fields['source_contact_id']['label'] = ts('Reported By');
f7305cbc 250 unset($this->_fields['status_id']['attributes']['required']);
6a488035
TO
251
252 if ($this->_caseType) {
253 $xmlProcessor = new CRM_Case_XMLProcessor_Process();
725fd9d9
N
254 $aTypes = array();
255 foreach ($this->_caseType as $key => $val) {
256 $activityTypes = $xmlProcessor->get($val, 'ActivityTypes', TRUE);
257 $aTypes = $aTypes + $activityTypes;
258 }
6a488035
TO
259
260 // remove Open Case activity type since we're inside an existing case
261 $openCaseID = CRM_Core_OptionGroup::getValue('activity_type', 'Open Case', 'name');
262 unset($aTypes[$openCaseID]);
263 asort($aTypes);
a1a2a83d 264 $this->_fields['followup_activity_type_id']['attributes'] = array('' => '- select activity type -') + $aTypes;
6a488035
TO
265 }
266
b7617307 267 parent::buildQuickForm();
6a488035
TO
268
269 if ($this->_action & (CRM_Core_Action::DELETE | CRM_Core_Action::DETACH | CRM_Core_Action::RENEW)) {
270 return;
271 }
272
6a488035
TO
273 $this->assign('urlPath', 'civicrm/case/activity');
274
275 $encounterMediums = CRM_Case_PseudoConstant::encounterMedium();
475e9f44
CW
276 // 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.
277 // Is that really a big problem?
6a488035
TO
278 if ($this->_activityTypeFile == 'OpenCase') {
279 $this->_encounterMedium = CRM_Core_DAO::getFieldValue('CRM_Activity_DAO_Activity', $this->_activityId,
280 'medium_id'
281 );
282 if (!array_key_exists($this->_encounterMedium, $encounterMediums)) {
283 $encounterMediums[$this->_encounterMedium] = CRM_Core_OptionGroup::getLabel('encounter_medium',
284 $this->_encounterMedium,
285 FALSE
286 );
287 }
288 }
289
290 $this->add('select', 'medium_id', ts('Medium'), $encounterMediums, TRUE);
725fd9d9
N
291 $i = 0;
292 foreach ($this->_caseId as $key => $val) {
a82f59a1 293 $this->_relatedContacts[] = $rgc = CRM_Case_BAO_Case::getRelatedAndGlobalContacts($val);
725fd9d9
N
294 $contName = CRM_Case_BAO_Case::getContactNames($val);
295 foreach ($contName as $nkey => $nval) {
e547f744 296 array_push($this->_relatedContacts[$i][0], $this->_relatedContacts[$i][0]['managerOf'] = $nval['display_name']);
725fd9d9
N
297 }
298 $i++;
299 }
6a488035 300
6a488035 301 //add case client in send a copy selector.CRM-4438.
725fd9d9 302 foreach ($this->_caseId as $key => $val) {
e547f744 303 $relatedContacts[] = $relCon = CRM_Case_BAO_Case::getContactNames($val);
725fd9d9
N
304 }
305
6a488035
TO
306 if (!empty($relatedContacts)) {
307 foreach ($relatedContacts as $relatedContact) {
308 $this->_relatedContacts[] = $relatedContact;
309 }
310 }
311
312 if (!empty($this->_relatedContacts)) {
313 $checkBoxes = array();
314 foreach ($this->_relatedContacts as $id => $row) {
ee1ccac5
EH
315 foreach ($row as $key => $value) {
316 $checkBoxes[$key] = $this->addElement('checkbox', $key, NULL, NULL, array('class' => 'select-row'));
317 }
6a488035
TO
318 }
319
320 $this->addGroup($checkBoxes, 'contact_check');
321 $this->addElement('checkbox', 'toggleSelect', NULL, NULL,
d664f648 322 array('class' => 'select-rows')
6a488035
TO
323 );
324 $this->assign('searchRows', $this->_relatedContacts);
325 }
a82f59a1 326 $this->_relatedContacts = $rgc + $relCon;
6a488035
TO
327
328 $this->addFormRule(array('CRM_Case_Form_Activity', 'formRule'), $this);
329 }
330
331 /**
d2e5d2ce 332 * Global form rule.
6a488035 333 *
64bd5a0e
TO
334 * @param array $fields
335 * The input form values.
336 * @param array $files
337 * The uploaded files if any.
77b97be7
EM
338 * @param $self
339 *
72b3a70c
CW
340 * @return bool|array
341 * true if no errors, else array of errors
6a488035 342 */
00be9182 343 public static function formRule($fields, $files, $self) {
6a488035
TO
344 // skip form rule if deleting
345 if (CRM_Utils_Array::value('_qf_Activity_next_', $fields) == 'Delete' || CRM_Utils_Array::value('_qf_Activity_next_', $fields) == 'Restore') {
346 return TRUE;
347 }
348
6ea16bbf 349 return parent::formRule($fields, $files, $self);
6a488035
TO
350 }
351
352 /**
d2e5d2ce 353 * Process the form submission.
6a488035 354 *
100fef9d 355 * @param array $params
6a488035 356 */
2d4a6b57 357 public function postProcess($params = NULL) {
6a488035
TO
358 $transaction = new CRM_Core_Transaction();
359
360 if ($this->_action & CRM_Core_Action::DELETE) {
361 $statusMsg = NULL;
362
363 //block deleting activities which affects
364 //case attributes.CRM-4543
365 $activityCondition = " AND v.name IN ('Open Case', 'Change Case Type', 'Change Case Status', 'Change Case Start Date')";
366 $caseAttributeActivities = CRM_Core_OptionGroup::values('activity_type', FALSE, FALSE, FALSE, $activityCondition);
367
368 if (!array_key_exists($this->_activityTypeId, $caseAttributeActivities)) {
369 $params = array('id' => $this->_activityId);
370 $activityDelete = CRM_Activity_BAO_Activity::deleteActivity($params, TRUE);
371 if ($activityDelete) {
372 $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 />');
373 }
374 }
375 else {
376 $statusMsg = ts("Selected Activity cannot be deleted.");
377 }
378
379 $tagParams = array(
380 'entity_table' => 'civicrm_activity',
21dfd5f5 381 'entity_id' => $this->_activityId,
6a488035
TO
382 );
383 CRM_Core_BAO_EntityTag::del($tagParams);
384
385 CRM_Core_Session::setStatus('', $statusMsg, 'info');
386 return;
387 }
388
389 if ($this->_action & CRM_Core_Action::RENEW) {
50237bc9 390 $statusMsg = NULL;
391 $params = array('id' => $this->_activityId);
6a488035
TO
392 $activityRestore = CRM_Activity_BAO_Activity::restoreActivity($params);
393 if ($activityRestore) {
394 $statusMsg = ts('The selected activity has been restored.<br />');
395 }
396 CRM_Core_Session::setStatus('', $statusMsg, 'info');
397 return;
398 }
399
400 // store the submitted values in an array
401 $params = $this->controller->exportValues($this->_name);
6a488035
TO
402
403 //set parent id if its edit mode
404 if ($parentId = CRM_Utils_Array::value('parent_id', $this->_defaults)) {
405 $params['parent_id'] = $parentId;
406 }
407
6a488035
TO
408 // store the dates with proper format
409 $params['activity_date_time'] = CRM_Utils_Date::processDate($params['activity_date_time'], $params['activity_date_time_time']);
410 $params['activity_type_id'] = $this->_activityTypeId;
411
412 // format with contact (target contact) values
3911d992
DJ
413 if (isset($params['target_contact_id'])) {
414 $params['target_contact_id'] = explode(',', $params['target_contact_id']);
6a488035
TO
415 }
416 else {
417 $params['target_contact_id'] = array();
418 }
419
420 // format activity custom data
a7488080 421 if (!empty($params['hidden_custom'])) {
6a488035 422 if ($this->_activityId) {
756b5b30 423 // retrieve and include the custom data of old Activity
424 $oldActivity = civicrm_api3('Activity', 'getsingle', array('id' => $this->_activityId));
309c49b2 425 $params = array_merge($oldActivity, $params);
756b5b30 426
6a488035
TO
427 // unset custom fields-id from params since we want custom
428 // fields to be saved for new activity.
429 foreach ($params as $key => $value) {
430 $match = array();
431 if (preg_match('/^(custom_\d+_)(\d+)$/', $key, $match)) {
432 $params[$match[1] . '-1'] = $params[$key];
433
434 // for autocomplete transfer hidden value instead of label
435 if ($params[$key] && isset($params[$key . '_id'])) {
436 $params[$match[1] . '-1_id'] = $params[$key . '_id'];
437 unset($params[$key . '_id']);
438 }
439 unset($params[$key]);
440 }
441 }
442 }
443
444 // build custom data getFields array
445 $customFields = CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE, $this->_activityTypeId);
446 $customFields = CRM_Utils_Array::crmArrayMerge($customFields,
447 CRM_Core_BAO_CustomField::getFields('Activity', FALSE, FALSE,
448 NULL, NULL, TRUE
449 )
450 );
451 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
6a488035
TO
452 $this->_activityId,
453 'Activity'
454 );
455 }
456
50237bc9 457 // assigning formatted value
a7488080 458 if (!empty($params['assignee_contact_id'])) {
6a488035
TO
459 $params['assignee_contact_id'] = explode(',', $params['assignee_contact_id']);
460 }
461 else {
462 $params['assignee_contact_id'] = array();
463 }
464
6a488035
TO
465 if (isset($this->_activityId)) {
466 // activity which hasn't been modified by a user yet
467 if ($this->_defaults['is_auto'] == 1) {
468 $params['is_auto'] = 0;
469 }
470
471 // always create a revision of an case activity. CRM-4533
472 $newActParams = $params;
473
474 // add target contact values in update mode
475 if (empty($params['target_contact_id']) && !empty($this->_defaults['target_contact'])) {
476 $newActParams['target_contact_id'] = $this->_defaults['target_contact'];
477 }
6a488035
TO
478 }
479
480 if (!isset($newActParams)) {
481 // add more attachments if needed for old activity
482 CRM_Core_BAO_File::formatAttachment($params,
483 $params,
484 'civicrm_activity'
485 );
486
487 // call begin post process, before the activity is created/updated.
488 $this->beginPostProcess($params);
725fd9d9
N
489 foreach ($this->_caseId as $key => $val) {
490 $params['case_id'] = $val;
491 // activity create/update
492 $activity = CRM_Activity_BAO_Activity::create($params);
493 $vvalue[] = array('case_id' => $val, 'actId' => $activity->id);
494 // call end post process, after the activity has been created/updated.
495 $this->endPostProcess($params, $activity);
496 }
6a488035
TO
497 }
498 else {
499 // since the params we need to set are very few, and we don't want rest of the
500 // work done by bao create method , lets use dao object to make the changes
501 $params = array('id' => $this->_activityId);
502 $params['is_current_revision'] = 0;
503 $activity = new CRM_Activity_DAO_Activity();
504 $activity->copyValues($params);
505 $activity->save();
506 }
507
508 // create a new version of activity if activity was found to
509 // have been modified/created by user
510 if (isset($newActParams)) {
511 // set proper original_id
a7488080 512 if (!empty($this->_defaults['original_id'])) {
6a488035
TO
513 $newActParams['original_id'] = $this->_defaults['original_id'];
514 }
515 else {
516 $newActParams['original_id'] = $activity->id;
517 }
6a488035 518
756b5b30 519 //is_current_revision will be set to 1 by default.
6a488035
TO
520 // add attachments if any
521 CRM_Core_BAO_File::formatAttachment($newActParams,
522 $newActParams,
523 'civicrm_activity'
524 );
525
526 // call begin post process, before the activity is created/updated.
527 $this->beginPostProcess($newActParams);
725fd9d9
N
528 foreach ($this->_caseId as $key => $val) {
529 $newActParams['case_id'] = $val;
530 $activity = CRM_Activity_BAO_Activity::create($newActParams);
e547f744 531 $vvalue[] = array('case_id' => $val, 'actId' => $activity->id);
725fd9d9
N
532 // call end post process, after the activity has been created/updated.
533 $this->endPostProcess($newActParams, $activity);
534 }
6a488035
TO
535 // copy files attached to old activity if any, to new one,
536 // as long as users have not selected the 'delete attachment' option.
a7488080 537 if (empty($newActParams['is_delete_attachment'])) {
6a488035
TO
538 CRM_Core_BAO_File::copyEntityFile('civicrm_activity', $this->_activityId,
539 'civicrm_activity', $activity->id
540 );
541 }
542
543 // copy back params to original var
544 $params = $newActParams;
545 }
546
725fd9d9
N
547 foreach ($vvalue as $vkey => $vval) {
548 if ($vval['actId']) {
549 // add tags if exists
550 $tagParams = array();
551 if (!empty($params['tag'])) {
552 foreach ($params['tag'] as $tag) {
553 $tagParams[$tag] = 1;
554 }
6a488035 555 }
6a488035 556
725fd9d9
N
557 //save static tags
558 CRM_Core_BAO_EntityTag::create($tagParams, 'civicrm_activity', $vval['actId']);
6a488035 559
725fd9d9
N
560 //save free tags
561 if (isset($params['taglist']) && !empty($params['taglist'])) {
562 CRM_Core_Form_Tag::postProcess($params['taglist'], $vval['actId'], 'civicrm_activity', $this);
563 }
6a488035 564 }
6a488035 565
725fd9d9
N
566 // update existing case record if needed
567 $caseParams = $params;
568 $caseParams['id'] = $vval['case_id'];
725fd9d9
N
569 if (!empty($caseParams['case_status_id'])) {
570 $caseParams['status_id'] = $caseParams['case_status_id'];
571 }
6a488035 572
725fd9d9
N
573 // unset params intended for activities only
574 unset($caseParams['subject'], $caseParams['details'],
575 $caseParams['status_id'], $caseParams['custom']
576 );
577 $case = CRM_Case_BAO_Case::create($caseParams);
578 // create case activity record
579 $caseParams = array(
580 'activity_id' => $vval['actId'],
581 'case_id' => $vval['case_id'],
582 );
583 CRM_Case_BAO_Case::processCaseActivity($caseParams);
6a488035
TO
584 }
585
6a488035
TO
586 // Insert civicrm_log record for the activity (e.g. store the
587 // created / edited by contact id and date for the activity)
588 // Note - civicrm_log is already created by CRM_Activity_BAO_Activity::create()
8ef12e64 589
6a488035
TO
590 // send copy to selected contacts.
591 $mailStatus = '';
592 $mailToContacts = array();
593
594 //CRM-5695
595 //check for notification settings for assignee contacts
596 $selectedContacts = array('contact_check');
44f817d4 597 $activityContacts = CRM_Activity_BAO_ActivityContact::buildOptions('record_type_id', 'validate');
034500d4 598 $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
aaffa79f 599 if (Civi::settings()->get('activity_assignee_notification')) {
6a488035
TO
600 $selectedContacts[] = 'assignee_contact_id';
601 }
602
725fd9d9
N
603 foreach ($vvalue as $vkey => $vval) {
604 foreach ($selectedContacts as $dnt => $val) {
35522279 605 if (array_key_exists($val, $params) && !CRM_Utils_Array::crmIsEmptyArray($params[$val])) {
cd122921 606 if ($val == 'contact_check') {
725fd9d9 607 $mailStatus = ts("A copy of the activity has also been sent to selected contacts(s).");
cd122921 608 }
609 else {
725fd9d9
N
610 $this->_relatedContacts = CRM_Activity_BAO_ActivityAssignment::getAssigneeNames(array($vval['actId']), TRUE, FALSE);
611 $mailStatus .= ' ' . ts("A copy of the activity has also been sent to assignee contacts(s).");
cd122921 612 }
725fd9d9
N
613 //build an associative array with unique email addresses.
614 foreach ($params[$val] as $key => $value) {
615 if ($val == 'contact_check') {
616 $id = $key;
6a488035
TO
617 }
618 else {
725fd9d9
N
619 $id = $value;
620 }
621
622 if (isset($id) && array_key_exists($id, $this->_relatedContacts) && isset($this->_relatedContacts[$id]['email'])) {
623 //if email already exists in array then append with ', ' another role only otherwise add it to array.
624 if ($contactDetails = CRM_Utils_Array::value($this->_relatedContacts[$id]['email'], $mailToContacts)) {
625 $caseRole = CRM_Utils_Array::value('role', $this->_relatedContacts[$id]);
626 $mailToContacts[$this->_relatedContacts[$id]['email']]['role'] = $contactDetails['role'] . ', ' . $caseRole;
627 }
628 else {
629 $mailToContacts[$this->_relatedContacts[$id]['email']] = $this->_relatedContacts[$id];
630 }
6a488035
TO
631 }
632 }
633 }
634 }
6a488035 635
cc7982a1 636 $extraParams = array('case_id' => $vval['case_id'], 'client_id' => $this->_currentlyViewedContactId);
637 $result = CRM_Activity_BAO_Activity::sendToAssignee($activity, $mailToContacts, $extraParams);
fc110b68 638 if (empty($result)) {
6a488035
TO
639 $mailStatus = '';
640 }
6a488035 641
725fd9d9
N
642 // create follow up activity if needed
643 $followupStatus = '';
644 if (!empty($params['followup_activity_type_id'])) {
645 $followupActivity = CRM_Activity_BAO_Activity::createFollowupActivity($vval['actId'], $params);
6a488035 646
725fd9d9
N
647 if ($followupActivity) {
648 $caseParams = array(
353ffa53
TO
649 'activity_id' => $followupActivity->id,
650 'case_id' => $vval['case_id'],
725fd9d9
N
651 );
652 CRM_Case_BAO_Case::processCaseActivity($caseParams);
7c77009f 653 $followupStatus = ts("A followup activity has been scheduled.") . '<br /><br />';
725fd9d9 654 }
6a488035 655 }
7c77009f 656 $title = ts("%1 Saved", array(1 => $this->_activityTypeName));
a62473e7 657 CRM_Core_Session::setStatus($followupStatus . $mailStatus, $title, 'success');
725fd9d9 658 }
6a488035 659 }
96025800 660
6a488035 661}