Merge pull request #17707 from seamuslee001/ref_permission_clause_search
[civicrm-core.git] / CRM / Event / Form / Task / Batch.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17
18/**
0f57ba7a 19 * This class provides the functionality for batch profile update for events.
6a488035
TO
20 */
21class CRM_Event_Form_Task_Batch extends CRM_Event_Form_Task {
22
23 /**
eceb18cc 24 * The title of the group.
6a488035
TO
25 *
26 * @var string
27 */
28 protected $_title;
29
30 /**
eceb18cc 31 * Maximum profile fields that will be displayed.
90b461f1 32 * @var int
6a488035
TO
33 */
34 protected $_maxFields = 9;
35
36 /**
eceb18cc 37 * Variable to store redirect path.
90b461f1 38 * @var string
6a488035
TO
39 */
40 protected $_userContext;
41
42 /**
100fef9d 43 * Variable to store previous status id.
90b461f1 44 * @var array
6a488035
TO
45 */
46 protected $_fromStatusIds;
47
48 /**
eceb18cc 49 * Build all the data structures needed to build the form.
6a488035
TO
50 *
51 * @return void
03e04002 52 */
00be9182 53 public function preProcess() {
353ffa53
TO
54 /*
55 * initialize the task and row fields
56 */
6a488035
TO
57 parent::preProcess();
58
59 //get the contact read only fields to display.
be2fb01f 60 $readOnlyFields = array_merge(['sort_name' => ts('Name')],
6a488035
TO
61 CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
62 'contact_autocomplete_options',
63 TRUE, NULL, FALSE, 'name', TRUE
64 )
65 );
66 //get the read only field data.
67 $returnProperties = array_fill_keys(array_keys($readOnlyFields), 1);
68 $contactDetails = CRM_Contact_BAO_Contact_Utils::contactDetails($this->_participantIds,
69 'CiviEvent', $returnProperties
70 );
71 $this->assign('contactDetails', $contactDetails);
72 $this->assign('readOnlyFields', $readOnlyFields);
73 }
74
75 /**
eceb18cc 76 * Build the form object.
6a488035 77 *
d81bc485 78 * @throws \CRM_Core_Exception
6a488035 79 */
00be9182 80 public function buildQuickForm() {
6a488035 81 $ufGroupId = $this->get('ufGroupId');
6a488035 82 if (!$ufGroupId) {
d81bc485 83 CRM_Core_Error::statusBounce('ufGroupId is missing');
6a488035
TO
84 }
85
b581842f 86 $this->_title = ts('Update multiple participants') . ' - ' . CRM_Core_BAO_UFGroup::getTitle($ufGroupId);
6a488035
TO
87 CRM_Utils_System::setTitle($this->_title);
88 $this->addDefaultButtons(ts('Save'));
d81bc485 89
6a488035 90 $this->_fields = CRM_Core_BAO_UFGroup::getFields($ufGroupId, FALSE, CRM_Core_Action::VIEW);
f72db5fa 91 if (array_key_exists('participant_status', $this->_fields)) {
3ea7ca33 92 $this->assign('statusProfile', 1);
93 $this->assignToTemplate();
94 }
6a488035
TO
95
96 // remove file type field and then limit fields
97 $suppressFields = FALSE;
be2fb01f 98 $removehtmlTypes = ['File'];
6a488035
TO
99 foreach ($this->_fields as $name => $field) {
100 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name) &&
101 in_array($this->_fields[$name]['html_type'], $removehtmlTypes)
102 ) {
103 $suppressFields = TRUE;
104 unset($this->_fields[$name]);
105 }
106
107 //fix to reduce size as we are using this field in grid
108 if (is_array($field['attributes']) && $this->_fields[$name]['attributes']['size'] > 19) {
109 //shrink class to "form-text-medium"
110 $this->_fields[$name]['attributes']['size'] = 19;
111 }
112 }
113
114 $this->_fields = array_slice($this->_fields, 0, $this->_maxFields);
115
be2fb01f 116 $this->addButtons([
90b461f1
SL
117 [
118 'type' => 'submit',
119 'name' => ts('Update Participant(s)'),
120 'isDefault' => TRUE,
121 ],
122 [
123 'type' => 'cancel',
124 'name' => ts('Cancel'),
125 ],
126 ]);
6a488035 127
6a488035
TO
128 $this->assign('profileTitle', $this->_title);
129 $this->assign('componentIds', $this->_participantIds);
130 $fileFieldExists = FALSE;
131
132 //load all campaigns.
133 if (array_key_exists('participant_campaign_id', $this->_fields)) {
be2fb01f 134 $this->_componentCampaigns = [];
6a488035
TO
135 CRM_Core_PseudoConstant::populate($this->_componentCampaigns,
136 'CRM_Event_DAO_Participant',
137 TRUE, 'campaign_id', 'id',
138 ' id IN (' . implode(' , ', array_values($this->_participantIds)) . ' ) '
139 );
140 }
141
142 //fix for CRM-2752
143 // get the option value for custom data type
c460c196
PN
144 $customDataType = CRM_Core_OptionGroup::values('custom_data_type', FALSE, FALSE, FALSE, NULL, 'name');
145 $this->_roleCustomDataTypeID = array_search('ParticipantRole', $customDataType);
146 $this->_eventNameCustomDataTypeID = array_search('ParticipantEventName', $customDataType);
147 $this->_eventTypeCustomDataTypeID = array_search('ParticipantEventType', $customDataType);
6a488035
TO
148
149 // build custom data getFields array
150 $customFieldsRole = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, $this->_roleCustomDataTypeID);
151
152 $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, $this->_eventNameCustomDataTypeID);
d623de42
M
153 $customFieldsEventType = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, $this->_eventTypeCustomDataTypeID);
154
6a488035
TO
155 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole,
156 CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, NULL, TRUE)
157 );
d623de42 158 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEventType, $customFields);
6a488035
TO
159 $this->_customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
160
161 foreach ($this->_participantIds as $participantId) {
162 $roleId = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Participant", $participantId, 'role_id');
163 $eventId = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Participant", $participantId, 'event_id');
d623de42 164 $eventTypeId = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Event", $eventId, 'event_type_id');
6a488035
TO
165 foreach ($this->_fields as $name => $field) {
166 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
9c1bc317 167 $customValue = $this->_customFields[$customFieldID] ?? NULL;
be2fb01f 168 $entityColumnValue = [];
a7488080 169 if (!empty($customValue['extends_entity_column_value'])) {
6a488035
TO
170 $entityColumnValue = explode(CRM_Core_DAO::VALUE_SEPARATOR,
171 $customValue['extends_entity_column_value']
172 );
173 }
9c1bc317 174 $entityColumnValueRole = $entityColumnValue[$roleId] ?? NULL;
9f8dff81 175 $entityColumnValueEventType = in_array($eventTypeId, $entityColumnValue) ? $eventTypeId : NULL;
6a488035
TO
176 if (($this->_roleCustomDataTypeID == $customValue['extends_entity_column_id']) &&
177 ($entityColumnValueRole)
178 ) {
179 CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $participantId);
180 }
181 elseif (($this->_eventNameCustomDataTypeID == $customValue['extends_entity_column_id']) &&
182 ($eventId == $entityColumnValueRole)
183 ) {
184 CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $participantId);
185 }
d623de42
M
186 elseif ($this->_eventTypeCustomDataTypeID == $customValue['extends_entity_column_id'] &&
187 ($entityColumnValueEventType == $eventTypeId)
188 ) {
189 CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $participantId);
190 }
6a488035
TO
191 elseif (CRM_Utils_System::isNull($entityColumnValueRole)) {
192 CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $participantId);
193 }
194 }
195 else {
d81bc485 196 if ($field['name'] === 'participant_role') {
6a488035
TO
197 $field['is_multiple'] = TRUE;
198 }
199 // handle non custom fields
200 CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $participantId);
201 }
202 }
203 }
204
205 $this->assign('fields', $this->_fields);
206
207 // don't set the status message when form is submitted.
208 $buttonName = $this->controller->getButtonName('submit');
209
d81bc485 210 if ($suppressFields && $buttonName !== '_qf_Batch_next') {
657c89d9 211 CRM_Core_Session::setStatus(ts("File type field(s) in the selected profile are not supported for Update multiple participants."), ts('Unsupported Field Type'), 'info');
6a488035
TO
212 }
213
214 $this->addDefaultButtons(ts('Update Participant(s)'));
215 }
216
217 /**
c490a46a 218 * Set default values for the form.
6a488035 219 *
d81bc485 220 * @return array
6a488035 221 */
00be9182 222 public function setDefaultValues() {
6a488035 223 if (empty($this->_fields)) {
d81bc485 224 return [];
6a488035
TO
225 }
226
be2fb01f 227 $defaults = [];
6a488035 228 foreach ($this->_participantIds as $participantId) {
be2fb01f 229 $details[$participantId] = [];
6a488035
TO
230
231 $details[$participantId] = CRM_Event_BAO_Participant::participantDetails($participantId);
232 CRM_Core_BAO_UFGroup::setProfileDefaults(NULL, $this->_fields, $defaults, FALSE, $participantId, 'Event');
233
234 //get the from status ids, CRM-4323
235 if (array_key_exists('participant_status', $this->_fields)) {
9c1bc317 236 $this->_fromStatusIds[$participantId] = $defaults["field[$participantId][participant_status]"] ?? NULL;
6a488035
TO
237 }
238 if (array_key_exists('participant_role', $this->_fields)) {
239 if ($defaults["field[{$participantId}][participant_role]"]) {
240 $roles = $defaults["field[{$participantId}][participant_role]"];
241 foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $roles) as $k => $v) {
242 $defaults["field[$participantId][participant_role][{$v}]"] = 1;
243 }
244 unset($defaults["field[{$participantId}][participant_role]"]);
245 }
246 }
247 }
248
249 $this->assign('details', $details);
250 return $defaults;
251 }
252
253 /**
eceb18cc 254 * Process the form after the input has been submitted and validated.
6a488035
TO
255 */
256 public function postProcess() {
257 $params = $this->exportValues();
0f57ba7a 258 $this->submit($params);
6a488035 259 }
6a488035 260
0cf587a7 261 /**
100fef9d
CW
262 * @param int $participantId
263 * @param int $statusId
0cf587a7 264 *
90b461f1 265 * @return mixed
d81bc485 266 * @throws \CRM_Core_Exception
267 * @throws \CiviCRM_API3_Exception
0cf587a7 268 */
00be9182 269 public static function updatePendingOnlineContribution($participantId, $statusId) {
6a488035 270 if (!$participantId || !$statusId) {
28a04ea9 271 return NULL;
6a488035
TO
272 }
273
274 $contributionId = CRM_Contribute_BAO_Contribution::checkOnlinePendingContribution($participantId,
275 'Event'
276 );
277 if (!$contributionId) {
278 return;
279 }
280
281 //status rules.
282 //1. participant - positive => contribution - completed.
283 //2. participant - negative => contribution - cancelled.
284
285 $positiveStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Positive'");
286 $negativeStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'");
287 $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
288
289 $contributionStatusId = NULL;
290 if (array_key_exists($statusId, $positiveStatuses)) {
291 $contributionStatusId = array_search('Completed', $contributionStatuses);
292 }
293 if (array_key_exists($statusId, $negativeStatuses)) {
294 $contributionStatusId = array_search('Cancelled', $contributionStatuses);
295 }
296
297 if (!$contributionStatusId) {
298 return;
299 }
300
be2fb01f 301 $params = [
6a488035
TO
302 'component_id' => $participantId,
303 'componentName' => 'Event',
304 'contribution_id' => $contributionId,
305 'contribution_status_id' => $contributionStatusId,
0bad10e7 306 'IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved' => 1,
be2fb01f 307 ];
6a488035
TO
308
309 //change related contribution status.
e577770c 310 $updatedStatusId = self::updateContributionStatus($params);
6a488035
TO
311
312 return $updatedStatusId;
313 }
96025800 314
e577770c
EM
315 /**
316 * Update contribution status.
317 *
d81bc485 318 * @param array $params
319 *
320 * @return NULL|int
321 * @throws \CRM_Core_Exception
322 * @throws \CiviCRM_API3_Exception
323 * @throws \Exception
324 *
e577770c
EM
325 * @deprecated
326 * This is only called from one place in the code &
327 * it is unclear whether it is a function on the way in or on the way out
328 *
e577770c
EM
329 */
330 public static function updateContributionStatus($params) {
331 // get minimum required values.
9c1bc317
CW
332 $statusId = $params['contribution_status_id'] ?? NULL;
333 $componentId = $params['component_id'] ?? NULL;
334 $componentName = $params['componentName'] ?? NULL;
335 $contributionId = $params['contribution_id'] ?? NULL;
e577770c
EM
336
337 if (!$contributionId || !$componentId || !$componentName || !$statusId) {
338 return NULL;
339 }
340
be2fb01f 341 $input = $ids = $objects = [];
e577770c
EM
342
343 //get the required ids.
344 $ids['contribution'] = $contributionId;
345
346 if (!$ids['contact'] = CRM_Utils_Array::value('contact_id', $params)) {
347 $ids['contact'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
348 $contributionId,
349 'contact_id'
350 );
351 }
352
d81bc485 353 if ($componentName === 'Event') {
e577770c
EM
354 $name = 'event';
355 $ids['participant'] = $componentId;
356
357 if (!$ids['event'] = CRM_Utils_Array::value('event_id', $params)) {
358 $ids['event'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
359 $componentId,
360 'event_id'
361 );
362 }
363 }
364
d81bc485 365 if ($componentName === 'Membership') {
e577770c
EM
366 $name = 'contribute';
367 $ids['membership'] = $componentId;
368 }
369 $ids['contributionPage'] = NULL;
370 $ids['contributionRecur'] = NULL;
371 $input['component'] = $name;
372
373 $baseIPN = new CRM_Core_Payment_BaseIPN();
e577770c
EM
374
375 // reset template values.
376 $template = CRM_Core_Smarty::singleton();
377 $template->clearTemplateVars();
378
379 if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
d81bc485 380 throw new CRM_Core_Exception('validation error');
e577770c
EM
381 }
382
383 $contribution = &$objects['contribution'];
384
be2fb01f 385 $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', [
e577770c
EM
386 'labelColumn' => 'name',
387 'flip' => 1,
be2fb01f 388 ]);
9c1bc317 389 $input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'] = $params['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'] ?? NULL;
e577770c 390 if ($statusId == $contributionStatuses['Cancelled']) {
8f6fb3fa 391 $transaction = new CRM_Core_Transaction();
e577770c
EM
392 $baseIPN->cancelled($objects, $transaction, $input);
393 $transaction->commit();
394 return $statusId;
395 }
396 elseif ($statusId == $contributionStatuses['Failed']) {
8f6fb3fa 397 $transaction = new CRM_Core_Transaction();
e577770c
EM
398 $baseIPN->failed($objects, $transaction, $input);
399 $transaction->commit();
400 return $statusId;
401 }
402
403 // status is not pending
404 if ($contribution->contribution_status_id != $contributionStatuses['Pending']) {
e577770c
EM
405 return;
406 }
407
408 //set values for ipn code.
be2fb01f 409 foreach ([
90b461f1
SL
410 'fee_amount',
411 'check_number',
412 'payment_instrument_id',
413 ] as $field) {
e577770c
EM
414 if (!$input[$field] = CRM_Utils_Array::value($field, $params)) {
415 $input[$field] = $contribution->$field;
416 }
417 }
418 if (!$input['trxn_id'] = CRM_Utils_Array::value('trxn_id', $params)) {
419 $input['trxn_id'] = $contribution->invoice_id;
420 }
421 if (!$input['amount'] = CRM_Utils_Array::value('total_amount', $params)) {
422 $input['amount'] = $contribution->total_amount;
423 }
424 $input['is_test'] = $contribution->is_test;
425 $input['net_amount'] = $contribution->net_amount;
426 if (!empty($input['fee_amount']) && !empty($input['amount'])) {
427 $input['net_amount'] = $input['amount'] - $input['fee_amount'];
428 }
429
430 //complete the contribution.
2ea48796 431 // @todo use the api - ie civicrm_api3('Contribution', 'completetransaction', $input);
432 // as this method is not preferred / supported.
8f6fb3fa 433 CRM_Contribute_BAO_Contribution::completeOrder($input, $ids, $objects);
e577770c
EM
434
435 // reset template values before processing next transactions
436 $template->clearTemplateVars();
437
438 return $statusId;
439 }
440
3ea7ca33 441 /**
442 * Assign the minimal set of variables to the template.
443 */
444 public function assignToTemplate() {
be2fb01f 445 $notifyingStatuses = ['Pending from waitlist', 'Pending from approval', 'Expired', 'Cancelled'];
3ea7ca33 446 $notifyingStatuses = array_intersect($notifyingStatuses, CRM_Event_PseudoConstant::participantStatus());
1aa1efef 447 $this->assign('status', TRUE);
3ea7ca33 448 if (!empty($notifyingStatuses)) {
4a64b915
AH
449 $s = '<em>' . implode('</em>, <em>', $notifyingStatuses) . '</em>';
450 $this->assign('notifyingStatuses', $s);
3ea7ca33 451 }
3ea7ca33 452 }
453
0f57ba7a 454 /**
d81bc485 455 * @param array $params
456 *
457 * @throws \CRM_Core_Exception
458 * @throws \CiviCRM_API3_Exception
0f57ba7a 459 */
460 public function submit($params) {
461 $statusClasses = CRM_Event_PseudoConstant::participantStatusClass();
462 if (isset($params['field'])) {
463 foreach ($params['field'] as $key => $value) {
464
465 //check for custom data
466 $value['custom'] = CRM_Core_BAO_CustomField::postProcess($value,
467 $key,
468 'Participant'
469 );
a4f468b6 470 foreach (array_keys($value) as $fieldName) {
471 // Unset the original custom field now that it has been formatting to the 'custom'
472 // array as it may not be in the right format for the api as is (notably for
473 // multiple checkbox values).
3eb99314 474 // @todo extract submit functions on other Batch update classes &
475 // extend CRM_Event_Form_Task_BatchTest::testSubmit with a data provider to test them.
a4f468b6 476 if (substr($fieldName, 0, 7) === 'custom_') {
477 unset($value[$fieldName]);
478 }
479 }
0f57ba7a 480
481 $value['id'] = $key;
482
483 if (!empty($value['participant_role'])) {
484 if (is_array($value['participant_role'])) {
485 $value['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($value['participant_role']));
486 }
487 else {
488 $value['role_id'] = $value['participant_role'];
489 }
490 }
491
492 //need to send mail when status change
493 $statusChange = FALSE;
494 $relatedStatusChange = FALSE;
495 if (!empty($value['participant_status'])) {
496 $value['status_id'] = $value['participant_status'];
9c1bc317 497 $fromStatusId = $this->_fromStatusIds[$key] ?? NULL;
0f57ba7a 498 if (!$fromStatusId) {
499 $fromStatusId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $key, 'status_id');
500 }
501
502 if ($fromStatusId != $value['status_id']) {
503 $relatedStatusChange = TRUE;
504 }
505 if ($statusClasses[$fromStatusId] != $statusClasses[$value['status_id']]) {
506 $statusChange = TRUE;
507 }
508 }
509
510 unset($value['participant_status']);
511
512 civicrm_api3('Participant', 'create', $value);
513
514 //need to trigger mails when we change status
515 if ($statusChange) {
be2fb01f 516 CRM_Event_BAO_Participant::transitionParticipants([$key], $value['status_id'], $fromStatusId);
0f57ba7a 517 }
518 if ($relatedStatusChange) {
519 //update related contribution status, CRM-4395
520 self::updatePendingOnlineContribution($key, $value['status_id']);
521 }
522 }
523 CRM_Core_Session::setStatus(ts('The updates have been saved.'), ts('Saved'), 'success');
524 }
525 else {
526 CRM_Core_Session::setStatus(ts('No updates have been saved.'), ts('Not Saved'), 'alert');
527 }
528 }
529
6a488035 530}