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