Hide payment options if js disabled CRM-12149
[civicrm-core.git] / CRM / Event / Form / Registration / Register.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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 *
30 *
31 * @package CRM
32 * @copyright CiviCRM LLC (c) 2004-2013
33 * $Id$
34 *
35 */
36
37/**
38 * This class generates form components for processing Event
39 *
40 */
41class CRM_Event_Form_Registration_Register extends CRM_Event_Form_Registration {
42
43 /**
44 * The fields involved in this page
45 *
46 */
47 public $_fields;
48
49 /**
50 * The defaults involved in this page
51 *
52 */
53 public $_defaults;
54
55 /**
56 * The status message that user view.
57 *
58 */
59 protected $_waitlistMsg = NULL;
60 protected $_requireApprovalMsg = NULL;
61
62 public $_quickConfig = NULL;
63
64 /**
65 * Allow deveopera to use hook_civicrm_buildForm()
66 * to override the registration dupe check
67 * CRM-7604
68 */
69 public $_skipDupeRegistrationCheck = FALSE;
70
71 protected $_ppType;
72
73 /**
74 * Function to set variables up before form is built
75 *
76 * @return void
77 * @access public
78 */
79 function preProcess() {
80 parent::preProcess();
81 $this->_ppType = CRM_Utils_Array::value('type', $_GET);
82 $this->assign('ppType', FALSE);
83 if ($this->_ppType) {
84 $this->assign('ppType', TRUE);
85 return CRM_Core_Payment_ProcessorForm::preProcess($this);
86 }
87
88 //get payPal express id and make it available to template
89 $paymentProcessors = $this->get('paymentProcessors');
90 $this->assign('payPalExpressId', 0);
91 if (!empty($paymentProcessors)) {
92 foreach ($paymentProcessors as $ppId => $values) {
93 $payPalExpressId = ($values['payment_processor_type'] == 'PayPal_Express') ? $values['id'] : 0;
94 $this->assign('payPalExpressId', $payPalExpressId);
95 if ($payPalExpressId) {
96 break;
97 }
98 }
99 }
100
101 //CRM-4320.
102 //here we can't use parent $this->_allowWaitlist as user might
103 //walk back and we maight set this value in this postProcess.
104 //(we set when spaces < group count and want to allow become part of waiting )
105
106 $eventFull = CRM_Event_BAO_Participant::eventFull($this->_eventId, FALSE, CRM_Utils_Array::value('has_waitlist', $this->_values['event']));
107
108 $this->_allowWaitlist = FALSE;
109 if ($eventFull && !$this->_allowConfirmation &&
110 CRM_Utils_Array::value('has_waitlist', $this->_values['event'])
111 ) {
112 $this->_allowWaitlist = TRUE;
113 $this->_waitlistMsg = CRM_Utils_Array::value('waitlist_text', $this->_values['event']);
114 if (!$this->_waitlistMsg) {
115 $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.');
116 }
117 }
118 $this->set('allowWaitlist', $this->_allowWaitlist);
119
120 //To check if the user is already registered for the event(CRM-2426)
121 if (!$this->_skipDupeRegistrationCheck) {
122 self::checkRegistration(NULL, $this);
123 }
124
125 $this->assign('availableRegistrations', $this->_availableRegistrations);
126
127 // get the participant values from EventFees.php, CRM-4320
128 if ($this->_allowConfirmation) {
129 CRM_Event_Form_EventFees::preProcess($this);
130 }
131
132 if (CRM_Utils_Array::value('hidden_processor', $_POST)) {
133 $this->set('type', CRM_Utils_Array::value('payment_processor', $_POST));
134 $this->set('mode', $this->_mode);
135 $this->set('paymentProcessor', $this->_paymentProcessor);
136
137 CRM_Core_Payment_ProcessorForm::preProcess($this);
138 CRM_Core_Payment_ProcessorForm::buildQuickForm($this);
139 }
140
141 }
142
143 /**
144 * This function sets the default values for the form. For edit/view mode
145 * the default values are retrieved from the database
c4c5b5fe 146 * Adding discussion from CRM-11915 as code comments
147 * When multiple payment processors are configured for a event and user does any selection changes for them on online event registeration page :
148 * The 'Register' page gets loaded through ajax and following happens :
149 * the setDefaults function is called with the variable _ppType set with selected payment processor type,
150 * so in the 'if' condition checked whether the selected payment processor's billing mode is of 'billing form mode'. If its not, don't setDefaults for billing form and return instead.
151 *- For payment processors of billing mode 'Notify' - return from setDefaults before the code for billing profile population execution .
152 * (done this is because for payment processors with 'Notify' mode billing profile form doesn't get rendered on UI)
6a488035
TO
153 *
154 * @access public
155 *
156 * @return None
157 */
158 function setDefaultValues() {
159 if ($this->_ppType && !($this->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM)) {
c4c5b5fe 160 // see function comment block for explanation of this
6a488035
TO
161 return;
162 }
163
164 $contactID = parent::getContactID();
165 if ($contactID) {
c4c5b5fe 166 //@todo CRM-11915 I observed that even when the billing block is not present the routine to retrieve the billing defaults is still called - which seems a bit redundant.
6a488035
TO
167 $names = array(
168 'first_name', 'middle_name', 'last_name',
169 "street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}",
170 "country_id-{$this->_bltID}", "state_province_id-{$this->_bltID}",
171 );
172
173 foreach ($names as $name) {
174 $fields[$name] = 1;
175 }
176 $fields["state_province-{$this->_bltID}"] = 1;
177 $fields["country-{$this->_bltID}"] = 1;
178 $fields["email-{$this->_bltID}"] = 1;
179 $fields['email-Primary'] = 1;
180
181 CRM_Core_BAO_UFGroup::setProfileDefaults($contactID, $fields, $this->_defaults);
182
183 // use primary email address if billing email address is empty
184 if (empty($this->_defaults["email-{$this->_bltID}"]) &&
185 !empty($this->_defaults['email-Primary'])
186 ) {
187 $this->_defaults["email-{$this->_bltID}"] = $this->_defaults['email-Primary'];
188 }
189
190 foreach ($names as $name) {
191 if (isset($this->_defaults[$name])) {
192 $this->_defaults['billing_' . $name] = $this->_defaults[$name];
193 }
194 }
195 }
196 $config = CRM_Core_Config::singleton();
197 // set default country from config if no country set
198 if (!CRM_Utils_Array::value("billing_country_id-{$this->_bltID}", $this->_defaults)) {
199 $this->_defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
200 }
201
202 // now fix all state country selectors
203 CRM_Core_BAO_Address::fixAllStateSelects($this, $this->_defaults);
204
205 if ($this->_ppType) {
206 return $this->_defaults;
207 }
208
209 if ($contactID) {
210 $options = array();
211 $fields = array();
212
213 if (!empty($this->_fields)) {
214 $removeCustomFieldTypes = array('Participant');
215 foreach ($this->_fields as $name => $dontCare) {
216 if (substr($name, 0, 7) == 'custom_') {
217 $id = substr($name, 7);
218 if (!$this->_allowConfirmation &&
219 !CRM_Core_BAO_CustomGroup::checkCustomField($id, $removeCustomFieldTypes)
220 ) {
221 continue;
222 }
223 // ignore component fields
224 }
225 elseif ((substr($name, 0, 12) == 'participant_')) {
226 continue;
227 }
228 $fields[$name] = 1;
229 }
230 }
231 }
3feb567a
DL
232
233 if (!empty($fields)) {
234 CRM_Core_BAO_UFGroup::setProfileDefaults($contactID, $fields, $this->_defaults);
235 }
236
6a488035
TO
237 //if event is monetary and pay later is enabled and payment
238 //processor is not available then freeze the pay later checkbox with
239 //default check
240 if (CRM_Utils_Array::value('is_pay_later', $this->_values['event']) &&
241 !is_array($this->_paymentProcessor)
242 ) {
243 $this->_defaults['is_pay_later'] = 1;
244 }
245
246 //set custom field defaults
247 if (!empty($this->_fields)) {
248 //load default campaign from page.
249 if (array_key_exists('participant_campaign_id', $this->_fields)) {
250 $this->_defaults['participant_campaign_id'] = CRM_Utils_Array::value('campaign_id',
251 $this->_values['event']
252 );
253 }
254
255 foreach ($this->_fields as $name => $field) {
256 if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
257 // fix for CRM-1743
258 if (!isset($this->_defaults[$name])) {
259 CRM_Core_BAO_CustomField::setProfileDefaults($customFieldID, $name, $this->_defaults,
260 NULL, CRM_Profile_Form::MODE_REGISTER
261 );
262 }
263 }
264 }
265 }
266
267 //fix for CRM-3088, default value for discount set.
268 $discountId = NULL;
269 if (!empty($this->_values['discount'])) {
270 $discountId = CRM_Core_BAO_Discount::findSet($this->_eventId, 'civicrm_event');
271 if ($discountId) {
272 if (isset($this->_values['event']['default_discount_fee_id'])) {
273 $discountKey = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue',
274 $this->_values['event']['default_discount_fee_id'],
275 'weight', 'id'
276 );
277
278 $this->_defaults['amount'] = key(array_slice($this->_values['discount'][$discountId],
279 $discountKey - 1, $discountKey, TRUE
280 ));
281 }
282 }
283 }
284
285 // add this event's default participant role to defaults array
286 // (for cases where participant_role field is included in form via profile)
287 if ($this->_values['event']['default_role_id']) {
288 $this->_defaults['participant_role'] =
289 $this->_defaults['participant_role_id'] = $this->_values['event']['default_role_id'];
290 }
291 if ($this->_priceSetId && !empty($this->_feeBlock)) {
292 foreach ($this->_feeBlock as $key => $val) {
293 foreach ($val['options'] as $keys => $values) {
294 if ($values['is_default'] &&
295 !CRM_Utils_Array::value('is_full', $values)
296 ) {
297
298 if ($val['html_type'] == 'CheckBox') {
299 $this->_defaults["price_{$key}"][$keys] = 1;
300 }
301 else {
302 $this->_defaults["price_{$key}"] = $keys;
303 }
304 }
305 }
306 }
307 }
308
309 //set default participant fields, CRM-4320.
310 $hasAdditionalParticipants = FALSE;
311 if ($this->_allowConfirmation) {
312 $this->_contactId = $contactID;
313 $this->_discountId = $discountId;
314 $forcePayLater = CRM_Utils_Array::value('is_pay_later', $this->_defaults, FALSE);
315 $this->_defaults = array_merge($this->_defaults, CRM_Event_Form_EventFees::setDefaultValues($this));
316 $this->_defaults['is_pay_later'] = $forcePayLater;
317
318 if ($this->_additionalParticipantIds) {
319 $hasAdditionalParticipants = TRUE;
320 $this->_defaults['additional_participants'] = count($this->_additionalParticipantIds);
321 }
322 }
323 $this->assign('hasAdditionalParticipants', $hasAdditionalParticipants);
324
325 // //hack to simplify credit card entry for testing
326 // $this->_defaults['credit_card_type'] = 'Visa';
327 // $this->_defaults['credit_card_number'] = '4807731747657838';
328 // $this->_defaults['cvv2'] = '000';
329 // $this->_defaults['credit_card_exp_date'] = array( 'Y' => '2010', 'M' => '05' );
330
331 // to process Custom data that are appended to URL
332 $getDefaults = CRM_Core_BAO_CustomGroup::extractGetParams($this, "'Contact', 'Individual', 'Contribution', 'Participant'");
333 if (!empty($getDefaults)) {
334 $this->_defaults = array_merge($this->_defaults, $getDefaults);
335 }
336
337 return $this->_defaults;
338 }
339
340 /**
341 * Function to build the form
342 *
343 * @return None
344 * @access public
345 */
346 public function buildQuickForm() {
347 if ($this->_ppType) {
348 return CRM_Core_Payment_ProcessorForm::buildQuickForm($this);
349 }
350
351 $contactID = parent::getContactID();
352 $this->assign('contact_id', $contactID);
353 $display_name = '';
354 if ($contactID) {
355 $display_name = CRM_Contact_BAO_Contact::displayName($contactID);
356 }
357 $this->assign('display_name', $display_name);
358
359 $config = CRM_Core_Config::singleton();
360 $this->add('hidden', 'scriptFee', NULL);
361 $this->add('hidden', 'scriptArray', NULL);
362
363 $bypassPayment = $allowGroupOnWaitlist = $isAdditionalParticipants = FALSE;
364 if ($this->_values['event']['is_multiple_registrations']) {
365 // don't allow to add additional during confirmation if not preregistered.
366 if (!$this->_allowConfirmation || $this->_additionalParticipantIds) {
367 // Hardcode maximum number of additional participants here for now. May need to make this configurable per event.
368 // Label is value + 1, since the code sees this is ADDITIONAL participants (in addition to "self")
369 $additionalOptions = array('' => ts('1'), 1 => ts('2'), 2 => ts('3'), 3 => ts('4'), 4 => ts('5'),
370 5 => ts('6'), 6 => ts('7'), 7 => ts('8'), 8 => ts('9'), 9 => ts('10'),
371 );
372 $element = $this->add('select', 'additional_participants',
373 ts('How many people are you registering?'),
374 $additionalOptions,
375 NULL,
376 array('onChange' => "allowParticipant()")
377 );
378 $isAdditionalParticipants = TRUE;
379 }
380 }
381
382 //hack to allow group to register w/ waiting
383 if ((CRM_Utils_Array::value('is_multiple_registrations', $this->_values['event']) ||
384 $this->_priceSetId
385 ) &&
386 !$this->_allowConfirmation &&
387 is_numeric($this->_availableRegistrations)
388 && CRM_Utils_Array::value('has_waitlist', $this->_values['event'])
389 ) {
390 $bypassPayment = TRUE;
391 //case might be group become as a part of waitlist.
392 //If not waitlist then they require admin approve.
393 $allowGroupOnWaitlist = TRUE;
394 $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));
395
396 if ($this->_requireApproval) {
397 $this->_requireApprovalMsg = CRM_Utils_Array::value('approval_req_text', $this->_values['event'],
398 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.')
399 );
400 }
401 }
402
403 //case where only approval needed - no waitlist.
404 if ($this->_requireApproval &&
405 !$this->_allowWaitlist && !$bypassPayment
406 ) {
407 $this->_requireApprovalMsg = CRM_Utils_Array::value('approval_req_text', $this->_values['event'],
408 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.')
409 );
410 }
411
412 //lets display status to primary page only.
413 $this->assign('waitlistMsg', $this->_waitlistMsg);
414 $this->assign('requireApprovalMsg', $this->_requireApprovalMsg);
415 $this->assign('allowGroupOnWaitlist', $allowGroupOnWaitlist);
416 $this->assign('isAdditionalParticipants', $isAdditionalParticipants);
417
418 $this->buildCustom($this->_values['custom_pre_id'], 'customPre');
419 $this->buildCustom($this->_values['custom_post_id'], 'customPost');
420
421 //lets get js on two different qf elements.
422 $showHidePayfieldName = NULL;
423 $showHidePaymentInformation = FALSE;
424 if ($this->_values['event']['is_monetary']) {
425 self::buildAmount($this);
426 }
427
428 $pps = NULL;
429 $this->_paymentProcessors = $this->get('paymentProcessors');
430 if (!empty($this->_paymentProcessors)) {
431 $pps = $this->_paymentProcessors;
432 foreach ($pps as $key => & $name) {
433 $pps[$key] = $name['name'];
434 }
435 }
436
437 if (CRM_Utils_Array::value('is_pay_later', $this->_values['event']) &&
438 ($this->_allowConfirmation || (!$this->_requireApproval && !$this->_allowWaitlist))
439 ) {
440 $pps[0] = $this->_values['event']['pay_later_text'];
441 }
442
443 if ($this->_values['event']['is_monetary']) {
444 if (count($pps) > 1) {
445 $this->addRadio('payment_processor', ts('Payment Method'), $pps,
446 NULL, "&nbsp;", TRUE
447 );
448 }
449 elseif (!empty($pps)) {
450 $ppKeys = array_keys($pps);
451 $currentPP = array_pop($ppKeys);
452 $this->addElement('hidden', 'payment_processor', $currentPP);
453 }
454 }
455
456 //lets add some qf element to bypass payment validations, CRM-4320
457 if ($bypassPayment) {
458 $this->addElement('hidden', 'bypass_payment', NULL, array('id' => 'bypass_payment'));
459 }
460 $this->assign('bypassPayment', $bypassPayment);
461 $this->assign('showHidePaymentInformation', $showHidePaymentInformation);
462
463 $userID = parent::getContactID();
464
465 if (!$userID) {
466 $createCMSUser = FALSE;
467
468 if ($this->_values['custom_pre_id']) {
469 $profileID = $this->_values['custom_pre_id'];
470 $createCMSUser = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $profileID, 'is_cms_user');
471 }
472
473 if (!$createCMSUser &&
474 $this->_values['custom_post_id']
475 ) {
476 if (!is_array($this->_values['custom_post_id'])) {
477 $profileIDs = array($this->_values['custom_post_id']);
478 }
479 else {
480 $profileIDs = $this->_values['custom_post_id'];
481 }
482 foreach ($profileIDs as $pid) {
483 if (CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $pid, 'is_cms_user')) {
484 $profileID = $pid;
485 $createCMSUser = TRUE;
486 break;
487 }
488 }
489 }
490
491 if ($createCMSUser) {
492 CRM_Core_BAO_CMSUser::buildForm($this, $profileID, TRUE);
493 }
494 }
495
496 //we have to load confirm contribution button in template
497 //when multiple payment processor as the user
498 //can toggle with payment processor selection
499 $billingModePaymentProcessors = 0;
500 if (!CRM_Utils_System::isNull($this->_paymentProcessors)) {
501 foreach ($this->_paymentProcessors as $key => $values) {
502 if ($values['billing_mode'] == CRM_Core_Payment::BILLING_MODE_BUTTON) {
503 $billingModePaymentProcessors++;
504 }
505 }
506 }
507
508 if ($billingModePaymentProcessors && count($this->_paymentProcessors) == $billingModePaymentProcessors) {
509 $allAreBillingModeProcessors = TRUE;
510 } else {
511 $allAreBillingModeProcessors = FALSE;
512 }
513
514 if (!$allAreBillingModeProcessors ||
515 CRM_Utils_Array::value('is_pay_later', $this->_values['event']) || $bypassPayment
516 ) {
517
518 //freeze button to avoid multiple calls.
519 $js = NULL;
520
521 if (!CRM_Utils_Array::value('is_monetary', $this->_values['event'])) {
522 $js = array('onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');");
523 }
524 $this->addButtons(array(
525 array(
526 'type' => 'upload',
527 'name' => ts('Continue >>'),
528 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
529 'isDefault' => TRUE,
530 'js' => $js,
531 ),
532 )
533 );
534 }
535
536 $this->addFormRule(array('CRM_Event_Form_Registration_Register', 'formRule'), $this);
537
538 // add pcp fields
539 if ($this->_pcpId) {
540 CRM_PCP_BAO_PCP::buildPcp($this->_pcpId, $this);
541 }
542 }
543
544 /**
545 * build the radio/text form elements for the amount field
546 *
547 * @param object $form form object
548 * @param boolean $required true if you want to add formRule
549 * @param int $discountId discount id for the event
550 *
551 * @return void
552 * @access public
553 * @static
554 */
555 static public function buildAmount(&$form, $required = TRUE, $discountId = NULL) {
556 //if payment done, no need to build the fee block.
557 if (isset($form->_paymentId) && $form->_paymentId) {
558 //fix to diaplay line item in update mode.
559 $form->assign('priceSet', isset($form->_priceSet) ? $form->_priceSet : NULL);
560 return;
561 }
562
563 $feeFields = CRM_Utils_Array::value('fee', $form->_values);
564
565 if (is_array($feeFields)) {
566 $form->_feeBlock = &$form->_values['fee'];
567 }
568
569 //check for discount.
570 $discountedFee = CRM_Utils_Array::value('discount', $form->_values);
571 if (is_array($discountedFee) && !empty($discountedFee)) {
572 if (!$discountId) {
573 $form->_discountId = $discountId = CRM_Core_BAO_Discount::findSet($form->_eventId, 'civicrm_event');
574 }
575 if ($discountId) {
576 $form->_feeBlock = &$form->_values['discount'][$discountId];
577 }
578 }
579 if (!is_array($form->_feeBlock)) {
580 $form->_feeBlock = array();
581 }
582
583 //its time to call the hook.
584 CRM_Utils_Hook::buildAmount('event', $form, $form->_feeBlock);
585
586 //reset required if participant is skipped.
587 $button = substr($form->controller->getButtonName(), -4);
588 if ($required && $button == 'skip') {
589 $required = FALSE;
590 }
591
592 $className = CRM_Utils_System::getClassName($form);
593
594 //build the priceset fields.
595 if (isset($form->_priceSetId) && $form->_priceSetId) {
596
597 //format price set fields across option full.
598 self::formatFieldsForOptionFull($form);
599
600 if (CRM_Utils_Array::value('is_quick_config', $form->_priceSet)) {
601 $form->_quickConfig = $form->_priceSet['is_quick_config'];
602 }
603 $form->add('hidden', 'priceSetId', $form->_priceSetId);
604
605 foreach ($form->_feeBlock as $field) {
606 if (CRM_Utils_Array::value('visibility', $field) == 'public' ||
607 $className == 'CRM_Event_Form_Participant'
608 ) {
609 $fieldId = $field['id'];
610 $elementName = 'price_' . $fieldId;
611
612 $isRequire = CRM_Utils_Array::value('is_required', $field);
613 if ($button == 'skip') {
614 $isRequire = FALSE;
615 }
616
617 //user might modified w/ hook.
618 $options = CRM_Utils_Array::value('options', $field);
619 if (!is_array($options)) {
620 continue;
621 }
622
623 $optionFullIds = CRM_Utils_Array::value('option_full_ids', $field, array());
624
625 //soft suppress required rule when option is full.
626 if (!empty($optionFullIds) && (count($options) == count($optionFullIds))) {
627 $isRequire = FALSE;
628 }
629
630 //build the element.
631 CRM_Price_BAO_Field::addQuickFormElement($form,
632 $elementName,
633 $fieldId,
634 FALSE,
635 $isRequire,
636 NULL,
637 $options,
638 $optionFullIds
639 );
640 }
641 }
642 $form->assign('priceSet', $form->_priceSet);
643 }
644 else {
645 $eventFeeBlockValues = array();
646 foreach ($form->_feeBlock as $fee) {
647 if (is_array($fee)) {
648
649 //CRM-7632, CRM-6201
650 $totalAmountJs = NULL;
651 if ($className == 'CRM_Event_Form_Participant') {
652 $totalAmountJs = array('onClick' => "fillTotalAmount(" . $fee['value'] . ")");
653 }
654
655 $eventFeeBlockValues['amount_id_' . $fee['amount_id']] = $fee['value'];
656 $elements[] = &$form->createElement('radio', NULL, '',
657 CRM_Utils_Money::format($fee['value']) . ' ' .
658 $fee['label'],
659 $fee['amount_id'],
660 $totalAmountJs
661 );
662 }
663 }
664 $form->assign('eventFeeBlockValues', json_encode($eventFeeBlockValues));
665
666 $form->_defaults['amount'] = CRM_Utils_Array::value('default_fee_id', $form->_values['event']);
667 $element = &$form->addGroup($elements, 'amount', ts('Event Fee(s)'), '<br />');
668 if (isset($form->_online) && $form->_online) {
669 $element->freeze();
670 }
671 if ($required) {
672 $form->addRule('amount', ts('Fee Level is a required field.'), 'required');
673 }
674 }
675 }
676
677 public static function formatFieldsForOptionFull(&$form) {
678 $priceSet = $form->get('priceSet');
679 $priceSetId = $form->get('priceSetId');
680 if (!$priceSetId ||
681 !is_array($priceSet) ||
682 empty($priceSet) ||
683 !CRM_Utils_Array::value('optionsMaxValueTotal', $priceSet)
684 ) {
685 return;
686 }
687
688 $skipParticipants = $formattedPriceSetDefaults = array();
689 if ($form->_allowConfirmation && (isset($form->_pId) || isset($form->_additionalParticipantId))) {
690 $participantId = isset($form->_pId) ? $form->_pId : $form->_additionalParticipantId;
691 $pricesetDefaults = CRM_Event_Form_EventFees::setDefaultPriceSet($participantId,
692 $form->_eventId
693 );
694 // modify options full to respect the selected fields
695 // options on confirmation.
696 $formattedPriceSetDefaults = self::formatPriceSetParams($form, $pricesetDefaultOptions);
697
698 // to skip current registered participants fields option count on confirmation.
699 $skipParticipants[] = $form->_participantId;
700 if (!empty($form->_additionalParticipantIds)) {
701 $skipParticipants = array_merge($skipParticipants, $form->_additionalParticipantIds);
702 }
703 }
704
705 $className = CRM_Utils_System::getClassName($form);
706
707 //get the current price event price set options count.
708 $currentOptionsCount = self::getPriceSetOptionCount($form);
709 $recordedOptionsCount = CRM_Event_BAO_Participant::priceSetOptionsCount($form->_eventId, $skipParticipants);
710
711 foreach ($form->_feeBlock as & $field) {
712 $optionFullIds = array();
713 $fieldId = $field['id'];
714 if (!is_array($field['options'])) {
715 continue;
716 }
717 foreach ($field['options'] as & $option) {
718 $optId = $option['id'];
719 $count = CRM_Utils_Array::value('count', $option, 0);
720 $maxValue = CRM_Utils_Array::value('max_value', $option, 0);
721 $dbTotalCount = CRM_Utils_Array::value($optId, $recordedOptionsCount, 0);
722 $currentTotalCount = CRM_Utils_Array::value($optId, $currentOptionsCount, 0);
723
724 // Do not consider current count for select field,
725 // since we are not going to freeze the options.
726 if ($field['html_type'] == 'Select') {
727 $totalCount = $dbTotalCount;
728 }
729 else {
730 $totalCount = $currentTotalCount + $dbTotalCount;
731 }
732
733 $isFull = FALSE;
734 if ($maxValue &&
735 (($totalCount >= $maxValue) || ($totalCount + $count > $maxValue))
736 ) {
737 $isFull = TRUE;
738 $optionFullIds[$optId] = $optId;
739 }
740
741 //here option is not full,
742 //but we don't want to allow participant to increase
743 //seats at the time of re-walking registration.
744 if ($count &&
745 $form->_allowConfirmation &&
746 !empty($formattedPriceSetDefaults)
747 ) {
748 if (!CRM_Utils_Array::value("price_{$field}", $formattedPriceSetDefaults) ||
749 !CRM_Utils_Array::value($opId, $formattedPriceSetDefaults["price_{$fieldId}"])
750 ) {
751 $optionFullIds[$optId] = $optId;
752 $isFull = TRUE;
753 }
754 }
755 $option['is_full'] = $isFull;
756 $option['db_total_count'] = $dbTotalCount;
757 $option['total_option_count'] = $dbTotalCount + $currentTotalCount;
758 }
759
760 //ignore option full for offline registration.
761 if ($className == 'CRM_Event_Form_Participant') {
762 $optionFullIds = array();
763 }
764
765 //finally get option ids in.
766 $field['option_full_ids'] = $optionFullIds;
767 }
768 }
769
770 /**
771 * global form rule
772 *
773 * @param array $fields the input form values
774 * @param array $files the uploaded files if any
775 * @param array $options additional user data
776 *
777 * @return true if no errors, else array of errors
778 * @access public
779 * @static
780 */
781 static function formRule($fields, $files, $self) {
782 $errors = array();
783 //check that either an email or firstname+lastname is included in the form(CRM-9587)
784 self::checkProfileComplete($fields, $errors, $self->_eventId);
785 //To check if the user is already registered for the event(CRM-2426)
786 if (!$self->_skipDupeRegistrationCheck) {
168e792f 787 self::checkRegistration($fields, $self);
6a488035
TO
788 }
789 //check for availability of registrations.
790 if (!$self->_allowConfirmation &&
791 !CRM_Utils_Array::value('bypass_payment', $fields) &&
792 is_numeric($self->_availableRegistrations) &&
793 CRM_Utils_Array::value('additional_participants', $fields) >= $self->_availableRegistrations
794 ) {
795 $errors['additional_participants'] = ts("There is only enough space left on this event for %1 participant(s).", array(1 => $self->_availableRegistrations));
796 }
797
798 // during confirmation don't allow to increase additional participants, CRM-4320
799 if ($self->_allowConfirmation &&
800 CRM_Utils_Array::value('additional_participants', $fields) &&
801 is_array($self->_additionalParticipantIds) &&
802 $fields['additional_participants'] > count($self->_additionalParticipantIds)
803 ) {
804 $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)));
805 }
806
807 //don't allow to register w/ waiting if enough spaces available.
808 if (CRM_Utils_Array::value('bypass_payment', $fields)) {
809 if (!is_numeric($self->_availableRegistrations) ||
810 (!CRM_Utils_Array::value('priceSetId', $fields) && CRM_Utils_Array::value('additional_participants', $fields) < $self->_availableRegistrations)
811 ) {
812 $errors['bypass_payment'] = ts("Oops. There are enough available spaces in this event. You can not add yourself to the waiting list.");
813 }
814 }
815
816 if (CRM_Utils_Array::value('additional_participants', $fields) &&
817 !CRM_Utils_Rule::positiveInteger($fields['additional_participants'])
818 ) {
819 $errors['additional_participants'] = ts('Please enter a whole number for Number of additional people.');
820 }
821
822 // priceset validations
823 if (CRM_Utils_Array::value('priceSetId', $fields)) {
824 //format params.
825 $formatted = self::formatPriceSetParams($self, $fields);
826 $ppParams = array($formatted);
827 $priceSetErrors = self::validatePriceSet($self, $ppParams);
828 $primaryParticipantCount = self::getParticipantCount($self, $ppParams);
829
830 //get price set fields errors in.
831 $errors = array_merge($errors, CRM_Utils_Array::value(0, $priceSetErrors, array()));
832
833 $totalParticipants = $primaryParticipantCount;
834 if (CRM_Utils_Array::value('additional_participants', $fields)) {
835 $totalParticipants += $fields['additional_participants'];
836 }
837
838 if (!CRM_Utils_Array::value('bypass_payment', $fields) &&
839 !$self->_allowConfirmation &&
840 is_numeric($self->_availableRegistrations) &&
841 $self->_availableRegistrations < $totalParticipants
842 ) {
843 $errors['_qf_default'] = ts("Only %1 Registrations available.", array(1 => $self->_availableRegistrations));
844 }
845
846 $lineItem = array();
847 CRM_Price_BAO_Set::processAmount($self->_values['fee'], $fields, $lineItem);
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 }
851 }
852
853 if ($self->_values['event']['is_monetary']) {
854 if (is_array($self->_paymentProcessor)) {
855 $payment = CRM_Core_Payment::singleton($self->_mode, $self->_paymentProcessor, $this);
856 $error = $payment->checkConfig($self->_mode);
857 if ($error) {
858 $errors['_qf_default'] = $error;
859 }
860 }
861 // return if this is express mode
862 $config = CRM_Core_Config::singleton();
863 if ($self->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_BUTTON) {
864 if (CRM_Utils_Array::value($self->_expressButtonName . '_x', $fields) ||
865 CRM_Utils_Array::value($self->_expressButtonName . '_y', $fields) ||
866 CRM_Utils_Array::value($self->_expressButtonName, $fields)
867 ) {
868 return empty($errors) ? TRUE : $errors;
869 }
870 }
871
872 $isZeroAmount = $skipPayementValidation = FALSE;
873 if (CRM_Utils_Array::value('priceSetId', $fields)) {
874 if (CRM_Utils_Array::value('amount', $fields) == 0) {
875 $isZeroAmount = TRUE;
876 }
877 }
878 elseif (CRM_Utils_Array::value('amount', $fields) &&
879 (isset($self->_values['discount'][$fields['amount']])
880 && CRM_Utils_Array::value('value', $self->_values['discount'][$fields['amount']]) == 0
881 )
882 ) {
883 $isZeroAmount = TRUE;
884 }
885 elseif (CRM_Utils_Array::value('amount', $fields) &&
886 (isset($self->_values['fee'][$fields['amount']])
887 && CRM_Utils_Array::value('value', $self->_values['fee'][$fields['amount']]) == 0
888 )
889 ) {
890 $isZeroAmount = TRUE;
891 }
892
893 if ($isZeroAmount && !($self->_forcePayement && CRM_Utils_Array::value('additional_participants', $fields))) {
894 $skipPayementValidation = TRUE;
895 }
896
897 // also return if paylater mode or zero fees for valid members
898 if (CRM_Utils_Array::value('is_pay_later', $fields) ||
899 CRM_Utils_Array::value('bypass_payment', $fields) ||
900 $skipPayementValidation ||
901 (!$self->_allowConfirmation && ($self->_requireApproval || $self->_allowWaitlist))
902 ) {
903 return empty($errors) ? TRUE : $errors;
904 }
905 if (property_exists($self, '_paymentFields') && !empty($self->_paymentFields )) {
906 foreach ($self->_paymentFields as $name => $fld) {
907 if ($fld['is_required'] &&
908 CRM_Utils_System::isNull(CRM_Utils_Array::value($name, $fields))
909 ) {
910 $errors[$name] = ts('%1 is a required field.', array(1 => $fld['title']));
911 }
912 }
913 }
914 }
915 // make sure that credit card number and cvv are valid
916 if (CRM_Utils_Array::value('credit_card_type', $fields)) {
917 if (CRM_Utils_Array::value('credit_card_number', $fields) &&
918 !CRM_Utils_Rule::creditCardNumber($fields['credit_card_number'], $fields['credit_card_type'])
919 ) {
920 $errors['credit_card_number'] = ts('Please enter a valid Credit Card Number');
921 }
922
923 if (CRM_Utils_Array::value('cvv2', $fields) &&
924 !CRM_Utils_Rule::cvv($fields['cvv2'], $fields['credit_card_type'])
925 ) {
926 $errors['cvv2'] = ts('Please enter a valid Credit Card Verification Number');
927 }
928 }
929 foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
930 if ($greetingType = CRM_Utils_Array::value($greeting, $fields)) {
931 $customizedValue = CRM_Core_OptionGroup::getValue($greeting, 'Customized', 'name');
932 if ($customizedValue == $greetingType && empty($fields[$greeting . '_custom'])) {
933 $errors[$customizedGreeting] = ts('Custom %1 is a required field if %1 is of type Customized.',
934 array(1 => ucwords(str_replace('_', ' ', $greeting)))
935 );
936 }
937 }
938 }
939 return empty($errors) ? TRUE : $errors;
940 }
941
942 /**
943 * Check if profiles are complete when event registration occurs(CRM-9587)
944 *
945 */
946 static function checkProfileComplete($fields, &$errors, $eventId) {
947 $email = '';
948 foreach ($fields as $fieldname => $fieldvalue) {
949 if (substr($fieldname, 0, 6) == 'email-' && $fieldvalue) {
950 $email = $fieldvalue;
951 }
952 }
953
954 if (!$email && !(CRM_Utils_Array::value('first_name', $fields) &&
955 CRM_Utils_Array::value('last_name', $fields)
956 )) {
957 $defaults = $params = array('id' => $eventId);
958 CRM_Event_BAO_Event::retrieve($params, $defaults);
959 $message = ts("Mandatory fields (first name and last name, OR email address) are missing from this form.");
960 $errors['_qf_default'] = $message;
961 }
962 }
963
964 /**
965 * Function to process the form
966 *
967 * @access public
968 *
969 * @return None
970 */
971 public function postProcess() {
972 // get the submitted form values.
973 $params = $this->controller->exportValues($this->_name);
974
975 //set as Primary participant
976 $params['is_primary'] = 1;
977
978 if ($this->_values['event']['is_pay_later'] && !array_key_exists('hidden_processor', $params)) {
979 $params['is_pay_later'] = 1;
980 }
981 else {
982 $params['is_pay_later'] = 0;
983 }
984
985 $this->set('is_pay_later', $params['is_pay_later']);
986
987 // assign pay later stuff
988 $this->_params['is_pay_later'] = CRM_Utils_Array::value('is_pay_later', $params, FALSE);
989 $this->assign('is_pay_later', $params['is_pay_later']);
990 if ($params['is_pay_later']) {
991 $this->assign('pay_later_text', $this->_values['event']['pay_later_text']);
992 $this->assign('pay_later_receipt', $this->_values['event']['pay_later_receipt']);
993 }
6a488035 994
168e792f
DL
995 if (!$this->_allowConfirmation) {
996 // check if the participant is already registered
997 if (!$this->_skipDupeRegistrationCheck) {
998 $params['contact_id'] = self::checkRegistration($params, $this, FALSE, TRUE, TRUE);
999 }
1000 }
1001
6a488035
TO
1002 if (CRM_Utils_Array::value('image_URL', $params)) {
1003 CRM_Contact_BAO_Contact::processImageParams($params);
1004 }
1005
1006 //carry campaign to partcipants.
1007 if (array_key_exists('participant_campaign_id', $params)) {
1008 $params['campaign_id'] = $params['participant_campaign_id'];
1009 }
1010 else {
1011 $params['campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->_values['event']);
1012 }
1013
1014 //hack to allow group to register w/ waiting
1015 $primaryParticipantCount = self::getParticipantCount($this, $params);
1016
1017 $totalParticipants = $primaryParticipantCount;
1018 if (CRM_Utils_Array::value('additional_participants', $params)) {
1019 $totalParticipants += $params['additional_participants'];
1020 }
1021 if (!$this->_allowConfirmation &&
1022 CRM_Utils_Array::value('bypass_payment', $params) &&
1023 is_numeric($this->_availableRegistrations) &&
1024 $totalParticipants > $this->_availableRegistrations
1025 ) {
1026 $this->_allowWaitlist = TRUE;
1027 $this->set('allowWaitlist', TRUE);
1028 }
1029
1030 //carry participant id if pre-registered.
1031 if ($this->_allowConfirmation && $this->_participantId) {
1032 $params['participant_id'] = $this->_participantId;
1033 }
1034
1035 $params['defaultRole'] = 1;
1036 if (array_key_exists('participant_role', $params)) {
1037 $params['participant_role_id'] = $params['participant_role'];
1038 }
1039
1040 if (array_key_exists('participant_role_id', $params)) {
1041 $params['defaultRole'] = 0;
1042 }
1043 if (!CRM_Utils_Array::value('participant_role_id', $params) &&
1044 $this->_values['event']['default_role_id']
1045 ) {
1046 $params['participant_role_id'] = $this->_values['event']['default_role_id'];
1047 }
1048
1049 $config = CRM_Core_Config::singleton();
1050 $params['currencyID'] = $config->defaultCurrency;
1051
1052 if ($this->_values['event']['is_monetary']) {
1053 // we first reset the confirm page so it accepts new values
1054 $this->controller->resetPage('Confirm');
1055
1056 //added for discount
1057 $discountId = CRM_Core_BAO_Discount::findSet($this->_eventId, 'civicrm_event');
1058
1059 if (!empty($this->_values['discount'][$discountId])) {
1060 $params['discount_id'] = $discountId;
1061 $params['amount_level'] = $this->_values['discount'][$discountId][$params['amount']]['label'];
1062
1063 $params['amount'] = $this->_values['discount'][$discountId][$params['amount']]['value'];
1064 }
1065 elseif (empty($params['priceSetId'])) {
1066 $params['amount_level'] = $this->_values['fee'][$params['amount']]['label'];
1067 $params['amount'] = $this->_values['fee'][$params['amount']]['value'];
1068 }
1069 else {
1070 $lineItem = array();
1071 CRM_Price_BAO_Set::processAmount($this->_values['fee'], $params, $lineItem);
1072 $this->set('lineItem', array($lineItem));
1073 $this->set('lineItemParticipantsCount', array($primaryParticipantCount));
1074 }
1075
1076 $this->set('amount', $params['amount']);
1077 $this->set('amount_level', $params['amount_level']);
1078
1079 // generate and set an invoiceID for this transaction
1080 $invoiceID = md5(uniqid(rand(), TRUE));
1081 $this->set('invoiceID', $invoiceID);
1082
1083 if (is_array($this->_paymentProcessor)) {
1084 $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
1085 }
1086 // default mode is direct
1087 $this->set('contributeMode', 'direct');
1088
1089 if (isset($params["state_province_id-{$this->_bltID}"]) &&
1090 $params["state_province_id-{$this->_bltID}"]
1091 ) {
1092 $params["state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($params["state_province_id-{$this->_bltID}"]);
1093 }
1094
1095 if (isset($params["country_id-{$this->_bltID}"]) &&
1096 $params["country_id-{$this->_bltID}"]
1097 ) {
1098 $params["country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($params["country_id-{$this->_bltID}"]);
1099 }
1100 if (isset($params['credit_card_exp_date'])) {
1101 $params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($params);
1102 $params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($params);
1103 }
1104 if ($this->_values['event']['is_monetary']) {
1105 $params['ip_address'] = CRM_Utils_System::ipAddress();
1106 $params['currencyID'] = $config->defaultCurrency;
1107 $params['payment_action'] = 'Sale';
1108 $params['invoiceID'] = $invoiceID;
1109 }
1110
1111 $this->_params = array();
1112 $this->_params[] = $params;
1113 $this->set('params', $this->_params);
1114
1115 if ($this->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_BUTTON) {
1116 //get the button name
1117 $buttonName = $this->controller->getButtonName();
1118 if (in_array($buttonName,
1119 array(
1120 $this->_expressButtonName,
1121 $this->_expressButtonName . '_x',
1122 $this->_expressButtonName . '_y',
1123 )
1124 ) &&
1125 !CRM_Utils_Array::value('is_pay_later', $params) &&
1126 !$this->_allowWaitlist &&
1127 !$this->_requireApproval
1128 ) {
1129 $this->set('contributeMode', 'express');
1130
1131 // Send Event Name & Id in Params
1132 $params['eventName'] = $this->_values['event']['title'];
1133 $params['eventId'] = $this->_values['event']['id'];
1134
1135 $params['cancelURL'] = CRM_Utils_System::url('civicrm/event/register',
1136 "_qf_Register_display=1&qfKey={$this->controller->_key}",
1137 TRUE, NULL, FALSE
1138 );
1139 if (CRM_Utils_Array::value('additional_participants', $params, FALSE)) {
1140 $urlArgs = "_qf_Participant_1_display=1&rfp=1&qfKey={$this->controller->_key}";
1141 }
1142 else {
1143 $urlArgs = "_qf_Confirm_display=1&rfp=1&qfKey={$this->controller->_key}";
1144 }
1145 $params['returnURL'] = CRM_Utils_System::url('civicrm/event/register',
1146 $urlArgs,
1147 TRUE, NULL, FALSE
1148 );
1149 $params['invoiceID'] = $invoiceID;
1150
1151 //default action is Sale
1152 $params['payment_action'] = 'Sale';
1153
1154 $token = $payment->setExpressCheckout($params);
1155 if (is_a($token, 'CRM_Core_Error')) {
1156 CRM_Core_Error::displaySessionError($token);
1157 CRM_Utils_System::redirect($params['cancelURL']);
1158 }
1159
1160 $this->set('token', $token);
1161
1162 $paymentURL = $this->_paymentProcessor['url_site'] . "/cgi-bin/webscr?cmd=_express-checkout&token=$token";
1163
1164 CRM_Utils_System::redirect($paymentURL);
1165 }
1166 }
1167 elseif ($this->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_NOTIFY) {
1168 $this->set('contributeMode', 'notify');
1169 }
1170 }
1171 else {
1172 $session = CRM_Core_Session::singleton();
1173 $params['description'] = ts('Online Event Registration') . ' ' . $this->_values['event']['title'];
1174
1175 $this->_params = array();
1176 $this->_params[] = $params;
1177 $this->set('params', $this->_params);
1178
1179 if (!CRM_Utils_Array::value('additional_participants', $params)) {
1180 self::processRegistration($this->_params);
1181 }
1182 }
1183
1184 // If registering > 1 participant, give status message
1185 if (CRM_Utils_Array::value('additional_participants', $params, FALSE)) {
1186 $statusMsg = ts('Registration information for participant 1 has been saved.');
1187 CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
1188 }
1189 }
1190 //end of function
1191
1192 /*
168e792f 1193 * Function to process Registration of free event
6a488035 1194 *
168e792f
DL
1195 * @param array $param Form valuess
1196 * @param int contactID
6a488035 1197 *
168e792f
DL
1198 * @return None
1199 * access public
6a488035
TO
1200 *
1201 */
1202 public function processRegistration($params, $contactID = NULL) {
1203 $session = CRM_Core_Session::singleton();
1204 $this->_participantInfo = array();
1205
1206 // CRM-4320, lets build array of cancelled additional participant ids
1207 // those are drop or skip by primary at the time of confirmation.
1208 // get all in and then unset those are confirmed.
1209 $cancelledIds = $this->_additionalParticipantIds;
1210
1211 $participantCount = array();
1212 foreach ($params as $participantNum => $record) {
1213 if ($record == 'skip') {
1214 $participantCount[$participantNum] = 'skip';
1215 }
1216 elseif ($participantNum) {
1217 $participantCount[$participantNum] = 'participant';
1218 }
1219 }
1220
1221 $registerByID = NULL;
1222 foreach ($params as $key => $value) {
1223 if ($value != 'skip') {
1224 $fields = NULL;
1225
1226 // setting register by Id and unset contactId.
1227 if (!CRM_Utils_Array::value('is_primary', $value)) {
1228 $contactID = NULL;
1229 $registerByID = $this->get('registerByID');
1230 if ($registerByID) {
1231 $value['registered_by_id'] = $registerByID;
1232 }
1233 // get an email if one exists for the participant
1234 $participantEmail = '';
1235 foreach (array_keys($value) as $valueName) {
1236 if (substr($valueName, 0, 6) == 'email-') {
1237 $participantEmail = $value[$valueName];
1238 }
1239 }
1240 if ($participantEmail) {
1241 $this->_participantInfo[] = $participantEmail;
1242 }
1243 else {
1244 $this->_participantInfo[] = $value['first_name'] . ' ' . $value['last_name'];
1245 }
1246 }
1247 elseif (CRM_Utils_Array::value('contact_id', $value)) {
1248 $contactID = $value['contact_id'];
1249 }
1250 else {
1251 $contactID = parent::getContactID();
1252 }
1253
1254 CRM_Event_Form_Registration_Confirm::fixLocationFields($value, $fields);
1255 //for free event or additional participant, dont create billing email address.
1256 if (!CRM_Utils_Array::value('is_primary', $value) || !$this->_values['event']['is_monetary']) {
1257 unset($value["email-{$this->_bltID}"]);
1258 }
1259
1260 $contactID = CRM_Event_Form_Registration_Confirm::updateContactFields($contactID, $value, $fields);
1261
1262 // lets store the contactID in the session
1263 // we dont store in userID in case the user is doing multiple
1264 // transactions etc
1265 // for things like tell a friend
1266 if (!parent::getContactID() && CRM_Utils_Array::value('is_primary', $value)) {
1267 $session->set('transaction.userID', $contactID);
1268 }
1269
1270 //lets get the status if require approval or waiting.
1271
1272 $waitingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
1273 if ($this->_allowWaitlist && !$this->_allowConfirmation) {
1274 $value['participant_status_id'] = $value['participant_status'] = array_search('On waitlist', $waitingStatuses);
1275 }
1276 elseif ($this->_requireApproval && !$this->_allowConfirmation) {
1277 $value['participant_status_id'] = $value['participant_status'] = array_search('Awaiting approval', $waitingStatuses);
1278 }
1279
1280 $this->set('value', $value);
1281 $this->confirmPostProcess($contactID, NULL, NULL);
1282
1283 //lets get additional participant id to cancel.
1284 if ($this->_allowConfirmation && is_array($cancelledIds)) {
1285 $additonalId = CRM_Utils_Array::value('participant_id', $value);
1286 if ($additonalId && $key = array_search($additonalId, $cancelledIds)) {
1287 unset($cancelledIds[$key]);
1288 }
1289 }
1290 }
1291 }
1292
1293 // update status and send mail to cancelled additonal participants, CRM-4320
1294 if ($this->_allowConfirmation && is_array($cancelledIds) && !empty($cancelledIds)) {
1295 $cancelledId = array_search('Cancelled',
1296 CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'")
1297 );
1298 CRM_Event_BAO_Participant::transitionParticipants($cancelledIds, $cancelledId);
1299 }
1300
1301 //set information about additional participants if exists
1302 if (count($this->_participantInfo)) {
1303 $this->set('participantInfo', $this->_participantInfo);
1304 }
1305
1306 //send mail Confirmation/Receipt
1307 if ($this->_contributeMode != 'checkout' ||
1308 $this->_contributeMode != 'notify'
1309 ) {
1310 $isTest = FALSE;
1311 if ($this->_action & CRM_Core_Action::PREVIEW) {
1312 $isTest = TRUE;
1313 }
1314
1315 //handle if no additional participant.
1316 if (!$registerByID) {
1317 $registerByID = $this->get('registerByID');
1318 }
1319 $primaryContactId = $this->get('primaryContactId');
1320
1321 //build an array of custom profile and assigning it to template.
1322 $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($registerByID, NULL,
1323 $primaryContactId, $isTest, TRUE
1324 );
1325
1326 //lets carry all paticipant params w/ values.
1327 foreach ($additionalIDs as $participantID => $contactId) {
1328 $participantNum = NULL;
1329 if ($participantID == $registerByID) {
1330 $participantNum = 0;
1331 }
1332 else {
1333 if ($participantNum = array_search('participant', $participantCount)) {
1334 unset($participantCount[$participantNum]);
1335 }
1336 }
1337
1338 if ($participantNum === NULL) {
1339 break;
1340 }
1341
1342 //carry the participant submitted values.
1343 $this->_values['params'][$participantID] = $params[$participantNum];
1344 }
1345
1346 //lets send mails to all with meanigful text, CRM-4320.
1347 $this->assign('isOnWaitlist', $this->_allowWaitlist);
1348 $this->assign('isRequireApproval', $this->_requireApproval);
1349
1350 foreach ($additionalIDs as $participantID => $contactId) {
1351 if ($participantID == $registerByID) {
1352 //set as Primary Participant
1353 $this->assign('isPrimary', 1);
1354
1355 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($participantID, $this->_values, NULL, $isTest);
1356
1357 if (count($customProfile)) {
1358 $this->assign('customProfile', $customProfile);
1359 $this->set('customProfile', $customProfile);
1360 }
1361 }
1362 else {
1363 $this->assign('isPrimary', 0);
1364 $this->assign('customProfile', NULL);
1365 }
1366
1367 //send Confirmation mail to Primary & additional Participants if exists
1368 CRM_Event_BAO_Event::sendMail($contactId, $this->_values, $participantID, $isTest);
1369 }
1370 }
1371 }
1372
1373 /**
1374 * Method to check if the user is already registered for the event
1375 * and if result found redirect to the event info page
1376 *
1377 * @param array $fields the input form values(anonymous user)
1378 * @param array $self event data
168e792f
DL
1379 * @param boolean $isAdditional treat isAdditional participants a bit differently
1380 * @param boolean $returnContactId just find and return the contactID match to use
1381 * @param boolean $useDedupeRules force usage of dedupe rules
6a488035
TO
1382 *
1383 * @return void
1384 * @access public
1385 */
168e792f 1386 function checkRegistration($fields, &$self, $isAdditional = FALSE, $returnContactId = FALSE, $useDedupeRules = FALSE) {
6a488035
TO
1387 // CRM-3907, skip check for preview registrations
1388 // CRM-4320 participant need to walk wizard
1389 if (!$returnContactId &&
1390 ($self->_mode == 'test' || $self->_allowConfirmation)
1391 ) {
1392 return FALSE;
1393 }
1394
1395 $contactID = NULL;
1396 $session = CRM_Core_Session::singleton();
1397 if (!$isAdditional) {
1398 $contactID = parent::getContactID();
1399 }
1400
1401 if (!$contactID &&
1402 is_array($fields) &&
1403 !empty($fields)
1404 ) {
1405
1406 //CRM-6996
1407 //as we are allowing w/ same email address,
1408 //lets check w/ other contact params.
1409 if ($self->_values['event']['allow_same_participant_emails']) {
1410 $params = $fields;
1411 $level = ($isAdditional) ? 'Supervised' : 'Unsupervised';
1412
1413 $dedupeParams = CRM_Dedupe_Finder::formatParams($params, 'Individual');
1414
1415 // disable permission based on cache since event registration is public page/feature.
1416 $dedupeParams['check_permission'] = FALSE;
1417 $ids = CRM_Dedupe_Finder::dupesByParams($dedupeParams, 'Individual', $level);
1418 $contactID = CRM_Utils_Array::value(0, $ids);
1419 }
1420 else {
1421 foreach ($fields as $fieldname => $fieldvalue) {
1422 if (substr($fieldname, 0, 6) == 'email-') {
1423 $emailString = trim($fieldvalue);
1424 if (!empty($emailString)) {
1425 $match = CRM_Contact_BAO_Contact::matchContactOnEmail($emailString, 'Individual');
1426 if (!empty($match)) {
1427 $contactID = $match->contact_id;
1428 }
1429 }
1430 }
1431 }
1432 }
1433 }
1434
1435 if ($returnContactId) {
1436 // CRM-7377
1437 // return contactID if contact already exists
1438 return $contactID;
1439 }
1440
1441 if ($contactID) {
1442 $participant = new CRM_Event_BAO_Participant();
1443 $participant->contact_id = $contactID;
1444 $participant->event_id = $self->_values['event']['id'];
1445 if (!empty($fields['participant_role']) && is_numeric($fields['participant_role'])) {
1446 $participant->role_id = $fields['participant_role'];
1447 }
1448 else {
1449 $participant->role_id = $self->_values['event']['default_role_id'];
1450 }
1451 $participant->is_test = 0;
1452 $participant->find();
1453 $statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
1454 while ($participant->fetch()) {
1455 if (array_key_exists($participant->status_id, $statusTypes)) {
1456 if (!$isAdditional && !$self->_values['event']['allow_same_participant_emails']) {
1457 $registerUrl = CRM_Utils_System::url('civicrm/event/register',
1458 "reset=1&id={$self->_values['event']['id']}&cid=0"
1459 );
1460 if ($self->_pcpId) {
1461 $registerUrl .= '&pcpId=' . $self->_pcpId;
1462 }
1463
1464 $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 gotten this message in error, please contact the site administrator.") . ' ' . ts('You can also <a href="%1">register another participant</a>.', array(1 => $registerUrl));
1465 $session->setStatus($status, ts('Oops.'), 'alert');
1466 $url = CRM_Utils_System::url('civicrm/event/info',
1467 "reset=1&id={$self->_values['event']['id']}&noFullMsg=true"
1468 );
1469 if ($self->_action & CRM_Core_Action::PREVIEW) {
1470 $url .= '&action=preview';
1471 }
1472
1473 if ($self->_pcpId) {
1474 $url .= '&pcpId=' . $self->_pcpId;
1475 }
1476
1477 CRM_Utils_System::redirect($url);
1478 }
1479
1480 if ($isAdditional) {
1481 $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 gotten this message in error, please contact the site administrator.");
1482 $session->setStatus($status, ts('Oops.'), 'alert');
1483 return $participant->id;
1484 }
1485 }
1486 }
1487 }
1488 }
1489}
1490