Merge pull request #5686 from josephlacey/bower-adds
[civicrm-core.git] / CRM / Event / Form / Registration.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
33 * $Id$
34 *
35 */
36
37 /**
38 * This class generates form components for processing Event
39 *
40 */
41 class CRM_Event_Form_Registration extends CRM_Core_Form {
42
43 /**
44 * How many locationBlocks should we display?
45 *
46 * @var int
47 * @const
48 */
49 const LOCATION_BLOCKS = 1;
50
51 /**
52 * The id of the event we are proceessing.
53 *
54 * @var int
55 */
56 public $_eventId;
57
58 /**
59 * The array of ids of all the participant we are proceessing.
60 *
61 * @var int
62 */
63 protected $_participantIDS = NULL;
64
65 /**
66 * The id of the participant we are proceessing.
67 *
68 * @var int
69 */
70 protected $_participantId;
71
72 /**
73 * Is participant able to walk registration wizard.
74 *
75 * @var Boolean
76 */
77 public $_allowConfirmation;
78
79 /**
80 * Is participant requires approval.
81 *
82 * @var Boolean
83 */
84 public $_requireApproval;
85
86 /**
87 * Is event configured for waitlist.
88 *
89 * @var Boolean
90 */
91 public $_allowWaitlist;
92
93 /**
94 * Store additional participant ids.
95 * when there are pre-registered.
96 *
97 * @var array
98 */
99 public $_additionalParticipantIds;
100
101 /**
102 * The mode that we are in.
103 *
104 * @var string
105 * @protect
106 */
107 public $_mode;
108
109 /**
110 * The values for the contribution db object.
111 *
112 * @var array
113 */
114 public $_values;
115
116 /**
117 * The paymentProcessor attributes for this page.
118 *
119 * @var array
120 */
121 public $_paymentProcessor;
122
123 /**
124 * The params submitted by the form and computed by the app.
125 *
126 * @var array
127 */
128 protected $_params;
129
130 /**
131 * The fields involved in this contribution page.
132 *
133 * @var array
134 */
135 public $_fields;
136
137 /**
138 * The billing location id for this contribiution page.
139 *
140 * @var int
141 */
142 public $_bltID;
143
144 /**
145 * Price Set ID, if the new price set method is used
146 *
147 * @var int
148 */
149 public $_priceSetId = NULL;
150
151 /**
152 * Array of fields for the price set.
153 *
154 * @var array
155 */
156 public $_priceSet;
157
158 public $_action;
159
160 public $_pcpId;
161
162 /* Is event already full.
163 *
164 * @var boolean
165 */
166
167 public $_isEventFull;
168
169 public $_lineItem;
170 public $_lineItemParticipantsCount;
171 public $_availableRegistrations;
172
173 public $_forcePayement;
174
175 public $_isBillingAddressRequiredForPayLater;
176
177 /**
178 * Set variables up before form is built.
179 *
180 * @return void
181 */
182 public function preProcess() {
183 $this->_eventId = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
184 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE);
185
186 //CRM-4320
187 $this->_participantId = CRM_Utils_Request::retrieve('participantId', 'Positive', $this);
188
189 // current mode
190 $this->_mode = ($this->_action == 1024) ? 'test' : 'live';
191
192 $this->_values = $this->get('values');
193 $this->_fields = $this->get('fields');
194 $this->_bltID = $this->get('bltID');
195 $this->_paymentProcessor = $this->get('paymentProcessor');
196 $this->_priceSetId = $this->get('priceSetId');
197 $this->_priceSet = $this->get('priceSet');
198 $this->_lineItem = $this->get('lineItem');
199 $this->_isEventFull = $this->get('isEventFull');
200 $this->_lineItemParticipantsCount = $this->get('lineItemParticipants');
201 if (!is_array($this->_lineItem)) {
202 $this->_lineItem = array();
203 }
204 if (!is_array($this->_lineItemParticipantsCount)) {
205 $this->_lineItemParticipantsCount = array();
206 }
207 $this->_availableRegistrations = $this->get('availableRegistrations');
208 $this->_participantIDS = $this->get('participantIDs');
209
210 //check if participant allow to walk registration wizard.
211 $this->_allowConfirmation = $this->get('allowConfirmation');
212
213 // check for Approval
214 $this->_requireApproval = $this->get('requireApproval');
215
216 // check for waitlisting.
217 $this->_allowWaitlist = $this->get('allowWaitlist');
218
219 $this->_forcePayement = $this->get('forcePayement');
220
221 //get the additional participant ids.
222 $this->_additionalParticipantIds = $this->get('additionalParticipantIds');
223 $config = CRM_Core_Config::singleton();
224
225 if (!$this->_values) {
226 // create redirect URL to send folks back to event info page is registration not available
227 $infoUrl = CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$this->_eventId}",
228 FALSE, NULL, FALSE, TRUE
229 );
230
231 // this is the first time we are hitting this, so check for permissions here
232 if (!CRM_Core_Permission::event(CRM_Core_Permission::EDIT, $this->_eventId, 'register for events')) {
233 CRM_Core_Error::statusBounce(ts('You do not have permission to register for this event'), $infoUrl);
234 }
235
236 // get all the values from the dao object
237 $this->_values = $this->_fields = array();
238 $this->_forcePayement = FALSE;
239
240 //retrieve event information
241 $params = array('id' => $this->_eventId);
242 CRM_Event_BAO_Event::retrieve($params, $this->_values['event']);
243
244 $this->checkValidEvent($infoUrl);
245 // get the participant values, CRM-4320
246 $this->_allowConfirmation = FALSE;
247 if ($this->_participantId) {
248 $this->processFirstParticipant($this->_participantId);
249 }
250 //check for additional participants.
251 if ($this->_allowConfirmation && $this->_values['event']['is_multiple_registrations']) {
252 $additionalParticipantIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_participantId);
253 $cnt = 1;
254 foreach ($additionalParticipantIds as $additionalParticipantId) {
255 $this->_additionalParticipantIds[$cnt] = $additionalParticipantId;
256 $cnt++;
257 }
258 $this->set('additionalParticipantIds', $this->_additionalParticipantIds);
259 }
260
261 $eventFull = CRM_Event_BAO_Participant::eventFull($this->_eventId, FALSE,
262 CRM_Utils_Array::value('has_waitlist', $this->_values['event'])
263 );
264
265 $this->_allowWaitlist = $this->_isEventFull = FALSE;
266 if ($eventFull && !$this->_allowConfirmation) {
267 $this->_isEventFull = TRUE;
268 //lets redirecting to info only when to waiting list.
269 $this->_allowWaitlist = CRM_Utils_Array::value('has_waitlist', $this->_values['event']);
270 if (!$this->_allowWaitlist) {
271 CRM_Utils_System::redirect($infoUrl);
272 }
273 }
274 $this->set('isEventFull', $this->_isEventFull);
275 $this->set('allowWaitlist', $this->_allowWaitlist);
276
277 //check for require requires approval.
278 $this->_requireApproval = FALSE;
279 if (!empty($this->_values['event']['requires_approval']) && !$this->_allowConfirmation) {
280 $this->_requireApproval = TRUE;
281 }
282 $this->set('requireApproval', $this->_requireApproval);
283
284 if (isset($this->_values['event']['default_role_id'])) {
285 $participant_role = CRM_Core_OptionGroup::values('participant_role');
286 $this->_values['event']['participant_role'] = $participant_role["{$this->_values['event']['default_role_id']}"];
287 }
288 // check for is_monetary status
289 $isMonetary = CRM_Utils_Array::value('is_monetary', $this->_values['event']);
290 $isPayLater = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_eventId, 'is_pay_later');
291 //check for variour combination for paylater, payment
292 //process with paid event.
293 if ($isMonetary && (!$isPayLater || !empty($this->_values['event']['payment_processor']))) {
294 $ppID = CRM_Utils_Array::value('payment_processor',
295 $this->_values['event']
296 );
297 if (!$ppID) {
298 CRM_Core_Error::statusBounce(ts('A payment processor must be selected for this event registration page, or the event must be configured to give users the option to pay later (contact the site administrator for assistance).'), $infoUrl);
299 }
300 $ppIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $ppID);
301 $this->_paymentProcessors = CRM_Financial_BAO_PaymentProcessor::getPayments($ppIds,
302 $this->_mode
303 );
304 $this->set('paymentProcessors', $this->_paymentProcessors);
305
306 //set default payment processor
307 if (!empty($this->_paymentProcessors) && empty($this->_paymentProcessor)) {
308 foreach ($this->_paymentProcessors as $ppId => $values) {
309 if ($values['is_default'] == 1 || (count($this->_paymentProcessors) == 1)) {
310 $defaultProcessorId = $ppId;
311 break;
312 }
313 }
314 }
315
316 if (isset($defaultProcessorId)) {
317 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($defaultProcessorId, $this->_mode);
318 }
319 // make sure we have a valid payment class, else abort
320 if ($this->_values['event']['is_monetary']) {
321 if (!CRM_Utils_System::isNull($this->_paymentProcessors)) {
322 foreach ($this->_paymentProcessors as $eachPaymentProcessor) {
323 // check selected payment processor is active
324 if (!$eachPaymentProcessor) {
325 CRM_Core_Error::fatal(ts('The site administrator must set a Payment Processor for this event in order to use online registration.'));
326 }
327 // ensure that processor has a valid config
328 $payment = CRM_Core_Payment::singleton($this->_mode, $eachPaymentProcessor, $this);
329 $error = $payment->checkConfig();
330 if (!empty($error)) {
331 CRM_Core_Error::fatal($error);
332 }
333 }
334 }
335 }
336 }
337 //init event fee.
338 self::initEventFee($this, $this->_eventId);
339
340 // get the profile ids
341 $ufJoinParams = array(
342 'entity_table' => 'civicrm_event',
343 // CRM-4377: CiviEvent for the main participant, CiviEvent_Additional for additional participants
344 'module' => 'CiviEvent',
345 'entity_id' => $this->_eventId,
346 );
347 list($this->_values['custom_pre_id'],
348 $this->_values['custom_post_id']
349 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
350
351 // set profiles for additional participants
352 if ($this->_values['event']['is_multiple_registrations']) {
353 // CRM-4377: CiviEvent for the main participant, CiviEvent_Additional for additional participants
354 $ufJoinParams['module'] = 'CiviEvent_Additional';
355
356 list($this->_values['additional_custom_pre_id'],
357 $this->_values['additional_custom_post_id'], $preActive, $postActive
358 ) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
359
360 // CRM-4377: we need to maintain backward compatibility, hence if there is profile for main contact
361 // set same profile for additional contacts.
362 if ($this->_values['custom_pre_id'] && !$this->_values['additional_custom_pre_id']) {
363 $this->_values['additional_custom_pre_id'] = $this->_values['custom_pre_id'];
364 }
365
366 if ($this->_values['custom_post_id'] && !$this->_values['additional_custom_post_id']) {
367 $this->_values['additional_custom_post_id'] = $this->_values['custom_post_id'];
368 }
369 // now check for no profile condition, in that case is_active = 0
370 if (isset($preActive) && !$preActive) {
371 unset($this->_values['additional_custom_pre_id']);
372 }
373 if (isset($postActive) && !$postActive) {
374 unset($this->_values['additional_custom_post_id']);
375 }
376 }
377 // get the billing location type
378 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
379 // CRM-8108 remove ts from Billing as the location type can not be translated in CiviCRM!
380 //$this->_bltID = array_search( ts('Billing'), $locationTypes );
381 $this->_bltID = array_search('Billing', $locationTypes);
382 if (!$this->_bltID) {
383 CRM_Core_Error::fatal(ts('Please set a location type of %1', array(1 => 'Billing')));
384 }
385 $this->set('bltID', $this->_bltID);
386
387 if ($this->_values['event']['is_monetary']) {
388 CRM_Core_Payment_Form::setPaymentFieldsByProcessor($this, $this->_paymentProcessor);
389 }
390 $params = array('entity_id' => $this->_eventId, 'entity_table' => 'civicrm_event');
391 $this->_values['location'] = CRM_Core_BAO_Location::getValues($params, TRUE);
392
393 $this->set('values', $this->_values);
394 $this->set('fields', $this->_fields);
395
396 $this->_availableRegistrations
397 = CRM_Event_BAO_Participant::eventFull(
398 $this->_values['event']['id'], TRUE,
399 CRM_Utils_Array::value('has_waitlist', $this->_values['event'])
400 );
401 $this->set('availableRegistrations', $this->_availableRegistrations);
402 }
403 $this->assign_by_ref('paymentProcessor', $this->_paymentProcessor);
404
405 // check if this is a paypal auto return and redirect accordingly
406 if (CRM_Core_Payment::paypalRedirect($this->_paymentProcessor)) {
407 $url = CRM_Utils_System::url('civicrm/event/register',
408 "_qf_ThankYou_display=1&qfKey={$this->controller->_key}"
409 );
410 CRM_Utils_System::redirect($url);
411 }
412 $this->_contributeMode = $this->get('contributeMode');
413 $this->assign('contributeMode', $this->_contributeMode);
414
415 // setting CMS page title
416 CRM_Utils_System::setTitle($this->_values['event']['title']);
417 $this->assign('title', $this->_values['event']['title']);
418
419 $this->assign('paidEvent', $this->_values['event']['is_monetary']);
420
421 // we do not want to display recently viewed items on Registration pages
422 $this->assign('displayRecent', FALSE);
423 // Registration page values are cleared from session, so can't use normal Printer Friendly view.
424 // Use Browser Print instead.
425 $this->assign('browserPrint', TRUE);
426
427 $isShowLocation = CRM_Utils_Array::value('is_show_location', $this->_values['event']);
428 $this->assign('isShowLocation', $isShowLocation);
429 // Handle PCP
430 $pcpId = CRM_Utils_Request::retrieve('pcpId', 'Positive', $this);
431 if ($pcpId) {
432 $pcp = CRM_PCP_BAO_PCP::handlePcp($pcpId, 'event', $this->_values['event']);
433 $this->_pcpId = $pcp['pcpId'];
434 $this->_values['event']['intro_text'] = CRM_Utils_Array::value('intro_text', $pcp['pcpInfo']);
435 }
436
437 // assign all event properties so wizard templates can display event info.
438 $this->assign('event', $this->_values['event']);
439 $this->assign('location', $this->_values['location']);
440 $this->assign('bltID', $this->_bltID);
441 $isShowLocation = CRM_Utils_Array::value('is_show_location', $this->_values['event']);
442 $this->assign('isShowLocation', $isShowLocation);
443 //CRM-6907
444 $config->defaultCurrency = CRM_Utils_Array::value('currency', $this->_values['event'],
445 $config->defaultCurrency
446 );
447
448 //lets allow user to override campaign.
449 $campID = CRM_Utils_Request::retrieve('campID', 'Positive', $this);
450 if ($campID && CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Campaign', $campID)) {
451 $this->_values['event']['campaign_id'] = $campID;
452 }
453
454 // check if billing block is required for pay later
455 if (CRM_Utils_Array::value('is_pay_later', $this->_values['event'])) {
456 $this->_isBillingAddressRequiredForPayLater = CRM_Utils_Array::value('is_billing_required', $this->_values['event']);
457 $this->assign('isBillingAddressRequiredForPayLater', $this->_isBillingAddressRequiredForPayLater);
458 }
459 }
460
461 /**
462 * Assign the minimal set of variables to the template.
463 *
464 * @return void
465 */
466 public function assignToTemplate() {
467 //process only primary participant params
468 $this->_params = $this->get('params');
469 if (isset($this->_params[0])) {
470 $params = $this->_params[0];
471 }
472 $name = '';
473 if (!empty($params['billing_first_name'])) {
474 $name = $params['billing_first_name'];
475 }
476
477 if (!empty($params['billing_middle_name'])) {
478 $name .= " {$params['billing_middle_name']}";
479 }
480
481 if (!empty($params['billing_last_name'])) {
482 $name .= " {$params['billing_last_name']}";
483 }
484 $this->assign('billingName', $name);
485 $this->set('name', $name);
486
487 $vars = array(
488 'amount',
489 'currencyID',
490 'credit_card_type',
491 'trxn_id',
492 'amount_level',
493 'receive_date',
494 );
495
496 foreach ($vars as $v) {
497 if (!empty($params[$v])) {
498 if ($v == 'receive_date') {
499 $this->assign($v, CRM_Utils_Date::mysqlToIso($params[$v]));
500 }
501 else {
502 $this->assign($v, $params[$v]);
503 }
504 }
505 elseif (CRM_Utils_Array::value('amount', $params) == 0) {
506 $this->assign($v, CRM_Utils_Array::value($v, $params));
507 }
508 }
509
510 // assign the address formatted up for display
511 $addressParts = array(
512 "street_address-{$this->_bltID}",
513 "city-{$this->_bltID}",
514 "postal_code-{$this->_bltID}",
515 "state_province-{$this->_bltID}",
516 "country-{$this->_bltID}",
517 );
518 $addressFields = array();
519 foreach ($addressParts as $part) {
520 list($n, $id) = explode('-', $part);
521 if (isset($params['billing_' . $part])) {
522 $addressFields[$n] = CRM_Utils_Array::value('billing_' . $part, $params);
523 }
524 }
525
526 $this->assign('address', CRM_Utils_Address::format($addressFields));
527
528 if ($this->_contributeMode == 'direct' && empty($params['is_pay_later'])) {
529 $date = CRM_Utils_Date::format(CRM_Utils_Array::value('credit_card_exp_date', $params));
530 $date = CRM_Utils_Date::mysqlToIso($date);
531 $this->assign('credit_card_exp_date', $date);
532 $this->assign('credit_card_number',
533 CRM_Utils_System::mungeCreditCard(CRM_Utils_Array::value('credit_card_number', $params))
534 );
535 }
536
537 // get the email that the confirmation would have been sent to
538 $session = CRM_Core_Session::singleton();
539
540 // assign is_email_confirm to templates
541 if (isset($this->_values['event']['is_email_confirm'])) {
542 $this->assign('is_email_confirm', $this->_values['event']['is_email_confirm']);
543 }
544
545 // assign pay later stuff
546 $params['is_pay_later'] = CRM_Utils_Array::value('is_pay_later', $params, FALSE);
547 $this->assign('is_pay_later', $params['is_pay_later']);
548 if ($params['is_pay_later']) {
549 $this->assign('pay_later_text', $this->_values['event']['pay_later_text']);
550 $this->assign('pay_later_receipt', $this->_values['event']['pay_later_receipt']);
551 }
552
553 // also assign all participantIDs to the template
554 // useful in generating confirmation numbers if needed
555 $this->assign('participantIDs',
556 $this->_participantIDS
557 );
558 }
559
560 /**
561 * Add the custom fields.
562 *
563 * @param int $id
564 * @param string $name
565 * @param bool $viewOnly
566 *
567 * @return void
568 */
569 public function buildCustom($id, $name, $viewOnly = FALSE) {
570 if ($id) {
571 $button = substr($this->controller->getButtonName(), -4);
572 $cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
573 $session = CRM_Core_Session::singleton();
574 $contactID = $session->get('userID');
575
576 // we don't allow conflicting fields to be
577 // configured via profile
578 $fieldsToIgnore = array(
579 'participant_fee_amount' => 1,
580 'participant_fee_level' => 1,
581 );
582 if ($contactID) {
583 //FIX CRM-9653
584 if (is_array($id)) {
585 $fields = array();
586 foreach ($id as $profileID) {
587 $field = CRM_Core_BAO_UFGroup::getFields($profileID, FALSE, CRM_Core_Action::ADD,
588 NULL, NULL, FALSE, NULL,
589 FALSE, NULL, CRM_Core_Permission::CREATE,
590 'field_name', TRUE
591 );
592 $fields = array_merge($fields, $field);
593 }
594 }
595 else {
596 if (CRM_Core_BAO_UFGroup::filterUFGroups($id, $contactID)) {
597 $fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD,
598 NULL, NULL, FALSE, NULL,
599 FALSE, NULL, CRM_Core_Permission::CREATE,
600 'field_name', TRUE
601 );
602 }
603 }
604 }
605 else {
606 $fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD,
607 NULL, NULL, FALSE, NULL,
608 FALSE, NULL, CRM_Core_Permission::CREATE,
609 'field_name', TRUE
610 );
611 }
612
613 if (array_intersect_key($fields, $fieldsToIgnore)) {
614 $fields = array_diff_key($fields, $fieldsToIgnore);
615 CRM_Core_Session::setStatus(ts('Some of the profile fields cannot be configured for this page.'));
616 }
617 $addCaptcha = FALSE;
618
619 if (!empty($this->_fields)) {
620 $fields = @array_diff_assoc($fields, $this->_fields);
621 }
622
623 if (empty($this->_params[0]['additional_participants']) &&
624 is_null($cid)
625 ) {
626 CRM_Core_BAO_Address::checkContactSharedAddressFields($fields, $contactID);
627 }
628 $this->assign($name, $fields);
629 if (is_array($fields)) {
630 foreach ($fields as $key => $field) {
631 if ($viewOnly &&
632 isset($field['data_type']) &&
633 $field['data_type'] == 'File' || ($viewOnly && $field['name'] == 'image_URL')
634 ) {
635 // ignore file upload fields
636 continue;
637 }
638 //make the field optional if primary participant
639 //have been skip the additional participant.
640 if ($button == 'skip') {
641 $field['is_required'] = FALSE;
642 }
643 // CRM-11316 Is ReCAPTCHA enabled for this profile AND is this an anonymous visitor
644 elseif ($field['add_captcha'] && !$contactID) {
645 // only add captcha for first page
646 $addCaptcha = TRUE;
647 }
648 list($prefixName, $index) = CRM_Utils_System::explode('-', $key, 2);
649 CRM_Core_BAO_UFGroup::buildProfile($this, $field, CRM_Profile_Form::MODE_CREATE, $contactID, TRUE);
650
651 $this->_fields[$key] = $field;
652 }
653 }
654
655 if ($addCaptcha && !$viewOnly) {
656 $captcha = CRM_Utils_ReCAPTCHA::singleton();
657 $captcha->add($this);
658 $this->assign('isCaptcha', TRUE);
659 }
660 }
661 }
662
663 /**
664 * @param CRM_Core_Form $form
665 * @param int $eventID
666 *
667 * @throws Exception
668 */
669 public static function initEventFee(&$form, $eventID) {
670 // get price info
671
672 // retrive all active price set fields.
673 $discountId = CRM_Core_BAO_Discount::findSet($eventID, 'civicrm_event');
674 if (property_exists($form, '_discountId') && $form->_discountId) {
675 $discountId = $form->_discountId;
676 }
677 if ($discountId) {
678 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Core_BAO_Discount', $discountId, 'price_set_id');
679 $price = CRM_Price_BAO_PriceSet::initSet($form, $eventID, 'civicrm_event', TRUE, $priceSetId);
680 }
681 else {
682 $price = CRM_Price_BAO_PriceSet::initSet($form, $eventID, 'civicrm_event', TRUE);
683 }
684
685 if (property_exists($form, '_context') && ($form->_context == 'standalone'
686 || $form->_context == 'participant')
687 ) {
688 $discountedEvent = CRM_Core_BAO_Discount::getOptionGroup($eventID, 'civicrm_event');
689 if (is_array($discountedEvent)) {
690 foreach ($discountedEvent as $key => $priceSetId) {
691 $priceSet = CRM_Price_BAO_PriceSet::getSetDetail($priceSetId);
692 $priceSet = CRM_Utils_Array::value($priceSetId, $priceSet);
693 $form->_values['discount'][$key] = CRM_Utils_Array::value('fields', $priceSet);
694 $fieldID = key($form->_values['discount'][$key]);
695 $form->_values['discount'][$key][$fieldID]['name'] = CRM_Core_DAO::getFieldValue(
696 'CRM_Price_DAO_PriceSet',
697 $priceSetId,
698 'title'
699 );
700 }
701 }
702 }
703 $eventFee = CRM_Utils_Array::value('fee', $form->_values);
704 if (!is_array($eventFee) || empty($eventFee)) {
705 $form->_values['fee'] = array();
706 }
707
708 //fix for non-upgraded price sets.CRM-4256.
709 if (isset($form->_isPaidEvent)) {
710 $isPaidEvent = $form->_isPaidEvent;
711 }
712 else {
713 $isPaidEvent = CRM_Utils_Array::value('is_monetary', $form->_values['event']);
714 }
715 if ($isPaidEvent && empty($form->_values['fee'])) {
716 if (CRM_Utils_System::getClassName($form) != 'CRM_Event_Form_Participant') {
717 CRM_Core_Error::fatal(ts('No Fee Level(s) or Price Set is configured for this event.<br />Click <a href=\'%1\'>CiviEvent >> Manage Event >> Configure >> Event Fees</a> to configure the Fee Level(s) or Price Set for this event.', array(1 => CRM_Utils_System::url('civicrm/event/manage/fee', 'reset=1&action=update&id=' . $form->_eventId))));
718 }
719 }
720 }
721
722 /**
723 * Handle process after the confirmation of payment by User.
724 *
725 * @param int $contactID
726 * @param null $contribution
727 * @param null $payment
728 *
729 * @return void
730 */
731 public function confirmPostProcess($contactID = NULL, $contribution = NULL, $payment = NULL) {
732 // add/update contact information
733 $fields = array();
734 unset($this->_params['note']);
735
736 //to avoid conflict overwrite $this->_params
737 $this->_params = $this->get('value');
738
739 //get the amount of primary participant
740 if (!empty($this->_params['is_primary'])) {
741 $this->_params['fee_amount'] = $this->get('primaryParticipantAmount');
742 }
743
744 // add participant record
745 $participant = CRM_Event_Form_Registration::addParticipant($this, $contactID);
746 $this->_participantIDS[] = $participant->id;
747
748 //setting register_by_id field and primaryContactId
749 if (!empty($this->_params['is_primary'])) {
750 $this->set('registerByID', $participant->id);
751 $this->set('primaryContactId', $contactID);
752
753 // CRM-10032
754 $this->processFirstParticipant($participant->id);
755 }
756
757 CRM_Core_BAO_CustomValueTable::postProcess($this->_params,
758 CRM_Core_DAO::$_nullArray,
759 'civicrm_participant',
760 $participant->id,
761 'Participant'
762 );
763
764 $createPayment = (CRM_Utils_Array::value('amount', $this->_params, 0) != 0) ? TRUE : FALSE;
765
766 // force to create zero amount payment, CRM-5095
767 // we know the amout is zero since createPayment is false
768 if (!$createPayment &&
769 (isset($contribution) && $contribution->id) &&
770 $this->_priceSetId &&
771 $this->_lineItem
772 ) {
773 $createPayment = TRUE;
774 }
775
776 if ($createPayment && $this->_values['event']['is_monetary'] && !empty($this->_params['contributionID'])) {
777 $paymentParams = array(
778 'participant_id' => $participant->id,
779 'contribution_id' => $contribution->id,
780 );
781 $ids = array();
782 $paymentPartcipant = CRM_Event_BAO_ParticipantPayment::create($paymentParams, $ids);
783 }
784
785 //set only primary participant's params for transfer checkout.
786 if (($this->_contributeMode == 'checkout' || $this->_contributeMode == 'notify') && !empty($this->_params['is_primary'])) {
787 $this->_params['participantID'] = $participant->id;
788 $this->set('primaryParticipant', $this->_params);
789 }
790
791 $this->assign('action', $this->_action);
792
793 // create CMS user
794 if (!empty($this->_params['cms_create_account'])) {
795 $this->_params['contactID'] = $contactID;
796
797 if (array_key_exists('email-5', $this->_params)) {
798 $mail = 'email-5';
799 }
800 else {
801 foreach ($this->_params as $name => $dontCare) {
802 if (substr($name, 0, 5) == 'email') {
803 $mail = $name;
804 break;
805 }
806 }
807 }
808
809 // we should use primary email for
810 // 1. free event registration.
811 // 2. pay later participant.
812 // 3. waiting list participant.
813 // 4. require approval participant.
814 if (!empty($this->_params['is_pay_later']) ||
815 $this->_allowWaitlist || $this->_requireApproval || empty($this->_values['event']['is_monetary'])
816 ) {
817 $mail = 'email-Primary';
818 }
819
820 if (!CRM_Core_BAO_CMSUser::create($this->_params, $mail)) {
821 CRM_Core_Error::statusBounce(ts('Your profile is not saved and Account is not created.'));
822 }
823 }
824 }
825
826 /**
827 * Process the participant.
828 *
829 * @param CRM_Core_Form $form
830 * @param int $contactID
831 * @return \CRM_Event_BAO_Participant
832 */
833 public static function addParticipant(&$form, $contactID) {
834 if (empty($form->_params)) {
835 return NULL;
836 }
837 $params = $form->_params;
838 $transaction = new CRM_Core_Transaction();
839
840 $groupName = 'participant_role';
841 $query = "
842 SELECT v.label as label ,v.value as value
843 FROM civicrm_option_value v,
844 civicrm_option_group g
845 WHERE v.option_group_id = g.id
846 AND g.name = %1
847 AND v.is_active = 1
848 AND g.is_active = 1
849 ";
850 $p = array(1 => array($groupName, 'String'));
851
852 $dao = CRM_Core_DAO::executeQuery($query, $p);
853 if ($dao->fetch()) {
854 $roleID = $dao->value;
855 }
856
857 // handle register date CRM-4320
858 $registerDate = NULL;
859 if (!empty($form->_allowConfirmation) && $form->_participantId) {
860 $registerDate = $params['participant_register_date'];
861 }
862 elseif (!empty($params['participant_register_date']) &&
863 is_array($params['participant_register_date']) &&
864 !empty($params['participant_register_date'])
865 ) {
866 $registerDate = CRM_Utils_Date::format($params['participant_register_date']);
867 }
868
869 $participantFields = CRM_Event_DAO_Participant::fields();
870 $participantParams = array(
871 'id' => CRM_Utils_Array::value('participant_id', $params),
872 'contact_id' => $contactID,
873 'event_id' => $form->_eventId ? $form->_eventId : $params['event_id'],
874 'status_id' => CRM_Utils_Array::value('participant_status',
875 $params, 1
876 ),
877 'role_id' => CRM_Utils_Array::value('participant_role_id',
878 $params, $roleID
879 ),
880 'register_date' => ($registerDate) ? $registerDate : date('YmdHis'),
881 'source' => CRM_Utils_String::ellipsify(
882 isset($params['participant_source']) ? CRM_Utils_Array::value('participant_source', $params) : CRM_Utils_Array::value('description', $params),
883 $participantFields['participant_source']['maxlength']
884 ),
885 'fee_level' => CRM_Utils_Array::value('amount_level', $params),
886 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0),
887 'fee_amount' => CRM_Utils_Array::value('fee_amount', $params),
888 'registered_by_id' => CRM_Utils_Array::value('registered_by_id', $params),
889 'discount_id' => CRM_Utils_Array::value('discount_id', $params),
890 'fee_currency' => CRM_Utils_Array::value('currencyID', $params),
891 'campaign_id' => CRM_Utils_Array::value('campaign_id', $params),
892 );
893
894 if ($form->_action & CRM_Core_Action::PREVIEW || CRM_Utils_Array::value('mode', $params) == 'test') {
895 $participantParams['is_test'] = 1;
896 }
897 else {
898 $participantParams['is_test'] = 0;
899 }
900
901 if (!empty($form->_params['note'])) {
902 $participantParams['note'] = $form->_params['note'];
903 }
904 elseif (!empty($form->_params['participant_note'])) {
905 $participantParams['note'] = $form->_params['participant_note'];
906 }
907
908 // reuse id if one already exists for this one (can happen
909 // with back button being hit etc)
910 if (!$participantParams['id'] && !empty($params['contributionID'])) {
911 $pID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
912 $params['contributionID'],
913 'participant_id',
914 'contribution_id'
915 );
916 $participantParams['id'] = $pID;
917 }
918 $participantParams['discount_id'] = CRM_Core_BAO_Discount::findSet($form->_eventId, 'civicrm_event');
919
920 if (!$participantParams['discount_id']) {
921 $participantParams['discount_id'] = "null";
922 }
923
924 $participant = CRM_Event_BAO_Participant::create($participantParams);
925
926 $transaction->commit();
927
928 return $participant;
929 }
930
931 /* Calculate the total participant count as per params.
932 *
933 * @param array $params
934 * User params.
935 *
936 * @return $totalCount total participant count.
937 */
938 /**
939 * @param CRM_Core_Form $form
940 * @param array $params
941 * @param bool $skipCurrent
942 *
943 * @return int|string
944 */
945 public static function getParticipantCount(&$form, $params, $skipCurrent = FALSE) {
946 $totalCount = 0;
947 if (!is_array($params) || empty($params)) {
948 return $totalCount;
949 }
950
951 $priceSetId = $form->get('priceSetId');
952 $addParticipantNum = substr($form->_name, 12);
953 $priceSetFields = $priceSetDetails = array();
954 $hasPriceFieldsCount = FALSE;
955 if ($priceSetId) {
956 $priceSetDetails = $form->get('priceSet');
957 if (isset($priceSetDetails['optionsCountTotal'])
958 && $priceSetDetails['optionsCountTotal']
959 ) {
960 $hasPriceFieldsCount = TRUE;
961 $priceSetFields = $priceSetDetails['optionsCountDetails']['fields'];
962 }
963 }
964
965 $singleFormParams = FALSE;
966 foreach ($params as $key => $val) {
967 if (!is_numeric($key)) {
968 $singleFormParams = TRUE;
969 break;
970 }
971 }
972
973 //first format the params.
974 if ($singleFormParams) {
975 $params = self::formatPriceSetParams($form, $params);
976 $params = array($params);
977 }
978
979 foreach ($params as $key => $values) {
980 if (!is_numeric($key) ||
981 $values == 'skip' ||
982 ($skipCurrent && ($addParticipantNum == $key))
983 ) {
984 continue;
985 }
986 $count = 1;
987
988 $usedCache = FALSE;
989 $cacheCount = CRM_Utils_Array::value($key, $form->_lineItemParticipantsCount);
990 if ($cacheCount && is_numeric($cacheCount)) {
991 $count = $cacheCount;
992 $usedCache = TRUE;
993 }
994
995 if (!$usedCache && $hasPriceFieldsCount) {
996 $count = 0;
997 foreach ($values as $valKey => $value) {
998 if (strpos($valKey, 'price_') === FALSE) {
999 continue;
1000 }
1001 $priceFieldId = substr($valKey, 6);
1002 if (!$priceFieldId ||
1003 !is_array($value) ||
1004 !array_key_exists($priceFieldId, $priceSetFields)
1005 ) {
1006 continue;
1007 }
1008 foreach ($value as $optId => $optVal) {
1009 $currentCount = $priceSetFields[$priceFieldId]['options'][$optId] * $optVal;
1010 if ($currentCount) {
1011 $count += $currentCount;
1012 }
1013 }
1014 }
1015 if (!$count) {
1016 $count = 1;
1017 }
1018 }
1019 $totalCount += $count;
1020 }
1021 if (!$totalCount) {
1022 $totalCount = 1;
1023 }
1024
1025 return $totalCount;
1026 }
1027
1028 /* Format user submitted price set params.
1029 * Convert price set each param as an array.
1030 *
1031 * @param array $params
1032 * An array of user submitted params.
1033 *
1034 *
1035 * @return array
1036 * , formatted price set params.
1037 */
1038 /**
1039 * @param CRM_Core_Form $form
1040 * @param array $params
1041 *
1042 * @return mixed
1043 */
1044 public static function formatPriceSetParams(&$form, $params) {
1045 if (!is_array($params) || empty($params)) {
1046 return $params;
1047 }
1048
1049 $priceSetId = $form->get('priceSetId');
1050 if (!$priceSetId) {
1051 return $params;
1052 }
1053 $priceSetDetails = $form->get('priceSet');
1054
1055 foreach ($params as $key => & $value) {
1056 $vals = array();
1057 if (strpos($key, 'price_') !== FALSE) {
1058 $fieldId = substr($key, 6);
1059 if (!array_key_exists($fieldId, $priceSetDetails['fields']) ||
1060 is_array($value) ||
1061 !$value
1062 ) {
1063 continue;
1064 }
1065 $field = $priceSetDetails['fields'][$fieldId];
1066 if ($field['html_type'] == 'Text') {
1067 $fieldOption = current($field['options']);
1068 $value = array($fieldOption['id'] => $value);
1069 }
1070 else {
1071 $value = array($value => TRUE);
1072 }
1073 }
1074 }
1075
1076 return $params;
1077 }
1078
1079 /* Calculate total count for each price set options.
1080 * those are currently selected by user.
1081 *
1082 * @param $form
1083 * Form object.
1084 *
1085 *
1086 * @return array
1087 * , array of each option w/ count total.
1088 */
1089 /**
1090 * @param $form
1091 *
1092 * @return array
1093 */
1094 public static function getPriceSetOptionCount(&$form) {
1095 $params = $form->get('params');
1096 $priceSet = $form->get('priceSet');
1097 $priceSetId = $form->get('priceSetId');
1098
1099 $optionsCount = array();
1100 if (!$priceSetId ||
1101 !is_array($priceSet) ||
1102 empty($priceSet) ||
1103 !is_array($params) ||
1104 empty($params)
1105 ) {
1106 return $optionsCount;
1107 }
1108
1109 $priceSetFields = $priceMaxFieldDetails = array();
1110 if (!empty($priceSet['optionsCountTotal'])) {
1111 $priceSetFields = $priceSet['optionsCountDetails']['fields'];
1112 }
1113
1114 if (!empty($priceSet['optionsMaxValueTotal'])) {
1115 $priceMaxFieldDetails = $priceSet['optionsMaxValueDetails']['fields'];
1116 }
1117
1118 $addParticipantNum = substr($form->_name, 12);
1119 foreach ($params as $pCnt => $values) {
1120 if ($values == 'skip' ||
1121 $pCnt === $addParticipantNum
1122 ) {
1123 continue;
1124 }
1125
1126 foreach ($values as $valKey => $value) {
1127 if (strpos($valKey, 'price_') === FALSE) {
1128 continue;
1129 }
1130
1131 $priceFieldId = substr($valKey, 6);
1132 if (!$priceFieldId ||
1133 !is_array($value) ||
1134 !(array_key_exists($priceFieldId, $priceSetFields) || array_key_exists($priceFieldId, $priceMaxFieldDetails))
1135 ) {
1136 continue;
1137 }
1138
1139 foreach ($value as $optId => $optVal) {
1140 if (CRM_Utils_Array::value('html_type', $priceSet['fields'][$priceFieldId]) == 'Text') {
1141 $currentCount = $optVal;
1142 }
1143 else {
1144 $currentCount = 1;
1145 }
1146
1147 if (isset($priceSetFields[$priceFieldId]) && isset($priceSetFields[$priceFieldId]['options'][$optId])) {
1148 $currentCount = $priceSetFields[$priceFieldId]['options'][$optId] * $optVal;
1149 }
1150
1151 $optionsCount[$optId] = $currentCount + CRM_Utils_Array::value($optId, $optionsCount, 0);
1152 }
1153 }
1154 }
1155
1156 return $optionsCount;
1157 }
1158
1159 /**
1160 * @param string $suffix
1161 *
1162 * @return null|string
1163 */
1164 public function checkTemplateFileExists($suffix = '') {
1165 if ($this->_eventId) {
1166 $templateName = $this->_name;
1167 if (substr($templateName, 0, 12) == 'Participant_') {
1168 $templateName = 'AdditionalParticipant';
1169 }
1170
1171 $templateFile = "CRM/Event/Form/Registration/{$this->_eventId}/{$templateName}.{$suffix}tpl";
1172 $template = CRM_Core_Form::getTemplate();
1173 if ($template->template_exists($templateFile)) {
1174 return $templateFile;
1175 }
1176 }
1177 return NULL;
1178 }
1179
1180 /**
1181 * @return null|string
1182 */
1183 public function getTemplateFileName() {
1184 $fileName = $this->checkTemplateFileExists();
1185 return $fileName ? $fileName : parent::getTemplateFileName();
1186 }
1187
1188 /**
1189 * @return null|string
1190 */
1191 public function overrideExtraTemplateFileName() {
1192 $fileName = $this->checkTemplateFileExists('extra.');
1193 return $fileName ? $fileName : parent::overrideExtraTemplateFileName();
1194 }
1195
1196 /**
1197 * Reset values for all options those are full.
1198 *
1199 */
1200 public static function resetElementValue($optionFullIds = array(), &$form) {
1201 if (!is_array($optionFullIds) ||
1202 empty($optionFullIds) ||
1203 !$form->isSubmitted()
1204 ) {
1205 return;
1206 }
1207
1208 foreach ($optionFullIds as $fldId => $optIds) {
1209 $name = "price_$fldId";
1210 if (!$form->elementExists($name)) {
1211 continue;
1212 }
1213
1214 $element = $form->getElement($name);
1215 $eleType = $element->getType();
1216
1217 $resetSubmitted = FALSE;
1218 switch ($eleType) {
1219 case 'text':
1220 if ($element->getValue() && $element->isFrozen()) {
1221 $label = "{$element->getLabel()}<tt>(x)</tt>";
1222 $element->setLabel($label);
1223 $element->setPersistantFreeze();
1224 $resetSubmitted = TRUE;
1225 }
1226 break;
1227
1228 case 'group':
1229 if (is_array($element->_elements)) {
1230 foreach ($element->_elements as $child) {
1231 $childType = $child->getType();
1232 $methodName = 'getName';
1233 if ($childType) {
1234 $methodName = 'getValue';
1235 }
1236 if (in_array($child->{$methodName}(), $optIds) && $child->isFrozen()) {
1237 $resetSubmitted = TRUE;
1238 $child->setPersistantFreeze();
1239 }
1240 }
1241 }
1242 break;
1243
1244 case 'select':
1245 $value = $element->getValue();
1246 if (in_array($value[0], $optIds)) {
1247 foreach ($element->_options as $option) {
1248 if ($option['attr']['value'] === "crm_disabled_opt-{$value[0]}") {
1249 $placeholder = html_entity_decode($option['text'], ENT_QUOTES, "UTF-8");
1250 $element->updateAttributes(array('placeholder' => $placeholder));
1251 break;
1252 }
1253 }
1254 $resetSubmitted = TRUE;
1255 }
1256 break;
1257 }
1258
1259 //finally unset values from submitted.
1260 if ($resetSubmitted) {
1261 self::resetSubmittedValue($name, $optIds, $form);
1262 }
1263 }
1264 }
1265
1266 /**
1267 * @param string $elementName
1268 * @param array $optionIds
1269 */
1270 public static function resetSubmittedValue($elementName, $optionIds = array(), &$form) {
1271 if (empty($elementName) ||
1272 !$form->elementExists($elementName) ||
1273 !$form->getSubmitValue($elementName)
1274 ) {
1275 return;
1276 }
1277 foreach (array(
1278 'constantValues',
1279 'submitValues',
1280 'defaultValues',
1281 ) as $val) {
1282 $values = $form->{"_$val"};
1283 if (!is_array($values) || empty($values)) {
1284 continue;
1285 }
1286 $eleVal = CRM_Utils_Array::value($elementName, $values);
1287 if (empty($eleVal)) {
1288 continue;
1289 }
1290 if (is_array($eleVal)) {
1291 $found = FALSE;
1292 foreach ($eleVal as $keyId => $ignore) {
1293 if (in_array($keyId, $optionIds)) {
1294 $found = TRUE;
1295 unset($values[$elementName][$keyId]);
1296 }
1297 }
1298 if ($found && empty($values[$elementName][$keyId])) {
1299 $values[$elementName][$keyId] = NULL;
1300 }
1301 }
1302 else {
1303 if (!empty($keyId)) {
1304 $values[$elementName][$keyId] = NULL;
1305 }
1306 }
1307 }
1308 }
1309
1310 /**
1311 * Validate price set submitted params for price option limit,
1312 * as well as user should select at least one price field option.
1313 *
1314 * @param CRM_Core_Form $form
1315 * @param array $params
1316 *
1317 * @return array
1318 */
1319 public static function validatePriceSet(&$form, $params) {
1320 $errors = array();
1321 $hasOptMaxValue = FALSE;
1322 if (!is_array($params) || empty($params)) {
1323 return $errors;
1324 }
1325
1326 $currentParticipantNum = substr($form->_name, 12);
1327 if (!$currentParticipantNum) {
1328 $currentParticipantNum = 0;
1329 }
1330
1331 $priceSetId = $form->get('priceSetId');
1332 $priceSetDetails = $form->get('priceSet');
1333 if (
1334 !$priceSetId ||
1335 !is_array($priceSetDetails) ||
1336 empty($priceSetDetails)
1337 ) {
1338 return $errors;
1339 }
1340
1341 $optionsCountDetails = $optionsMaxValueDetails = array();
1342 if (
1343 isset($priceSetDetails['optionsMaxValueTotal'])
1344 && $priceSetDetails['optionsMaxValueTotal']
1345 ) {
1346 $hasOptMaxValue = TRUE;
1347 $optionsMaxValueDetails = $priceSetDetails['optionsMaxValueDetails']['fields'];
1348 }
1349 if (
1350 isset($priceSetDetails['optionsCountTotal'])
1351 && $priceSetDetails['optionsCountTotal']
1352 ) {
1353 $hasOptCount = TRUE;
1354 $optionsCountDetails = $priceSetDetails['optionsCountDetails']['fields'];
1355 }
1356 $feeBlock = $form->_feeBlock;
1357
1358 if (empty($feeBlock)) {
1359 $feeBlock = $priceSetDetails['fields'];
1360 }
1361
1362 $optionMaxValues = $fieldSelected = array();
1363 foreach ($params as $pNum => $values) {
1364 if (!is_array($values) || $values == 'skip') {
1365 continue;
1366 }
1367
1368 foreach ($values as $valKey => $value) {
1369 if (strpos($valKey, 'price_') === FALSE) {
1370 continue;
1371 }
1372 $priceFieldId = substr($valKey, 6);
1373 $noneOptionValueSelected = FALSE;
1374 if (!$feeBlock[$priceFieldId]['is_required'] && $value == 0) {
1375 $noneOptionValueSelected = TRUE;
1376 }
1377
1378 if (
1379 !$priceFieldId ||
1380 (!$noneOptionValueSelected && !is_array($value))
1381 ) {
1382 continue;
1383 }
1384
1385 $fieldSelected[$pNum] = TRUE;
1386
1387 if (!$hasOptMaxValue || !is_array($value)) {
1388 continue;
1389 }
1390
1391 foreach ($value as $optId => $optVal) {
1392 if (CRM_Utils_Array::value('html_type', $feeBlock[$priceFieldId]) == 'Text') {
1393 $currentMaxValue = $optVal;
1394 }
1395 else {
1396 $currentMaxValue = 1;
1397 }
1398
1399 if (isset($optionsCountDetails[$priceFieldId]) && isset($optionsCountDetails[$priceFieldId]['options'][$optId])) {
1400 $currentMaxValue = $optionsCountDetails[$priceFieldId]['options'][$optId] * $optVal;
1401 }
1402 if (empty($optionMaxValues)) {
1403 $optionMaxValues[$priceFieldId][$optId] = $currentMaxValue;
1404 }
1405 else {
1406 $optionMaxValues[$priceFieldId][$optId]
1407 = $currentMaxValue + CRM_Utils_Array::value($optId, CRM_Utils_Array::value($priceFieldId, $optionMaxValues), 0);
1408 }
1409 $soldOutPnum[$optId] = $pNum;
1410 }
1411 }
1412
1413 //validate for price field selection.
1414 if (empty($fieldSelected[$pNum])) {
1415 $errors[$pNum]['_qf_default'] = ts('Select at least one option from Event Fee(s).');
1416 }
1417 }
1418
1419 //validate for option max value.
1420 foreach ($optionMaxValues as $fieldId => $values) {
1421 $options = CRM_Utils_Array::value('options', $feeBlock[$fieldId], array());
1422 foreach ($values as $optId => $total) {
1423 $optMax = $optionsMaxValueDetails[$fieldId]['options'][$optId];
1424 $opDbCount = CRM_Utils_Array::value('db_total_count', $options[$optId], 0);
1425 $total += $opDbCount;
1426 if ($optMax && ($total > $optMax)) {
1427 if ($opDbCount && ($opDbCount >= $optMax)) {
1428 $errors[$soldOutPnum[$optId]]["price_{$fieldId}"]
1429 = ts('Sorry, this option is currently sold out.');
1430 }
1431 elseif (($optMax - $opDbCount) == 1) {
1432 $errors[$soldOutPnum[$optId]]["price_{$fieldId}"]
1433 = ts('Sorry, currently only a single seat is available for this option.', array(1 => ($optMax - $opDbCount)));
1434 }
1435 else {
1436 $errors[$soldOutPnum[$optId]]["price_{$fieldId}"]
1437 = ts('Sorry, currently only %1 seats are available for this option.', array(1 => ($optMax - $opDbCount)));
1438 }
1439 }
1440 }
1441 }
1442 return $errors;
1443 }
1444
1445 /**
1446 * set the first participant ID if not set, CRM-10032
1447 *
1448 * @param int $participantID
1449 */
1450 public function processFirstParticipant($participantID) {
1451 $this->_participantId = $participantID;
1452 $this->set('participantId', $this->_participantId);
1453
1454 $ids = $participantValues = array();
1455 $participantParams = array('id' => $this->_participantId);
1456 CRM_Event_BAO_Participant::getValues($participantParams, $participantValues, $ids);
1457 $this->_values['participant'] = $participantValues[$this->_participantId];
1458 $this->set('values', $this->_values);
1459
1460 // also set the allow confirmation stuff
1461 if (array_key_exists(
1462 $this->_values['participant']['status_id'],
1463 CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Pending'")
1464 )) {
1465 $this->_allowConfirmation = TRUE;
1466 $this->set('allowConfirmation', TRUE);
1467 }
1468 }
1469
1470 /**
1471 * @todo - combine this with CRM_Event_BAO_Event::validRegistrationRequest
1472 * (probably extract relevant values here & call that with them & handle bounces & redirects here -as
1473 * those belong in the form layer)
1474 *
1475 * @param string $redirect
1476 */
1477 public function checkValidEvent($redirect = NULL) {
1478 // is the event active (enabled)?
1479 if (!$this->_values['event']['is_active']) {
1480 // form is inactive, die a fatal death
1481 CRM_Core_Error::statusBounce(ts('The event you requested is currently unavailable (contact the site administrator for assistance).'));
1482 }
1483
1484 // is online registration is enabled?
1485 if (!$this->_values['event']['is_online_registration']) {
1486 CRM_Core_Error::statusBounce(ts('Online registration is not currently available for this event (contact the site administrator for assistance).'), $redirect);
1487 }
1488
1489 // is this an event template ?
1490 if (!empty($this->_values['event']['is_template'])) {
1491 CRM_Core_Error::statusBounce(ts('Event templates are not meant to be registered.'), $redirect);
1492 }
1493
1494 $now = date('YmdHis');
1495 $startDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('registration_start_date',
1496 $this->_values['event']
1497 ));
1498
1499 if (
1500 $startDate &&
1501 $startDate >= $now
1502 ) {
1503 CRM_Core_Error::statusBounce(ts('Registration for this event begins on %1', array(1 => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('registration_start_date', $this->_values['event'])))), $redirect);
1504 }
1505
1506 $endDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('registration_end_date',
1507 $this->_values['event']
1508 ));
1509 $eventEndDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('event_end_date', $this->_values['event']));
1510 if (
1511 $endDate &&
1512 $endDate < $now
1513 ) {
1514 CRM_Core_Error::statusBounce(ts('Registration for this event ended on %1', array(1 => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('registration_end_date', $this->_values['event'])))), $redirect);
1515 }
1516 if (!empty($eventEndDate) && $eventEndDate < $now) {
1517 CRM_Core_Error::statusBounce(ts('Event ended on %1', array(1 => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('event_end_date', $this->_values['event'])))), $redirect);
1518 }
1519 }
1520
1521 }