Merge pull request #13258 from eileenmcnaughton/isam
[civicrm-core.git] / CRM / Event / Form / Registration / Register.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
8c9251b3 6 | Copyright CiviCRM LLC (c) 2004-2018 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
6a488035 29 * @package CRM
8c9251b3 30 * @copyright CiviCRM LLC (c) 2004-2018
6a488035
TO
31 */
32
33/**
3bdf1f3a 34 * This class generates form components for processing Event.
6a488035
TO
35 */
36class CRM_Event_Form_Registration_Register extends CRM_Event_Form_Registration {
37
38 /**
66f9e52b 39 * The fields involved in this page.
6a488035
TO
40 */
41 public $_fields;
42
6a488035
TO
43 /**
44 * The status message that user view.
6a488035
TO
45 */
46 protected $_waitlistMsg = NULL;
47 protected $_requireApprovalMsg = NULL;
48
3bdf1f3a 49 /**
50 * Deprecated parameter that we hope to remove.
51 *
52 * @var bool
53 */
6a488035
TO
54 public $_quickConfig = NULL;
55
56 /**
3bdf1f3a 57 * Skip duplicate check.
58 *
59 * This can be set using hook_civicrm_buildForm() to override the registration dupe check.
6a488035
TO
60 * CRM-7604
61 */
62 public $_skipDupeRegistrationCheck = FALSE;
63
cc789d46 64 public $_paymentProcessorID;
6a488035 65
16d1c8e2 66 /**
3bdf1f3a 67 * Show fee block or not.
68 *
16d1c8e2 69 * @var boolean determines if fee block should be shown or hidden
70 */
71 public $_noFees;
72
cc789d46 73 /**
3bdf1f3a 74 * Array of payment related fields to potentially display on this form (generally credit card or debit card fields).
75 *
76 * This is rendered via billingBlock.tpl.
77 *
cc789d46
EM
78 * @var array
79 */
80 public $_paymentFields = array();
81
7b64dc81 82 /**
83 * Get the contact id for the registration.
84 *
85 * @param array $fields
86 * @param CRM_Core_Form $self
87 * @param bool $isAdditional
88 *
89 * @return int|null
90 */
d2d97ffe 91 public static function getRegistrationContactID($fields, $self, $isAdditional) {
7b64dc81 92
93 $contactID = NULL;
94 if (!$isAdditional) {
95 $contactID = $self->getContactID();
96 }
97 if (!$contactID && is_array($fields) && $fields) {
fc918c27 98 $contactID = CRM_Contact_BAO_Contact::getFirstDuplicateContact($fields, 'Individual', 'Unsupervised', array(), FALSE, CRM_Utils_Array::value('dedupe_rule_group_id', $self->_values['event']));
7b64dc81 99 }
100 return $contactID;
101 }
102
6a488035 103 /**
66f9e52b 104 * Set variables up before form is built.
6a488035 105 */
00be9182 106 public function preProcess() {
6a488035 107 parent::preProcess();
7bf9cde2 108
6a488035
TO
109 //CRM-4320.
110 //here we can't use parent $this->_allowWaitlist as user might
cc789d46 111 //walk back and we might set this value in this postProcess.
6a488035 112 //(we set when spaces < group count and want to allow become part of waiting )
6a488035
TO
113 $eventFull = CRM_Event_BAO_Participant::eventFull($this->_eventId, FALSE, CRM_Utils_Array::value('has_waitlist', $this->_values['event']));
114
b6a469c5
CW
115 // Get payment processors if appropriate for this event
116 // We hide the payment fields if the event is full or requires approval,
117 // and the current user has not yet been approved CRM-12279
16d1c8e2 118 $this->_noFees = (($eventFull || $this->_requireApproval) && !$this->_allowConfirmation);
42e3a033
EM
119 $this->_paymentProcessors = $this->_noFees ? array() : $this->get('paymentProcessors');
120 $this->preProcessPaymentOptions();
b6a469c5 121
6a488035 122 $this->_allowWaitlist = FALSE;
8cc574cf 123 if ($eventFull && !$this->_allowConfirmation && !empty($this->_values['event']['has_waitlist'])) {
6a488035
TO
124 $this->_allowWaitlist = TRUE;
125 $this->_waitlistMsg = CRM_Utils_Array::value('waitlist_text', $this->_values['event']);
126 if (!$this->_waitlistMsg) {
127 $this->_waitlistMsg = ts('This event is currently full. However you can register now and get added to a waiting list. You will be notified if spaces become available.');
128 }
129 }
130 $this->set('allowWaitlist', $this->_allowWaitlist);
131
132 //To check if the user is already registered for the event(CRM-2426)
133 if (!$this->_skipDupeRegistrationCheck) {
134 self::checkRegistration(NULL, $this);
135 }
136
137 $this->assign('availableRegistrations', $this->_availableRegistrations);
138
139 // get the participant values from EventFees.php, CRM-4320
140 if ($this->_allowConfirmation) {
141 CRM_Event_Form_EventFees::preProcess($this);
142 }
6a488035
TO
143 }
144
145 /**
70d1766d 146 * Set default values for the form.
6a488035 147 */
00be9182 148 public function setDefaultValues() {
2ab5ff1d 149 $this->_defaults = array();
5ec4b965 150 if (!$this->_allowConfirmation && $this->_requireApproval) {
151 $this->_defaults['bypass_payment'] = 1;
152 }
5c280496 153 $contactID = $this->getContactID();
70d1766d 154 CRM_Core_Payment_Form::setDefaultValues($this, $contactID);
a28e436f 155
c7d52684 156 CRM_Event_BAO_Participant::formatFieldsAndSetProfileDefaults($contactID, $this);
3feb567a 157
13ac605f
DG
158 // Set default payment processor as default payment_processor radio button value
159 if (!empty($this->_paymentProcessors)) {
160 foreach ($this->_paymentProcessors as $pid => $value) {
a7488080 161 if (!empty($value['is_default'])) {
e02d7e96 162 $this->_defaults['payment_processor_id'] = $pid;
13ac605f
DG
163 }
164 }
165 }
166
6a488035
TO
167 //if event is monetary and pay later is enabled and payment
168 //processor is not available then freeze the pay later checkbox with
169 //default check
a7488080 170 if (!empty($this->_values['event']['is_pay_later']) &&
6a488035
TO
171 !is_array($this->_paymentProcessor)
172 ) {
173 $this->_defaults['is_pay_later'] = 1;
174 }
175
176 //set custom field defaults
177 if (!empty($this->_fields)) {
178 //load default campaign from page.
179 if (array_key_exists('participant_campaign_id', $this->_fields)) {
180 $this->_defaults['participant_campaign_id'] = CRM_Utils_Array::value('campaign_id',
181 $this->_values['event']
182 );
183 }
184
185 foreach ($this->_fields as $name => $field) {
186 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
187 // fix for CRM-1743
188 if (!isset($this->_defaults[$name])) {
189 CRM_Core_BAO_CustomField::setProfileDefaults($customFieldID, $name, $this->_defaults,
190 NULL, CRM_Profile_Form::MODE_REGISTER
191 );
192 }
193 }
194 }
195 }
196
197 //fix for CRM-3088, default value for discount set.
198 $discountId = NULL;
199 if (!empty($this->_values['discount'])) {
200 $discountId = CRM_Core_BAO_Discount::findSet($this->_eventId, 'civicrm_event');
201 if ($discountId) {
202 if (isset($this->_values['event']['default_discount_fee_id'])) {
203 $discountKey = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue',
204 $this->_values['event']['default_discount_fee_id'],
205 'weight', 'id'
206 );
207
208 $this->_defaults['amount'] = key(array_slice($this->_values['discount'][$discountId],
353ffa53
TO
209 $discountKey - 1, $discountKey, TRUE
210 ));
6a488035
TO
211 }
212 }
213 }
214
215 // add this event's default participant role to defaults array
216 // (for cases where participant_role field is included in form via profile)
217 if ($this->_values['event']['default_role_id']) {
608e6658 218 $this->_defaults['participant_role']
219 = $this->_defaults['participant_role_id'] = $this->_values['event']['default_role_id'];
6a488035
TO
220 }
221 if ($this->_priceSetId && !empty($this->_feeBlock)) {
222 foreach ($this->_feeBlock as $key => $val) {
0dc0b759 223 if (empty($val['options'])) {
224 continue;
225 }
226 $optionFullIds = CRM_Utils_Array::value('option_full_ids', $val, array());
6a488035 227 foreach ($val['options'] as $keys => $values) {
8cc574cf 228 if ($values['is_default'] && empty($values['is_full'])) {
6a488035
TO
229
230 if ($val['html_type'] == 'CheckBox') {
231 $this->_defaults["price_{$key}"][$keys] = 1;
232 }
233 else {
234 $this->_defaults["price_{$key}"] = $keys;
235 }
236 }
237 }
0dc0b759 238 $unsetSubmittedOptions[$val['id']] = $optionFullIds;
6a488035 239 }
0dc0b759 240 //reset values for all options those are full.
241 CRM_Event_Form_Registration::resetElementValue($unsetSubmittedOptions, $this);
6a488035
TO
242 }
243
244 //set default participant fields, CRM-4320.
245 $hasAdditionalParticipants = FALSE;
246 if ($this->_allowConfirmation) {
247 $this->_contactId = $contactID;
248 $this->_discountId = $discountId;
249 $forcePayLater = CRM_Utils_Array::value('is_pay_later', $this->_defaults, FALSE);
250 $this->_defaults = array_merge($this->_defaults, CRM_Event_Form_EventFees::setDefaultValues($this));
251 $this->_defaults['is_pay_later'] = $forcePayLater;
252
253 if ($this->_additionalParticipantIds) {
254 $hasAdditionalParticipants = TRUE;
255 $this->_defaults['additional_participants'] = count($this->_additionalParticipantIds);
256 }
257 }
258 $this->assign('hasAdditionalParticipants', $hasAdditionalParticipants);
259
260 // //hack to simplify credit card entry for testing
261 // $this->_defaults['credit_card_type'] = 'Visa';
262 // $this->_defaults['credit_card_number'] = '4807731747657838';
263 // $this->_defaults['cvv2'] = '000';
264 // $this->_defaults['credit_card_exp_date'] = array( 'Y' => '2010', 'M' => '05' );
265
266 // to process Custom data that are appended to URL
267 $getDefaults = CRM_Core_BAO_CustomGroup::extractGetParams($this, "'Contact', 'Individual', 'Contribution', 'Participant'");
268 if (!empty($getDefaults)) {
269 $this->_defaults = array_merge($this->_defaults, $getDefaults);
270 }
271
272 return $this->_defaults;
273 }
274
275 /**
66f9e52b 276 * Build the form object.
6a488035
TO
277 */
278 public function buildQuickForm() {
4839c695
KJ
279 // build profiles first so that we can determine address fields etc
280 // and then show copy address checkbox
281 $this->buildCustom($this->_values['custom_pre_id'], 'customPre');
282 $this->buildCustom($this->_values['custom_post_id'], 'customPost');
283
d38c288e 284 // CRM-18399: used by template to pass pre profile id as a url arg
285 $this->assign('custom_pre_id', $this->_values['custom_pre_id']);
4839c695 286
cc789d46 287 CRM_Core_Payment_ProcessorForm::buildQuickForm($this);
6a488035 288
5c280496 289 $contactID = $this->getContactID();
37326fa1
DG
290 if ($contactID) {
291 $this->assign('contact_id', $contactID);
f498a273 292 $this->assign('display_name', CRM_Contact_BAO_Contact::displayName($contactID));
37326fa1 293 }
6a488035 294
6a488035
TO
295 $this->add('hidden', 'scriptFee', NULL);
296 $this->add('hidden', 'scriptArray', NULL);
297
298 $bypassPayment = $allowGroupOnWaitlist = $isAdditionalParticipants = FALSE;
299 if ($this->_values['event']['is_multiple_registrations']) {
300 // don't allow to add additional during confirmation if not preregistered.
301 if (!$this->_allowConfirmation || $this->_additionalParticipantIds) {
f1bc01e0 302 // CRM-17745: Make maximum additional participants configurable
6a488035 303 // Label is value + 1, since the code sees this is ADDITIONAL participants (in addition to "self")
f1bc01e0
J
304 $additionalOptions = array();
305 $additionalOptions[''] = 1;
30ddbdcb 306 for ($i = 1; $i <= $this->_values['event']['max_additional_participants']; $i++) {
f1bc01e0
J
307 $additionalOptions[$i] = $i + 1;
308 }
5f39c1a6 309 $this->add('select', 'additional_participants',
6a488035
TO
310 ts('How many people are you registering?'),
311 $additionalOptions,
312 NULL,
313 array('onChange' => "allowParticipant()")
314 );
315 $isAdditionalParticipants = TRUE;
316 }
317 }
318
5ec4b965 319 if (!$this->_allowConfirmation) {
320 $bypassPayment = TRUE;
321 }
322
6a488035 323 //hack to allow group to register w/ waiting
8cc574cf 324 if ((!empty($this->_values['event']['is_multiple_registrations']) ||
6a488035
TO
325 $this->_priceSetId
326 ) &&
327 !$this->_allowConfirmation &&
353ffa53
TO
328 is_numeric($this->_availableRegistrations) && !empty($this->_values['event']['has_waitlist'])
329 ) {
6a488035
TO
330 $bypassPayment = TRUE;
331 //case might be group become as a part of waitlist.
332 //If not waitlist then they require admin approve.
333 $allowGroupOnWaitlist = TRUE;
334 $this->_waitlistMsg = ts("This event has only %1 space(s) left. If you continue and register more than %1 people (including yourself ), the whole group will be wait listed. Or, you can reduce the number of people you are registering to %1 to avoid being put on the waiting list.", array(1 => $this->_availableRegistrations));
335
336 if ($this->_requireApproval) {
337 $this->_requireApprovalMsg = CRM_Utils_Array::value('approval_req_text', $this->_values['event'],
338 ts('Registration for this event requires approval. Once your registration(s) have been reviewed, you will receive an email with a link to a web page where you can complete the registration process.')
339 );
340 }
341 }
342
343 //case where only approval needed - no waitlist.
344 if ($this->_requireApproval &&
345 !$this->_allowWaitlist && !$bypassPayment
346 ) {
347 $this->_requireApprovalMsg = CRM_Utils_Array::value('approval_req_text', $this->_values['event'],
348 ts('Registration for this event requires approval. Once your registration has been reviewed, you will receive an email with a link to a web page where you can complete the registration process.')
349 );
350 }
351
352 //lets display status to primary page only.
353 $this->assign('waitlistMsg', $this->_waitlistMsg);
354 $this->assign('requireApprovalMsg', $this->_requireApprovalMsg);
355 $this->assign('allowGroupOnWaitlist', $allowGroupOnWaitlist);
356 $this->assign('isAdditionalParticipants', $isAdditionalParticipants);
357
6a488035
TO
358 if ($this->_values['event']['is_monetary']) {
359 self::buildAmount($this);
360 }
361
596bff78 362 $pps = array();
363 //@todo this processor adding fn is another one duplicated on contribute - a shared
364 // common class would make this sort of thing extractable
cf6a124f 365 $onlinePaymentProcessorEnabled = FALSE;
6a488035 366 if (!empty($this->_paymentProcessors)) {
596bff78 367 foreach ($this->_paymentProcessors as $key => $name) {
22e263ad 368 if ($name['billing_mode'] == 1) {
596bff78 369 $onlinePaymentProcessorEnabled = TRUE;
370 }
6a488035
TO
371 $pps[$key] = $name['name'];
372 }
373 }
aa288d3f 374 if ($this->getContactID() === 0 && !$this->_values['event']['is_multiple_registrations']) {
e1ce628e 375 //@todo we are blocking for multiple registrations because we haven't tested
596bff78 376 $this->addCidZeroOptions($onlinePaymentProcessorEnabled);
377 }
a7488080 378 if (!empty($this->_values['event']['is_pay_later']) &&
6a488035
TO
379 ($this->_allowConfirmation || (!$this->_requireApproval && !$this->_allowWaitlist))
380 ) {
381 $pps[0] = $this->_values['event']['pay_later_text'];
382 }
383
384 if ($this->_values['event']['is_monetary']) {
385 if (count($pps) > 1) {
e02d7e96 386 $this->addRadio('payment_processor_id', ts('Payment Method'), $pps,
fdf1844b 387 NULL, "&nbsp;"
6a488035
TO
388 );
389 }
390 elseif (!empty($pps)) {
391 $ppKeys = array_keys($pps);
392 $currentPP = array_pop($ppKeys);
e02d7e96 393 $this->addElement('hidden', 'payment_processor_id', $currentPP);
6a488035
TO
394 }
395 }
396
5ec4b965 397 $this->addElement('hidden', 'bypass_payment', NULL, array('id' => 'bypass_payment'));
398
6a488035 399 $this->assign('bypassPayment', $bypassPayment);
6a488035 400
5c280496 401 $userID = $this->getContactID();
6a488035
TO
402
403 if (!$userID) {
404 $createCMSUser = FALSE;
405
406 if ($this->_values['custom_pre_id']) {
407 $profileID = $this->_values['custom_pre_id'];
408 $createCMSUser = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $profileID, 'is_cms_user');
409 }
410
411 if (!$createCMSUser &&
412 $this->_values['custom_post_id']
413 ) {
414 if (!is_array($this->_values['custom_post_id'])) {
415 $profileIDs = array($this->_values['custom_post_id']);
416 }
417 else {
418 $profileIDs = $this->_values['custom_post_id'];
419 }
420 foreach ($profileIDs as $pid) {
421 if (CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $pid, 'is_cms_user')) {
422 $profileID = $pid;
423 $createCMSUser = TRUE;
424 break;
425 }
426 }
427 }
428
429 if ($createCMSUser) {
430 CRM_Core_BAO_CMSUser::buildForm($this, $profileID, TRUE);
431 }
432 }
433
434 //we have to load confirm contribution button in template
435 //when multiple payment processor as the user
436 //can toggle with payment processor selection
437 $billingModePaymentProcessors = 0;
438 if (!CRM_Utils_System::isNull($this->_paymentProcessors)) {
439 foreach ($this->_paymentProcessors as $key => $values) {
440 if ($values['billing_mode'] == CRM_Core_Payment::BILLING_MODE_BUTTON) {
441 $billingModePaymentProcessors++;
442 }
443 }
444 }
445
446 if ($billingModePaymentProcessors && count($this->_paymentProcessors) == $billingModePaymentProcessors) {
447 $allAreBillingModeProcessors = TRUE;
0db6c3e1
TO
448 }
449 else {
6a488035
TO
450 $allAreBillingModeProcessors = FALSE;
451 }
452
8cc574cf 453 if (!$allAreBillingModeProcessors || !empty($this->_values['event']['is_pay_later']) || $bypassPayment
6a488035
TO
454 ) {
455
456 //freeze button to avoid multiple calls.
457 $js = NULL;
458
a7488080 459 if (empty($this->_values['event']['is_monetary'])) {
6a488035
TO
460 $js = array('onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');");
461 }
2a6da8d7 462
1909126f 463 // CRM-11182 - Optional confirmation screen
464 // Change button label depending on whether the next action is confirm or register
465 if (
466 !$this->_values['event']['is_multiple_registrations']
d6121d3e 467 && !$this->_values['event']['is_monetary']
1909126f 468 && !$this->_values['event']['is_confirm_enabled']
469 ) {
f212d37d 470 $buttonLabel = ts('Register');
0db6c3e1
TO
471 }
472 else {
f212d37d 473 $buttonLabel = ts('Continue');
1909126f 474 }
2a6da8d7 475
6a488035
TO
476 $this->addButtons(array(
477 array(
478 'type' => 'upload',
1909126f 479 'name' => $buttonLabel,
6a488035
TO
480 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
481 'isDefault' => TRUE,
482 'js' => $js,
483 ),
484 )
485 );
486 }
487
488 $this->addFormRule(array('CRM_Event_Form_Registration_Register', 'formRule'), $this);
86c0d461 489 $this->unsavedChangesWarn = TRUE;
6a488035
TO
490
491 // add pcp fields
492 if ($this->_pcpId) {
493 CRM_PCP_BAO_PCP::buildPcp($this->_pcpId, $this);
494 }
495 }
496
497 /**
100fef9d 498 * Build the radio/text form elements for the amount field
6a488035 499 *
d4dd1e85
TO
500 * @param CRM_Core_Form $form
501 * Form object.
502 * @param bool $required
503 * True if you want to add formRule.
504 * @param int $discountId
505 * Discount id for the event.
6a488035
TO
506 */
507 static public function buildAmount(&$form, $required = TRUE, $discountId = NULL) {
16d1c8e2 508 // build amount only when needed, skip incase of event full and waitlisting is enabled
509 // and few other conditions check preProcess()
a2a1e950 510 if (property_exists($form, '_noFees') && $form->_noFees) {
16d1c8e2 511 return;
512 }
513
6a488035 514 //if payment done, no need to build the fee block.
7bf9cde2 515 if (!empty($form->_paymentId)) {
b6e641a4 516 //fix to display line item in update mode.
6a488035
TO
517 $form->assign('priceSet', isset($form->_priceSet) ? $form->_priceSet : NULL);
518 return;
519 }
520
521 $feeFields = CRM_Utils_Array::value('fee', $form->_values);
522
523 if (is_array($feeFields)) {
524 $form->_feeBlock = &$form->_values['fee'];
525 }
526
527 //check for discount.
528 $discountedFee = CRM_Utils_Array::value('discount', $form->_values);
529 if (is_array($discountedFee) && !empty($discountedFee)) {
530 if (!$discountId) {
531 $form->_discountId = $discountId = CRM_Core_BAO_Discount::findSet($form->_eventId, 'civicrm_event');
532 }
533 if ($discountId) {
534 $form->_feeBlock = &$form->_values['discount'][$discountId];
535 }
536 }
537 if (!is_array($form->_feeBlock)) {
538 $form->_feeBlock = array();
539 }
540
541 //its time to call the hook.
542 CRM_Utils_Hook::buildAmount('event', $form, $form->_feeBlock);
543
544 //reset required if participant is skipped.
545 $button = substr($form->controller->getButtonName(), -4);
546 if ($required && $button == 'skip') {
547 $required = FALSE;
548 }
549
550 $className = CRM_Utils_System::getClassName($form);
551
552 //build the priceset fields.
553 if (isset($form->_priceSetId) && $form->_priceSetId) {
554
555 //format price set fields across option full.
556 self::formatFieldsForOptionFull($form);
557
a7488080 558 if (!empty($form->_priceSet['is_quick_config'])) {
6a488035
TO
559 $form->_quickConfig = $form->_priceSet['is_quick_config'];
560 }
561 $form->add('hidden', 'priceSetId', $form->_priceSetId);
562
c7b3d063 563 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
ab8a593e 564 $adminFieldVisible = FALSE;
c7b3d063 565 if (CRM_Core_Permission::check('administer CiviCRM')) {
4eeb9a5b 566 $adminFieldVisible = TRUE;
c7b3d063
DG
567 }
568
a13c171d
CR
569 $hideAdminValues = TRUE;
570 if (CRM_Core_Permission::check('edit event participants')) {
571 $hideAdminValues = FALSE;
572 }
573
6a488035 574 foreach ($form->_feeBlock as $field) {
d06f3157 575 // public AND admin visibility fields are included for back-office registration and back-office change selections
6a488035 576 if (CRM_Utils_Array::value('visibility', $field) == 'public' ||
4eeb9a5b 577 (CRM_Utils_Array::value('visibility', $field) == 'admin' && $adminFieldVisible == TRUE) ||
d06f3157
DG
578 $className == 'CRM_Event_Form_Participant' ||
579 $className == 'CRM_Event_Form_ParticipantFeeSelection'
6a488035
TO
580 ) {
581 $fieldId = $field['id'];
582 $elementName = 'price_' . $fieldId;
583
584 $isRequire = CRM_Utils_Array::value('is_required', $field);
585 if ($button == 'skip') {
586 $isRequire = FALSE;
587 }
588
589 //user might modified w/ hook.
590 $options = CRM_Utils_Array::value('options', $field);
a13c171d
CR
591 $formClasses = array('CRM_Event_Form_Participant', 'CRM_Event_Form_ParticipantFeeSelection');
592
6a488035
TO
593 if (!is_array($options)) {
594 continue;
595 }
a13c171d 596 elseif ($hideAdminValues && !in_array($className, $formClasses)) {
ad2785a2
CR
597 $publicVisibilityID = CRM_Price_BAO_PriceField::getVisibilityOptionID('public');
598 $adminVisibilityID = CRM_Price_BAO_PriceField::getVisibilityOptionID('admin');
599
a13c171d 600 foreach ($options as $key => $currentOption) {
ad2785a2
CR
601 $optionVisibility = CRM_Utils_Array::value('visibility_id', $currentOption, $publicVisibilityID);
602 if ($optionVisibility == $adminVisibilityID) {
a13c171d
CR
603 unset($options[$key]);
604 }
605 }
606 }
6a488035
TO
607
608 $optionFullIds = CRM_Utils_Array::value('option_full_ids', $field, array());
609
610 //soft suppress required rule when option is full.
611 if (!empty($optionFullIds) && (count($options) == count($optionFullIds))) {
612 $isRequire = FALSE;
613 }
1019b2fe
SL
614 if (!empty($options)) {
615 //build the element.
616 CRM_Price_BAO_PriceField::addQuickFormElement($form,
617 $elementName,
618 $fieldId,
619 FALSE,
620 $isRequire,
621 NULL,
622 $options,
623 $optionFullIds
624 );
625 }
6a488035
TO
626 }
627 }
628 $form->assign('priceSet', $form->_priceSet);
629 }
630 else {
631 $eventFeeBlockValues = array();
632 foreach ($form->_feeBlock as $fee) {
633 if (is_array($fee)) {
634
635 //CRM-7632, CRM-6201
636 $totalAmountJs = NULL;
637 if ($className == 'CRM_Event_Form_Participant') {
638 $totalAmountJs = array('onClick' => "fillTotalAmount(" . $fee['value'] . ")");
639 }
640
641 $eventFeeBlockValues['amount_id_' . $fee['amount_id']] = $fee['value'];
642 $elements[] = &$form->createElement('radio', NULL, '',
643 CRM_Utils_Money::format($fee['value']) . ' ' .
644 $fee['label'],
645 $fee['amount_id'],
646 $totalAmountJs
647 );
648 }
649 }
650 $form->assign('eventFeeBlockValues', json_encode($eventFeeBlockValues));
651
652 $form->_defaults['amount'] = CRM_Utils_Array::value('default_fee_id', $form->_values['event']);
653 $element = &$form->addGroup($elements, 'amount', ts('Event Fee(s)'), '<br />');
654 if (isset($form->_online) && $form->_online) {
655 $element->freeze();
656 }
657 if ($required) {
658 $form->addRule('amount', ts('Fee Level is a required field.'), 'required');
659 }
660 }
661 }
662
0cf587a7 663 /**
c490a46a 664 * @param CRM_Core_Form $form
0cf587a7 665 */
6a488035
TO
666 public static function formatFieldsForOptionFull(&$form) {
667 $priceSet = $form->get('priceSet');
668 $priceSetId = $form->get('priceSetId');
e9bb507e 669 $defaultPricefieldIds = array();
670 if (!empty($form->_values['line_items'])) {
671 foreach ($form->_values['line_items'] as $lineItem) {
672 $defaultPricefieldIds[] = $lineItem['price_field_value_id'];
673 }
674 }
6a488035
TO
675 if (!$priceSetId ||
676 !is_array($priceSet) ||
353ffa53
TO
677 empty($priceSet) || empty($priceSet['optionsMaxValueTotal'])
678 ) {
6a488035
TO
679 return;
680 }
681
682 $skipParticipants = $formattedPriceSetDefaults = array();
e03317f1 683 if (!empty($form->_allowConfirmation) && (isset($form->_pId) || isset($form->_additionalParticipantId))) {
6a488035
TO
684 $participantId = isset($form->_pId) ? $form->_pId : $form->_additionalParticipantId;
685 $pricesetDefaults = CRM_Event_Form_EventFees::setDefaultPriceSet($participantId,
686 $form->_eventId
687 );
688 // modify options full to respect the selected fields
689 // options on confirmation.
217d80ab 690 $formattedPriceSetDefaults = self::formatPriceSetParams($form, $pricesetDefaults);
6a488035
TO
691
692 // to skip current registered participants fields option count on confirmation.
693 $skipParticipants[] = $form->_participantId;
694 if (!empty($form->_additionalParticipantIds)) {
695 $skipParticipants = array_merge($skipParticipants, $form->_additionalParticipantIds);
696 }
697 }
698
699 $className = CRM_Utils_System::getClassName($form);
700
701 //get the current price event price set options count.
702 $currentOptionsCount = self::getPriceSetOptionCount($form);
703 $recordedOptionsCount = CRM_Event_BAO_Participant::priceSetOptionsCount($form->_eventId, $skipParticipants);
e9bb507e 704 $optionFullTotalAmount = 0;
0dc0b759 705 $currentParticipantNo = (int) substr($form->_name, 12);
6a488035
TO
706 foreach ($form->_feeBlock as & $field) {
707 $optionFullIds = array();
708 $fieldId = $field['id'];
709 if (!is_array($field['options'])) {
710 continue;
711 }
712 foreach ($field['options'] as & $option) {
353ffa53
TO
713 $optId = $option['id'];
714 $count = CRM_Utils_Array::value('count', $option, 0);
715 $maxValue = CRM_Utils_Array::value('max_value', $option, 0);
716 $dbTotalCount = CRM_Utils_Array::value($optId, $recordedOptionsCount, 0);
6a488035
TO
717 $currentTotalCount = CRM_Utils_Array::value($optId, $currentOptionsCount, 0);
718
79b152ac 719 $totalCount = $currentTotalCount + $dbTotalCount;
6a488035
TO
720 $isFull = FALSE;
721 if ($maxValue &&
0dc0b759 722 (($totalCount >= $maxValue) &&
723 (empty($form->_lineItem[$currentParticipantNo][$optId]['price_field_id']) || $dbTotalCount >= $maxValue))
6a488035
TO
724 ) {
725 $isFull = TRUE;
726 $optionFullIds[$optId] = $optId;
e9bb507e 727 if ($field['html_type'] != 'Select') {
728 if (in_array($optId, $defaultPricefieldIds)) {
729 $optionFullTotalAmount += CRM_Utils_Array::value('amount', $option);
730 }
731 }
732 else {
733 if (!empty($defaultPricefieldIds) && in_array($optId, $defaultPricefieldIds)) {
734 unset($optionFullIds[$optId]);
735 }
736 }
6a488035 737 }
6a488035
TO
738 //here option is not full,
739 //but we don't want to allow participant to increase
740 //seats at the time of re-walking registration.
741 if ($count &&
8dfe9fe3 742 !empty($form->_allowConfirmation) &&
6a488035
TO
743 !empty($formattedPriceSetDefaults)
744 ) {
217d80ab 745 if (empty($formattedPriceSetDefaults["price_{$field}"]) || empty($formattedPriceSetDefaults["price_{$fieldId}"][$optId])) {
6a488035
TO
746 $optionFullIds[$optId] = $optId;
747 $isFull = TRUE;
748 }
749 }
750 $option['is_full'] = $isFull;
751 $option['db_total_count'] = $dbTotalCount;
752 $option['total_option_count'] = $dbTotalCount + $currentTotalCount;
753 }
754
755 //ignore option full for offline registration.
756 if ($className == 'CRM_Event_Form_Participant') {
757 $optionFullIds = array();
758 }
759
760 //finally get option ids in.
761 $field['option_full_ids'] = $optionFullIds;
762 }
e9bb507e 763 $form->assign('optionFullTotalAmount', $optionFullTotalAmount);
6a488035
TO
764 }
765
766 /**
66f9e52b 767 * Global form rule.
6a488035 768 *
d4dd1e85
TO
769 * @param array $fields
770 * The input form values.
771 * @param array $files
772 * The uploaded files if any.
2a6da8d7
EM
773 * @param $self
774 *
6a488035 775 *
72b3a70c
CW
776 * @return bool|array
777 * true if no errors, else array of errors
6a488035 778 */
00be9182 779 public static function formRule($fields, $files, $self) {
6a488035
TO
780 $errors = array();
781 //check that either an email or firstname+lastname is included in the form(CRM-9587)
782 self::checkProfileComplete($fields, $errors, $self->_eventId);
783 //To check if the user is already registered for the event(CRM-2426)
784 if (!$self->_skipDupeRegistrationCheck) {
168e792f 785 self::checkRegistration($fields, $self);
6a488035
TO
786 }
787 //check for availability of registrations.
8cc574cf 788 if (!$self->_allowConfirmation && empty($fields['bypass_payment']) &&
6a488035
TO
789 is_numeric($self->_availableRegistrations) &&
790 CRM_Utils_Array::value('additional_participants', $fields) >= $self->_availableRegistrations
791 ) {
792 $errors['additional_participants'] = ts("There is only enough space left on this event for %1 participant(s).", array(1 => $self->_availableRegistrations));
793 }
794
795 // during confirmation don't allow to increase additional participants, CRM-4320
8cc574cf 796 if ($self->_allowConfirmation && !empty($fields['additional_participants']) &&
6a488035
TO
797 is_array($self->_additionalParticipantIds) &&
798 $fields['additional_participants'] > count($self->_additionalParticipantIds)
799 ) {
800 $errors['additional_participants'] = ts("Oops. It looks like you are trying to increase the number of additional people you are registering for. You can confirm registration for a maximum of %1 additional people.", array(1 => count($self->_additionalParticipantIds)));
801 }
802
803 //don't allow to register w/ waiting if enough spaces available.
5ec4b965 804 if (!empty($fields['bypass_payment']) && $self->_allowConfirmation) {
6a488035 805 if (!is_numeric($self->_availableRegistrations) ||
8cc574cf 806 (empty($fields['priceSetId']) && CRM_Utils_Array::value('additional_participants', $fields) < $self->_availableRegistrations)
6a488035
TO
807 ) {
808 $errors['bypass_payment'] = ts("Oops. There are enough available spaces in this event. You can not add yourself to the waiting list.");
809 }
810 }
811
a7488080 812 if (!empty($fields['additional_participants']) &&
6a488035
TO
813 !CRM_Utils_Rule::positiveInteger($fields['additional_participants'])
814 ) {
815 $errors['additional_participants'] = ts('Please enter a whole number for Number of additional people.');
816 }
817
818 // priceset validations
0dc0b759 819 if (!empty($fields['priceSetId']) &&
820 !$self->_requireApproval && !$self->_allowWaitlist
821 ) {
6a488035
TO
822 //format params.
823 $formatted = self::formatPriceSetParams($self, $fields);
824 $ppParams = array($formatted);
825 $priceSetErrors = self::validatePriceSet($self, $ppParams);
826 $primaryParticipantCount = self::getParticipantCount($self, $ppParams);
827
828 //get price set fields errors in.
829 $errors = array_merge($errors, CRM_Utils_Array::value(0, $priceSetErrors, array()));
830
831 $totalParticipants = $primaryParticipantCount;
a7488080 832 if (!empty($fields['additional_participants'])) {
6a488035
TO
833 $totalParticipants += $fields['additional_participants'];
834 }
835
a7488080 836 if (empty($fields['bypass_payment']) &&
6a488035
TO
837 !$self->_allowConfirmation &&
838 is_numeric($self->_availableRegistrations) &&
839 $self->_availableRegistrations < $totalParticipants
840 ) {
841 $errors['_qf_default'] = ts("Only %1 Registrations available.", array(1 => $self->_availableRegistrations));
842 }
843
844 $lineItem = array();
9da8dc8c 845 CRM_Price_BAO_PriceSet::processAmount($self->_values['fee'], $fields, $lineItem);
601c7a24 846
847 $minAmt = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $fields['priceSetId'], 'min_amount');
6a488035
TO
848 if ($fields['amount'] < 0) {
849 $errors['_qf_default'] = ts('Event Fee(s) can not be less than zero. Please select the options accordingly');
850 }
601c7a24 851 elseif (!empty($minAmt) && $fields['amount'] < $minAmt) {
852 $errors['_qf_default'] = ts('A minimum amount of %1 should be selected from Event Fee(s).', array(
853 1 => CRM_Utils_Money::format($minAmt),
854 ));
855 }
6a488035
TO
856 }
857
f48e6cf7 858 // @todo - can we remove the 'is_monetary' concept?
6a488035 859 if ($self->_values['event']['is_monetary']) {
1019b2fe
SL
860 if (empty($self->_requireApproval) && !empty($fields['amount']) && $fields['amount'] > 0 &&
861 !isset($fields['payment_processor_id'])) {
e02d7e96 862 $errors['payment_processor_id'] = ts('Please select a Payment Method');
0d588131 863 }
6a488035 864
0d588131 865 $isZeroAmount = $skipPaymentValidation = FALSE;
a7488080 866 if (!empty($fields['priceSetId'])) {
6a488035
TO
867 if (CRM_Utils_Array::value('amount', $fields) == 0) {
868 $isZeroAmount = TRUE;
869 }
870 }
a7488080 871 elseif (!empty($fields['amount']) &&
6a488035
TO
872 (isset($self->_values['discount'][$fields['amount']])
873 && CRM_Utils_Array::value('value', $self->_values['discount'][$fields['amount']]) == 0
874 )
875 ) {
876 $isZeroAmount = TRUE;
877 }
a7488080 878 elseif (!empty($fields['amount']) &&
6a488035
TO
879 (isset($self->_values['fee'][$fields['amount']])
880 && CRM_Utils_Array::value('value', $self->_values['fee'][$fields['amount']]) == 0
881 )
882 ) {
883 $isZeroAmount = TRUE;
884 }
885
8cc574cf 886 if ($isZeroAmount && !($self->_forcePayement && !empty($fields['additional_participants']))) {
0d588131 887 $skipPaymentValidation = TRUE;
6a488035
TO
888 }
889
f48e6cf7 890 // also return if zero fees for valid members
891 if (!empty($fields['bypass_payment']) ||
0d588131 892 $skipPaymentValidation ||
6a488035
TO
893 (!$self->_allowConfirmation && ($self->_requireApproval || $self->_allowWaitlist))
894 ) {
895 return empty($errors) ? TRUE : $errors;
896 }
f48e6cf7 897 CRM_Core_Payment_Form::validatePaymentInstrument(
898 $fields['payment_processor_id'],
899 $fields,
900 $errors,
901 (!$self->_isBillingAddressRequiredForPayLater ? NULL : 'billing')
902 );
6a488035 903 }
6a488035 904
6a488035
TO
905 foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
906 if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) {
233319bf 907 $customizedValue = CRM_Core_PseudoConstant::getKey('CRM_Contact_BAO_Contact', $greeting . '_id', 'Customized');
6a488035 908 if ($customizedValue == $greetingType && empty($fields[$greeting . '_custom'])) {
217d80ab 909 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
6a488035
TO
910 array(1 => ucwords(str_replace('_', ' ', $greeting)))
911 );
912 }
913 }
914 }
915 return empty($errors) ? TRUE : $errors;
916 }
917
918 /**
ec022878 919 * Check if profiles are complete when event registration occurs(CRM-9587).
920 *
921 * @param array $fields
922 * @param array $errors
923 * @param int $eventId
6a488035 924 */
00be9182 925 public static function checkProfileComplete($fields, &$errors, $eventId) {
6a488035
TO
926 $email = '';
927 foreach ($fields as $fieldname => $fieldvalue) {
928 if (substr($fieldname, 0, 6) == 'email-' && $fieldvalue) {
929 $email = $fieldvalue;
930 }
931 }
932
8cc574cf 933 if (!$email && !(!empty($fields['first_name']) && !empty($fields['last_name']))) {
6a488035
TO
934 $defaults = $params = array('id' => $eventId);
935 CRM_Event_BAO_Event::retrieve($params, $defaults);
936 $message = ts("Mandatory fields (first name and last name, OR email address) are missing from this form.");
937 $errors['_qf_default'] = $message;
938 }
939 }
940
941 /**
66f9e52b 942 * Process the form submission.
6a488035
TO
943 */
944 public function postProcess() {
945 // get the submitted form values.
946 $params = $this->controller->exportValues($this->_name);
947
948 //set as Primary participant
949 $params['is_primary'] = 1;
950
8ae4d0d3 951 if ($this->_values['event']['is_pay_later']
e02d7e96 952 && (!array_key_exists('hidden_processor', $params) || $params['payment_processor_id'] == 0)
353ffa53 953 ) {
6a488035
TO
954 $params['is_pay_later'] = 1;
955 }
956 else {
957 $params['is_pay_later'] = 0;
958 }
959
960 $this->set('is_pay_later', $params['is_pay_later']);
961
962 // assign pay later stuff
963 $this->_params['is_pay_later'] = CRM_Utils_Array::value('is_pay_later', $params, FALSE);
964 $this->assign('is_pay_later', $params['is_pay_later']);
965 if ($params['is_pay_later']) {
966 $this->assign('pay_later_text', $this->_values['event']['pay_later_text']);
967 $this->assign('pay_later_receipt', $this->_values['event']['pay_later_receipt']);
968 }
6a488035 969
168e792f
DL
970 if (!$this->_allowConfirmation) {
971 // check if the participant is already registered
972 if (!$this->_skipDupeRegistrationCheck) {
7dfe13ab 973 $params['contact_id'] = self::getRegistrationContactID($params, $this, FALSE);
168e792f
DL
974 }
975 }
976
a7488080 977 if (!empty($params['image_URL'])) {
6a488035
TO
978 CRM_Contact_BAO_Contact::processImageParams($params);
979 }
980
981 //carry campaign to partcipants.
982 if (array_key_exists('participant_campaign_id', $params)) {
983 $params['campaign_id'] = $params['participant_campaign_id'];
984 }
985 else {
986 $params['campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->_values['event']);
987 }
988
989 //hack to allow group to register w/ waiting
990 $primaryParticipantCount = self::getParticipantCount($this, $params);
991
992 $totalParticipants = $primaryParticipantCount;
a7488080 993 if (!empty($params['additional_participants'])) {
6a488035
TO
994 $totalParticipants += $params['additional_participants'];
995 }
8cc574cf 996 if (!$this->_allowConfirmation && !empty($params['bypass_payment']) &&
6a488035
TO
997 is_numeric($this->_availableRegistrations) &&
998 $totalParticipants > $this->_availableRegistrations
999 ) {
1000 $this->_allowWaitlist = TRUE;
1001 $this->set('allowWaitlist', TRUE);
1002 }
1003
1004 //carry participant id if pre-registered.
1005 if ($this->_allowConfirmation && $this->_participantId) {
1006 $params['participant_id'] = $this->_participantId;
1007 }
1008
1009 $params['defaultRole'] = 1;
1010 if (array_key_exists('participant_role', $params)) {
1011 $params['participant_role_id'] = $params['participant_role'];
1012 }
1013
1014 if (array_key_exists('participant_role_id', $params)) {
1015 $params['defaultRole'] = 0;
1016 }
a7488080 1017 if (empty($params['participant_role_id']) &&
6a488035
TO
1018 $this->_values['event']['default_role_id']
1019 ) {
1020 $params['participant_role_id'] = $this->_values['event']['default_role_id'];
1021 }
1022
1023 $config = CRM_Core_Config::singleton();
1024 $params['currencyID'] = $config->defaultCurrency;
1025
1026 if ($this->_values['event']['is_monetary']) {
1027 // we first reset the confirm page so it accepts new values
1028 $this->controller->resetPage('Confirm');
1029
1030 //added for discount
1031 $discountId = CRM_Core_BAO_Discount::findSet($this->_eventId, 'civicrm_event');
c039f658 1032 $params['amount_level'] = $this->getAmountLevel($params, $discountId);
6a488035
TO
1033 if (!empty($this->_values['discount'][$discountId])) {
1034 $params['discount_id'] = $discountId;
6a488035
TO
1035 $params['amount'] = $this->_values['discount'][$discountId][$params['amount']]['value'];
1036 }
1037 elseif (empty($params['priceSetId'])) {
16d1c8e2 1038 if (!empty($params['amount'])) {
16d1c8e2 1039 $params['amount'] = $this->_values['fee'][$params['amount']]['value'];
1040 }
1041 else {
c039f658 1042 $params['amount'] = '';
16d1c8e2 1043 }
6a488035
TO
1044 }
1045 else {
1046 $lineItem = array();
9da8dc8c 1047 CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem);
d91b8b33 1048 if ($params['tax_amount']) {
1049 $this->set('tax_amount', $params['tax_amount']);
1050 }
9d8d8fd0 1051 $submittedLineItems = $this->get('lineItem');
1052 if (!empty($submittedLineItems) && is_array($submittedLineItems)) {
0dc0b759 1053 $submittedLineItems[0] = $lineItem;
1054 }
1055 else {
1056 $submittedLineItems = array($lineItem);
1057 }
dba6436f 1058 $submittedLineItems = array_filter($submittedLineItems);
0dc0b759 1059 $this->set('lineItem', $submittedLineItems);
6a488035
TO
1060 $this->set('lineItemParticipantsCount', array($primaryParticipantCount));
1061 }
1062
1063 $this->set('amount', $params['amount']);
1064 $this->set('amount_level', $params['amount_level']);
1065
1066 // generate and set an invoiceID for this transaction
1067 $invoiceID = md5(uniqid(rand(), TRUE));
1068 $this->set('invoiceID', $invoiceID);
1069
b0c462ac 1070 if ($this->_paymentProcessor) {
077017db 1071 $payment = $this->_paymentProcessor['object'];
ec022878 1072 $payment->setBaseReturnUrl('civicrm/event/register');
6a488035 1073 }
0eb1f7ff 1074
1075 // ContributeMode is a deprecated concept. It is short-hand for a bunch of
1076 // assumptions we are working to remove.
6a488035
TO
1077 $this->set('contributeMode', 'direct');
1078
0eb1f7ff 1079 // This code is duplicated multiple places and should be consolidated.
6a488035
TO
1080 if (isset($params["state_province_id-{$this->_bltID}"]) &&
1081 $params["state_province_id-{$this->_bltID}"]
1082 ) {
1083 $params["state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($params["state_province_id-{$this->_bltID}"]);
1084 }
1085
1086 if (isset($params["country_id-{$this->_bltID}"]) &&
1087 $params["country_id-{$this->_bltID}"]
1088 ) {
1089 $params["country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($params["country_id-{$this->_bltID}"]);
1090 }
1091 if (isset($params['credit_card_exp_date'])) {
1092 $params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($params);
1093 $params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($params);
1094 }
1095 if ($this->_values['event']['is_monetary']) {
1096 $params['ip_address'] = CRM_Utils_System::ipAddress();
1097 $params['currencyID'] = $config->defaultCurrency;
6a488035
TO
1098 $params['invoiceID'] = $invoiceID;
1099 }
d0ebccea 1100 $this->_params = $this->get('params');
ec022878 1101 // Set the button so we know what
1102 $params['button'] = $this->controller->getButtonName();
d0ebccea 1103 if (!empty($this->_params) && is_array($this->_params)) {
0dc0b759 1104 $this->_params[0] = $params;
1105 }
1106 else {
1107 $this->_params = array();
1108 $this->_params[] = $params;
1109 }
6a488035 1110 $this->set('params', $this->_params);
f92fc7eb 1111 if ($this->_paymentProcessor &&
223190c8 1112 // Actually we don't really need to check if it supports pre-approval - we could just call
1113 // it regardless as the function we call re-acts tot the rests of the preApproval call.
ec022878 1114 $this->_paymentProcessor['object']->supports('preApproval')
1115 && !$this->_allowWaitlist &&
1116 !$this->_requireApproval
f92fc7eb 1117 ) {
6a488035 1118
0f2b049e 1119 // The concept of contributeMode is deprecated - but still needs removal from the message templates.
ec022878 1120 $this->set('contributeMode', 'express');
6a488035 1121
ec022878 1122 // Send Event Name & Id in Params
1123 $params['eventName'] = $this->_values['event']['title'];
1124 $params['eventId'] = $this->_values['event']['id'];
6a488035 1125
ec022878 1126 $params['cancelURL'] = CRM_Utils_System::url('civicrm/event/register',
1127 "_qf_Register_display=1&qfKey={$this->controller->_key}",
1128 TRUE, NULL, FALSE
1129 );
1130 if (CRM_Utils_Array::value('additional_participants', $params, FALSE)) {
1131 $urlArgs = "_qf_Participant_1_display=1&rfp=1&qfKey={$this->controller->_key}";
1132 }
1133 else {
1134 $urlArgs = "_qf_Confirm_display=1&rfp=1&qfKey={$this->controller->_key}";
1135 }
1136 $params['returnURL'] = CRM_Utils_System::url('civicrm/event/register',
1137 $urlArgs,
1138 TRUE, NULL, FALSE
1139 );
1140 $params['invoiceID'] = $invoiceID;
6a488035 1141
ec022878 1142 $params['component'] = 'event';
223190c8 1143 $this->handlePreApproval($params);
6a488035 1144 }
f92fc7eb
CW
1145 elseif ($this->_paymentProcessor &&
1146 $this->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_NOTIFY
1147 ) {
0f2b049e 1148 // The concept of contributeMode is deprecated - but still needs removal from the message templates.
6a488035
TO
1149 $this->set('contributeMode', 'notify');
1150 }
13f230bc 1151 }
1152 else {
1153 $params['description'] = ts('Online Event Registration') . ' ' . $this->_values['event']['title'];
6a488035 1154
13f230bc 1155 $this->_params = array();
1156 $this->_params[] = $params;
1157 $this->set('params', $this->_params);
6a488035 1158
13f230bc 1159 if (
1160 empty($params['additional_participants'])
1161 && !$this->_values['event']['is_confirm_enabled'] // CRM-11182 - Optional confirmation screen
1162 ) {
3033e657 1163 $this->processRegistration($this->_params);
6a488035
TO
1164 }
1165 }
1166
1167 // If registering > 1 participant, give status message
1168 if (CRM_Utils_Array::value('additional_participants', $params, FALSE)) {
1169 $statusMsg = ts('Registration information for participant 1 has been saved.');
1170 CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
1171 }
1172 }
6a488035 1173
6a488035 1174 /**
66f9e52b 1175 * Method to check if the user is already registered for the event.
6a488035
TO
1176 * and if result found redirect to the event info page
1177 *
d4dd1e85
TO
1178 * @param array $fields
1179 * The input form values(anonymous user).
ec022878 1180 * @param CRM_Event_Form_Registration_Register $self
d4dd1e85
TO
1181 * Event data.
1182 * @param bool $isAdditional
1183 * Treat isAdditional participants a bit differently.
6a488035 1184 *
54957108 1185 * @return int
6a488035 1186 */
7dfe13ab 1187 public static function checkRegistration($fields, &$self, $isAdditional = FALSE) {
6a488035
TO
1188 // CRM-3907, skip check for preview registrations
1189 // CRM-4320 participant need to walk wizard
7dfe13ab 1190 if (
6a488035
TO
1191 ($self->_mode == 'test' || $self->_allowConfirmation)
1192 ) {
1193 return FALSE;
1194 }
1195
7b64dc81 1196 $contactID = self::getRegistrationContactID($fields, $self, $isAdditional);
6a488035 1197
6a488035
TO
1198 if ($contactID) {
1199 $participant = new CRM_Event_BAO_Participant();
1200 $participant->contact_id = $contactID;
1201 $participant->event_id = $self->_values['event']['id'];
1202 if (!empty($fields['participant_role']) && is_numeric($fields['participant_role'])) {
1203 $participant->role_id = $fields['participant_role'];
1204 }
1205 else {
1206 $participant->role_id = $self->_values['event']['default_role_id'];
1207 }
1208 $participant->is_test = 0;
1209 $participant->find();
1210 $statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
1211 while ($participant->fetch()) {
1212 if (array_key_exists($participant->status_id, $statusTypes)) {
1213 if (!$isAdditional && !$self->_values['event']['allow_same_participant_emails']) {
1214 $registerUrl = CRM_Utils_System::url('civicrm/event/register',
1215 "reset=1&id={$self->_values['event']['id']}&cid=0"
1216 );
1217 if ($self->_pcpId) {
1218 $registerUrl .= '&pcpId=' . $self->_pcpId;
1219 }
1220
06141953 1221 $status = ts("It looks like you are already registered for this event. If you want to change your registration, or you feel that you've received this message in error, please contact the site administrator.") . ' ' . ts('You can also <a href="%1">register another participant</a>.', array(1 => $registerUrl));
7dfe13ab 1222 CRM_Core_Session::singleton()->setStatus($status, ts('Oops.'), 'alert');
6a488035
TO
1223 $url = CRM_Utils_System::url('civicrm/event/info',
1224 "reset=1&id={$self->_values['event']['id']}&noFullMsg=true"
1225 );
1226 if ($self->_action & CRM_Core_Action::PREVIEW) {
1227 $url .= '&action=preview';
1228 }
1229
1230 if ($self->_pcpId) {
1231 $url .= '&pcpId=' . $self->_pcpId;
1232 }
1233
1234 CRM_Utils_System::redirect($url);
1235 }
1236
1237 if ($isAdditional) {
06141953 1238 $status = ts("It looks like this participant is already registered for this event. If you want to change your registration, or you feel that you've received this message in error, please contact the site administrator.");
7dfe13ab 1239 CRM_Core_Session::singleton()->setStatus($status, ts('Oops.'), 'alert');
6a488035
TO
1240 return $participant->id;
1241 }
1242 }
1243 }
1244 }
1245 }
96025800 1246
6a488035 1247}