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