Merge pull request #15144 from JKingsnorth/copying-events-contribution-pages
[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);
6a488035
TO
397
398 $isShowLocation = CRM_Utils_Array::value('is_show_location', $this->_values['event']);
399 $this->assign('isShowLocation', $isShowLocation);
6a488035
TO
400 // Handle PCP
401 $pcpId = CRM_Utils_Request::retrieve('pcpId', 'Positive', $this);
402 if ($pcpId) {
353ffa53
TO
403 $pcp = CRM_PCP_BAO_PCP::handlePcp($pcpId, 'event', $this->_values['event']);
404 $this->_pcpId = $pcp['pcpId'];
2fd5e617 405 $this->_values['event']['intro_text'] = CRM_Utils_Array::value('intro_text', $pcp['pcpInfo']);
6a488035
TO
406 }
407
408 // assign all event properties so wizard templates can display event info.
409 $this->assign('event', $this->_values['event']);
410 $this->assign('location', $this->_values['location']);
411 $this->assign('bltID', $this->_bltID);
412 $isShowLocation = CRM_Utils_Array::value('is_show_location', $this->_values['event']);
413 $this->assign('isShowLocation', $isShowLocation);
85939a77 414 CRM_Contribute_BAO_Contribution_Utils::overrideDefaultCurrency($this->_values['event']);
6a488035
TO
415
416 //lets allow user to override campaign.
417 $campID = CRM_Utils_Request::retrieve('campID', 'Positive', $this);
418 if ($campID && CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Campaign', $campID)) {
419 $this->_values['event']['campaign_id'] = $campID;
420 }
8ae4d0d3 421
f48e6cf7 422 // Set the same value for is_billing_required as contribution page so code can be shared.
423 $this->_values['is_billing_required'] = CRM_Utils_Array::value('is_billing_required', $this->_values['event']);
8ae4d0d3 424 // check if billing block is required for pay later
f48e6cf7 425 // note that I have started removing the use of isBillingAddressRequiredForPayLater in favour of letting
426 // the CRM_Core_Payment_Manual class handle it - but there are ~300 references to it in the code base so only
427 // removing in very limited cases.
8ae4d0d3 428 if (CRM_Utils_Array::value('is_pay_later', $this->_values['event'])) {
429 $this->_isBillingAddressRequiredForPayLater = CRM_Utils_Array::value('is_billing_required', $this->_values['event']);
430 $this->assign('isBillingAddressRequiredForPayLater', $this->_isBillingAddressRequiredForPayLater);
431 }
6a488035
TO
432 }
433
434 /**
66f9e52b 435 * Assign the minimal set of variables to the template.
6a488035 436 */
00be9182 437 public function assignToTemplate() {
6a488035
TO
438 //process only primary participant params
439 $this->_params = $this->get('params');
440 if (isset($this->_params[0])) {
441 $params = $this->_params[0];
442 }
443 $name = '';
a7488080 444 if (!empty($params['billing_first_name'])) {
6a488035
TO
445 $name = $params['billing_first_name'];
446 }
447
a7488080 448 if (!empty($params['billing_middle_name'])) {
6a488035
TO
449 $name .= " {$params['billing_middle_name']}";
450 }
451
a7488080 452 if (!empty($params['billing_last_name'])) {
6a488035
TO
453 $name .= " {$params['billing_last_name']}";
454 }
455 $this->assign('billingName', $name);
456 $this->set('name', $name);
457
458 $vars = array(
353ffa53
TO
459 'amount',
460 'currencyID',
461 'credit_card_type',
462 'trxn_id',
463 'amount_level',
464 'receive_date',
6a488035
TO
465 );
466
467 foreach ($vars as $v) {
a7488080 468 if (!empty($params[$v])) {
6a488035
TO
469 if ($v == 'receive_date') {
470 $this->assign($v, CRM_Utils_Date::mysqlToIso($params[$v]));
471 }
472 else {
473 $this->assign($v, $params[$v]);
474 }
475 }
de6c59ca 476 elseif (empty($params['amount'])) {
6a488035
TO
477 $this->assign($v, CRM_Utils_Array::value($v, $params));
478 }
479 }
480
0b50eca0 481 $this->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters($params, $this->_bltID));
6a488035 482
0f2b049e 483 // The concept of contributeMode is deprecated.
8cc574cf 484 if ($this->_contributeMode == 'direct' && empty($params['is_pay_later'])) {
6a488035
TO
485 $date = CRM_Utils_Date::format(CRM_Utils_Array::value('credit_card_exp_date', $params));
486 $date = CRM_Utils_Date::mysqlToIso($date);
487 $this->assign('credit_card_exp_date', $date);
488 $this->assign('credit_card_number',
489 CRM_Utils_System::mungeCreditCard(CRM_Utils_Array::value('credit_card_number', $params))
490 );
491 }
492
493 // get the email that the confirmation would have been sent to
494 $session = CRM_Core_Session::singleton();
495
496 // assign is_email_confirm to templates
497 if (isset($this->_values['event']['is_email_confirm'])) {
498 $this->assign('is_email_confirm', $this->_values['event']['is_email_confirm']);
499 }
500
501 // assign pay later stuff
502 $params['is_pay_later'] = CRM_Utils_Array::value('is_pay_later', $params, FALSE);
503 $this->assign('is_pay_later', $params['is_pay_later']);
504 if ($params['is_pay_later']) {
505 $this->assign('pay_later_text', $this->_values['event']['pay_later_text']);
506 $this->assign('pay_later_receipt', $this->_values['event']['pay_later_receipt']);
507 }
508
509 // also assign all participantIDs to the template
510 // useful in generating confirmation numbers if needed
f12392c8 511 $this->assign('participantIDs', $this->_participantIDS);
6a488035
TO
512 }
513
514 /**
66f9e52b 515 * Add the custom fields.
6a488035 516 *
100fef9d
CW
517 * @param int $id
518 * @param string $name
77b97be7 519 * @param bool $viewOnly
6a488035 520 */
00be9182 521 public function buildCustom($id, $name, $viewOnly = FALSE) {
6a488035 522 if ($id) {
353ffa53
TO
523 $button = substr($this->controller->getButtonName(), -4);
524 $cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
525 $session = CRM_Core_Session::singleton();
6a488035
TO
526 $contactID = $session->get('userID');
527
528 // we don't allow conflicting fields to be
529 // configured via profile
530 $fieldsToIgnore = array(
531 'participant_fee_amount' => 1,
532 'participant_fee_level' => 1,
533 );
534 if ($contactID) {
535 //FIX CRM-9653
536 if (is_array($id)) {
537 $fields = array();
538 foreach ($id as $profileID) {
539 $field = CRM_Core_BAO_UFGroup::getFields($profileID, FALSE, CRM_Core_Action::ADD,
540 NULL, NULL, FALSE, NULL,
541 FALSE, NULL, CRM_Core_Permission::CREATE,
542 'field_name', TRUE
543 );
544 $fields = array_merge($fields, $field);
545 }
546 }
547 else {
548 if (CRM_Core_BAO_UFGroup::filterUFGroups($id, $contactID)) {
549 $fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD,
550 NULL, NULL, FALSE, NULL,
551 FALSE, NULL, CRM_Core_Permission::CREATE,
552 'field_name', TRUE
553 );
554 }
555 }
556 }
557 else {
558 $fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD,
559 NULL, NULL, FALSE, NULL,
560 FALSE, NULL, CRM_Core_Permission::CREATE,
561 'field_name', TRUE
562 );
563 }
564
565 if (array_intersect_key($fields, $fieldsToIgnore)) {
566 $fields = array_diff_key($fields, $fieldsToIgnore);
567 CRM_Core_Session::setStatus(ts('Some of the profile fields cannot be configured for this page.'));
568 }
569 $addCaptcha = FALSE;
a2149acc 570
571 if (!empty($this->_fields)) {
572 $fields = @array_diff_assoc($fields, $this->_fields);
573 }
574
a7488080 575 if (empty($this->_params[0]['additional_participants']) &&
6a488035
TO
576 is_null($cid)
577 ) {
578 CRM_Core_BAO_Address::checkContactSharedAddressFields($fields, $contactID);
579 }
580 $this->assign($name, $fields);
6a488035
TO
581 if (is_array($fields)) {
582 foreach ($fields as $key => $field) {
583 if ($viewOnly &&
584 isset($field['data_type']) &&
585 $field['data_type'] == 'File' || ($viewOnly && $field['name'] == 'image_URL')
586 ) {
587 // ignore file upload fields
588 continue;
589 }
590 //make the field optional if primary participant
591 //have been skip the additional participant.
592 if ($button == 'skip') {
593 $field['is_required'] = FALSE;
da8d9879 594 }
71fc6ea4 595 // CRM-11316 Is ReCAPTCHA enabled for this profile AND is this an anonymous visitor
353ffa53 596 elseif ($field['add_captcha'] && !$contactID) {
6a488035
TO
597 // only add captcha for first page
598 $addCaptcha = TRUE;
599 }
6a488035 600 list($prefixName, $index) = CRM_Utils_System::explode('-', $key, 2);
6a488035
TO
601 CRM_Core_BAO_UFGroup::buildProfile($this, $field, CRM_Profile_Form::MODE_CREATE, $contactID, TRUE);
602
603 $this->_fields[$key] = $field;
604 }
605 }
4839c695 606
6a488035 607 if ($addCaptcha && !$viewOnly) {
268ff0e8 608 CRM_Utils_ReCAPTCHA::enableCaptchaOnForm($this);
6a488035
TO
609 }
610 }
611 }
612
0cf587a7 613 /**
3bdf1f3a 614 * Initiate event fee.
615 *
c490a46a 616 * @param CRM_Core_Form $form
100fef9d 617 * @param int $eventID
0cf587a7
EM
618 *
619 * @throws Exception
620 */
00be9182 621 public static function initEventFee(&$form, $eventID) {
6a488035
TO
622 // get price info
623
624 // retrive all active price set fields.
625 $discountId = CRM_Core_BAO_Discount::findSet($eventID, 'civicrm_event');
8567d0f8
PN
626 if (property_exists($form, '_discountId') && $form->_discountId) {
627 $discountId = $form->_discountId;
628 }
d4acad97
SB
629
630 //CRM-16456 get all price field including expired one.
631 $getAllPriceField = TRUE;
632 $className = CRM_Utils_System::getClassName($form);
633 if ($className == 'CRM_Event_Form_ParticipantFeeSelection' && $form->_action == CRM_Core_Action::UPDATE) {
634 $getAllPriceField = FALSE;
635 }
636
6a488035
TO
637 if ($discountId) {
638 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Core_BAO_Discount', $discountId, 'price_set_id');
d4acad97 639 $price = CRM_Price_BAO_PriceSet::initSet($form, $eventID, 'civicrm_event', $getAllPriceField, $priceSetId);
6a488035
TO
640 }
641 else {
d4acad97 642 $price = CRM_Price_BAO_PriceSet::initSet($form, $eventID, 'civicrm_event', $getAllPriceField);
6a488035 643 }
8ef12e64 644
645 if (property_exists($form, '_context') && ($form->_context == 'standalone'
353ffa53
TO
646 || $form->_context == 'participant')
647 ) {
8567d0f8 648 $discountedEvent = CRM_Core_BAO_Discount::getOptionGroup($eventID, 'civicrm_event');
481a74f4 649 if (is_array($discountedEvent)) {
8567d0f8 650 foreach ($discountedEvent as $key => $priceSetId) {
9da8dc8c 651 $priceSet = CRM_Price_BAO_PriceSet::getSetDetail($priceSetId);
8567d0f8
PN
652 $priceSet = CRM_Utils_Array::value($priceSetId, $priceSet);
653 $form->_values['discount'][$key] = CRM_Utils_Array::value('fields', $priceSet);
654 $fieldID = key($form->_values['discount'][$key]);
655 $form->_values['discount'][$key][$fieldID]['name'] = CRM_Core_DAO::getFieldValue(
9da8dc8c 656 'CRM_Price_DAO_PriceSet',
8567d0f8
PN
657 $priceSetId,
658 'title'
659 );
660 }
661 }
662 }
6a488035
TO
663 $eventFee = CRM_Utils_Array::value('fee', $form->_values);
664 if (!is_array($eventFee) || empty($eventFee)) {
665 $form->_values['fee'] = array();
666 }
667
668 //fix for non-upgraded price sets.CRM-4256.
669 if (isset($form->_isPaidEvent)) {
670 $isPaidEvent = $form->_isPaidEvent;
671 }
672 else {
673 $isPaidEvent = CRM_Utils_Array::value('is_monetary', $form->_values['event']);
674 }
a8b59c2c 675 if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
4323dc6c
PN
676 && !empty($form->_values['fee'])
677 ) {
b61d1bce 678 foreach ($form->_values['fee'] as $k => $fees) {
9ed3cd18
E
679 foreach ($fees['options'] as $options) {
680 if (!CRM_Core_Permission::check('add contributions of type ' . CRM_Contribute_PseudoConstant::financialType($options['financial_type_id']))) {
b61d1bce 681 unset($form->_values['fee'][$k]);
9ed3cd18
E
682 }
683 }
684 }
685 }
6a488035
TO
686 if ($isPaidEvent && empty($form->_values['fee'])) {
687 if (CRM_Utils_System::getClassName($form) != 'CRM_Event_Form_Participant') {
688 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))));
689 }
690 }
691 }
692
693 /**
66f9e52b 694 * Handle process after the confirmation of payment by User.
6a488035 695 *
100fef9d 696 * @param int $contactID
d5ce773d 697 * @param \CRM_Contribute_BAO_Contribution $contribution
6a488035 698 */
d5ce773d 699 public function confirmPostProcess($contactID = NULL, $contribution = NULL) {
6a488035 700 // add/update contact information
6a488035
TO
701 unset($this->_params['note']);
702
703 //to avoid conflict overwrite $this->_params
704 $this->_params = $this->get('value');
705
706 //get the amount of primary participant
a7488080 707 if (!empty($this->_params['is_primary'])) {
6a488035
TO
708 $this->_params['fee_amount'] = $this->get('primaryParticipantAmount');
709 }
710
711 // add participant record
bf2c70af 712 $participant = CRM_Event_Form_Registration::addParticipant($this, $contactID);
6a488035
TO
713 $this->_participantIDS[] = $participant->id;
714
715 //setting register_by_id field and primaryContactId
a7488080 716 if (!empty($this->_params['is_primary'])) {
6a488035
TO
717 $this->set('registerByID', $participant->id);
718 $this->set('primaryContactId', $contactID);
719
720 // CRM-10032
721 $this->processFirstParticipant($participant->id);
722 }
c0f73fab 723 $this->_params['participantID'] = $participant->id;
724 $this->set('primaryParticipant', $this->_params);
6a488035
TO
725
726 CRM_Core_BAO_CustomValueTable::postProcess($this->_params,
6a488035
TO
727 'civicrm_participant',
728 $participant->id,
729 'Participant'
730 );
731
732 $createPayment = (CRM_Utils_Array::value('amount', $this->_params, 0) != 0) ? TRUE : FALSE;
733
734 // force to create zero amount payment, CRM-5095
735 // we know the amout is zero since createPayment is false
736 if (!$createPayment &&
737 (isset($contribution) && $contribution->id) &&
738 $this->_priceSetId &&
739 $this->_lineItem
740 ) {
741 $createPayment = TRUE;
742 }
743
8cc574cf 744 if ($createPayment && $this->_values['event']['is_monetary'] && !empty($this->_params['contributionID'])) {
6a488035
TO
745 $paymentParams = array(
746 'participant_id' => $participant->id,
747 'contribution_id' => $contribution->id,
748 );
a5750507 749 $paymentPartcipant = CRM_Event_BAO_ParticipantPayment::create($paymentParams);
6a488035
TO
750 }
751
6a488035
TO
752 $this->assign('action', $this->_action);
753
754 // create CMS user
a7488080 755 if (!empty($this->_params['cms_create_account'])) {
6a488035
TO
756 $this->_params['contactID'] = $contactID;
757
758 if (array_key_exists('email-5', $this->_params)) {
353ffa53 759 $mail = 'email-5';
0db6c3e1
TO
760 }
761 else {
6a488035
TO
762 foreach ($this->_params as $name => $dontCare) {
763 if (substr($name, 0, 5) == 'email') {
764 $mail = $name;
765 break;
766 }
767 }
768 }
769
770 // we should use primary email for
e13b1333 771 // 1. pay later participant.
772 // 2. waiting list participant.
773 // 3. require approval participant.
a7488080 774 if (!empty($this->_params['is_pay_later']) ||
e13b1333 775 $this->_allowWaitlist || $this->_requireApproval
353ffa53 776 ) {
6a488035
TO
777 $mail = 'email-Primary';
778 }
779
780 if (!CRM_Core_BAO_CMSUser::create($this->_params, $mail)) {
781 CRM_Core_Error::statusBounce(ts('Your profile is not saved and Account is not created.'));
782 }
783 }
784 }
785
786 /**
66f9e52b 787 * Process the participant.
6a488035 788 *
3ab5efa9 789 * @param CRM_Core_Form $form
100fef9d 790 * @param int $contactID
3bdf1f3a 791 *
3ab5efa9 792 * @return \CRM_Event_BAO_Participant
6a488035 793 */
bf2c70af 794 public static function addParticipant(&$form, $contactID) {
795 if (empty($form->_params)) {
7c550ca0 796 return NULL;
bf2c70af 797 }
798 $params = $form->_params;
6a488035
TO
799 $transaction = new CRM_Core_Transaction();
800
6a488035
TO
801 // handle register date CRM-4320
802 $registerDate = NULL;
bf2c70af 803 if (!empty($form->_allowConfirmation) && $form->_participantId) {
6a488035
TO
804 $registerDate = $params['participant_register_date'];
805 }
a7488080 806 elseif (!empty($params['participant_register_date']) &&
6a488035
TO
807 is_array($params['participant_register_date']) &&
808 !empty($params['participant_register_date'])
809 ) {
810 $registerDate = CRM_Utils_Date::format($params['participant_register_date']);
811 }
812
6441bcc8 813 $participantFields = CRM_Event_DAO_Participant::fields();
6ea503d4
TO
814 $participantParams = array(
815 'id' => CRM_Utils_Array::value('participant_id', $params),
6a488035 816 'contact_id' => $contactID,
bf2c70af 817 'event_id' => $form->_eventId ? $form->_eventId : $params['event_id'],
6a488035
TO
818 'status_id' => CRM_Utils_Array::value('participant_status',
819 $params, 1
820 ),
413859f5 821 'role_id' => CRM_Utils_Array::value('participant_role_id', $params) ?: self::getDefaultRoleID(),
6a488035 822 'register_date' => ($registerDate) ? $registerDate : date('YmdHis'),
6441bcc8 823 'source' => CRM_Utils_String::ellipsify(
7c550ca0 824 isset($params['participant_source']) ? CRM_Utils_Array::value('participant_source', $params) : CRM_Utils_Array::value('description', $params),
6441bcc8
NG
825 $participantFields['participant_source']['maxlength']
826 ),
6a488035
TO
827 'fee_level' => CRM_Utils_Array::value('amount_level', $params),
828 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0),
829 'fee_amount' => CRM_Utils_Array::value('fee_amount', $params),
830 'registered_by_id' => CRM_Utils_Array::value('registered_by_id', $params),
831 'discount_id' => CRM_Utils_Array::value('discount_id', $params),
832 'fee_currency' => CRM_Utils_Array::value('currencyID', $params),
833 'campaign_id' => CRM_Utils_Array::value('campaign_id', $params),
834 );
835
bf2c70af 836 if ($form->_action & CRM_Core_Action::PREVIEW || CRM_Utils_Array::value('mode', $params) == 'test') {
6a488035
TO
837 $participantParams['is_test'] = 1;
838 }
839 else {
840 $participantParams['is_test'] = 0;
841 }
842
bf2c70af 843 if (!empty($form->_params['note'])) {
844 $participantParams['note'] = $form->_params['note'];
6a488035 845 }
bf2c70af 846 elseif (!empty($form->_params['participant_note'])) {
847 $participantParams['note'] = $form->_params['participant_note'];
6a488035
TO
848 }
849
850 // reuse id if one already exists for this one (can happen
851 // with back button being hit etc)
8cc574cf 852 if (!$participantParams['id'] && !empty($params['contributionID'])) {
6a488035
TO
853 $pID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
854 $params['contributionID'],
855 'participant_id',
856 'contribution_id'
857 );
858 $participantParams['id'] = $pID;
859 }
bf2c70af 860 $participantParams['discount_id'] = CRM_Core_BAO_Discount::findSet($form->_eventId, 'civicrm_event');
6a488035
TO
861
862 if (!$participantParams['discount_id']) {
863 $participantParams['discount_id'] = "null";
864 }
865
866 $participant = CRM_Event_BAO_Participant::create($participantParams);
867
868 $transaction->commit();
869
870 return $participant;
871 }
872
413859f5
MWMC
873 /**
874 * Get the ID of the default (first) participant role
875 *
876 * @return int
877 * @throws \CiviCRM_API3_Exception
878 */
879 private static function getDefaultRoleID() {
880 return (int) civicrm_api3('OptionValue', 'getvalue', [
881 'return' => "value",
882 'option_group_id' => "participant_role",
883 'is_active' => 1,
884 'options' => ['limit' => 1, 'sort' => "is_default DESC"],
885 ]);
886 }
887
0cf587a7 888 /**
3bdf1f3a 889 * Calculate the total participant count as per params.
890 *
c490a46a
CW
891 * @param CRM_Core_Form $form
892 * @param array $params
3bdf1f3a 893 * User params.
0cf587a7
EM
894 * @param bool $skipCurrent
895 *
3bdf1f3a 896 * @return int
0cf587a7 897 */
6a488035
TO
898 public static function getParticipantCount(&$form, $params, $skipCurrent = FALSE) {
899 $totalCount = 0;
900 if (!is_array($params) || empty($params)) {
901 return $totalCount;
902 }
903
353ffa53
TO
904 $priceSetId = $form->get('priceSetId');
905 $addParticipantNum = substr($form->_name, 12);
906 $priceSetFields = $priceSetDetails = array();
6a488035
TO
907 $hasPriceFieldsCount = FALSE;
908 if ($priceSetId) {
909 $priceSetDetails = $form->get('priceSet');
910 if (isset($priceSetDetails['optionsCountTotal'])
911 && $priceSetDetails['optionsCountTotal']
912 ) {
913 $hasPriceFieldsCount = TRUE;
914 $priceSetFields = $priceSetDetails['optionsCountDetails']['fields'];
915 }
916 }
917
918 $singleFormParams = FALSE;
919 foreach ($params as $key => $val) {
920 if (!is_numeric($key)) {
921 $singleFormParams = TRUE;
922 break;
923 }
924 }
925
926 //first format the params.
927 if ($singleFormParams) {
928 $params = self::formatPriceSetParams($form, $params);
929 $params = array($params);
930 }
931
932 foreach ($params as $key => $values) {
933 if (!is_numeric($key) ||
934 $values == 'skip' ||
935 ($skipCurrent && ($addParticipantNum == $key))
936 ) {
937 continue;
938 }
939 $count = 1;
940
941 $usedCache = FALSE;
942 $cacheCount = CRM_Utils_Array::value($key, $form->_lineItemParticipantsCount);
943 if ($cacheCount && is_numeric($cacheCount)) {
944 $count = $cacheCount;
945 $usedCache = TRUE;
946 }
947
948 if (!$usedCache && $hasPriceFieldsCount) {
949 $count = 0;
950 foreach ($values as $valKey => $value) {
951 if (strpos($valKey, 'price_') === FALSE) {
952 continue;
953 }
954 $priceFieldId = substr($valKey, 6);
955 if (!$priceFieldId ||
956 !is_array($value) ||
957 !array_key_exists($priceFieldId, $priceSetFields)
958 ) {
959 continue;
960 }
961 foreach ($value as $optId => $optVal) {
962 $currentCount = $priceSetFields[$priceFieldId]['options'][$optId] * $optVal;
963 if ($currentCount) {
964 $count += $currentCount;
965 }
966 }
967 }
968 if (!$count) {
969 $count = 1;
970 }
971 }
972 $totalCount += $count;
973 }
974 if (!$totalCount) {
975 $totalCount = 1;
976 }
977
978 return $totalCount;
979 }
980
3bdf1f3a 981 /**
982 * Format user submitted price set params.
983 *
6a488035
TO
984 * Convert price set each param as an array.
985 *
3bdf1f3a 986 * @param CRM_Core_Form $form
5a4f6742 987 * @param array $params
d4dd1e85 988 * An array of user submitted params.
6a488035 989 *
a6c01b45 990 * @return array
3bdf1f3a 991 * Formatted price set params.
0cf587a7 992 */
6a488035
TO
993 public static function formatPriceSetParams(&$form, $params) {
994 if (!is_array($params) || empty($params)) {
995 return $params;
996 }
997
998 $priceSetId = $form->get('priceSetId');
999 if (!$priceSetId) {
1000 return $params;
1001 }
1002 $priceSetDetails = $form->get('priceSet');
1003
1004 foreach ($params as $key => & $value) {
1005 $vals = array();
1006 if (strpos($key, 'price_') !== FALSE) {
1007 $fieldId = substr($key, 6);
1008 if (!array_key_exists($fieldId, $priceSetDetails['fields']) ||
1009 is_array($value) ||
1010 !$value
1011 ) {
1012 continue;
1013 }
1014 $field = $priceSetDetails['fields'][$fieldId];
1015 if ($field['html_type'] == 'Text') {
1016 $fieldOption = current($field['options']);
1017 $value = array($fieldOption['id'] => $value);
1018 }
1019 else {
1020 $value = array($value => TRUE);
1021 }
1022 }
1023 }
1024
1025 return $params;
1026 }
1027
3bdf1f3a 1028 /**
1029 * Calculate total count for each price set options.
6a488035 1030 *
3bdf1f3a 1031 * - currently selected by user.
6a488035 1032 *
3bdf1f3a 1033 * @param CRM_Core_Form $form
1034 * Form object.
0cf587a7
EM
1035 *
1036 * @return array
3bdf1f3a 1037 * array of each option w/ count total.
0cf587a7 1038 */
169be3c1 1039 public static function getPriceSetOptionCount(&$form) {
353ffa53
TO
1040 $params = $form->get('params');
1041 $priceSet = $form->get('priceSet');
6a488035
TO
1042 $priceSetId = $form->get('priceSetId');
1043
1044 $optionsCount = array();
1045 if (!$priceSetId ||
1046 !is_array($priceSet) ||
1047 empty($priceSet) ||
1048 !is_array($params) ||
1049 empty($params)
1050 ) {
1051 return $optionsCount;
1052 }
1053
1054 $priceSetFields = $priceMaxFieldDetails = array();
a7488080 1055 if (!empty($priceSet['optionsCountTotal'])) {
6a488035
TO
1056 $priceSetFields = $priceSet['optionsCountDetails']['fields'];
1057 }
1058
a7488080 1059 if (!empty($priceSet['optionsMaxValueTotal'])) {
6a488035
TO
1060 $priceMaxFieldDetails = $priceSet['optionsMaxValueDetails']['fields'];
1061 }
1062
1063 $addParticipantNum = substr($form->_name, 12);
1064 foreach ($params as $pCnt => $values) {
1065 if ($values == 'skip' ||
79b152ac 1066 $pCnt === $addParticipantNum
6a488035
TO
1067 ) {
1068 continue;
1069 }
1070
1071 foreach ($values as $valKey => $value) {
1072 if (strpos($valKey, 'price_') === FALSE) {
1073 continue;
1074 }
1075
1076 $priceFieldId = substr($valKey, 6);
1077 if (!$priceFieldId ||
1078 !is_array($value) ||
1079 !(array_key_exists($priceFieldId, $priceSetFields) || array_key_exists($priceFieldId, $priceMaxFieldDetails))
1080 ) {
1081 continue;
1082 }
1083
1084 foreach ($value as $optId => $optVal) {
1085 if (CRM_Utils_Array::value('html_type', $priceSet['fields'][$priceFieldId]) == 'Text') {
1086 $currentCount = $optVal;
1087 }
1088 else {
1089 $currentCount = 1;
1090 }
1091
1092 if (isset($priceSetFields[$priceFieldId]) && isset($priceSetFields[$priceFieldId]['options'][$optId])) {
1093 $currentCount = $priceSetFields[$priceFieldId]['options'][$optId] * $optVal;
1094 }
1095
1096 $optionsCount[$optId] = $currentCount + CRM_Utils_Array::value($optId, $optionsCount, 0);
1097 }
1098 }
1099 }
1100
1101 return $optionsCount;
1102 }
1103
0cf587a7 1104 /**
3bdf1f3a 1105 * Check if template file exists.
1106 *
0cf587a7
EM
1107 * @param string $suffix
1108 *
1109 * @return null|string
1110 */
00be9182 1111 public function checkTemplateFileExists($suffix = '') {
6a488035
TO
1112 if ($this->_eventId) {
1113 $templateName = $this->_name;
1114 if (substr($templateName, 0, 12) == 'Participant_') {
1115 $templateName = 'AdditionalParticipant';
1116 }
1117
1118 $templateFile = "CRM/Event/Form/Registration/{$this->_eventId}/{$templateName}.{$suffix}tpl";
1119 $template = CRM_Core_Form::getTemplate();
1120 if ($template->template_exists($templateFile)) {
1121 return $templateFile;
1122 }
1123 }
1124 return NULL;
1125 }
1126
0cf587a7 1127 /**
3bdf1f3a 1128 * Get template file name.
1129 *
0cf587a7
EM
1130 * @return null|string
1131 */
00be9182 1132 public function getTemplateFileName() {
6a488035
TO
1133 $fileName = $this->checkTemplateFileExists();
1134 return $fileName ? $fileName : parent::getTemplateFileName();
1135 }
1136
0cf587a7 1137 /**
3bdf1f3a 1138 * Override extra template name.
1139 *
0cf587a7
EM
1140 * @return null|string
1141 */
00be9182 1142 public function overrideExtraTemplateFileName() {
6a488035
TO
1143 $fileName = $this->checkTemplateFileExists('extra.');
1144 return $fileName ? $fileName : parent::overrideExtraTemplateFileName();
1145 }
1146
0dc0b759 1147 /**
1148 * Reset values for all options those are full.
1149 *
780422d7 1150 * @param array $optionFullIds
3bdf1f3a 1151 * @param CRM_Core_Form $form
0dc0b759 1152 */
1153 public static function resetElementValue($optionFullIds = array(), &$form) {
1154 if (!is_array($optionFullIds) ||
1155 empty($optionFullIds) ||
1156 !$form->isSubmitted()
1157 ) {
1158 return;
1159 }
1160
1161 foreach ($optionFullIds as $fldId => $optIds) {
1162 $name = "price_$fldId";
1163 if (!$form->elementExists($name)) {
1164 continue;
1165 }
1166
1167 $element = $form->getElement($name);
1168 $eleType = $element->getType();
1169
1170 $resetSubmitted = FALSE;
1171 switch ($eleType) {
1172 case 'text':
1173 if ($element->getValue() && $element->isFrozen()) {
1174 $label = "{$element->getLabel()}<tt>(x)</tt>";
1175 $element->setLabel($label);
1176 $element->setPersistantFreeze();
1177 $resetSubmitted = TRUE;
1178 }
1179 break;
1180
1181 case 'group':
1182 if (is_array($element->_elements)) {
1183 foreach ($element->_elements as $child) {
1184 $childType = $child->getType();
1185 $methodName = 'getName';
1186 if ($childType) {
1187 $methodName = 'getValue';
1188 }
1189 if (in_array($child->{$methodName}(), $optIds) && $child->isFrozen()) {
1190 $resetSubmitted = TRUE;
1191 $child->setPersistantFreeze();
1192 }
1193 }
1194 }
1195 break;
1196
1197 case 'select':
9d8d8fd0 1198 $value = $element->getValue();
1199 if (in_array($value[0], $optIds)) {
0dc0b759 1200 foreach ($element->_options as $option) {
d0ebccea 1201 if ($option['attr']['value'] === "crm_disabled_opt-{$value[0]}") {
2ae4d103 1202 $placeholder = html_entity_decode($option['text'], ENT_QUOTES, "UTF-8");
0dc0b759 1203 $element->updateAttributes(array('placeholder' => $placeholder));
1204 break;
1205 }
1206 }
1207 $resetSubmitted = TRUE;
1208 }
1209 break;
1210 }
1211
1212 //finally unset values from submitted.
1213 if ($resetSubmitted) {
1214 self::resetSubmittedValue($name, $optIds, $form);
1215 }
1216 }
1217 }
1218
1219 /**
3bdf1f3a 1220 * Reset submitted value.
1221 *
0dc0b759 1222 * @param string $elementName
1223 * @param array $optionIds
c91b34a5 1224 * @param CRM_Core_Form $form
0dc0b759 1225 */
1226 public static function resetSubmittedValue($elementName, $optionIds = array(), &$form) {
1227 if (empty($elementName) ||
1228 !$form->elementExists($elementName) ||
1229 !$form->getSubmitValue($elementName)
1230 ) {
1231 return;
1232 }
1233 foreach (array(
90b461f1
SL
1234 'constantValues',
1235 'submitValues',
1236 'defaultValues',
1237 ) as $val) {
0dc0b759 1238 $values = $form->{"_$val"};
1239 if (!is_array($values) || empty($values)) {
1240 continue;
1241 }
1242 $eleVal = CRM_Utils_Array::value($elementName, $values);
1243 if (empty($eleVal)) {
1244 continue;
1245 }
1246 if (is_array($eleVal)) {
1247 $found = FALSE;
1248 foreach ($eleVal as $keyId => $ignore) {
1249 if (in_array($keyId, $optionIds)) {
1250 $found = TRUE;
1251 unset($values[$elementName][$keyId]);
1252 }
1253 }
1254 if ($found && empty($values[$elementName][$keyId])) {
1255 $values[$elementName][$keyId] = NULL;
1256 }
1257 }
1258 else {
1259 if (!empty($keyId)) {
1260 $values[$elementName][$keyId] = NULL;
1261 }
1262 }
1263 }
1264 }
1265
da8d9879 1266 /**
3bdf1f3a 1267 * Validate price set submitted params for price option limit.
1268 *
1269 * User should select at least one price field option.
72b3a70c
CW
1270 *
1271 * @param CRM_Core_Form $form
1272 * @param array $params
1273 *
1274 * @return array
6a488035 1275 */
00be9182 1276 public static function validatePriceSet(&$form, $params) {
6a488035
TO
1277 $errors = array();
1278 $hasOptMaxValue = FALSE;
1279 if (!is_array($params) || empty($params)) {
1280 return $errors;
1281 }
1282
1283 $currentParticipantNum = substr($form->_name, 12);
1284 if (!$currentParticipantNum) {
1285 $currentParticipantNum = 0;
1286 }
1287
1288 $priceSetId = $form->get('priceSetId');
1289 $priceSetDetails = $form->get('priceSet');
1290 if (
1291 !$priceSetId ||
1292 !is_array($priceSetDetails) ||
1293 empty($priceSetDetails)
1294 ) {
1295 return $errors;
1296 }
1297
1298 $optionsCountDetails = $optionsMaxValueDetails = array();
1299 if (
1300 isset($priceSetDetails['optionsMaxValueTotal'])
1301 && $priceSetDetails['optionsMaxValueTotal']
1302 ) {
1303 $hasOptMaxValue = TRUE;
1304 $optionsMaxValueDetails = $priceSetDetails['optionsMaxValueDetails']['fields'];
1305 }
1306 if (
1307 isset($priceSetDetails['optionsCountTotal'])
1308 && $priceSetDetails['optionsCountTotal']
1309 ) {
1310 $hasOptCount = TRUE;
1311 $optionsCountDetails = $priceSetDetails['optionsCountDetails']['fields'];
1312 }
1313 $feeBlock = $form->_feeBlock;
1314
1315 if (empty($feeBlock)) {
1316 $feeBlock = $priceSetDetails['fields'];
1317 }
1318
db7f1024 1319 $optionMaxValues = $fieldSelected = array();
6a488035
TO
1320 foreach ($params as $pNum => $values) {
1321 if (!is_array($values) || $values == 'skip') {
1322 continue;
1323 }
1324
1325 foreach ($values as $valKey => $value) {
1326 if (strpos($valKey, 'price_') === FALSE) {
1327 continue;
1328 }
1329 $priceFieldId = substr($valKey, 6);
1330 $noneOptionValueSelected = FALSE;
1331 if (!$feeBlock[$priceFieldId]['is_required'] && $value == 0) {
1332 $noneOptionValueSelected = TRUE;
1333 }
1334
1335 if (
1336 !$priceFieldId ||
1337 (!$noneOptionValueSelected && !is_array($value))
1338 ) {
1339 continue;
1340 }
1341
1342 $fieldSelected[$pNum] = TRUE;
1343
1344 if (!$hasOptMaxValue || !is_array($value)) {
1345 continue;
1346 }
1347
1348 foreach ($value as $optId => $optVal) {
1349 if (CRM_Utils_Array::value('html_type', $feeBlock[$priceFieldId]) == 'Text') {
1350 $currentMaxValue = $optVal;
1351 }
1352 else {
1353 $currentMaxValue = 1;
1354 }
1355
1356 if (isset($optionsCountDetails[$priceFieldId]) && isset($optionsCountDetails[$priceFieldId]['options'][$optId])) {
1357 $currentMaxValue = $optionsCountDetails[$priceFieldId]['options'][$optId] * $optVal;
1358 }
1359 if (empty($optionMaxValues)) {
1360 $optionMaxValues[$priceFieldId][$optId] = $currentMaxValue;
1361 }
1362 else {
7c550ca0
WA
1363 $optionMaxValues[$priceFieldId][$optId]
1364 = $currentMaxValue + CRM_Utils_Array::value($optId, CRM_Utils_Array::value($priceFieldId, $optionMaxValues), 0);
6a488035 1365 }
0dc0b759 1366 $soldOutPnum[$optId] = $pNum;
6a488035
TO
1367 }
1368 }
0dc0b759 1369
1370 //validate for price field selection.
db7f1024 1371 if (empty($fieldSelected[$pNum])) {
0dc0b759 1372 $errors[$pNum]['_qf_default'] = ts('Select at least one option from Event Fee(s).');
1373 }
6a488035
TO
1374 }
1375
1376 //validate for option max value.
1377 foreach ($optionMaxValues as $fieldId => $values) {
1378 $options = CRM_Utils_Array::value('options', $feeBlock[$fieldId], array());
1379 foreach ($values as $optId => $total) {
1380 $optMax = $optionsMaxValueDetails[$fieldId]['options'][$optId];
1381 $opDbCount = CRM_Utils_Array::value('db_total_count', $options[$optId], 0);
1382 $total += $opDbCount;
0dc0b759 1383 if ($optMax && ($total > $optMax)) {
6a488035 1384 if ($opDbCount && ($opDbCount >= $optMax)) {
0dc0b759 1385 $errors[$soldOutPnum[$optId]]["price_{$fieldId}"]
7c550ca0 1386 = ts('Sorry, this option is currently sold out.');
6a488035
TO
1387 }
1388 elseif (($optMax - $opDbCount) == 1) {
0dc0b759 1389 $errors[$soldOutPnum[$optId]]["price_{$fieldId}"]
a3fdddaa 1390 = ts('Sorry, currently only a single space is available for this option.', array(1 => ($optMax - $opDbCount)));
6a488035
TO
1391 }
1392 else {
0dc0b759 1393 $errors[$soldOutPnum[$optId]]["price_{$fieldId}"]
a3fdddaa 1394 = ts('Sorry, currently only %1 spaces are available for this option.', array(1 => ($optMax - $opDbCount)));
6a488035
TO
1395 }
1396 }
1397 }
1398 }
6a488035
TO
1399 return $errors;
1400 }
1401
0cf587a7 1402 /**
3bdf1f3a 1403 * Set the first participant ID if not set.
1404 *
1405 * CRM-10032.
72b3a70c 1406 *
100fef9d 1407 * @param int $participantID
0cf587a7 1408 */
00be9182 1409 public function processFirstParticipant($participantID) {
6a488035
TO
1410 $this->_participantId = $participantID;
1411 $this->set('participantId', $this->_participantId);
1412
1413 $ids = $participantValues = array();
1414 $participantParams = array('id' => $this->_participantId);
1415 CRM_Event_BAO_Participant::getValues($participantParams, $participantValues, $ids);
1416 $this->_values['participant'] = $participantValues[$this->_participantId];
1417 $this->set('values', $this->_values);
1418
1419 // also set the allow confirmation stuff
1420 if (array_key_exists(
353ffa53
TO
1421 $this->_values['participant']['status_id'],
1422 CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Pending'")
1423 )) {
6a488035
TO
1424 $this->_allowConfirmation = TRUE;
1425 $this->set('allowConfirmation', TRUE);
1426 }
1427 }
1428
e2d09ab4 1429 /**
3bdf1f3a 1430 * Check if event is valid.
1431 *
e2d09ab4
EM
1432 * @todo - combine this with CRM_Event_BAO_Event::validRegistrationRequest
1433 * (probably extract relevant values here & call that with them & handle bounces & redirects here -as
1434 * those belong in the form layer)
1435 *
1436 * @param string $redirect
1437 */
00be9182 1438 public function checkValidEvent($redirect = NULL) {
6a488035
TO
1439 // is the event active (enabled)?
1440 if (!$this->_values['event']['is_active']) {
1441 // form is inactive, die a fatal death
1442 CRM_Core_Error::statusBounce(ts('The event you requested is currently unavailable (contact the site administrator for assistance).'));
1443 }
1444
1445 // is online registration is enabled?
1446 if (!$this->_values['event']['is_online_registration']) {
1447 CRM_Core_Error::statusBounce(ts('Online registration is not currently available for this event (contact the site administrator for assistance).'), $redirect);
1448 }
1449
1450 // is this an event template ?
a7488080 1451 if (!empty($this->_values['event']['is_template'])) {
6a488035
TO
1452 CRM_Core_Error::statusBounce(ts('Event templates are not meant to be registered.'), $redirect);
1453 }
1454
1455 $now = date('YmdHis');
1456 $startDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('registration_start_date',
353ffa53
TO
1457 $this->_values['event']
1458 ));
6a488035
TO
1459
1460 if (
1461 $startDate &&
1462 $startDate >= $now
1463 ) {
5e29b453 1464 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
1465 }
1466
ce5694b5 1467 $regEndDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('registration_end_date',
353ffa53
TO
1468 $this->_values['event']
1469 ));
4bd9b7a9 1470 $eventEndDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('event_end_date', $this->_values['event']));
b612d89b 1471 if (($regEndDate && ($regEndDate < $now)) || (empty($regEndDate) && !empty($eventEndDate) && ($eventEndDate < $now))) {
ce5694b5 1472 $endDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('registration_end_date', $this->_values['event']));
1473 if (empty($regEndDate)) {
1474 $endDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('event_end_date', $this->_values['event']));
1475 }
5e29b453 1476 CRM_Core_Error::statusBounce(ts('Registration for this event ended on %1', array(1 => $endDate)), $redirect, ts('Sorry'));
6a488035
TO
1477 }
1478 }
96025800 1479
c039f658 1480 /**
1481 * Get the amount level for the event payment.
1482 *
1483 * The amount level is the string stored on the contribution record that describes the purchase.
1484 *
1485 * @param array $params
1486 * @param int|null $discountID
1487 *
1488 * @return string
1489 */
1490 protected function getAmountLevel($params, $discountID) {
1491 // @todo move handling of discount ID to the BAO function - preferably by converting it to a price_set with
1492 // time settings.
1493 if (!empty($this->_values['discount'][$discountID])) {
1494 return $this->_values['discount'][$discountID][$params['amount']]['label'];
1495 }
e173279c 1496 if (empty($params['priceSetId'])) {
1497 // CRM-17509 An example of this is where the person is being waitlisted & there is no payment.
1498 // ideally we would have calculated amount first & only call this is there is an
1499 // amount but the flow needs more changes for that.
1500 return '';
1501 }
c039f658 1502 return CRM_Price_BAO_PriceSet::getAmountLevelText($params);
1503 }
1504
3033e657 1505 /**
1506 * Process Registration of free event.
1507 *
1508 * @param array $params
1509 * Form values.
1510 * @param int $contactID
1511 */
1512 public function processRegistration($params, $contactID = NULL) {
1513 $session = CRM_Core_Session::singleton();
1514 $this->_participantInfo = array();
1515
1516 // CRM-4320, lets build array of cancelled additional participant ids
1517 // those are drop or skip by primary at the time of confirmation.
1518 // get all in and then unset those are confirmed.
1519 $cancelledIds = $this->_additionalParticipantIds;
1520
1521 $participantCount = array();
1522 foreach ($params as $participantNum => $record) {
1523 if ($record == 'skip') {
1524 $participantCount[$participantNum] = 'skip';
1525 }
1526 elseif ($participantNum) {
1527 $participantCount[$participantNum] = 'participant';
1528 }
1529 }
1530
1531 $registerByID = NULL;
1532 foreach ($params as $key => $value) {
1533 if ($value != 'skip') {
1534 $fields = NULL;
1535
1536 // setting register by Id and unset contactId.
1537 if (empty($value['is_primary'])) {
1538 $contactID = NULL;
1539 $registerByID = $this->get('registerByID');
1540 if ($registerByID) {
1541 $value['registered_by_id'] = $registerByID;
1542 }
1543 // get an email if one exists for the participant
1544 $participantEmail = '';
1545 foreach (array_keys($value) as $valueName) {
1546 if (substr($valueName, 0, 6) == 'email-') {
1547 $participantEmail = $value[$valueName];
1548 }
1549 }
1550 if ($participantEmail) {
1551 $this->_participantInfo[] = $participantEmail;
1552 }
1553 else {
1554 $this->_participantInfo[] = $value['first_name'] . ' ' . $value['last_name'];
1555 }
1556 }
1557 elseif (!empty($value['contact_id'])) {
1558 $contactID = $value['contact_id'];
1559 }
1560 else {
1561 $contactID = $this->getContactID();
1562 }
1563
1564 CRM_Event_Form_Registration_Confirm::fixLocationFields($value, $fields, $this);
1565 //for free event or additional participant, dont create billing email address.
1566 if (empty($value['is_primary']) || !$this->_values['event']['is_monetary']) {
1567 unset($value["email-{$this->_bltID}"]);
1568 }
1569
1570 $contactID = CRM_Event_Form_Registration_Confirm::updateContactFields($contactID, $value, $fields, $this);
1571
1572 // lets store the contactID in the session
1573 // we dont store in userID in case the user is doing multiple
1574 // transactions etc
1575 // for things like tell a friend
1576 if (!$this->getContactID() && !empty($value['is_primary'])) {
1577 $session->set('transaction.userID', $contactID);
1578 }
1579
1580 //lets get the status if require approval or waiting.
1581
1582 $waitingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
1583 if ($this->_allowWaitlist && !$this->_allowConfirmation) {
1584 $value['participant_status_id'] = $value['participant_status'] = array_search('On waitlist', $waitingStatuses);
1585 }
1586 elseif ($this->_requireApproval && !$this->_allowConfirmation) {
1587 $value['participant_status_id'] = $value['participant_status'] = array_search('Awaiting approval', $waitingStatuses);
1588 }
1589
1590 $this->set('value', $value);
d5ce773d 1591 $this->confirmPostProcess($contactID, NULL);
3033e657 1592
1593 //lets get additional participant id to cancel.
1594 if ($this->_allowConfirmation && is_array($cancelledIds)) {
1595 $additonalId = CRM_Utils_Array::value('participant_id', $value);
1596 if ($additonalId && $key = array_search($additonalId, $cancelledIds)) {
1597 unset($cancelledIds[$key]);
1598 }
1599 }
1600 }
1601 }
1602
1603 // update status and send mail to cancelled additional participants, CRM-4320
1604 if ($this->_allowConfirmation && is_array($cancelledIds) && !empty($cancelledIds)) {
1605 $cancelledId = array_search('Cancelled',
1606 CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'")
1607 );
1608 CRM_Event_BAO_Participant::transitionParticipants($cancelledIds, $cancelledId);
1609 }
1610
1611 //set information about additional participants if exists
1612 if (count($this->_participantInfo)) {
1613 $this->set('participantInfo', $this->_participantInfo);
1614 }
1615
1616 //send mail Confirmation/Receipt
1617 if ($this->_contributeMode != 'checkout' ||
1618 $this->_contributeMode != 'notify'
1619 ) {
1620 $isTest = FALSE;
1621 if ($this->_action & CRM_Core_Action::PREVIEW) {
1622 $isTest = TRUE;
1623 }
1624
1625 //handle if no additional participant.
1626 if (!$registerByID) {
1627 $registerByID = $this->get('registerByID');
1628 }
1629 $primaryContactId = $this->get('primaryContactId');
1630
1631 //build an array of custom profile and assigning it to template.
1632 $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($registerByID, NULL,
1633 $primaryContactId, $isTest, TRUE
1634 );
1635
1636 //lets carry all participant params w/ values.
1637 foreach ($additionalIDs as $participantID => $contactId) {
1638 $participantNum = NULL;
1639 if ($participantID == $registerByID) {
1640 $participantNum = 0;
1641 }
1642 else {
1643 if ($participantNum = array_search('participant', $participantCount)) {
1644 unset($participantCount[$participantNum]);
1645 }
1646 }
1647
1648 if ($participantNum === NULL) {
1649 break;
1650 }
1651
1652 //carry the participant submitted values.
1653 $this->_values['params'][$participantID] = $params[$participantNum];
1654 }
1655
1656 //lets send mails to all with meanigful text, CRM-4320.
1657 $this->assign('isOnWaitlist', $this->_allowWaitlist);
1658 $this->assign('isRequireApproval', $this->_requireApproval);
1659
1660 foreach ($additionalIDs as $participantID => $contactId) {
1661 if ($participantID == $registerByID) {
1662 //set as Primary Participant
1663 $this->assign('isPrimary', 1);
1664
1665 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($participantID, $this->_values, NULL, $isTest);
1666
1667 if (count($customProfile)) {
1668 $this->assign('customProfile', $customProfile);
1669 $this->set('customProfile', $customProfile);
1670 }
1671 }
1672 else {
1673 $this->assign('isPrimary', 0);
1674 $this->assign('customProfile', NULL);
1675 }
1676
1677 //send Confirmation mail to Primary & additional Participants if exists
1678 CRM_Event_BAO_Event::sendMail($contactId, $this->_values, $participantID, $isTest);
1679 }
1680 }
1681 }
1682
6a488035 1683}