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