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