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