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