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