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