method cannot be a protected static when called from CRM/Event/Form/Registration...
[civicrm-core.git] / CRM / Event / Form / Registration / Register.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
31 */
32
33 /**
34 * This class generates form components for processing Event.
35 */
36 class CRM_Event_Form_Registration_Register extends CRM_Event_Form_Registration {
37
38 /**
39 * The fields involved in this page.
40 */
41 public $_fields;
42
43 /**
44 * The status message that user view.
45 */
46 protected $_waitlistMsg = NULL;
47 protected $_requireApprovalMsg = NULL;
48
49 /**
50 * Deprecated parameter that we hope to remove.
51 *
52 * @var bool
53 */
54 public $_quickConfig = NULL;
55
56 /**
57 * Skip duplicate check.
58 *
59 * This can be set using hook_civicrm_buildForm() to override the registration dupe check.
60 * CRM-7604
61 */
62 public $_skipDupeRegistrationCheck = FALSE;
63
64 public $_paymentProcessorID;
65
66 /**
67 * Show fee block or not.
68 *
69 * @var boolean determines if fee block should be shown or hidden
70 */
71 public $_noFees;
72
73 /**
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 *
78 * @var array
79 */
80 public $_paymentFields = array();
81
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 */
91 static function getRegistrationContactID($fields, $self, $isAdditional) {
92
93 $contactID = NULL;
94 if (!$isAdditional) {
95 $contactID = $self->getContactID();
96 }
97 if (!$contactID && is_array($fields) && $fields) {
98 $contactID = CRM_Contact_BAO_Contact::getFirstDuplicateContact($fields, 'Individual', 'Unsupervised', array(), FALSE, CRM_Utils_Array::value('dedupe_rule_group_id', $self->_values['event']));
99 }
100 return $contactID;
101 }
102
103 /**
104 * Set variables up before form is built.
105 */
106 public function preProcess() {
107 parent::preProcess();
108
109 //CRM-4320.
110 //here we can't use parent $this->_allowWaitlist as user might
111 //walk back and we might set this value in this postProcess.
112 //(we set when spaces < group count and want to allow become part of waiting )
113 $eventFull = CRM_Event_BAO_Participant::eventFull($this->_eventId, FALSE, CRM_Utils_Array::value('has_waitlist', $this->_values['event']));
114
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
118 $this->_noFees = (($eventFull || $this->_requireApproval) && !$this->_allowConfirmation);
119 $this->_paymentProcessors = $this->_noFees ? array() : $this->get('paymentProcessors');
120 $this->preProcessPaymentOptions();
121
122 $this->_allowWaitlist = FALSE;
123 if ($eventFull && !$this->_allowConfirmation && !empty($this->_values['event']['has_waitlist'])) {
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 }
143 }
144
145 /**
146 * Set default values for the form.
147 */
148 public function setDefaultValues() {
149 $this->_defaults = array();
150 if (!$this->_allowConfirmation && $this->_requireApproval) {
151 $this->_defaults['bypass_payment'] = 1;
152 }
153 $contactID = $this->getContactID();
154 CRM_Core_Payment_Form::setDefaultValues($this, $contactID);
155
156 CRM_Event_BAO_Participant::formatFieldsAndSetProfileDefaults($contactID, $this);
157
158 // Set default payment processor as default payment_processor radio button value
159 if (!empty($this->_paymentProcessors)) {
160 foreach ($this->_paymentProcessors as $pid => $value) {
161 if (!empty($value['is_default'])) {
162 $this->_defaults['payment_processor_id'] = $pid;
163 }
164 }
165 }
166
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
170 if (!empty($this->_values['event']['is_pay_later']) &&
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],
209 $discountKey - 1, $discountKey, TRUE
210 ));
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']) {
218 $this->_defaults['participant_role']
219 = $this->_defaults['participant_role_id'] = $this->_values['event']['default_role_id'];
220 }
221 if ($this->_priceSetId && !empty($this->_feeBlock)) {
222 foreach ($this->_feeBlock as $key => $val) {
223 if (empty($val['options'])) {
224 continue;
225 }
226 $optionFullIds = CRM_Utils_Array::value('option_full_ids', $val, array());
227 foreach ($val['options'] as $keys => $values) {
228 if ($values['is_default'] && empty($values['is_full'])) {
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 }
238 $unsetSubmittedOptions[$val['id']] = $optionFullIds;
239 }
240 //reset values for all options those are full.
241 CRM_Event_Form_Registration::resetElementValue($unsetSubmittedOptions, $this);
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 /**
276 * Build the form object.
277 */
278 public function buildQuickForm() {
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
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']);
286
287 CRM_Core_Payment_ProcessorForm::buildQuickForm($this);
288
289 $contactID = $this->getContactID();
290 if ($contactID) {
291 $this->assign('contact_id', $contactID);
292 $this->assign('display_name', CRM_Contact_BAO_Contact::displayName($contactID));
293 }
294
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) {
302 // CRM-17745: Make maximum additional participants configurable
303 // Label is value + 1, since the code sees this is ADDITIONAL participants (in addition to "self")
304 $additionalOptions = array();
305 $additionalOptions[''] = 1;
306 for ($i = 1; $i <= $this->_values['event']['max_additional_participants']; $i++) {
307 $additionalOptions[$i] = $i + 1;
308 }
309 $this->add('select', 'additional_participants',
310 ts('How many people are you registering?'),
311 $additionalOptions,
312 NULL,
313 array('onChange' => "allowParticipant()")
314 );
315 $isAdditionalParticipants = TRUE;
316 }
317 }
318
319 if (!$this->_allowConfirmation) {
320 $bypassPayment = TRUE;
321 }
322
323 //hack to allow group to register w/ waiting
324 if ((!empty($this->_values['event']['is_multiple_registrations']) ||
325 $this->_priceSetId
326 ) &&
327 !$this->_allowConfirmation &&
328 is_numeric($this->_availableRegistrations) && !empty($this->_values['event']['has_waitlist'])
329 ) {
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
358 if ($this->_values['event']['is_monetary']) {
359 self::buildAmount($this);
360 }
361
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
365 $onlinePaymentProcessorEnabled = FALSE;
366 if (!empty($this->_paymentProcessors)) {
367 foreach ($this->_paymentProcessors as $key => $name) {
368 if ($name['billing_mode'] == 1) {
369 $onlinePaymentProcessorEnabled = TRUE;
370 }
371 $pps[$key] = $name['name'];
372 }
373 }
374 if ($this->getContactID() === 0 && !$this->_values['event']['is_multiple_registrations']) {
375 //@todo we are blocking for multiple registrations because we haven't tested
376 $this->addCidZeroOptions($onlinePaymentProcessorEnabled);
377 }
378 if (!empty($this->_values['event']['is_pay_later']) &&
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) {
386 $this->addRadio('payment_processor_id', ts('Payment Method'), $pps,
387 NULL, "&nbsp;"
388 );
389 }
390 elseif (!empty($pps)) {
391 $ppKeys = array_keys($pps);
392 $currentPP = array_pop($ppKeys);
393 $this->addElement('hidden', 'payment_processor_id', $currentPP);
394 }
395 }
396
397 $this->addElement('hidden', 'bypass_payment', NULL, array('id' => 'bypass_payment'));
398
399 $this->assign('bypassPayment', $bypassPayment);
400
401 $userID = $this->getContactID();
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;
448 }
449 else {
450 $allAreBillingModeProcessors = FALSE;
451 }
452
453 if (!$allAreBillingModeProcessors || !empty($this->_values['event']['is_pay_later']) || $bypassPayment
454 ) {
455
456 //freeze button to avoid multiple calls.
457 $js = NULL;
458
459 if (empty($this->_values['event']['is_monetary'])) {
460 $js = array('onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');");
461 }
462
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']
467 && !$this->_values['event']['is_monetary']
468 && !$this->_values['event']['is_confirm_enabled']
469 ) {
470 $buttonLabel = ts('Register');
471 }
472 else {
473 $buttonLabel = ts('Continue');
474 }
475
476 $this->addButtons(array(
477 array(
478 'type' => 'upload',
479 'name' => $buttonLabel,
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);
489 $this->unsavedChangesWarn = TRUE;
490
491 // add pcp fields
492 if ($this->_pcpId) {
493 CRM_PCP_BAO_PCP::buildPcp($this->_pcpId, $this);
494 }
495 }
496
497 /**
498 * Build the radio/text form elements for the amount field
499 *
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.
506 */
507 static public function buildAmount(&$form, $required = TRUE, $discountId = NULL) {
508 // build amount only when needed, skip incase of event full and waitlisting is enabled
509 // and few other conditions check preProcess()
510 if (property_exists($form, '_noFees') && $form->_noFees) {
511 return;
512 }
513
514 //if payment done, no need to build the fee block.
515 if (!empty($form->_paymentId)) {
516 //fix to display line item in update mode.
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
558 if (!empty($form->_priceSet['is_quick_config'])) {
559 $form->_quickConfig = $form->_priceSet['is_quick_config'];
560 }
561 $form->add('hidden', 'priceSetId', $form->_priceSetId);
562
563 // CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
564 $adminFieldVisible = FALSE;
565 if (CRM_Core_Permission::check('administer CiviCRM')) {
566 $adminFieldVisible = TRUE;
567 }
568
569 foreach ($form->_feeBlock as $field) {
570 // public AND admin visibility fields are included for back-office registration and back-office change selections
571 if (CRM_Utils_Array::value('visibility', $field) == 'public' ||
572 (CRM_Utils_Array::value('visibility', $field) == 'admin' && $adminFieldVisible == TRUE) ||
573 $className == 'CRM_Event_Form_Participant' ||
574 $className == 'CRM_Event_Form_ParticipantFeeSelection'
575 ) {
576 $fieldId = $field['id'];
577 $elementName = 'price_' . $fieldId;
578
579 $isRequire = CRM_Utils_Array::value('is_required', $field);
580 if ($button == 'skip') {
581 $isRequire = FALSE;
582 }
583
584 //user might modified w/ hook.
585 $options = CRM_Utils_Array::value('options', $field);
586 if (!is_array($options)) {
587 continue;
588 }
589
590 $optionFullIds = CRM_Utils_Array::value('option_full_ids', $field, array());
591
592 //soft suppress required rule when option is full.
593 if (!empty($optionFullIds) && (count($options) == count($optionFullIds))) {
594 $isRequire = FALSE;
595 }
596 if (!empty($options)) {
597 //build the element.
598 CRM_Price_BAO_PriceField::addQuickFormElement($form,
599 $elementName,
600 $fieldId,
601 FALSE,
602 $isRequire,
603 NULL,
604 $options,
605 $optionFullIds
606 );
607 }
608 }
609 }
610 $form->assign('priceSet', $form->_priceSet);
611 }
612 else {
613 $eventFeeBlockValues = array();
614 foreach ($form->_feeBlock as $fee) {
615 if (is_array($fee)) {
616
617 //CRM-7632, CRM-6201
618 $totalAmountJs = NULL;
619 if ($className == 'CRM_Event_Form_Participant') {
620 $totalAmountJs = array('onClick' => "fillTotalAmount(" . $fee['value'] . ")");
621 }
622
623 $eventFeeBlockValues['amount_id_' . $fee['amount_id']] = $fee['value'];
624 $elements[] = &$form->createElement('radio', NULL, '',
625 CRM_Utils_Money::format($fee['value']) . ' ' .
626 $fee['label'],
627 $fee['amount_id'],
628 $totalAmountJs
629 );
630 }
631 }
632 $form->assign('eventFeeBlockValues', json_encode($eventFeeBlockValues));
633
634 $form->_defaults['amount'] = CRM_Utils_Array::value('default_fee_id', $form->_values['event']);
635 $element = &$form->addGroup($elements, 'amount', ts('Event Fee(s)'), '<br />');
636 if (isset($form->_online) && $form->_online) {
637 $element->freeze();
638 }
639 if ($required) {
640 $form->addRule('amount', ts('Fee Level is a required field.'), 'required');
641 }
642 }
643 }
644
645 /**
646 * @param CRM_Core_Form $form
647 */
648 public static function formatFieldsForOptionFull(&$form) {
649 $priceSet = $form->get('priceSet');
650 $priceSetId = $form->get('priceSetId');
651 $defaultPricefieldIds = array();
652 if (!empty($form->_values['line_items'])) {
653 foreach ($form->_values['line_items'] as $lineItem) {
654 $defaultPricefieldIds[] = $lineItem['price_field_value_id'];
655 }
656 }
657 if (!$priceSetId ||
658 !is_array($priceSet) ||
659 empty($priceSet) || empty($priceSet['optionsMaxValueTotal'])
660 ) {
661 return;
662 }
663
664 $skipParticipants = $formattedPriceSetDefaults = array();
665 if (!empty($form->_allowConfirmation) && (isset($form->_pId) || isset($form->_additionalParticipantId))) {
666 $participantId = isset($form->_pId) ? $form->_pId : $form->_additionalParticipantId;
667 $pricesetDefaults = CRM_Event_Form_EventFees::setDefaultPriceSet($participantId,
668 $form->_eventId
669 );
670 // modify options full to respect the selected fields
671 // options on confirmation.
672 $formattedPriceSetDefaults = self::formatPriceSetParams($form, $pricesetDefaults);
673
674 // to skip current registered participants fields option count on confirmation.
675 $skipParticipants[] = $form->_participantId;
676 if (!empty($form->_additionalParticipantIds)) {
677 $skipParticipants = array_merge($skipParticipants, $form->_additionalParticipantIds);
678 }
679 }
680
681 $className = CRM_Utils_System::getClassName($form);
682
683 //get the current price event price set options count.
684 $currentOptionsCount = self::getPriceSetOptionCount($form);
685 $recordedOptionsCount = CRM_Event_BAO_Participant::priceSetOptionsCount($form->_eventId, $skipParticipants);
686 $optionFullTotalAmount = 0;
687 $currentParticipantNo = (int) substr($form->_name, 12);
688 foreach ($form->_feeBlock as & $field) {
689 $optionFullIds = array();
690 $fieldId = $field['id'];
691 if (!is_array($field['options'])) {
692 continue;
693 }
694 foreach ($field['options'] as & $option) {
695 $optId = $option['id'];
696 $count = CRM_Utils_Array::value('count', $option, 0);
697 $maxValue = CRM_Utils_Array::value('max_value', $option, 0);
698 $dbTotalCount = CRM_Utils_Array::value($optId, $recordedOptionsCount, 0);
699 $currentTotalCount = CRM_Utils_Array::value($optId, $currentOptionsCount, 0);
700
701 $totalCount = $currentTotalCount + $dbTotalCount;
702 $isFull = FALSE;
703 if ($maxValue &&
704 (($totalCount >= $maxValue) &&
705 (empty($form->_lineItem[$currentParticipantNo][$optId]['price_field_id']) || $dbTotalCount >= $maxValue))
706 ) {
707 $isFull = TRUE;
708 $optionFullIds[$optId] = $optId;
709 if ($field['html_type'] != 'Select') {
710 if (in_array($optId, $defaultPricefieldIds)) {
711 $optionFullTotalAmount += CRM_Utils_Array::value('amount', $option);
712 }
713 }
714 else {
715 if (!empty($defaultPricefieldIds) && in_array($optId, $defaultPricefieldIds)) {
716 unset($optionFullIds[$optId]);
717 }
718 }
719 }
720 //here option is not full,
721 //but we don't want to allow participant to increase
722 //seats at the time of re-walking registration.
723 if ($count &&
724 !empty($form->_allowConfirmation) &&
725 !empty($formattedPriceSetDefaults)
726 ) {
727 if (empty($formattedPriceSetDefaults["price_{$field}"]) || empty($formattedPriceSetDefaults["price_{$fieldId}"][$optId])) {
728 $optionFullIds[$optId] = $optId;
729 $isFull = TRUE;
730 }
731 }
732 $option['is_full'] = $isFull;
733 $option['db_total_count'] = $dbTotalCount;
734 $option['total_option_count'] = $dbTotalCount + $currentTotalCount;
735 }
736
737 //ignore option full for offline registration.
738 if ($className == 'CRM_Event_Form_Participant') {
739 $optionFullIds = array();
740 }
741
742 //finally get option ids in.
743 $field['option_full_ids'] = $optionFullIds;
744 }
745 $form->assign('optionFullTotalAmount', $optionFullTotalAmount);
746 }
747
748 /**
749 * Global form rule.
750 *
751 * @param array $fields
752 * The input form values.
753 * @param array $files
754 * The uploaded files if any.
755 * @param $self
756 *
757 *
758 * @return bool|array
759 * true if no errors, else array of errors
760 */
761 public static function formRule($fields, $files, $self) {
762 $errors = array();
763 //check that either an email or firstname+lastname is included in the form(CRM-9587)
764 self::checkProfileComplete($fields, $errors, $self->_eventId);
765 //To check if the user is already registered for the event(CRM-2426)
766 if (!$self->_skipDupeRegistrationCheck) {
767 self::checkRegistration($fields, $self);
768 }
769 //check for availability of registrations.
770 if (!$self->_allowConfirmation && empty($fields['bypass_payment']) &&
771 is_numeric($self->_availableRegistrations) &&
772 CRM_Utils_Array::value('additional_participants', $fields) >= $self->_availableRegistrations
773 ) {
774 $errors['additional_participants'] = ts("There is only enough space left on this event for %1 participant(s).", array(1 => $self->_availableRegistrations));
775 }
776
777 // during confirmation don't allow to increase additional participants, CRM-4320
778 if ($self->_allowConfirmation && !empty($fields['additional_participants']) &&
779 is_array($self->_additionalParticipantIds) &&
780 $fields['additional_participants'] > count($self->_additionalParticipantIds)
781 ) {
782 $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)));
783 }
784
785 //don't allow to register w/ waiting if enough spaces available.
786 if (!empty($fields['bypass_payment']) && $self->_allowConfirmation) {
787 if (!is_numeric($self->_availableRegistrations) ||
788 (empty($fields['priceSetId']) && CRM_Utils_Array::value('additional_participants', $fields) < $self->_availableRegistrations)
789 ) {
790 $errors['bypass_payment'] = ts("Oops. There are enough available spaces in this event. You can not add yourself to the waiting list.");
791 }
792 }
793
794 if (!empty($fields['additional_participants']) &&
795 !CRM_Utils_Rule::positiveInteger($fields['additional_participants'])
796 ) {
797 $errors['additional_participants'] = ts('Please enter a whole number for Number of additional people.');
798 }
799
800 // priceset validations
801 if (!empty($fields['priceSetId']) &&
802 !$self->_requireApproval && !$self->_allowWaitlist
803 ) {
804 //format params.
805 $formatted = self::formatPriceSetParams($self, $fields);
806 $ppParams = array($formatted);
807 $priceSetErrors = self::validatePriceSet($self, $ppParams);
808 $primaryParticipantCount = self::getParticipantCount($self, $ppParams);
809
810 //get price set fields errors in.
811 $errors = array_merge($errors, CRM_Utils_Array::value(0, $priceSetErrors, array()));
812
813 $totalParticipants = $primaryParticipantCount;
814 if (!empty($fields['additional_participants'])) {
815 $totalParticipants += $fields['additional_participants'];
816 }
817
818 if (empty($fields['bypass_payment']) &&
819 !$self->_allowConfirmation &&
820 is_numeric($self->_availableRegistrations) &&
821 $self->_availableRegistrations < $totalParticipants
822 ) {
823 $errors['_qf_default'] = ts("Only %1 Registrations available.", array(1 => $self->_availableRegistrations));
824 }
825
826 $lineItem = array();
827 CRM_Price_BAO_PriceSet::processAmount($self->_values['fee'], $fields, $lineItem);
828
829 $minAmt = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $fields['priceSetId'], 'min_amount');
830 if ($fields['amount'] < 0) {
831 $errors['_qf_default'] = ts('Event Fee(s) can not be less than zero. Please select the options accordingly');
832 }
833 elseif (!empty($minAmt) && $fields['amount'] < $minAmt) {
834 $errors['_qf_default'] = ts('A minimum amount of %1 should be selected from Event Fee(s).', array(
835 1 => CRM_Utils_Money::format($minAmt),
836 ));
837 }
838 }
839
840 // @todo - can we remove the 'is_monetary' concept?
841 if ($self->_values['event']['is_monetary']) {
842 if (empty($self->_requireApproval) && !empty($fields['amount']) && $fields['amount'] > 0 &&
843 !isset($fields['payment_processor_id'])) {
844 $errors['payment_processor_id'] = ts('Please select a Payment Method');
845 }
846
847 $isZeroAmount = $skipPaymentValidation = FALSE;
848 if (!empty($fields['priceSetId'])) {
849 if (CRM_Utils_Array::value('amount', $fields) == 0) {
850 $isZeroAmount = TRUE;
851 }
852 }
853 elseif (!empty($fields['amount']) &&
854 (isset($self->_values['discount'][$fields['amount']])
855 && CRM_Utils_Array::value('value', $self->_values['discount'][$fields['amount']]) == 0
856 )
857 ) {
858 $isZeroAmount = TRUE;
859 }
860 elseif (!empty($fields['amount']) &&
861 (isset($self->_values['fee'][$fields['amount']])
862 && CRM_Utils_Array::value('value', $self->_values['fee'][$fields['amount']]) == 0
863 )
864 ) {
865 $isZeroAmount = TRUE;
866 }
867
868 if ($isZeroAmount && !($self->_forcePayement && !empty($fields['additional_participants']))) {
869 $skipPaymentValidation = TRUE;
870 }
871
872 // also return if zero fees for valid members
873 if (!empty($fields['bypass_payment']) ||
874 $skipPaymentValidation ||
875 (!$self->_allowConfirmation && ($self->_requireApproval || $self->_allowWaitlist))
876 ) {
877 return empty($errors) ? TRUE : $errors;
878 }
879 CRM_Core_Payment_Form::validatePaymentInstrument(
880 $fields['payment_processor_id'],
881 $fields,
882 $errors,
883 (!$self->_isBillingAddressRequiredForPayLater ? NULL : 'billing')
884 );
885 }
886
887 foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
888 if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) {
889 $customizedValue = CRM_Core_OptionGroup::getValue($greeting, 'Customized', 'name');
890 if ($customizedValue == $greetingType && empty($fields[$greeting . '_custom'])) {
891 $errors[$greeting . '_custom'] = ts('Custom %1 is a required field if %1 is of type Customized.',
892 array(1 => ucwords(str_replace('_', ' ', $greeting)))
893 );
894 }
895 }
896 }
897 return empty($errors) ? TRUE : $errors;
898 }
899
900 /**
901 * Check if profiles are complete when event registration occurs(CRM-9587).
902 *
903 * @param array $fields
904 * @param array $errors
905 * @param int $eventId
906 */
907 public static function checkProfileComplete($fields, &$errors, $eventId) {
908 $email = '';
909 foreach ($fields as $fieldname => $fieldvalue) {
910 if (substr($fieldname, 0, 6) == 'email-' && $fieldvalue) {
911 $email = $fieldvalue;
912 }
913 }
914
915 if (!$email && !(!empty($fields['first_name']) && !empty($fields['last_name']))) {
916 $defaults = $params = array('id' => $eventId);
917 CRM_Event_BAO_Event::retrieve($params, $defaults);
918 $message = ts("Mandatory fields (first name and last name, OR email address) are missing from this form.");
919 $errors['_qf_default'] = $message;
920 }
921 }
922
923 /**
924 * Process the form submission.
925 */
926 public function postProcess() {
927 // get the submitted form values.
928 $params = $this->controller->exportValues($this->_name);
929
930 //set as Primary participant
931 $params['is_primary'] = 1;
932
933 if ($this->_values['event']['is_pay_later']
934 && (!array_key_exists('hidden_processor', $params) || $params['payment_processor_id'] == 0)
935 ) {
936 $params['is_pay_later'] = 1;
937 }
938 else {
939 $params['is_pay_later'] = 0;
940 }
941
942 $this->set('is_pay_later', $params['is_pay_later']);
943
944 // assign pay later stuff
945 $this->_params['is_pay_later'] = CRM_Utils_Array::value('is_pay_later', $params, FALSE);
946 $this->assign('is_pay_later', $params['is_pay_later']);
947 if ($params['is_pay_later']) {
948 $this->assign('pay_later_text', $this->_values['event']['pay_later_text']);
949 $this->assign('pay_later_receipt', $this->_values['event']['pay_later_receipt']);
950 }
951
952 if (!$this->_allowConfirmation) {
953 // check if the participant is already registered
954 if (!$this->_skipDupeRegistrationCheck) {
955 $params['contact_id'] = self::getRegistrationContactID($params, $this, FALSE);
956 }
957 }
958
959 if (!empty($params['image_URL'])) {
960 CRM_Contact_BAO_Contact::processImageParams($params);
961 }
962
963 //carry campaign to partcipants.
964 if (array_key_exists('participant_campaign_id', $params)) {
965 $params['campaign_id'] = $params['participant_campaign_id'];
966 }
967 else {
968 $params['campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->_values['event']);
969 }
970
971 //hack to allow group to register w/ waiting
972 $primaryParticipantCount = self::getParticipantCount($this, $params);
973
974 $totalParticipants = $primaryParticipantCount;
975 if (!empty($params['additional_participants'])) {
976 $totalParticipants += $params['additional_participants'];
977 }
978 if (!$this->_allowConfirmation && !empty($params['bypass_payment']) &&
979 is_numeric($this->_availableRegistrations) &&
980 $totalParticipants > $this->_availableRegistrations
981 ) {
982 $this->_allowWaitlist = TRUE;
983 $this->set('allowWaitlist', TRUE);
984 }
985
986 //carry participant id if pre-registered.
987 if ($this->_allowConfirmation && $this->_participantId) {
988 $params['participant_id'] = $this->_participantId;
989 }
990
991 $params['defaultRole'] = 1;
992 if (array_key_exists('participant_role', $params)) {
993 $params['participant_role_id'] = $params['participant_role'];
994 }
995
996 if (array_key_exists('participant_role_id', $params)) {
997 $params['defaultRole'] = 0;
998 }
999 if (empty($params['participant_role_id']) &&
1000 $this->_values['event']['default_role_id']
1001 ) {
1002 $params['participant_role_id'] = $this->_values['event']['default_role_id'];
1003 }
1004
1005 $config = CRM_Core_Config::singleton();
1006 $params['currencyID'] = $config->defaultCurrency;
1007
1008 if ($this->_values['event']['is_monetary']) {
1009 // we first reset the confirm page so it accepts new values
1010 $this->controller->resetPage('Confirm');
1011
1012 //added for discount
1013 $discountId = CRM_Core_BAO_Discount::findSet($this->_eventId, 'civicrm_event');
1014 $params['amount_level'] = $this->getAmountLevel($params, $discountId);
1015 if (!empty($this->_values['discount'][$discountId])) {
1016 $params['discount_id'] = $discountId;
1017 $params['amount'] = $this->_values['discount'][$discountId][$params['amount']]['value'];
1018 }
1019 elseif (empty($params['priceSetId'])) {
1020 if (!empty($params['amount'])) {
1021 $params['amount'] = $this->_values['fee'][$params['amount']]['value'];
1022 }
1023 else {
1024 $params['amount'] = '';
1025 }
1026 }
1027 else {
1028 $lineItem = array();
1029 CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem);
1030 if ($params['tax_amount']) {
1031 $this->set('tax_amount', $params['tax_amount']);
1032 }
1033 $submittedLineItems = $this->get('lineItem');
1034 if (!empty($submittedLineItems) && is_array($submittedLineItems)) {
1035 $submittedLineItems[0] = $lineItem;
1036 }
1037 else {
1038 $submittedLineItems = array($lineItem);
1039 }
1040 $submittedLineItems = array_filter($submittedLineItems);
1041 $this->set('lineItem', $submittedLineItems);
1042 $this->set('lineItemParticipantsCount', array($primaryParticipantCount));
1043 }
1044
1045 $this->set('amount', $params['amount']);
1046 $this->set('amount_level', $params['amount_level']);
1047
1048 // generate and set an invoiceID for this transaction
1049 $invoiceID = md5(uniqid(rand(), TRUE));
1050 $this->set('invoiceID', $invoiceID);
1051
1052 if ($this->_paymentProcessor) {
1053 $payment = $this->_paymentProcessor['object'];
1054 $payment->setBaseReturnUrl('civicrm/event/register');
1055 }
1056
1057 // ContributeMode is a deprecated concept. It is short-hand for a bunch of
1058 // assumptions we are working to remove.
1059 $this->set('contributeMode', 'direct');
1060
1061 // This code is duplicated multiple places and should be consolidated.
1062 if (isset($params["state_province_id-{$this->_bltID}"]) &&
1063 $params["state_province_id-{$this->_bltID}"]
1064 ) {
1065 $params["state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($params["state_province_id-{$this->_bltID}"]);
1066 }
1067
1068 if (isset($params["country_id-{$this->_bltID}"]) &&
1069 $params["country_id-{$this->_bltID}"]
1070 ) {
1071 $params["country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($params["country_id-{$this->_bltID}"]);
1072 }
1073 if (isset($params['credit_card_exp_date'])) {
1074 $params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($params);
1075 $params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($params);
1076 }
1077 if ($this->_values['event']['is_monetary']) {
1078 $params['ip_address'] = CRM_Utils_System::ipAddress();
1079 $params['currencyID'] = $config->defaultCurrency;
1080 $params['invoiceID'] = $invoiceID;
1081 }
1082 $this->_params = $this->get('params');
1083 // Set the button so we know what
1084 $params['button'] = $this->controller->getButtonName();
1085 if (!empty($this->_params) && is_array($this->_params)) {
1086 $this->_params[0] = $params;
1087 }
1088 else {
1089 $this->_params = array();
1090 $this->_params[] = $params;
1091 }
1092 $this->set('params', $this->_params);
1093 if ($this->_paymentProcessor &&
1094 // Actually we don't really need to check if it supports pre-approval - we could just call
1095 // it regardless as the function we call re-acts tot the rests of the preApproval call.
1096 $this->_paymentProcessor['object']->supports('preApproval')
1097 && !$this->_allowWaitlist &&
1098 !$this->_requireApproval
1099 ) {
1100
1101 // The concept of contributeMode is deprecated - but still needs removal from the message templates.
1102 $this->set('contributeMode', 'express');
1103
1104 // Send Event Name & Id in Params
1105 $params['eventName'] = $this->_values['event']['title'];
1106 $params['eventId'] = $this->_values['event']['id'];
1107
1108 $params['cancelURL'] = CRM_Utils_System::url('civicrm/event/register',
1109 "_qf_Register_display=1&qfKey={$this->controller->_key}",
1110 TRUE, NULL, FALSE
1111 );
1112 if (CRM_Utils_Array::value('additional_participants', $params, FALSE)) {
1113 $urlArgs = "_qf_Participant_1_display=1&rfp=1&qfKey={$this->controller->_key}";
1114 }
1115 else {
1116 $urlArgs = "_qf_Confirm_display=1&rfp=1&qfKey={$this->controller->_key}";
1117 }
1118 $params['returnURL'] = CRM_Utils_System::url('civicrm/event/register',
1119 $urlArgs,
1120 TRUE, NULL, FALSE
1121 );
1122 $params['invoiceID'] = $invoiceID;
1123
1124 $params['component'] = 'event';
1125 $this->handlePreApproval($params);
1126 }
1127 elseif ($this->_paymentProcessor &&
1128 $this->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_NOTIFY
1129 ) {
1130 // The concept of contributeMode is deprecated - but still needs removal from the message templates.
1131 $this->set('contributeMode', 'notify');
1132 }
1133 }
1134 else {
1135 $params['description'] = ts('Online Event Registration') . ' ' . $this->_values['event']['title'];
1136
1137 $this->_params = array();
1138 $this->_params[] = $params;
1139 $this->set('params', $this->_params);
1140
1141 if (
1142 empty($params['additional_participants'])
1143 && !$this->_values['event']['is_confirm_enabled'] // CRM-11182 - Optional confirmation screen
1144 ) {
1145 $this->processRegistration($this->_params);
1146 }
1147 }
1148
1149 // If registering > 1 participant, give status message
1150 if (CRM_Utils_Array::value('additional_participants', $params, FALSE)) {
1151 $statusMsg = ts('Registration information for participant 1 has been saved.');
1152 CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
1153 }
1154 }
1155
1156 /**
1157 * Method to check if the user is already registered for the event.
1158 * and if result found redirect to the event info page
1159 *
1160 * @param array $fields
1161 * The input form values(anonymous user).
1162 * @param CRM_Event_Form_Registration_Register $self
1163 * Event data.
1164 * @param bool $isAdditional
1165 * Treat isAdditional participants a bit differently.
1166 *
1167 * @return int
1168 */
1169 public static function checkRegistration($fields, &$self, $isAdditional = FALSE) {
1170 // CRM-3907, skip check for preview registrations
1171 // CRM-4320 participant need to walk wizard
1172 if (
1173 ($self->_mode == 'test' || $self->_allowConfirmation)
1174 ) {
1175 return FALSE;
1176 }
1177
1178 $contactID = self::getRegistrationContactID($fields, $self, $isAdditional);
1179
1180 if ($contactID) {
1181 $participant = new CRM_Event_BAO_Participant();
1182 $participant->contact_id = $contactID;
1183 $participant->event_id = $self->_values['event']['id'];
1184 if (!empty($fields['participant_role']) && is_numeric($fields['participant_role'])) {
1185 $participant->role_id = $fields['participant_role'];
1186 }
1187 else {
1188 $participant->role_id = $self->_values['event']['default_role_id'];
1189 }
1190 $participant->is_test = 0;
1191 $participant->find();
1192 $statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
1193 while ($participant->fetch()) {
1194 if (array_key_exists($participant->status_id, $statusTypes)) {
1195 if (!$isAdditional && !$self->_values['event']['allow_same_participant_emails']) {
1196 $registerUrl = CRM_Utils_System::url('civicrm/event/register',
1197 "reset=1&id={$self->_values['event']['id']}&cid=0"
1198 );
1199 if ($self->_pcpId) {
1200 $registerUrl .= '&pcpId=' . $self->_pcpId;
1201 }
1202
1203 $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));
1204 CRM_Core_Session::singleton()->setStatus($status, ts('Oops.'), 'alert');
1205 $url = CRM_Utils_System::url('civicrm/event/info',
1206 "reset=1&id={$self->_values['event']['id']}&noFullMsg=true"
1207 );
1208 if ($self->_action & CRM_Core_Action::PREVIEW) {
1209 $url .= '&action=preview';
1210 }
1211
1212 if ($self->_pcpId) {
1213 $url .= '&pcpId=' . $self->_pcpId;
1214 }
1215
1216 CRM_Utils_System::redirect($url);
1217 }
1218
1219 if ($isAdditional) {
1220 $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.");
1221 CRM_Core_Session::singleton()->setStatus($status, ts('Oops.'), 'alert');
1222 return $participant->id;
1223 }
1224 }
1225 }
1226 }
1227 }
1228
1229 }