Simplify function signature as parameter is not used
[civicrm-core.git] / CRM / Event / Form / Registration.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
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/**
6a488035 29 * @package CRM
6b83d5bd 30 * @copyright CiviCRM LLC (c) 2004-2019
6a488035
TO
31 */
32
33/**
3bdf1f3a 34 * This class generates form components for processing Event.
6a488035
TO
35 */
36class CRM_Event_Form_Registration extends CRM_Core_Form {
37
38 /**
100fef9d 39 * How many locationBlocks should we display?
6a488035
TO
40 *
41 * @var int
42 * @const
43 */
7da04cde 44 const LOCATION_BLOCKS = 1;
6a488035
TO
45
46 /**
66f9e52b 47 * The id of the event we are proceessing.
6a488035
TO
48 *
49 * @var int
6a488035
TO
50 */
51 public $_eventId;
52
53 /**
66f9e52b 54 * The array of ids of all the participant we are proceessing.
6a488035
TO
55 *
56 * @var int
6a488035
TO
57 */
58 protected $_participantIDS = NULL;
59
60 /**
66f9e52b 61 * The id of the participant we are proceessing.
6a488035
TO
62 *
63 * @var int
6a488035
TO
64 */
65 protected $_participantId;
66
67 /**
100fef9d 68 * Is participant able to walk registration wizard.
6a488035 69 *
d51c6add 70 * @var bool
6a488035
TO
71 */
72 public $_allowConfirmation;
73
74 /**
66f9e52b 75 * Is participant requires approval.
6a488035 76 *
d51c6add 77 * @var bool
6a488035
TO
78 */
79 public $_requireApproval;
80
81 /**
100fef9d 82 * Is event configured for waitlist.
6a488035 83 *
d51c6add 84 * @var bool
6a488035
TO
85 */
86 public $_allowWaitlist;
87
88 /**
66f9e52b 89 * Store additional participant ids.
6a488035
TO
90 * when there are pre-registered.
91 *
92 * @var array
6a488035
TO
93 */
94 public $_additionalParticipantIds;
95
96 /**
66f9e52b 97 * The mode that we are in.
6a488035
TO
98 *
99 * @var string
100 * @protect
101 */
102 public $_mode;
103
104 /**
66f9e52b 105 * The values for the contribution db object.
6a488035
TO
106 *
107 * @var array
6a488035
TO
108 */
109 public $_values;
110
111 /**
66f9e52b 112 * The paymentProcessor attributes for this page.
6a488035
TO
113 *
114 * @var array
6a488035
TO
115 */
116 public $_paymentProcessor;
117
118 /**
66f9e52b 119 * The params submitted by the form and computed by the app.
6a488035
TO
120 *
121 * @var array
6a488035
TO
122 */
123 protected $_params;
124
125 /**
66f9e52b 126 * The fields involved in this contribution page.
6a488035
TO
127 *
128 * @var array
6a488035
TO
129 */
130 public $_fields;
131
132 /**
66f9e52b 133 * The billing location id for this contribiution page.
6a488035
TO
134 *
135 * @var int
6a488035
TO
136 */
137 public $_bltID;
138
139 /**
140 * Price Set ID, if the new price set method is used
141 *
142 * @var int
6a488035
TO
143 */
144 public $_priceSetId = NULL;
145
146 /**
66f9e52b 147 * Array of fields for the price set.
6a488035
TO
148 *
149 * @var array
6a488035
TO
150 */
151 public $_priceSet;
152
153 public $_action;
154
155 public $_pcpId;
156
90b461f1
SL
157 /**
158 * Is event already full.
e70a7fc0 159 *
d51c6add 160 * @var bool
90b461f1 161 *
e70a7fc0 162 */
6a488035 163
90b461f1 164
6a488035
TO
165 public $_isEventFull;
166
167 public $_lineItem;
168 public $_lineItemParticipantsCount;
169 public $_availableRegistrations;
170
18135422 171 /**
90b461f1 172 * @var bool
18135422 173 * @deprecated
18135422 174 */
8ae4d0d3 175 public $_isBillingAddressRequiredForPayLater;
176
18135422 177 /**
178 * Is this a back office form
179 *
180 * @var bool
181 */
182 public $isBackOffice = FALSE;
183
184 /**
185 * Payment instrument iD for the transaction.
186 *
187 * This will generally be drawn from the payment processor and is ignored for
188 * front end forms.
189 *
190 * @var int
191 */
192 public $paymentInstrumentID;
193
6a488035 194 /**
66f9e52b 195 * Set variables up before form is built.
6a488035 196 */
00be9182 197 public function preProcess() {
6a488035 198 $this->_eventId = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
0ebdca14 199 $this->_action = CRM_Utils_Request::retrieve('action', 'Alphanumeric', $this, FALSE, CRM_Core_Action::ADD);
6a488035
TO
200
201 //CRM-4320
202 $this->_participantId = CRM_Utils_Request::retrieve('participantId', 'Positive', $this);
203
204 // current mode
205 $this->_mode = ($this->_action == 1024) ? 'test' : 'live';
206
207 $this->_values = $this->get('values');
208 $this->_fields = $this->get('fields');
209 $this->_bltID = $this->get('bltID');
210 $this->_paymentProcessor = $this->get('paymentProcessor');
211 $this->_priceSetId = $this->get('priceSetId');
212 $this->_priceSet = $this->get('priceSet');
213 $this->_lineItem = $this->get('lineItem');
214 $this->_isEventFull = $this->get('isEventFull');
215 $this->_lineItemParticipantsCount = $this->get('lineItemParticipants');
216 if (!is_array($this->_lineItem)) {
217 $this->_lineItem = array();
218 }
219 if (!is_array($this->_lineItemParticipantsCount)) {
220 $this->_lineItemParticipantsCount = array();
221 }
222 $this->_availableRegistrations = $this->get('availableRegistrations');
6a488035
TO
223 $this->_participantIDS = $this->get('participantIDs');
224
225 //check if participant allow to walk registration wizard.
226 $this->_allowConfirmation = $this->get('allowConfirmation');
227
228 // check for Approval
229 $this->_requireApproval = $this->get('requireApproval');
230
231 // check for waitlisting.
232 $this->_allowWaitlist = $this->get('allowWaitlist');
233
6a488035
TO
234 //get the additional participant ids.
235 $this->_additionalParticipantIds = $this->get('additionalParticipantIds');
6a488035
TO
236 $config = CRM_Core_Config::singleton();
237
238 if (!$this->_values) {
239 // create redirect URL to send folks back to event info page is registration not available
96f7c53e 240 $infoUrl = CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$this->_eventId}",
6a488035
TO
241 FALSE, NULL, FALSE, TRUE
242 );
243
244 // this is the first time we are hitting this, so check for permissions here
e2d09ab4 245 if (!CRM_Core_Permission::event(CRM_Core_Permission::EDIT, $this->_eventId, 'register for events')) {
6a488035
TO
246 CRM_Core_Error::statusBounce(ts('You do not have permission to register for this event'), $infoUrl);
247 }
248
249 // get all the values from the dao object
96f7c53e 250 $this->_values = $this->_fields = array();
6a488035
TO
251
252 //retrieve event information
253 $params = array('id' => $this->_eventId);
254 CRM_Event_BAO_Event::retrieve($params, $this->_values['event']);
9ed3cd18
E
255 // check for is_monetary status
256 $isMonetary = CRM_Utils_Array::value('is_monetary', $this->_values['event']);
257 // check for ability to add contributions of type
a8b59c2c 258 if ($isMonetary
4323dc6c
PN
259 && CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
260 && !CRM_Core_Permission::check('add contributions of type ' . CRM_Contribute_PseudoConstant::financialType($this->_values['event']['financial_type_id']))
261 ) {
9ed3cd18
E
262 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
263 }
6a488035
TO
264
265 $this->checkValidEvent($infoUrl);
6a488035
TO
266 // get the participant values, CRM-4320
267 $this->_allowConfirmation = FALSE;
268 if ($this->_participantId) {
269 $this->processFirstParticipant($this->_participantId);
270 }
6a488035
TO
271 //check for additional participants.
272 if ($this->_allowConfirmation && $this->_values['event']['is_multiple_registrations']) {
273 $additionalParticipantIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_participantId);
274 $cnt = 1;
275 foreach ($additionalParticipantIds as $additionalParticipantId) {
276 $this->_additionalParticipantIds[$cnt] = $additionalParticipantId;
277 $cnt++;
278 }
279 $this->set('additionalParticipantIds', $this->_additionalParticipantIds);
280 }
281
96f7c53e 282 $eventFull = CRM_Event_BAO_Participant::eventFull($this->_eventId, FALSE,
6a488035
TO
283 CRM_Utils_Array::value('has_waitlist', $this->_values['event'])
284 );
285
96f7c53e 286 $this->_allowWaitlist = $this->_isEventFull = FALSE;
6a488035
TO
287 if ($eventFull && !$this->_allowConfirmation) {
288 $this->_isEventFull = TRUE;
289 //lets redirecting to info only when to waiting list.
290 $this->_allowWaitlist = CRM_Utils_Array::value('has_waitlist', $this->_values['event']);
291 if (!$this->_allowWaitlist) {
292 CRM_Utils_System::redirect($infoUrl);
293 }
294 }
295 $this->set('isEventFull', $this->_isEventFull);
296 $this->set('allowWaitlist', $this->_allowWaitlist);
297
298 //check for require requires approval.
299 $this->_requireApproval = FALSE;
a7488080 300 if (!empty($this->_values['event']['requires_approval']) && !$this->_allowConfirmation) {
6a488035
TO
301 $this->_requireApproval = TRUE;
302 }
303 $this->set('requireApproval', $this->_requireApproval);
304
6a488035
TO
305 if (isset($this->_values['event']['default_role_id'])) {
306 $participant_role = CRM_Core_OptionGroup::values('participant_role');
307 $this->_values['event']['participant_role'] = $participant_role["{$this->_values['event']['default_role_id']}"];
308 }
96f7c53e 309 $isPayLater = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_eventId, 'is_pay_later');
2c5311b9 310 //check for various combinations for paylater, payment
6a488035 311 //process with paid event.
8cc574cf 312 if ($isMonetary && (!$isPayLater || !empty($this->_values['event']['payment_processor']))) {
2c5311b9 313 $this->_paymentProcessorIDs = explode(CRM_Core_DAO::VALUE_SEPARATOR, CRM_Utils_Array::value('payment_processor',
6a488035 314 $this->_values['event']
2c5311b9 315 ));
cbcb5b49 316 $this->assignPaymentProcessor($isPayLater);
6a488035 317
6a488035 318 }
6a488035 319 //init event fee.
96f7c53e 320 self::initEventFee($this, $this->_eventId);
6a488035
TO
321
322 // get the profile ids
323 $ufJoinParams = array(
324 'entity_table' => 'civicrm_event',
325 // CRM-4377: CiviEvent for the main participant, CiviEvent_Additional for additional participants
326 'module' => 'CiviEvent',
327 'entity_id' => $this->_eventId,
328 );
329 list($this->_values['custom_pre_id'],
330 $this->_values['custom_post_id']
353ffa53 331 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
6a488035
TO
332
333 // set profiles for additional participants
334 if ($this->_values['event']['is_multiple_registrations']) {
96f7c53e
PJ
335 // CRM-4377: CiviEvent for the main participant, CiviEvent_Additional for additional participants
336 $ufJoinParams['module'] = 'CiviEvent_Additional';
337
6a488035
TO
338 list($this->_values['additional_custom_pre_id'],
339 $this->_values['additional_custom_post_id'], $preActive, $postActive
353ffa53 340 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
6a488035
TO
341
342 // CRM-4377: we need to maintain backward compatibility, hence if there is profile for main contact
343 // set same profile for additional contacts.
344 if ($this->_values['custom_pre_id'] && !$this->_values['additional_custom_pre_id']) {
345 $this->_values['additional_custom_pre_id'] = $this->_values['custom_pre_id'];
346 }
347
348 if ($this->_values['custom_post_id'] && !$this->_values['additional_custom_post_id']) {
349 $this->_values['additional_custom_post_id'] = $this->_values['custom_post_id'];
350 }
6a488035
TO
351 // now check for no profile condition, in that case is_active = 0
352 if (isset($preActive) && !$preActive) {
353 unset($this->_values['additional_custom_pre_id']);
354 }
6a488035
TO
355 if (isset($postActive) && !$postActive) {
356 unset($this->_values['additional_custom_post_id']);
357 }
358 }
8345c9d3
EM
359
360 $this->assignBillingType();
6a488035 361
a6513ad5
EM
362 if ($this->_values['event']['is_monetary']) {
363 CRM_Core_Payment_Form::setPaymentFieldsByProcessor($this, $this->_paymentProcessor);
6a488035 364 }
6a488035
TO
365 $params = array('entity_id' => $this->_eventId, 'entity_table' => 'civicrm_event');
366 $this->_values['location'] = CRM_Core_BAO_Location::getValues($params, TRUE);
367
368 $this->set('values', $this->_values);
369 $this->set('fields', $this->_fields);
370
7c550ca0
WA
371 $this->_availableRegistrations
372 = CRM_Event_BAO_Participant::eventFull(
96f7c53e 373 $this->_values['event']['id'], TRUE,
6a488035
TO
374 CRM_Utils_Array::value('has_waitlist', $this->_values['event'])
375 );
376 $this->set('availableRegistrations', $this->_availableRegistrations);
377 }
6a488035
TO
378 $this->assign_by_ref('paymentProcessor', $this->_paymentProcessor);
379
380 // check if this is a paypal auto return and redirect accordingly
381 if (CRM_Core_Payment::paypalRedirect($this->_paymentProcessor)) {
382 $url = CRM_Utils_System::url('civicrm/event/register',
383 "_qf_ThankYou_display=1&qfKey={$this->controller->_key}"
384 );
385 CRM_Utils_System::redirect($url);
386 }
0f2b049e 387 // The concept of contributeMode is deprecated.
6a488035
TO
388 $this->_contributeMode = $this->get('contributeMode');
389 $this->assign('contributeMode', $this->_contributeMode);
390
d7188a5d 391 $this->setTitle($this->_values['event']['title']);
6a488035
TO
392
393 $this->assign('paidEvent', $this->_values['event']['is_monetary']);
394
395 // we do not want to display recently viewed items on Registration pages
396 $this->assign('displayRecent', FALSE);
397 // Registration page values are cleared from session, so can't use normal Printer Friendly view.
398 // Use Browser Print instead.
399 $this->assign('browserPrint', TRUE);
400
401 $isShowLocation = CRM_Utils_Array::value('is_show_location', $this->_values['event']);
402 $this->assign('isShowLocation', $isShowLocation);
6a488035
TO
403 // Handle PCP
404 $pcpId = CRM_Utils_Request::retrieve('pcpId', 'Positive', $this);
405 if ($pcpId) {
353ffa53
TO
406 $pcp = CRM_PCP_BAO_PCP::handlePcp($pcpId, 'event', $this->_values['event']);
407 $this->_pcpId = $pcp['pcpId'];
2fd5e617 408 $this->_values['event']['intro_text'] = CRM_Utils_Array::value('intro_text', $pcp['pcpInfo']);
6a488035
TO
409 }
410
411 // assign all event properties so wizard templates can display event info.
412 $this->assign('event', $this->_values['event']);
413 $this->assign('location', $this->_values['location']);
414 $this->assign('bltID', $this->_bltID);
415 $isShowLocation = CRM_Utils_Array::value('is_show_location', $this->_values['event']);
416 $this->assign('isShowLocation', $isShowLocation);
85939a77 417 CRM_Contribute_BAO_Contribution_Utils::overrideDefaultCurrency($this->_values['event']);
6a488035
TO
418
419 //lets allow user to override campaign.
420 $campID = CRM_Utils_Request::retrieve('campID', 'Positive', $this);
421 if ($campID && CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Campaign', $campID)) {
422 $this->_values['event']['campaign_id'] = $campID;
423 }
8ae4d0d3 424
f48e6cf7 425 // Set the same value for is_billing_required as contribution page so code can be shared.
426 $this->_values['is_billing_required'] = CRM_Utils_Array::value('is_billing_required', $this->_values['event']);
8ae4d0d3 427 // check if billing block is required for pay later
f48e6cf7 428 // note that I have started removing the use of isBillingAddressRequiredForPayLater in favour of letting
429 // the CRM_Core_Payment_Manual class handle it - but there are ~300 references to it in the code base so only
430 // removing in very limited cases.
8ae4d0d3 431 if (CRM_Utils_Array::value('is_pay_later', $this->_values['event'])) {
432 $this->_isBillingAddressRequiredForPayLater = CRM_Utils_Array::value('is_billing_required', $this->_values['event']);
433 $this->assign('isBillingAddressRequiredForPayLater', $this->_isBillingAddressRequiredForPayLater);
434 }
6a488035
TO
435 }
436
437 /**
66f9e52b 438 * Assign the minimal set of variables to the template.
6a488035 439 */
00be9182 440 public function assignToTemplate() {
6a488035
TO
441 //process only primary participant params
442 $this->_params = $this->get('params');
443 if (isset($this->_params[0])) {
444 $params = $this->_params[0];
445 }
446 $name = '';
a7488080 447 if (!empty($params['billing_first_name'])) {
6a488035
TO
448 $name = $params['billing_first_name'];
449 }
450
a7488080 451 if (!empty($params['billing_middle_name'])) {
6a488035
TO
452 $name .= " {$params['billing_middle_name']}";
453 }
454
a7488080 455 if (!empty($params['billing_last_name'])) {
6a488035
TO
456 $name .= " {$params['billing_last_name']}";
457 }
458 $this->assign('billingName', $name);
459 $this->set('name', $name);
460
461 $vars = array(
353ffa53
TO
462 'amount',
463 'currencyID',
464 'credit_card_type',
465 'trxn_id',
466 'amount_level',
467 'receive_date',
6a488035
TO
468 );
469
470 foreach ($vars as $v) {
a7488080 471 if (!empty($params[$v])) {
6a488035
TO
472 if ($v == 'receive_date') {
473 $this->assign($v, CRM_Utils_Date::mysqlToIso($params[$v]));
474 }
475 else {
476 $this->assign($v, $params[$v]);
477 }
478 }
de6c59ca 479 elseif (empty($params['amount'])) {
6a488035
TO
480 $this->assign($v, CRM_Utils_Array::value($v, $params));
481 }
482 }
483
0b50eca0 484 $this->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters($params, $this->_bltID));
6a488035 485
0f2b049e 486 // The concept of contributeMode is deprecated.
8cc574cf 487 if ($this->_contributeMode == 'direct' && empty($params['is_pay_later'])) {
6a488035
TO
488 $date = CRM_Utils_Date::format(CRM_Utils_Array::value('credit_card_exp_date', $params));
489 $date = CRM_Utils_Date::mysqlToIso($date);
490 $this->assign('credit_card_exp_date', $date);
491 $this->assign('credit_card_number',
492 CRM_Utils_System::mungeCreditCard(CRM_Utils_Array::value('credit_card_number', $params))
493 );
494 }
495
496 // get the email that the confirmation would have been sent to
497 $session = CRM_Core_Session::singleton();
498
499 // assign is_email_confirm to templates
500 if (isset($this->_values['event']['is_email_confirm'])) {
501 $this->assign('is_email_confirm', $this->_values['event']['is_email_confirm']);
502 }
503
504 // assign pay later stuff
505 $params['is_pay_later'] = CRM_Utils_Array::value('is_pay_later', $params, FALSE);
506 $this->assign('is_pay_later', $params['is_pay_later']);
507 if ($params['is_pay_later']) {
508 $this->assign('pay_later_text', $this->_values['event']['pay_later_text']);
509 $this->assign('pay_later_receipt', $this->_values['event']['pay_later_receipt']);
510 }
511
512 // also assign all participantIDs to the template
513 // useful in generating confirmation numbers if needed
f12392c8 514 $this->assign('participantIDs', $this->_participantIDS);
6a488035
TO
515 }
516
517 /**
66f9e52b 518 * Add the custom fields.
6a488035 519 *
100fef9d
CW
520 * @param int $id
521 * @param string $name
77b97be7 522 * @param bool $viewOnly
6a488035 523 */
00be9182 524 public function buildCustom($id, $name, $viewOnly = FALSE) {
6a488035 525 if ($id) {
353ffa53
TO
526 $button = substr($this->controller->getButtonName(), -4);
527 $cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
528 $session = CRM_Core_Session::singleton();
6a488035
TO
529 $contactID = $session->get('userID');
530
531 // we don't allow conflicting fields to be
532 // configured via profile
533 $fieldsToIgnore = array(
534 'participant_fee_amount' => 1,
535 'participant_fee_level' => 1,
536 );
537 if ($contactID) {
538 //FIX CRM-9653
539 if (is_array($id)) {
540 $fields = array();
541 foreach ($id as $profileID) {
542 $field = CRM_Core_BAO_UFGroup::getFields($profileID, FALSE, CRM_Core_Action::ADD,
543 NULL, NULL, FALSE, NULL,
544 FALSE, NULL, CRM_Core_Permission::CREATE,
545 'field_name', TRUE
546 );
547 $fields = array_merge($fields, $field);
548 }
549 }
550 else {
551 if (CRM_Core_BAO_UFGroup::filterUFGroups($id, $contactID)) {
552 $fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD,
553 NULL, NULL, FALSE, NULL,
554 FALSE, NULL, CRM_Core_Permission::CREATE,
555 'field_name', TRUE
556 );
557 }
558 }
559 }
560 else {
561 $fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD,
562 NULL, NULL, FALSE, NULL,
563 FALSE, NULL, CRM_Core_Permission::CREATE,
564 'field_name', TRUE
565 );
566 }
567
568 if (array_intersect_key($fields, $fieldsToIgnore)) {
569 $fields = array_diff_key($fields, $fieldsToIgnore);
570 CRM_Core_Session::setStatus(ts('Some of the profile fields cannot be configured for this page.'));
571 }
572 $addCaptcha = FALSE;
a2149acc 573
574 if (!empty($this->_fields)) {
575 $fields = @array_diff_assoc($fields, $this->_fields);
576 }
577
a7488080 578 if (empty($this->_params[0]['additional_participants']) &&
6a488035
TO
579 is_null($cid)
580 ) {
581 CRM_Core_BAO_Address::checkContactSharedAddressFields($fields, $contactID);
582 }
583 $this->assign($name, $fields);
6a488035
TO
584 if (is_array($fields)) {
585 foreach ($fields as $key => $field) {
586 if ($viewOnly &&
587 isset($field['data_type']) &&
588 $field['data_type'] == 'File' || ($viewOnly && $field['name'] == 'image_URL')
589 ) {
590 // ignore file upload fields
591 continue;
592 }
593 //make the field optional if primary participant
594 //have been skip the additional participant.
595 if ($button == 'skip') {
596 $field['is_required'] = FALSE;
da8d9879 597 }
71fc6ea4 598 // CRM-11316 Is ReCAPTCHA enabled for this profile AND is this an anonymous visitor
353ffa53 599 elseif ($field['add_captcha'] && !$contactID) {
6a488035
TO
600 // only add captcha for first page
601 $addCaptcha = TRUE;
602 }
6a488035 603 list($prefixName, $index) = CRM_Utils_System::explode('-', $key, 2);
6a488035
TO
604 CRM_Core_BAO_UFGroup::buildProfile($this, $field, CRM_Profile_Form::MODE_CREATE, $contactID, TRUE);
605
606 $this->_fields[$key] = $field;
607 }
608 }
4839c695 609
6a488035 610 if ($addCaptcha && !$viewOnly) {
268ff0e8 611 CRM_Utils_ReCAPTCHA::enableCaptchaOnForm($this);
6a488035
TO
612 }
613 }
614 }
615
0cf587a7 616 /**
3bdf1f3a 617 * Initiate event fee.
618 *
c490a46a 619 * @param CRM_Core_Form $form
100fef9d 620 * @param int $eventID
0cf587a7
EM
621 *
622 * @throws Exception
623 */
00be9182 624 public static function initEventFee(&$form, $eventID) {
6a488035
TO
625 // get price info
626
627 // retrive all active price set fields.
628 $discountId = CRM_Core_BAO_Discount::findSet($eventID, 'civicrm_event');
8567d0f8
PN
629 if (property_exists($form, '_discountId') && $form->_discountId) {
630 $discountId = $form->_discountId;
631 }
d4acad97
SB
632
633 //CRM-16456 get all price field including expired one.
634 $getAllPriceField = TRUE;
635 $className = CRM_Utils_System::getClassName($form);
636 if ($className == 'CRM_Event_Form_ParticipantFeeSelection' && $form->_action == CRM_Core_Action::UPDATE) {
637 $getAllPriceField = FALSE;
638 }
639
6a488035
TO
640 if ($discountId) {
641 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Core_BAO_Discount', $discountId, 'price_set_id');
d4acad97 642 $price = CRM_Price_BAO_PriceSet::initSet($form, $eventID, 'civicrm_event', $getAllPriceField, $priceSetId);
6a488035
TO
643 }
644 else {
d4acad97 645 $price = CRM_Price_BAO_PriceSet::initSet($form, $eventID, 'civicrm_event', $getAllPriceField);
6a488035 646 }
8ef12e64 647
648 if (property_exists($form, '_context') && ($form->_context == 'standalone'
353ffa53
TO
649 || $form->_context == 'participant')
650 ) {
8567d0f8 651 $discountedEvent = CRM_Core_BAO_Discount::getOptionGroup($eventID, 'civicrm_event');
481a74f4 652 if (is_array($discountedEvent)) {
8567d0f8 653 foreach ($discountedEvent as $key => $priceSetId) {
9da8dc8c 654 $priceSet = CRM_Price_BAO_PriceSet::getSetDetail($priceSetId);
8567d0f8
PN
655 $priceSet = CRM_Utils_Array::value($priceSetId, $priceSet);
656 $form->_values['discount'][$key] = CRM_Utils_Array::value('fields', $priceSet);
657 $fieldID = key($form->_values['discount'][$key]);
658 $form->_values['discount'][$key][$fieldID]['name'] = CRM_Core_DAO::getFieldValue(
9da8dc8c 659 'CRM_Price_DAO_PriceSet',
8567d0f8
PN
660 $priceSetId,
661 'title'
662 );
663 }
664 }
665 }
6a488035
TO
666 $eventFee = CRM_Utils_Array::value('fee', $form->_values);
667 if (!is_array($eventFee) || empty($eventFee)) {
668 $form->_values['fee'] = array();
669 }
670
671 //fix for non-upgraded price sets.CRM-4256.
672 if (isset($form->_isPaidEvent)) {
673 $isPaidEvent = $form->_isPaidEvent;
674 }
675 else {
676 $isPaidEvent = CRM_Utils_Array::value('is_monetary', $form->_values['event']);
677 }
a8b59c2c 678 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
4323dc6c
PN
679 && !empty($form->_values['fee'])
680 ) {
b61d1bce 681 foreach ($form->_values['fee'] as $k => $fees) {
9ed3cd18
E
682 foreach ($fees['options'] as $options) {
683 if (!CRM_Core_Permission::check('add contributions of type ' . CRM_Contribute_PseudoConstant::financialType($options['financial_type_id']))) {
b61d1bce 684 unset($form->_values['fee'][$k]);
9ed3cd18
E
685 }
686 }
687 }
688 }
6a488035
TO
689 if ($isPaidEvent && empty($form->_values['fee'])) {
690 if (CRM_Utils_System::getClassName($form) != 'CRM_Event_Form_Participant') {
691 CRM_Core_Error::fatal(ts('No Fee Level(s) or Price Set is configured for this event.<br />Click <a href=\'%1\'>CiviEvent >> Manage Event >> Configure >> Event Fees</a> to configure the Fee Level(s) or Price Set for this event.', array(1 => CRM_Utils_System::url('civicrm/event/manage/fee', 'reset=1&action=update&id=' . $form->_eventId))));
692 }
693 }
694 }
695
696 /**
66f9e52b 697 * Handle process after the confirmation of payment by User.
6a488035 698 *
100fef9d 699 * @param int $contactID
d5ce773d 700 * @param \CRM_Contribute_BAO_Contribution $contribution
6a488035 701 */
d5ce773d 702 public function confirmPostProcess($contactID = NULL, $contribution = NULL) {
6a488035
TO
703 // add/update contact information
704 $fields = array();
705 unset($this->_params['note']);
706
707 //to avoid conflict overwrite $this->_params
708 $this->_params = $this->get('value');
709
710 //get the amount of primary participant
a7488080 711 if (!empty($this->_params['is_primary'])) {
6a488035
TO
712 $this->_params['fee_amount'] = $this->get('primaryParticipantAmount');
713 }
714
715 // add participant record
bf2c70af 716 $participant = CRM_Event_Form_Registration::addParticipant($this, $contactID);
6a488035
TO
717 $this->_participantIDS[] = $participant->id;
718
719 //setting register_by_id field and primaryContactId
a7488080 720 if (!empty($this->_params['is_primary'])) {
6a488035
TO
721 $this->set('registerByID', $participant->id);
722 $this->set('primaryContactId', $contactID);
723
724 // CRM-10032
725 $this->processFirstParticipant($participant->id);
726 }
727
728 CRM_Core_BAO_CustomValueTable::postProcess($this->_params,
6a488035
TO
729 'civicrm_participant',
730 $participant->id,
731 'Participant'
732 );
733
734 $createPayment = (CRM_Utils_Array::value('amount', $this->_params, 0) != 0) ? TRUE : FALSE;
735
736 // force to create zero amount payment, CRM-5095
737 // we know the amout is zero since createPayment is false
738 if (!$createPayment &&
739 (isset($contribution) && $contribution->id) &&
740 $this->_priceSetId &&
741 $this->_lineItem
742 ) {
743 $createPayment = TRUE;
744 }
745
8cc574cf 746 if ($createPayment && $this->_values['event']['is_monetary'] && !empty($this->_params['contributionID'])) {
6a488035
TO
747 $paymentParams = array(
748 'participant_id' => $participant->id,
749 'contribution_id' => $contribution->id,
750 );
a5750507 751 $paymentPartcipant = CRM_Event_BAO_ParticipantPayment::create($paymentParams);
6a488035
TO
752 }
753
754 //set only primary participant's params for transfer checkout.
0f2b049e 755 // The concept of contributeMode is deprecated.
8cc574cf 756 if (($this->_contributeMode == 'checkout' || $this->_contributeMode == 'notify') && !empty($this->_params['is_primary'])) {
6a488035
TO
757 $this->_params['participantID'] = $participant->id;
758 $this->set('primaryParticipant', $this->_params);
759 }
760
761 $this->assign('action', $this->_action);
762
763 // create CMS user
a7488080 764 if (!empty($this->_params['cms_create_account'])) {
6a488035
TO
765 $this->_params['contactID'] = $contactID;
766
767 if (array_key_exists('email-5', $this->_params)) {
353ffa53 768 $mail = 'email-5';
0db6c3e1
TO
769 }
770 else {
6a488035
TO
771 foreach ($this->_params as $name => $dontCare) {
772 if (substr($name, 0, 5) == 'email') {
773 $mail = $name;
774 break;
775 }
776 }
777 }
778
779 // we should use primary email for
e13b1333 780 // 1. pay later participant.
781 // 2. waiting list participant.
782 // 3. require approval participant.
a7488080 783 if (!empty($this->_params['is_pay_later']) ||
e13b1333 784 $this->_allowWaitlist || $this->_requireApproval
353ffa53 785 ) {
6a488035
TO
786 $mail = 'email-Primary';
787 }
788
789 if (!CRM_Core_BAO_CMSUser::create($this->_params, $mail)) {
790 CRM_Core_Error::statusBounce(ts('Your profile is not saved and Account is not created.'));
791 }
792 }
793 }
794
795 /**
66f9e52b 796 * Process the participant.
6a488035 797 *
3ab5efa9 798 * @param CRM_Core_Form $form
100fef9d 799 * @param int $contactID
3bdf1f3a 800 *
3ab5efa9 801 * @return \CRM_Event_BAO_Participant
6a488035 802 */
bf2c70af 803 public static function addParticipant(&$form, $contactID) {
804 if (empty($form->_params)) {
7c550ca0 805 return NULL;
bf2c70af 806 }
807 $params = $form->_params;
6a488035
TO
808 $transaction = new CRM_Core_Transaction();
809
6a488035
TO
810 // handle register date CRM-4320
811 $registerDate = NULL;
bf2c70af 812 if (!empty($form->_allowConfirmation) && $form->_participantId) {
6a488035
TO
813 $registerDate = $params['participant_register_date'];
814 }
a7488080 815 elseif (!empty($params['participant_register_date']) &&
6a488035
TO
816 is_array($params['participant_register_date']) &&
817 !empty($params['participant_register_date'])
818 ) {
819 $registerDate = CRM_Utils_Date::format($params['participant_register_date']);
820 }
821
6441bcc8 822 $participantFields = CRM_Event_DAO_Participant::fields();
6ea503d4
TO
823 $participantParams = array(
824 'id' => CRM_Utils_Array::value('participant_id', $params),
6a488035 825 'contact_id' => $contactID,
bf2c70af 826 'event_id' => $form->_eventId ? $form->_eventId : $params['event_id'],
6a488035
TO
827 'status_id' => CRM_Utils_Array::value('participant_status',
828 $params, 1
829 ),
413859f5 830 'role_id' => CRM_Utils_Array::value('participant_role_id', $params) ?: self::getDefaultRoleID(),
6a488035 831 'register_date' => ($registerDate) ? $registerDate : date('YmdHis'),
6441bcc8 832 'source' => CRM_Utils_String::ellipsify(
7c550ca0 833 isset($params['participant_source']) ? CRM_Utils_Array::value('participant_source', $params) : CRM_Utils_Array::value('description', $params),
6441bcc8
NG
834 $participantFields['participant_source']['maxlength']
835 ),
6a488035
TO
836 'fee_level' => CRM_Utils_Array::value('amount_level', $params),
837 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0),
838 'fee_amount' => CRM_Utils_Array::value('fee_amount', $params),
839 'registered_by_id' => CRM_Utils_Array::value('registered_by_id', $params),
840 'discount_id' => CRM_Utils_Array::value('discount_id', $params),
841 'fee_currency' => CRM_Utils_Array::value('currencyID', $params),
842 'campaign_id' => CRM_Utils_Array::value('campaign_id', $params),
843 );
844
bf2c70af 845 if ($form->_action & CRM_Core_Action::PREVIEW || CRM_Utils_Array::value('mode', $params) == 'test') {
6a488035
TO
846 $participantParams['is_test'] = 1;
847 }
848 else {
849 $participantParams['is_test'] = 0;
850 }
851
bf2c70af 852 if (!empty($form->_params['note'])) {
853 $participantParams['note'] = $form->_params['note'];
6a488035 854 }
bf2c70af 855 elseif (!empty($form->_params['participant_note'])) {
856 $participantParams['note'] = $form->_params['participant_note'];
6a488035
TO
857 }
858
859 // reuse id if one already exists for this one (can happen
860 // with back button being hit etc)
8cc574cf 861 if (!$participantParams['id'] && !empty($params['contributionID'])) {
6a488035
TO
862 $pID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
863 $params['contributionID'],
864 'participant_id',
865 'contribution_id'
866 );
867 $participantParams['id'] = $pID;
868 }
bf2c70af 869 $participantParams['discount_id'] = CRM_Core_BAO_Discount::findSet($form->_eventId, 'civicrm_event');
6a488035
TO
870
871 if (!$participantParams['discount_id']) {
872 $participantParams['discount_id'] = "null";
873 }
874
875 $participant = CRM_Event_BAO_Participant::create($participantParams);
876
877 $transaction->commit();
878
879 return $participant;
880 }
881
413859f5
MWMC
882 /**
883 * Get the ID of the default (first) participant role
884 *
885 * @return int
886 * @throws \CiviCRM_API3_Exception
887 */
888 private static function getDefaultRoleID() {
889 return (int) civicrm_api3('OptionValue', 'getvalue', [
890 'return' => "value",
891 'option_group_id' => "participant_role",
892 'is_active' => 1,
893 'options' => ['limit' => 1, 'sort' => "is_default DESC"],
894 ]);
895 }
896
0cf587a7 897 /**
3bdf1f3a 898 * Calculate the total participant count as per params.
899 *
c490a46a
CW
900 * @param CRM_Core_Form $form
901 * @param array $params
3bdf1f3a 902 * User params.
0cf587a7
EM
903 * @param bool $skipCurrent
904 *
3bdf1f3a 905 * @return int
0cf587a7 906 */
6a488035
TO
907 public static function getParticipantCount(&$form, $params, $skipCurrent = FALSE) {
908 $totalCount = 0;
909 if (!is_array($params) || empty($params)) {
910 return $totalCount;
911 }
912
353ffa53
TO
913 $priceSetId = $form->get('priceSetId');
914 $addParticipantNum = substr($form->_name, 12);
915 $priceSetFields = $priceSetDetails = array();
6a488035
TO
916 $hasPriceFieldsCount = FALSE;
917 if ($priceSetId) {
918 $priceSetDetails = $form->get('priceSet');
919 if (isset($priceSetDetails['optionsCountTotal'])
920 && $priceSetDetails['optionsCountTotal']
921 ) {
922 $hasPriceFieldsCount = TRUE;
923 $priceSetFields = $priceSetDetails['optionsCountDetails']['fields'];
924 }
925 }
926
927 $singleFormParams = FALSE;
928 foreach ($params as $key => $val) {
929 if (!is_numeric($key)) {
930 $singleFormParams = TRUE;
931 break;
932 }
933 }
934
935 //first format the params.
936 if ($singleFormParams) {
937 $params = self::formatPriceSetParams($form, $params);
938 $params = array($params);
939 }
940
941 foreach ($params as $key => $values) {
942 if (!is_numeric($key) ||
943 $values == 'skip' ||
944 ($skipCurrent && ($addParticipantNum == $key))
945 ) {
946 continue;
947 }
948 $count = 1;
949
950 $usedCache = FALSE;
951 $cacheCount = CRM_Utils_Array::value($key, $form->_lineItemParticipantsCount);
952 if ($cacheCount && is_numeric($cacheCount)) {
953 $count = $cacheCount;
954 $usedCache = TRUE;
955 }
956
957 if (!$usedCache && $hasPriceFieldsCount) {
958 $count = 0;
959 foreach ($values as $valKey => $value) {
960 if (strpos($valKey, 'price_') === FALSE) {
961 continue;
962 }
963 $priceFieldId = substr($valKey, 6);
964 if (!$priceFieldId ||
965 !is_array($value) ||
966 !array_key_exists($priceFieldId, $priceSetFields)
967 ) {
968 continue;
969 }
970 foreach ($value as $optId => $optVal) {
971 $currentCount = $priceSetFields[$priceFieldId]['options'][$optId] * $optVal;
972 if ($currentCount) {
973 $count += $currentCount;
974 }
975 }
976 }
977 if (!$count) {
978 $count = 1;
979 }
980 }
981 $totalCount += $count;
982 }
983 if (!$totalCount) {
984 $totalCount = 1;
985 }
986
987 return $totalCount;
988 }
989
3bdf1f3a 990 /**
991 * Format user submitted price set params.
992 *
6a488035
TO
993 * Convert price set each param as an array.
994 *
3bdf1f3a 995 * @param CRM_Core_Form $form
5a4f6742 996 * @param array $params
d4dd1e85 997 * An array of user submitted params.
6a488035 998 *
a6c01b45 999 * @return array
3bdf1f3a 1000 * Formatted price set params.
0cf587a7 1001 */
6a488035
TO
1002 public static function formatPriceSetParams(&$form, $params) {
1003 if (!is_array($params) || empty($params)) {
1004 return $params;
1005 }
1006
1007 $priceSetId = $form->get('priceSetId');
1008 if (!$priceSetId) {
1009 return $params;
1010 }
1011 $priceSetDetails = $form->get('priceSet');
1012
1013 foreach ($params as $key => & $value) {
1014 $vals = array();
1015 if (strpos($key, 'price_') !== FALSE) {
1016 $fieldId = substr($key, 6);
1017 if (!array_key_exists($fieldId, $priceSetDetails['fields']) ||
1018 is_array($value) ||
1019 !$value
1020 ) {
1021 continue;
1022 }
1023 $field = $priceSetDetails['fields'][$fieldId];
1024 if ($field['html_type'] == 'Text') {
1025 $fieldOption = current($field['options']);
1026 $value = array($fieldOption['id'] => $value);
1027 }
1028 else {
1029 $value = array($value => TRUE);
1030 }
1031 }
1032 }
1033
1034 return $params;
1035 }
1036
3bdf1f3a 1037 /**
1038 * Calculate total count for each price set options.
6a488035 1039 *
3bdf1f3a 1040 * - currently selected by user.
6a488035 1041 *
3bdf1f3a 1042 * @param CRM_Core_Form $form
1043 * Form object.
0cf587a7
EM
1044 *
1045 * @return array
3bdf1f3a 1046 * array of each option w/ count total.
0cf587a7 1047 */
169be3c1 1048 public static function getPriceSetOptionCount(&$form) {
353ffa53
TO
1049 $params = $form->get('params');
1050 $priceSet = $form->get('priceSet');
6a488035
TO
1051 $priceSetId = $form->get('priceSetId');
1052
1053 $optionsCount = array();
1054 if (!$priceSetId ||
1055 !is_array($priceSet) ||
1056 empty($priceSet) ||
1057 !is_array($params) ||
1058 empty($params)
1059 ) {
1060 return $optionsCount;
1061 }
1062
1063 $priceSetFields = $priceMaxFieldDetails = array();
a7488080 1064 if (!empty($priceSet['optionsCountTotal'])) {
6a488035
TO
1065 $priceSetFields = $priceSet['optionsCountDetails']['fields'];
1066 }
1067
a7488080 1068 if (!empty($priceSet['optionsMaxValueTotal'])) {
6a488035
TO
1069 $priceMaxFieldDetails = $priceSet['optionsMaxValueDetails']['fields'];
1070 }
1071
1072 $addParticipantNum = substr($form->_name, 12);
1073 foreach ($params as $pCnt => $values) {
1074 if ($values == 'skip' ||
79b152ac 1075 $pCnt === $addParticipantNum
6a488035
TO
1076 ) {
1077 continue;
1078 }
1079
1080 foreach ($values as $valKey => $value) {
1081 if (strpos($valKey, 'price_') === FALSE) {
1082 continue;
1083 }
1084
1085 $priceFieldId = substr($valKey, 6);
1086 if (!$priceFieldId ||
1087 !is_array($value) ||
1088 !(array_key_exists($priceFieldId, $priceSetFields) || array_key_exists($priceFieldId, $priceMaxFieldDetails))
1089 ) {
1090 continue;
1091 }
1092
1093 foreach ($value as $optId => $optVal) {
1094 if (CRM_Utils_Array::value('html_type', $priceSet['fields'][$priceFieldId]) == 'Text') {
1095 $currentCount = $optVal;
1096 }
1097 else {
1098 $currentCount = 1;
1099 }
1100
1101 if (isset($priceSetFields[$priceFieldId]) && isset($priceSetFields[$priceFieldId]['options'][$optId])) {
1102 $currentCount = $priceSetFields[$priceFieldId]['options'][$optId] * $optVal;
1103 }
1104
1105 $optionsCount[$optId] = $currentCount + CRM_Utils_Array::value($optId, $optionsCount, 0);
1106 }
1107 }
1108 }
1109
1110 return $optionsCount;
1111 }
1112
0cf587a7 1113 /**
3bdf1f3a 1114 * Check if template file exists.
1115 *
0cf587a7
EM
1116 * @param string $suffix
1117 *
1118 * @return null|string
1119 */
00be9182 1120 public function checkTemplateFileExists($suffix = '') {
6a488035
TO
1121 if ($this->_eventId) {
1122 $templateName = $this->_name;
1123 if (substr($templateName, 0, 12) == 'Participant_') {
1124 $templateName = 'AdditionalParticipant';
1125 }
1126
1127 $templateFile = "CRM/Event/Form/Registration/{$this->_eventId}/{$templateName}.{$suffix}tpl";
1128 $template = CRM_Core_Form::getTemplate();
1129 if ($template->template_exists($templateFile)) {
1130 return $templateFile;
1131 }
1132 }
1133 return NULL;
1134 }
1135
0cf587a7 1136 /**
3bdf1f3a 1137 * Get template file name.
1138 *
0cf587a7
EM
1139 * @return null|string
1140 */
00be9182 1141 public function getTemplateFileName() {
6a488035
TO
1142 $fileName = $this->checkTemplateFileExists();
1143 return $fileName ? $fileName : parent::getTemplateFileName();
1144 }
1145
0cf587a7 1146 /**
3bdf1f3a 1147 * Override extra template name.
1148 *
0cf587a7
EM
1149 * @return null|string
1150 */
00be9182 1151 public function overrideExtraTemplateFileName() {
6a488035
TO
1152 $fileName = $this->checkTemplateFileExists('extra.');
1153 return $fileName ? $fileName : parent::overrideExtraTemplateFileName();
1154 }
1155
0dc0b759 1156 /**
1157 * Reset values for all options those are full.
1158 *
780422d7 1159 * @param array $optionFullIds
3bdf1f3a 1160 * @param CRM_Core_Form $form
0dc0b759 1161 */
1162 public static function resetElementValue($optionFullIds = array(), &$form) {
1163 if (!is_array($optionFullIds) ||
1164 empty($optionFullIds) ||
1165 !$form->isSubmitted()
1166 ) {
1167 return;
1168 }
1169
1170 foreach ($optionFullIds as $fldId => $optIds) {
1171 $name = "price_$fldId";
1172 if (!$form->elementExists($name)) {
1173 continue;
1174 }
1175
1176 $element = $form->getElement($name);
1177 $eleType = $element->getType();
1178
1179 $resetSubmitted = FALSE;
1180 switch ($eleType) {
1181 case 'text':
1182 if ($element->getValue() && $element->isFrozen()) {
1183 $label = "{$element->getLabel()}<tt>(x)</tt>";
1184 $element->setLabel($label);
1185 $element->setPersistantFreeze();
1186 $resetSubmitted = TRUE;
1187 }
1188 break;
1189
1190 case 'group':
1191 if (is_array($element->_elements)) {
1192 foreach ($element->_elements as $child) {
1193 $childType = $child->getType();
1194 $methodName = 'getName';
1195 if ($childType) {
1196 $methodName = 'getValue';
1197 }
1198 if (in_array($child->{$methodName}(), $optIds) && $child->isFrozen()) {
1199 $resetSubmitted = TRUE;
1200 $child->setPersistantFreeze();
1201 }
1202 }
1203 }
1204 break;
1205
1206 case 'select':
9d8d8fd0 1207 $value = $element->getValue();
1208 if (in_array($value[0], $optIds)) {
0dc0b759 1209 foreach ($element->_options as $option) {
d0ebccea 1210 if ($option['attr']['value'] === "crm_disabled_opt-{$value[0]}") {
2ae4d103 1211 $placeholder = html_entity_decode($option['text'], ENT_QUOTES, "UTF-8");
0dc0b759 1212 $element->updateAttributes(array('placeholder' => $placeholder));
1213 break;
1214 }
1215 }
1216 $resetSubmitted = TRUE;
1217 }
1218 break;
1219 }
1220
1221 //finally unset values from submitted.
1222 if ($resetSubmitted) {
1223 self::resetSubmittedValue($name, $optIds, $form);
1224 }
1225 }
1226 }
1227
1228 /**
3bdf1f3a 1229 * Reset submitted value.
1230 *
0dc0b759 1231 * @param string $elementName
1232 * @param array $optionIds
c91b34a5 1233 * @param CRM_Core_Form $form
0dc0b759 1234 */
1235 public static function resetSubmittedValue($elementName, $optionIds = array(), &$form) {
1236 if (empty($elementName) ||
1237 !$form->elementExists($elementName) ||
1238 !$form->getSubmitValue($elementName)
1239 ) {
1240 return;
1241 }
1242 foreach (array(
90b461f1
SL
1243 'constantValues',
1244 'submitValues',
1245 'defaultValues',
1246 ) as $val) {
0dc0b759 1247 $values = $form->{"_$val"};
1248 if (!is_array($values) || empty($values)) {
1249 continue;
1250 }
1251 $eleVal = CRM_Utils_Array::value($elementName, $values);
1252 if (empty($eleVal)) {
1253 continue;
1254 }
1255 if (is_array($eleVal)) {
1256 $found = FALSE;
1257 foreach ($eleVal as $keyId => $ignore) {
1258 if (in_array($keyId, $optionIds)) {
1259 $found = TRUE;
1260 unset($values[$elementName][$keyId]);
1261 }
1262 }
1263 if ($found && empty($values[$elementName][$keyId])) {
1264 $values[$elementName][$keyId] = NULL;
1265 }
1266 }
1267 else {
1268 if (!empty($keyId)) {
1269 $values[$elementName][$keyId] = NULL;
1270 }
1271 }
1272 }
1273 }
1274
da8d9879 1275 /**
3bdf1f3a 1276 * Validate price set submitted params for price option limit.
1277 *
1278 * User should select at least one price field option.
72b3a70c
CW
1279 *
1280 * @param CRM_Core_Form $form
1281 * @param array $params
1282 *
1283 * @return array
6a488035 1284 */
00be9182 1285 public static function validatePriceSet(&$form, $params) {
6a488035
TO
1286 $errors = array();
1287 $hasOptMaxValue = FALSE;
1288 if (!is_array($params) || empty($params)) {
1289 return $errors;
1290 }
1291
1292 $currentParticipantNum = substr($form->_name, 12);
1293 if (!$currentParticipantNum) {
1294 $currentParticipantNum = 0;
1295 }
1296
1297 $priceSetId = $form->get('priceSetId');
1298 $priceSetDetails = $form->get('priceSet');
1299 if (
1300 !$priceSetId ||
1301 !is_array($priceSetDetails) ||
1302 empty($priceSetDetails)
1303 ) {
1304 return $errors;
1305 }
1306
1307 $optionsCountDetails = $optionsMaxValueDetails = array();
1308 if (
1309 isset($priceSetDetails['optionsMaxValueTotal'])
1310 && $priceSetDetails['optionsMaxValueTotal']
1311 ) {
1312 $hasOptMaxValue = TRUE;
1313 $optionsMaxValueDetails = $priceSetDetails['optionsMaxValueDetails']['fields'];
1314 }
1315 if (
1316 isset($priceSetDetails['optionsCountTotal'])
1317 && $priceSetDetails['optionsCountTotal']
1318 ) {
1319 $hasOptCount = TRUE;
1320 $optionsCountDetails = $priceSetDetails['optionsCountDetails']['fields'];
1321 }
1322 $feeBlock = $form->_feeBlock;
1323
1324 if (empty($feeBlock)) {
1325 $feeBlock = $priceSetDetails['fields'];
1326 }
1327
db7f1024 1328 $optionMaxValues = $fieldSelected = array();
6a488035
TO
1329 foreach ($params as $pNum => $values) {
1330 if (!is_array($values) || $values == 'skip') {
1331 continue;
1332 }
1333
1334 foreach ($values as $valKey => $value) {
1335 if (strpos($valKey, 'price_') === FALSE) {
1336 continue;
1337 }
1338 $priceFieldId = substr($valKey, 6);
1339 $noneOptionValueSelected = FALSE;
1340 if (!$feeBlock[$priceFieldId]['is_required'] && $value == 0) {
1341 $noneOptionValueSelected = TRUE;
1342 }
1343
1344 if (
1345 !$priceFieldId ||
1346 (!$noneOptionValueSelected && !is_array($value))
1347 ) {
1348 continue;
1349 }
1350
1351 $fieldSelected[$pNum] = TRUE;
1352
1353 if (!$hasOptMaxValue || !is_array($value)) {
1354 continue;
1355 }
1356
1357 foreach ($value as $optId => $optVal) {
1358 if (CRM_Utils_Array::value('html_type', $feeBlock[$priceFieldId]) == 'Text') {
1359 $currentMaxValue = $optVal;
1360 }
1361 else {
1362 $currentMaxValue = 1;
1363 }
1364
1365 if (isset($optionsCountDetails[$priceFieldId]) && isset($optionsCountDetails[$priceFieldId]['options'][$optId])) {
1366 $currentMaxValue = $optionsCountDetails[$priceFieldId]['options'][$optId] * $optVal;
1367 }
1368 if (empty($optionMaxValues)) {
1369 $optionMaxValues[$priceFieldId][$optId] = $currentMaxValue;
1370 }
1371 else {
7c550ca0
WA
1372 $optionMaxValues[$priceFieldId][$optId]
1373 = $currentMaxValue + CRM_Utils_Array::value($optId, CRM_Utils_Array::value($priceFieldId, $optionMaxValues), 0);
6a488035 1374 }
0dc0b759 1375 $soldOutPnum[$optId] = $pNum;
6a488035
TO
1376 }
1377 }
0dc0b759 1378
1379 //validate for price field selection.
db7f1024 1380 if (empty($fieldSelected[$pNum])) {
0dc0b759 1381 $errors[$pNum]['_qf_default'] = ts('Select at least one option from Event Fee(s).');
1382 }
6a488035
TO
1383 }
1384
1385 //validate for option max value.
1386 foreach ($optionMaxValues as $fieldId => $values) {
1387 $options = CRM_Utils_Array::value('options', $feeBlock[$fieldId], array());
1388 foreach ($values as $optId => $total) {
1389 $optMax = $optionsMaxValueDetails[$fieldId]['options'][$optId];
1390 $opDbCount = CRM_Utils_Array::value('db_total_count', $options[$optId], 0);
1391 $total += $opDbCount;
0dc0b759 1392 if ($optMax && ($total > $optMax)) {
6a488035 1393 if ($opDbCount && ($opDbCount >= $optMax)) {
0dc0b759 1394 $errors[$soldOutPnum[$optId]]["price_{$fieldId}"]
7c550ca0 1395 = ts('Sorry, this option is currently sold out.');
6a488035
TO
1396 }
1397 elseif (($optMax - $opDbCount) == 1) {
0dc0b759 1398 $errors[$soldOutPnum[$optId]]["price_{$fieldId}"]
a3fdddaa 1399 = ts('Sorry, currently only a single space is available for this option.', array(1 => ($optMax - $opDbCount)));
6a488035
TO
1400 }
1401 else {
0dc0b759 1402 $errors[$soldOutPnum[$optId]]["price_{$fieldId}"]
a3fdddaa 1403 = ts('Sorry, currently only %1 spaces are available for this option.', array(1 => ($optMax - $opDbCount)));
6a488035
TO
1404 }
1405 }
1406 }
1407 }
6a488035
TO
1408 return $errors;
1409 }
1410
0cf587a7 1411 /**
3bdf1f3a 1412 * Set the first participant ID if not set.
1413 *
1414 * CRM-10032.
72b3a70c 1415 *
100fef9d 1416 * @param int $participantID
0cf587a7 1417 */
00be9182 1418 public function processFirstParticipant($participantID) {
6a488035
TO
1419 $this->_participantId = $participantID;
1420 $this->set('participantId', $this->_participantId);
1421
1422 $ids = $participantValues = array();
1423 $participantParams = array('id' => $this->_participantId);
1424 CRM_Event_BAO_Participant::getValues($participantParams, $participantValues, $ids);
1425 $this->_values['participant'] = $participantValues[$this->_participantId];
1426 $this->set('values', $this->_values);
1427
1428 // also set the allow confirmation stuff
1429 if (array_key_exists(
353ffa53
TO
1430 $this->_values['participant']['status_id'],
1431 CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Pending'")
1432 )) {
6a488035
TO
1433 $this->_allowConfirmation = TRUE;
1434 $this->set('allowConfirmation', TRUE);
1435 }
1436 }
1437
e2d09ab4 1438 /**
3bdf1f3a 1439 * Check if event is valid.
1440 *
e2d09ab4
EM
1441 * @todo - combine this with CRM_Event_BAO_Event::validRegistrationRequest
1442 * (probably extract relevant values here & call that with them & handle bounces & redirects here -as
1443 * those belong in the form layer)
1444 *
1445 * @param string $redirect
1446 */
00be9182 1447 public function checkValidEvent($redirect = NULL) {
6a488035
TO
1448 // is the event active (enabled)?
1449 if (!$this->_values['event']['is_active']) {
1450 // form is inactive, die a fatal death
1451 CRM_Core_Error::statusBounce(ts('The event you requested is currently unavailable (contact the site administrator for assistance).'));
1452 }
1453
1454 // is online registration is enabled?
1455 if (!$this->_values['event']['is_online_registration']) {
1456 CRM_Core_Error::statusBounce(ts('Online registration is not currently available for this event (contact the site administrator for assistance).'), $redirect);
1457 }
1458
1459 // is this an event template ?
a7488080 1460 if (!empty($this->_values['event']['is_template'])) {
6a488035
TO
1461 CRM_Core_Error::statusBounce(ts('Event templates are not meant to be registered.'), $redirect);
1462 }
1463
1464 $now = date('YmdHis');
1465 $startDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('registration_start_date',
353ffa53
TO
1466 $this->_values['event']
1467 ));
6a488035
TO
1468
1469 if (
1470 $startDate &&
1471 $startDate >= $now
1472 ) {
5e29b453 1473 CRM_Core_Error::statusBounce(ts('Registration for this event begins on %1', array(1 => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('registration_start_date', $this->_values['event'])))), $redirect, ts('Sorry'));
6a488035
TO
1474 }
1475
ce5694b5 1476 $regEndDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('registration_end_date',
353ffa53
TO
1477 $this->_values['event']
1478 ));
4bd9b7a9 1479 $eventEndDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('event_end_date', $this->_values['event']));
b612d89b 1480 if (($regEndDate && ($regEndDate < $now)) || (empty($regEndDate) && !empty($eventEndDate) && ($eventEndDate < $now))) {
ce5694b5 1481 $endDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('registration_end_date', $this->_values['event']));
1482 if (empty($regEndDate)) {
1483 $endDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('event_end_date', $this->_values['event']));
1484 }
5e29b453 1485 CRM_Core_Error::statusBounce(ts('Registration for this event ended on %1', array(1 => $endDate)), $redirect, ts('Sorry'));
6a488035
TO
1486 }
1487 }
96025800 1488
c039f658 1489 /**
1490 * Get the amount level for the event payment.
1491 *
1492 * The amount level is the string stored on the contribution record that describes the purchase.
1493 *
1494 * @param array $params
1495 * @param int|null $discountID
1496 *
1497 * @return string
1498 */
1499 protected function getAmountLevel($params, $discountID) {
1500 // @todo move handling of discount ID to the BAO function - preferably by converting it to a price_set with
1501 // time settings.
1502 if (!empty($this->_values['discount'][$discountID])) {
1503 return $this->_values['discount'][$discountID][$params['amount']]['label'];
1504 }
e173279c 1505 if (empty($params['priceSetId'])) {
1506 // CRM-17509 An example of this is where the person is being waitlisted & there is no payment.
1507 // ideally we would have calculated amount first & only call this is there is an
1508 // amount but the flow needs more changes for that.
1509 return '';
1510 }
c039f658 1511 return CRM_Price_BAO_PriceSet::getAmountLevelText($params);
1512 }
1513
3033e657 1514 /**
1515 * Process Registration of free event.
1516 *
1517 * @param array $params
1518 * Form values.
1519 * @param int $contactID
1520 */
1521 public function processRegistration($params, $contactID = NULL) {
1522 $session = CRM_Core_Session::singleton();
1523 $this->_participantInfo = array();
1524
1525 // CRM-4320, lets build array of cancelled additional participant ids
1526 // those are drop or skip by primary at the time of confirmation.
1527 // get all in and then unset those are confirmed.
1528 $cancelledIds = $this->_additionalParticipantIds;
1529
1530 $participantCount = array();
1531 foreach ($params as $participantNum => $record) {
1532 if ($record == 'skip') {
1533 $participantCount[$participantNum] = 'skip';
1534 }
1535 elseif ($participantNum) {
1536 $participantCount[$participantNum] = 'participant';
1537 }
1538 }
1539
1540 $registerByID = NULL;
1541 foreach ($params as $key => $value) {
1542 if ($value != 'skip') {
1543 $fields = NULL;
1544
1545 // setting register by Id and unset contactId.
1546 if (empty($value['is_primary'])) {
1547 $contactID = NULL;
1548 $registerByID = $this->get('registerByID');
1549 if ($registerByID) {
1550 $value['registered_by_id'] = $registerByID;
1551 }
1552 // get an email if one exists for the participant
1553 $participantEmail = '';
1554 foreach (array_keys($value) as $valueName) {
1555 if (substr($valueName, 0, 6) == 'email-') {
1556 $participantEmail = $value[$valueName];
1557 }
1558 }
1559 if ($participantEmail) {
1560 $this->_participantInfo[] = $participantEmail;
1561 }
1562 else {
1563 $this->_participantInfo[] = $value['first_name'] . ' ' . $value['last_name'];
1564 }
1565 }
1566 elseif (!empty($value['contact_id'])) {
1567 $contactID = $value['contact_id'];
1568 }
1569 else {
1570 $contactID = $this->getContactID();
1571 }
1572
1573 CRM_Event_Form_Registration_Confirm::fixLocationFields($value, $fields, $this);
1574 //for free event or additional participant, dont create billing email address.
1575 if (empty($value['is_primary']) || !$this->_values['event']['is_monetary']) {
1576 unset($value["email-{$this->_bltID}"]);
1577 }
1578
1579 $contactID = CRM_Event_Form_Registration_Confirm::updateContactFields($contactID, $value, $fields, $this);
1580
1581 // lets store the contactID in the session
1582 // we dont store in userID in case the user is doing multiple
1583 // transactions etc
1584 // for things like tell a friend
1585 if (!$this->getContactID() && !empty($value['is_primary'])) {
1586 $session->set('transaction.userID', $contactID);
1587 }
1588
1589 //lets get the status if require approval or waiting.
1590
1591 $waitingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
1592 if ($this->_allowWaitlist && !$this->_allowConfirmation) {
1593 $value['participant_status_id'] = $value['participant_status'] = array_search('On waitlist', $waitingStatuses);
1594 }
1595 elseif ($this->_requireApproval && !$this->_allowConfirmation) {
1596 $value['participant_status_id'] = $value['participant_status'] = array_search('Awaiting approval', $waitingStatuses);
1597 }
1598
1599 $this->set('value', $value);
d5ce773d 1600 $this->confirmPostProcess($contactID, NULL);
3033e657 1601
1602 //lets get additional participant id to cancel.
1603 if ($this->_allowConfirmation && is_array($cancelledIds)) {
1604 $additonalId = CRM_Utils_Array::value('participant_id', $value);
1605 if ($additonalId && $key = array_search($additonalId, $cancelledIds)) {
1606 unset($cancelledIds[$key]);
1607 }
1608 }
1609 }
1610 }
1611
1612 // update status and send mail to cancelled additional participants, CRM-4320
1613 if ($this->_allowConfirmation && is_array($cancelledIds) && !empty($cancelledIds)) {
1614 $cancelledId = array_search('Cancelled',
1615 CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'")
1616 );
1617 CRM_Event_BAO_Participant::transitionParticipants($cancelledIds, $cancelledId);
1618 }
1619
1620 //set information about additional participants if exists
1621 if (count($this->_participantInfo)) {
1622 $this->set('participantInfo', $this->_participantInfo);
1623 }
1624
1625 //send mail Confirmation/Receipt
1626 if ($this->_contributeMode != 'checkout' ||
1627 $this->_contributeMode != 'notify'
1628 ) {
1629 $isTest = FALSE;
1630 if ($this->_action & CRM_Core_Action::PREVIEW) {
1631 $isTest = TRUE;
1632 }
1633
1634 //handle if no additional participant.
1635 if (!$registerByID) {
1636 $registerByID = $this->get('registerByID');
1637 }
1638 $primaryContactId = $this->get('primaryContactId');
1639
1640 //build an array of custom profile and assigning it to template.
1641 $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($registerByID, NULL,
1642 $primaryContactId, $isTest, TRUE
1643 );
1644
1645 //lets carry all participant params w/ values.
1646 foreach ($additionalIDs as $participantID => $contactId) {
1647 $participantNum = NULL;
1648 if ($participantID == $registerByID) {
1649 $participantNum = 0;
1650 }
1651 else {
1652 if ($participantNum = array_search('participant', $participantCount)) {
1653 unset($participantCount[$participantNum]);
1654 }
1655 }
1656
1657 if ($participantNum === NULL) {
1658 break;
1659 }
1660
1661 //carry the participant submitted values.
1662 $this->_values['params'][$participantID] = $params[$participantNum];
1663 }
1664
1665 //lets send mails to all with meanigful text, CRM-4320.
1666 $this->assign('isOnWaitlist', $this->_allowWaitlist);
1667 $this->assign('isRequireApproval', $this->_requireApproval);
1668
1669 foreach ($additionalIDs as $participantID => $contactId) {
1670 if ($participantID == $registerByID) {
1671 //set as Primary Participant
1672 $this->assign('isPrimary', 1);
1673
1674 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($participantID, $this->_values, NULL, $isTest);
1675
1676 if (count($customProfile)) {
1677 $this->assign('customProfile', $customProfile);
1678 $this->set('customProfile', $customProfile);
1679 }
1680 }
1681 else {
1682 $this->assign('isPrimary', 0);
1683 $this->assign('customProfile', NULL);
1684 }
1685
1686 //send Confirmation mail to Primary & additional Participants if exists
1687 CRM_Event_BAO_Event::sendMail($contactId, $this->_values, $participantID, $isTest);
1688 }
1689 }
1690 }
1691
6a488035 1692}