Merge pull request #4817 from williamtheaker/patch-2
[civicrm-core.git] / CRM / Event / Form / Registration.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
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
06b69b18 32 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
33 * $Id$
34 *
35 */
36
37/**
38 * This class generates form components for processing Event
39 *
40 */
41class CRM_Event_Form_Registration extends CRM_Core_Form {
42
43 /**
100fef9d 44 * How many locationBlocks should we display?
6a488035
TO
45 *
46 * @var int
47 * @const
48 */
7da04cde 49 const LOCATION_BLOCKS = 1;
6a488035
TO
50
51 /**
100fef9d 52 * The id of the event we are proceessing
6a488035
TO
53 *
54 * @var int
6a488035
TO
55 */
56 public $_eventId;
57
58 /**
100fef9d 59 * The array of ids of all the participant we are proceessing
6a488035
TO
60 *
61 * @var int
6a488035
TO
62 */
63 protected $_participantIDS = NULL;
64
65 /**
100fef9d 66 * The id of the participant we are proceessing
6a488035
TO
67 *
68 * @var int
6a488035
TO
69 */
70 protected $_participantId;
71
72 /**
100fef9d 73 * Is participant able to walk registration wizard.
6a488035
TO
74 *
75 * @var Boolean
6a488035
TO
76 */
77 public $_allowConfirmation;
78
79 /**
100fef9d 80 * Is participant requires approval
6a488035
TO
81 *
82 * @var Boolean
6a488035
TO
83 */
84 public $_requireApproval;
85
86 /**
100fef9d 87 * Is event configured for waitlist.
6a488035
TO
88 *
89 * @var Boolean
6a488035
TO
90 */
91 public $_allowWaitlist;
92
93 /**
100fef9d 94 * Store additional participant ids
6a488035
TO
95 * when there are pre-registered.
96 *
97 * @var array
6a488035
TO
98 */
99 public $_additionalParticipantIds;
100
101 /**
100fef9d 102 * The mode that we are in
6a488035
TO
103 *
104 * @var string
105 * @protect
106 */
107 public $_mode;
108
109 /**
100fef9d 110 * The values for the contribution db object
6a488035
TO
111 *
112 * @var array
6a488035
TO
113 */
114 public $_values;
115
116 /**
100fef9d 117 * The paymentProcessor attributes for this page
6a488035
TO
118 *
119 * @var array
6a488035
TO
120 */
121 public $_paymentProcessor;
122
123 /**
124 * The params submitted by the form and computed by the app
125 *
126 * @var array
6a488035
TO
127 */
128 protected $_params;
129
130 /**
131 * The fields involved in this contribution page
132 *
133 * @var array
6a488035
TO
134 */
135 public $_fields;
136
137 /**
138 * The billing location id for this contribiution page
139 *
140 * @var int
6a488035
TO
141 */
142 public $_bltID;
143
144 /**
145 * Price Set ID, if the new price set method is used
146 *
147 * @var int
6a488035
TO
148 */
149 public $_priceSetId = NULL;
150
151 /**
152 * Array of fields for the price set
153 *
154 * @var array
6a488035
TO
155 */
156 public $_priceSet;
157
158 public $_action;
159
160 public $_pcpId;
161
162 /* Is event already full.
163 *
164 * @var boolean
6a488035
TO
165 */
166
167 public $_isEventFull;
168
169 public $_lineItem;
170 public $_lineItemParticipantsCount;
171 public $_availableRegistrations;
172
173 public $_forcePayement;
174
8ae4d0d3 175 public $_isBillingAddressRequiredForPayLater;
176
6a488035 177 /**
100fef9d 178 * Set variables up before form is built
6a488035
TO
179 *
180 * @return void
6a488035 181 */
00be9182 182 public function preProcess() {
6a488035
TO
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');
6a488035
TO
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');
6a488035
TO
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
96f7c53e 227 $infoUrl = CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$this->_eventId}",
6a488035
TO
228 FALSE, NULL, FALSE, TRUE
229 );
230
231 // this is the first time we are hitting this, so check for permissions here
e2d09ab4 232 if (!CRM_Core_Permission::event(CRM_Core_Permission::EDIT, $this->_eventId, 'register for events')) {
6a488035
TO
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
96f7c53e 237 $this->_values = $this->_fields = array();
6a488035
TO
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);
6a488035
TO
245 // get the participant values, CRM-4320
246 $this->_allowConfirmation = FALSE;
247 if ($this->_participantId) {
248 $this->processFirstParticipant($this->_participantId);
249 }
6a488035
TO
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
96f7c53e 261 $eventFull = CRM_Event_BAO_Participant::eventFull($this->_eventId, FALSE,
6a488035
TO
262 CRM_Utils_Array::value('has_waitlist', $this->_values['event'])
263 );
264
96f7c53e 265 $this->_allowWaitlist = $this->_isEventFull = FALSE;
6a488035
TO
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;
a7488080 279 if (!empty($this->_values['event']['requires_approval']) && !$this->_allowConfirmation) {
6a488035
TO
280 $this->_requireApproval = TRUE;
281 }
282 $this->set('requireApproval', $this->_requireApproval);
283
6a488035
TO
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 }
6a488035
TO
288 // check for is_monetary status
289 $isMonetary = CRM_Utils_Array::value('is_monetary', $this->_values['event']);
96f7c53e 290 $isPayLater = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_eventId, 'is_pay_later');
6a488035
TO
291 //check for variour combination for paylater, payment
292 //process with paid event.
8cc574cf 293 if ($isMonetary && (!$isPayLater || !empty($this->_values['event']['payment_processor']))) {
6a488035
TO
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 }
6a488035
TO
300 $ppIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $ppID);
301 $this->_paymentProcessors = CRM_Financial_BAO_PaymentProcessor::getPayments($ppIds,
302 $this->_mode
303 );
6a488035
TO
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);
6a488035 318 }
6a488035
TO
319 // make sure we have a valid payment class, else abort
320 if ($this->_values['event']['is_monetary']) {
6a488035
TO
321 if (!CRM_Utils_System::isNull($this->_paymentProcessors)) {
322 foreach ($this->_paymentProcessors as $eachPaymentProcessor) {
6a488035
TO
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 }
6a488035
TO
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 }
6a488035 337 //init event fee.
96f7c53e 338 self::initEventFee($this, $this->_eventId);
6a488035
TO
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']) {
96f7c53e
PJ
353 // CRM-4377: CiviEvent for the main participant, CiviEvent_Additional for additional participants
354 $ufJoinParams['module'] = 'CiviEvent_Additional';
355
6a488035
TO
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 }
6a488035
TO
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 }
6a488035
TO
373 if (isset($postActive) && !$postActive) {
374 unset($this->_values['additional_custom_post_id']);
375 }
376 }
6a488035 377 // get the billing location type
180409a4 378 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
6a488035
TO
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);
6a488035
TO
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
a6513ad5
EM
387 if ($this->_values['event']['is_monetary']) {
388 CRM_Core_Payment_Form::setPaymentFieldsByProcessor($this, $this->_paymentProcessor);
6a488035 389 }
6a488035
TO
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(
96f7c53e 398 $this->_values['event']['id'], TRUE,
6a488035
TO
399 CRM_Utils_Array::value('has_waitlist', $this->_values['event'])
400 );
401 $this->set('availableRegistrations', $this->_availableRegistrations);
402 }
6a488035
TO
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 }
6a488035
TO
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);
6a488035
TO
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'];
2fd5e617 434 $this->_values['event']['intro_text'] = CRM_Utils_Array::value('intro_text', $pcp['pcpInfo']);
6a488035
TO
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);
6a488035 443 //CRM-6907
96f7c53e 444 $config->defaultCurrency = CRM_Utils_Array::value('currency', $this->_values['event'],
6a488035
TO
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 }
8ae4d0d3 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 }
6a488035
TO
459 }
460
461 /**
100fef9d 462 * Assign the minimal set of variables to the template
6a488035
TO
463 *
464 * @return void
6a488035 465 */
00be9182 466 public function assignToTemplate() {
6a488035
TO
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 = '';
a7488080 473 if (!empty($params['billing_first_name'])) {
6a488035
TO
474 $name = $params['billing_first_name'];
475 }
476
a7488080 477 if (!empty($params['billing_middle_name'])) {
6a488035
TO
478 $name .= " {$params['billing_middle_name']}";
479 }
480
a7488080 481 if (!empty($params['billing_last_name'])) {
6a488035
TO
482 $name .= " {$params['billing_last_name']}";
483 }
484 $this->assign('billingName', $name);
485 $this->set('name', $name);
486
487 $vars = array(
488 'amount', 'currencyID', 'credit_card_type',
489 'trxn_id', 'amount_level', 'receive_date',
490 );
491
492 foreach ($vars as $v) {
a7488080 493 if (!empty($params[$v])) {
6a488035
TO
494 if ($v == 'receive_date') {
495 $this->assign($v, CRM_Utils_Date::mysqlToIso($params[$v]));
496 }
497 else {
498 $this->assign($v, $params[$v]);
499 }
500 }
501 elseif (CRM_Utils_Array::value('amount', $params) == 0) {
502 $this->assign($v, CRM_Utils_Array::value($v, $params));
503 }
504 }
505
506 // assign the address formatted up for display
507 $addressParts = array(
508 "street_address-{$this->_bltID}",
509 "city-{$this->_bltID}",
510 "postal_code-{$this->_bltID}",
511 "state_province-{$this->_bltID}",
512 "country-{$this->_bltID}",
513 );
514 $addressFields = array();
515 foreach ($addressParts as $part) {
516 list($n, $id) = explode('-', $part);
517 if (isset($params['billing_' . $part])) {
518 $addressFields[$n] = CRM_Utils_Array::value('billing_' . $part, $params);
519 }
520 }
521
522 $this->assign('address', CRM_Utils_Address::format($addressFields));
523
8cc574cf 524 if ($this->_contributeMode == 'direct' && empty($params['is_pay_later'])) {
6a488035
TO
525 $date = CRM_Utils_Date::format(CRM_Utils_Array::value('credit_card_exp_date', $params));
526 $date = CRM_Utils_Date::mysqlToIso($date);
527 $this->assign('credit_card_exp_date', $date);
528 $this->assign('credit_card_number',
529 CRM_Utils_System::mungeCreditCard(CRM_Utils_Array::value('credit_card_number', $params))
530 );
531 }
532
533 // get the email that the confirmation would have been sent to
534 $session = CRM_Core_Session::singleton();
535
536 // assign is_email_confirm to templates
537 if (isset($this->_values['event']['is_email_confirm'])) {
538 $this->assign('is_email_confirm', $this->_values['event']['is_email_confirm']);
539 }
540
541 // assign pay later stuff
542 $params['is_pay_later'] = CRM_Utils_Array::value('is_pay_later', $params, FALSE);
543 $this->assign('is_pay_later', $params['is_pay_later']);
544 if ($params['is_pay_later']) {
545 $this->assign('pay_later_text', $this->_values['event']['pay_later_text']);
546 $this->assign('pay_later_receipt', $this->_values['event']['pay_later_receipt']);
547 }
548
549 // also assign all participantIDs to the template
550 // useful in generating confirmation numbers if needed
551 $this->assign('participantIDs',
552 $this->_participantIDS
553 );
554 }
555
556 /**
100fef9d 557 * Add the custom fields
6a488035 558 *
100fef9d
CW
559 * @param int $id
560 * @param string $name
77b97be7
EM
561 * @param bool $viewOnly
562 *
355ba699 563 * @return void
6a488035 564 */
00be9182 565 public function buildCustom($id, $name, $viewOnly = FALSE) {
6a488035
TO
566 if ($id) {
567 $button = substr($this->controller->getButtonName(), -4);
568 $cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
569 $session = CRM_Core_Session::singleton();
570 $contactID = $session->get('userID');
571
572 // we don't allow conflicting fields to be
573 // configured via profile
574 $fieldsToIgnore = array(
575 'participant_fee_amount' => 1,
576 'participant_fee_level' => 1,
577 );
578 if ($contactID) {
579 //FIX CRM-9653
580 if (is_array($id)) {
581 $fields = array();
582 foreach ($id as $profileID) {
583 $field = CRM_Core_BAO_UFGroup::getFields($profileID, FALSE, CRM_Core_Action::ADD,
584 NULL, NULL, FALSE, NULL,
585 FALSE, NULL, CRM_Core_Permission::CREATE,
586 'field_name', TRUE
587 );
588 $fields = array_merge($fields, $field);
589 }
590 }
591 else {
592 if (CRM_Core_BAO_UFGroup::filterUFGroups($id, $contactID)) {
593 $fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD,
594 NULL, NULL, FALSE, NULL,
595 FALSE, NULL, CRM_Core_Permission::CREATE,
596 'field_name', TRUE
597 );
598 }
599 }
600 }
601 else {
602 $fields = CRM_Core_BAO_UFGroup::getFields($id, FALSE, CRM_Core_Action::ADD,
603 NULL, NULL, FALSE, NULL,
604 FALSE, NULL, CRM_Core_Permission::CREATE,
605 'field_name', TRUE
606 );
607 }
608
609 if (array_intersect_key($fields, $fieldsToIgnore)) {
610 $fields = array_diff_key($fields, $fieldsToIgnore);
611 CRM_Core_Session::setStatus(ts('Some of the profile fields cannot be configured for this page.'));
612 }
613 $addCaptcha = FALSE;
a2149acc 614
615 if (!empty($this->_fields)) {
616 $fields = @array_diff_assoc($fields, $this->_fields);
617 }
618
a7488080 619 if (empty($this->_params[0]['additional_participants']) &&
6a488035
TO
620 is_null($cid)
621 ) {
622 CRM_Core_BAO_Address::checkContactSharedAddressFields($fields, $contactID);
623 }
624 $this->assign($name, $fields);
6a488035
TO
625 if (is_array($fields)) {
626 foreach ($fields as $key => $field) {
627 if ($viewOnly &&
628 isset($field['data_type']) &&
629 $field['data_type'] == 'File' || ($viewOnly && $field['name'] == 'image_URL')
630 ) {
631 // ignore file upload fields
632 continue;
633 }
634 //make the field optional if primary participant
635 //have been skip the additional participant.
636 if ($button == 'skip') {
637 $field['is_required'] = FALSE;
da8d9879 638 }
71fc6ea4
DG
639 // CRM-11316 Is ReCAPTCHA enabled for this profile AND is this an anonymous visitor
640 elseif ($field['add_captcha'] && !$contactID) {
6a488035
TO
641 // only add captcha for first page
642 $addCaptcha = TRUE;
643 }
6a488035 644 list($prefixName, $index) = CRM_Utils_System::explode('-', $key, 2);
6a488035
TO
645 CRM_Core_BAO_UFGroup::buildProfile($this, $field, CRM_Profile_Form::MODE_CREATE, $contactID, TRUE);
646
647 $this->_fields[$key] = $field;
648 }
649 }
4839c695 650
6a488035
TO
651 if ($addCaptcha && !$viewOnly) {
652 $captcha = CRM_Utils_ReCAPTCHA::singleton();
653 $captcha->add($this);
654 $this->assign('isCaptcha', TRUE);
655 }
656 }
657 }
658
0cf587a7 659 /**
c490a46a 660 * @param CRM_Core_Form $form
100fef9d 661 * @param int $eventID
0cf587a7
EM
662 *
663 * @throws Exception
664 */
00be9182 665 public static function initEventFee(&$form, $eventID) {
6a488035
TO
666 // get price info
667
668 // retrive all active price set fields.
669 $discountId = CRM_Core_BAO_Discount::findSet($eventID, 'civicrm_event');
8567d0f8
PN
670 if (property_exists($form, '_discountId') && $form->_discountId) {
671 $discountId = $form->_discountId;
672 }
6a488035
TO
673 if ($discountId) {
674 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Core_BAO_Discount', $discountId, 'price_set_id');
9da8dc8c 675 $price = CRM_Price_BAO_PriceSet::initSet($form, $eventID, 'civicrm_event', TRUE, $priceSetId);
6a488035
TO
676 }
677 else {
9da8dc8c 678 $price = CRM_Price_BAO_PriceSet::initSet($form, $eventID, 'civicrm_event', TRUE);
6a488035 679 }
8ef12e64 680
681 if (property_exists($form, '_context') && ($form->_context == 'standalone'
8567d0f8
PN
682 || $form->_context == 'participant')) {
683 $discountedEvent = CRM_Core_BAO_Discount::getOptionGroup($eventID, 'civicrm_event');
684 if (is_array( $discountedEvent)) {
685 foreach ($discountedEvent as $key => $priceSetId) {
9da8dc8c 686 $priceSet = CRM_Price_BAO_PriceSet::getSetDetail($priceSetId);
8567d0f8
PN
687 $priceSet = CRM_Utils_Array::value($priceSetId, $priceSet);
688 $form->_values['discount'][$key] = CRM_Utils_Array::value('fields', $priceSet);
689 $fieldID = key($form->_values['discount'][$key]);
690 $form->_values['discount'][$key][$fieldID]['name'] = CRM_Core_DAO::getFieldValue(
9da8dc8c 691 'CRM_Price_DAO_PriceSet',
8567d0f8
PN
692 $priceSetId,
693 'title'
694 );
695 }
696 }
697 }
6a488035
TO
698 $eventFee = CRM_Utils_Array::value('fee', $form->_values);
699 if (!is_array($eventFee) || empty($eventFee)) {
700 $form->_values['fee'] = array();
701 }
702
703 //fix for non-upgraded price sets.CRM-4256.
704 if (isset($form->_isPaidEvent)) {
705 $isPaidEvent = $form->_isPaidEvent;
706 }
707 else {
708 $isPaidEvent = CRM_Utils_Array::value('is_monetary', $form->_values['event']);
709 }
710 if ($isPaidEvent && empty($form->_values['fee'])) {
711 if (CRM_Utils_System::getClassName($form) != 'CRM_Event_Form_Participant') {
712 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))));
713 }
714 }
715 }
716
717 /**
100fef9d 718 * Handle process after the confirmation of payment by User
6a488035 719 *
100fef9d 720 * @param int $contactID
2a6da8d7
EM
721 * @param null $contribution
722 * @param null $payment
723 *
355ba699 724 * @return void
6a488035 725 */
00be9182 726 public function confirmPostProcess($contactID = NULL, $contribution = NULL, $payment = NULL) {
6a488035
TO
727 // add/update contact information
728 $fields = array();
729 unset($this->_params['note']);
730
731 //to avoid conflict overwrite $this->_params
732 $this->_params = $this->get('value');
733
734 //get the amount of primary participant
a7488080 735 if (!empty($this->_params['is_primary'])) {
6a488035
TO
736 $this->_params['fee_amount'] = $this->get('primaryParticipantAmount');
737 }
738
739 // add participant record
bf2c70af 740 $participant = CRM_Event_Form_Registration::addParticipant($this, $contactID);
6a488035
TO
741 $this->_participantIDS[] = $participant->id;
742
743 //setting register_by_id field and primaryContactId
a7488080 744 if (!empty($this->_params['is_primary'])) {
6a488035
TO
745 $this->set('registerByID', $participant->id);
746 $this->set('primaryContactId', $contactID);
747
748 // CRM-10032
749 $this->processFirstParticipant($participant->id);
750 }
751
752 CRM_Core_BAO_CustomValueTable::postProcess($this->_params,
753 CRM_Core_DAO::$_nullArray,
754 'civicrm_participant',
755 $participant->id,
756 'Participant'
757 );
758
759 $createPayment = (CRM_Utils_Array::value('amount', $this->_params, 0) != 0) ? TRUE : FALSE;
760
761 // force to create zero amount payment, CRM-5095
762 // we know the amout is zero since createPayment is false
763 if (!$createPayment &&
764 (isset($contribution) && $contribution->id) &&
765 $this->_priceSetId &&
766 $this->_lineItem
767 ) {
768 $createPayment = TRUE;
769 }
770
8cc574cf 771 if ($createPayment && $this->_values['event']['is_monetary'] && !empty($this->_params['contributionID'])) {
6a488035
TO
772 $paymentParams = array(
773 'participant_id' => $participant->id,
774 'contribution_id' => $contribution->id,
775 );
776 $ids = array();
777 $paymentPartcipant = CRM_Event_BAO_ParticipantPayment::create($paymentParams, $ids);
778 }
779
780 //set only primary participant's params for transfer checkout.
8cc574cf 781 if (($this->_contributeMode == 'checkout' || $this->_contributeMode == 'notify') && !empty($this->_params['is_primary'])) {
6a488035
TO
782 $this->_params['participantID'] = $participant->id;
783 $this->set('primaryParticipant', $this->_params);
784 }
785
786 $this->assign('action', $this->_action);
787
788 // create CMS user
a7488080 789 if (!empty($this->_params['cms_create_account'])) {
6a488035
TO
790 $this->_params['contactID'] = $contactID;
791
792 if (array_key_exists('email-5', $this->_params)) {
793 $mail = 'email-5';
794 } else {
795 foreach ($this->_params as $name => $dontCare) {
796 if (substr($name, 0, 5) == 'email') {
797 $mail = $name;
798 break;
799 }
800 }
801 }
802
803 // we should use primary email for
804 // 1. free event registration.
805 // 2. pay later participant.
806 // 3. waiting list participant.
807 // 4. require approval participant.
a7488080 808 if (!empty($this->_params['is_pay_later']) ||
8cc574cf 809 $this->_allowWaitlist || $this->_requireApproval || empty($this->_values['event']['is_monetary'])) {
6a488035
TO
810 $mail = 'email-Primary';
811 }
812
813 if (!CRM_Core_BAO_CMSUser::create($this->_params, $mail)) {
814 CRM_Core_Error::statusBounce(ts('Your profile is not saved and Account is not created.'));
815 }
816 }
817 }
818
819 /**
820 * Process the participant
821 *
c490a46a 822 * @param array $params
100fef9d 823 * @param int $contactID
dd244018 824 *
6a488035 825 * @return void
6a488035 826 */
bf2c70af 827 public static function addParticipant(&$form, $contactID) {
828 if (empty($form->_params)) {
829 return;
830 }
831 $params = $form->_params;
6a488035
TO
832 $transaction = new CRM_Core_Transaction();
833
834 $groupName = 'participant_role';
835 $query = "
836SELECT v.label as label ,v.value as value
837FROM civicrm_option_value v,
838 civicrm_option_group g
839WHERE v.option_group_id = g.id
840 AND g.name = %1
841 AND v.is_active = 1
842 AND g.is_active = 1
843";
844 $p = array(1 => array($groupName, 'String'));
845
846 $dao = CRM_Core_DAO::executeQuery($query, $p);
847 if ($dao->fetch()) {
848 $roleID = $dao->value;
849 }
850
851 // handle register date CRM-4320
852 $registerDate = NULL;
bf2c70af 853 if (!empty($form->_allowConfirmation) && $form->_participantId) {
6a488035
TO
854 $registerDate = $params['participant_register_date'];
855 }
a7488080 856 elseif (!empty($params['participant_register_date']) &&
6a488035
TO
857 is_array($params['participant_register_date']) &&
858 !empty($params['participant_register_date'])
859 ) {
860 $registerDate = CRM_Utils_Date::format($params['participant_register_date']);
861 }
862
6441bcc8 863 $participantFields = CRM_Event_DAO_Participant::fields();
6a488035
TO
864 $participantParams = array('id' => CRM_Utils_Array::value('participant_id', $params),
865 'contact_id' => $contactID,
bf2c70af 866 'event_id' => $form->_eventId ? $form->_eventId : $params['event_id'],
6a488035
TO
867 'status_id' => CRM_Utils_Array::value('participant_status',
868 $params, 1
869 ),
870 'role_id' => CRM_Utils_Array::value('participant_role_id',
871 $params, $roleID
872 ),
873 'register_date' => ($registerDate) ? $registerDate : date('YmdHis'),
6441bcc8
NG
874 'source' => CRM_Utils_String::ellipsify(
875 isset($params['participant_source']) ?
876 CRM_Utils_Array::value('participant_source', $params) : CRM_Utils_Array::value('description', $params),
877 $participantFields['participant_source']['maxlength']
878 ),
6a488035
TO
879 'fee_level' => CRM_Utils_Array::value('amount_level', $params),
880 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0),
881 'fee_amount' => CRM_Utils_Array::value('fee_amount', $params),
882 'registered_by_id' => CRM_Utils_Array::value('registered_by_id', $params),
883 'discount_id' => CRM_Utils_Array::value('discount_id', $params),
884 'fee_currency' => CRM_Utils_Array::value('currencyID', $params),
885 'campaign_id' => CRM_Utils_Array::value('campaign_id', $params),
886 );
887
bf2c70af 888 if ($form->_action & CRM_Core_Action::PREVIEW || CRM_Utils_Array::value('mode', $params) == 'test') {
6a488035
TO
889 $participantParams['is_test'] = 1;
890 }
891 else {
892 $participantParams['is_test'] = 0;
893 }
894
bf2c70af 895 if (!empty($form->_params['note'])) {
896 $participantParams['note'] = $form->_params['note'];
6a488035 897 }
bf2c70af 898 elseif (!empty($form->_params['participant_note'])) {
899 $participantParams['note'] = $form->_params['participant_note'];
6a488035
TO
900 }
901
902 // reuse id if one already exists for this one (can happen
903 // with back button being hit etc)
8cc574cf 904 if (!$participantParams['id'] && !empty($params['contributionID'])) {
6a488035
TO
905 $pID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
906 $params['contributionID'],
907 'participant_id',
908 'contribution_id'
909 );
910 $participantParams['id'] = $pID;
911 }
bf2c70af 912 $participantParams['discount_id'] = CRM_Core_BAO_Discount::findSet($form->_eventId, 'civicrm_event');
6a488035
TO
913
914 if (!$participantParams['discount_id']) {
915 $participantParams['discount_id'] = "null";
916 }
917
918 $participant = CRM_Event_BAO_Participant::create($participantParams);
919
920 $transaction->commit();
921
922 return $participant;
923 }
924
925 /* Calculate the total participant count as per params.
926 *
927 * @param array $params user params.
928 *
929 * @return $totalCount total participant count.
6a488035 930 */
0cf587a7 931 /**
c490a46a
CW
932 * @param CRM_Core_Form $form
933 * @param array $params
0cf587a7
EM
934 * @param bool $skipCurrent
935 *
936 * @return int|string
937 */
6a488035
TO
938 public static function getParticipantCount(&$form, $params, $skipCurrent = FALSE) {
939 $totalCount = 0;
940 if (!is_array($params) || empty($params)) {
941 return $totalCount;
942 }
943
944 $priceSetId = $form->get('priceSetId');
945 $addParticipantNum = substr($form->_name, 12);
946 $priceSetFields = $priceSetDetails = array();
947 $hasPriceFieldsCount = FALSE;
948 if ($priceSetId) {
949 $priceSetDetails = $form->get('priceSet');
950 if (isset($priceSetDetails['optionsCountTotal'])
951 && $priceSetDetails['optionsCountTotal']
952 ) {
953 $hasPriceFieldsCount = TRUE;
954 $priceSetFields = $priceSetDetails['optionsCountDetails']['fields'];
955 }
956 }
957
958 $singleFormParams = FALSE;
959 foreach ($params as $key => $val) {
960 if (!is_numeric($key)) {
961 $singleFormParams = TRUE;
962 break;
963 }
964 }
965
966 //first format the params.
967 if ($singleFormParams) {
968 $params = self::formatPriceSetParams($form, $params);
969 $params = array($params);
970 }
971
972 foreach ($params as $key => $values) {
973 if (!is_numeric($key) ||
974 $values == 'skip' ||
975 ($skipCurrent && ($addParticipantNum == $key))
976 ) {
977 continue;
978 }
979 $count = 1;
980
981 $usedCache = FALSE;
982 $cacheCount = CRM_Utils_Array::value($key, $form->_lineItemParticipantsCount);
983 if ($cacheCount && is_numeric($cacheCount)) {
984 $count = $cacheCount;
985 $usedCache = TRUE;
986 }
987
988 if (!$usedCache && $hasPriceFieldsCount) {
989 $count = 0;
990 foreach ($values as $valKey => $value) {
991 if (strpos($valKey, 'price_') === FALSE) {
992 continue;
993 }
994 $priceFieldId = substr($valKey, 6);
995 if (!$priceFieldId ||
996 !is_array($value) ||
997 !array_key_exists($priceFieldId, $priceSetFields)
998 ) {
999 continue;
1000 }
1001 foreach ($value as $optId => $optVal) {
1002 $currentCount = $priceSetFields[$priceFieldId]['options'][$optId] * $optVal;
1003 if ($currentCount) {
1004 $count += $currentCount;
1005 }
1006 }
1007 }
1008 if (!$count) {
1009 $count = 1;
1010 }
1011 }
1012 $totalCount += $count;
1013 }
1014 if (!$totalCount) {
1015 $totalCount = 1;
1016 }
1017
1018 return $totalCount;
1019 }
1020
1021 /* Format user submitted price set params.
1022 * Convert price set each param as an array.
1023 *
1024 * @param $params an array of user submitted params.
1025 *
1026 *
1027 * @return array $formatted, formatted price set params.
6a488035 1028 */
0cf587a7 1029 /**
c490a46a
CW
1030 * @param CRM_Core_Form $form
1031 * @param array $params
0cf587a7
EM
1032 *
1033 * @return mixed
1034 */
6a488035
TO
1035 public static function formatPriceSetParams(&$form, $params) {
1036 if (!is_array($params) || empty($params)) {
1037 return $params;
1038 }
1039
1040 $priceSetId = $form->get('priceSetId');
1041 if (!$priceSetId) {
1042 return $params;
1043 }
1044 $priceSetDetails = $form->get('priceSet');
1045
1046 foreach ($params as $key => & $value) {
1047 $vals = array();
1048 if (strpos($key, 'price_') !== FALSE) {
1049 $fieldId = substr($key, 6);
1050 if (!array_key_exists($fieldId, $priceSetDetails['fields']) ||
1051 is_array($value) ||
1052 !$value
1053 ) {
1054 continue;
1055 }
1056 $field = $priceSetDetails['fields'][$fieldId];
1057 if ($field['html_type'] == 'Text') {
1058 $fieldOption = current($field['options']);
1059 $value = array($fieldOption['id'] => $value);
1060 }
1061 else {
1062 $value = array($value => TRUE);
1063 }
1064 }
1065 }
1066
1067 return $params;
1068 }
1069
1070 /* Calculate total count for each price set options.
1071 * those are currently selected by user.
1072 *
1073 * @param $form form object.
1074 *
1075 *
1076 * @return array $optionsCount, array of each option w/ count total.
6a488035 1077 */
0cf587a7
EM
1078 /**
1079 * @param $form
1080 *
1081 * @return array
1082 */
169be3c1 1083 public static function getPriceSetOptionCount(&$form) {
6a488035
TO
1084 $params = $form->get('params');
1085 $priceSet = $form->get('priceSet');
1086 $priceSetId = $form->get('priceSetId');
1087
1088 $optionsCount = array();
1089 if (!$priceSetId ||
1090 !is_array($priceSet) ||
1091 empty($priceSet) ||
1092 !is_array($params) ||
1093 empty($params)
1094 ) {
1095 return $optionsCount;
1096 }
1097
1098 $priceSetFields = $priceMaxFieldDetails = array();
a7488080 1099 if (!empty($priceSet['optionsCountTotal'])) {
6a488035
TO
1100 $priceSetFields = $priceSet['optionsCountDetails']['fields'];
1101 }
1102
a7488080 1103 if (!empty($priceSet['optionsMaxValueTotal'])) {
6a488035
TO
1104 $priceMaxFieldDetails = $priceSet['optionsMaxValueDetails']['fields'];
1105 }
1106
1107 $addParticipantNum = substr($form->_name, 12);
1108 foreach ($params as $pCnt => $values) {
1109 if ($values == 'skip' ||
79b152ac 1110 $pCnt === $addParticipantNum
6a488035
TO
1111 ) {
1112 continue;
1113 }
1114
1115 foreach ($values as $valKey => $value) {
1116 if (strpos($valKey, 'price_') === FALSE) {
1117 continue;
1118 }
1119
1120 $priceFieldId = substr($valKey, 6);
1121 if (!$priceFieldId ||
1122 !is_array($value) ||
1123 !(array_key_exists($priceFieldId, $priceSetFields) || array_key_exists($priceFieldId, $priceMaxFieldDetails))
1124 ) {
1125 continue;
1126 }
1127
1128 foreach ($value as $optId => $optVal) {
1129 if (CRM_Utils_Array::value('html_type', $priceSet['fields'][$priceFieldId]) == 'Text') {
1130 $currentCount = $optVal;
1131 }
1132 else {
1133 $currentCount = 1;
1134 }
1135
1136 if (isset($priceSetFields[$priceFieldId]) && isset($priceSetFields[$priceFieldId]['options'][$optId])) {
1137 $currentCount = $priceSetFields[$priceFieldId]['options'][$optId] * $optVal;
1138 }
1139
1140 $optionsCount[$optId] = $currentCount + CRM_Utils_Array::value($optId, $optionsCount, 0);
1141 }
1142 }
1143 }
1144
1145 return $optionsCount;
1146 }
1147
0cf587a7
EM
1148 /**
1149 * @param string $suffix
1150 *
1151 * @return null|string
1152 */
00be9182 1153 public function checkTemplateFileExists($suffix = '') {
6a488035
TO
1154 if ($this->_eventId) {
1155 $templateName = $this->_name;
1156 if (substr($templateName, 0, 12) == 'Participant_') {
1157 $templateName = 'AdditionalParticipant';
1158 }
1159
1160 $templateFile = "CRM/Event/Form/Registration/{$this->_eventId}/{$templateName}.{$suffix}tpl";
1161 $template = CRM_Core_Form::getTemplate();
1162 if ($template->template_exists($templateFile)) {
1163 return $templateFile;
1164 }
1165 }
1166 return NULL;
1167 }
1168
0cf587a7
EM
1169 /**
1170 * @return null|string
1171 */
00be9182 1172 public function getTemplateFileName() {
6a488035
TO
1173 $fileName = $this->checkTemplateFileExists();
1174 return $fileName ? $fileName : parent::getTemplateFileName();
1175 }
1176
0cf587a7
EM
1177 /**
1178 * @return null|string
1179 */
00be9182 1180 public function overrideExtraTemplateFileName() {
6a488035
TO
1181 $fileName = $this->checkTemplateFileExists('extra.');
1182 return $fileName ? $fileName : parent::overrideExtraTemplateFileName();
1183 }
1184
da8d9879
DG
1185 /**
1186 * Validate price set submitted params for price option limit,
6a488035 1187 * as well as user should select at least one price field option.
da8d9879
DG
1188 * @param unknown_type $form
1189 * @param unknown_type $params
1190 * @return multitype:|Ambigous <multitype:, string, string>
6a488035 1191 */
00be9182 1192 public static function validatePriceSet(&$form, $params) {
6a488035
TO
1193 $errors = array();
1194 $hasOptMaxValue = FALSE;
1195 if (!is_array($params) || empty($params)) {
1196 return $errors;
1197 }
1198
1199 $currentParticipantNum = substr($form->_name, 12);
1200 if (!$currentParticipantNum) {
1201 $currentParticipantNum = 0;
1202 }
1203
1204 $priceSetId = $form->get('priceSetId');
1205 $priceSetDetails = $form->get('priceSet');
1206 if (
1207 !$priceSetId ||
1208 !is_array($priceSetDetails) ||
1209 empty($priceSetDetails)
1210 ) {
1211 return $errors;
1212 }
1213
1214 $optionsCountDetails = $optionsMaxValueDetails = array();
1215 if (
1216 isset($priceSetDetails['optionsMaxValueTotal'])
1217 && $priceSetDetails['optionsMaxValueTotal']
1218 ) {
1219 $hasOptMaxValue = TRUE;
1220 $optionsMaxValueDetails = $priceSetDetails['optionsMaxValueDetails']['fields'];
1221 }
1222 if (
1223 isset($priceSetDetails['optionsCountTotal'])
1224 && $priceSetDetails['optionsCountTotal']
1225 ) {
1226 $hasOptCount = TRUE;
1227 $optionsCountDetails = $priceSetDetails['optionsCountDetails']['fields'];
1228 }
1229 $feeBlock = $form->_feeBlock;
1230
1231 if (empty($feeBlock)) {
1232 $feeBlock = $priceSetDetails['fields'];
1233 }
1234
1235 $optionMaxValues = $fieldSelected = array();
1236 foreach ($params as $pNum => $values) {
1237 if (!is_array($values) || $values == 'skip') {
1238 continue;
1239 }
1240
1241 foreach ($values as $valKey => $value) {
1242 if (strpos($valKey, 'price_') === FALSE) {
1243 continue;
1244 }
1245 $priceFieldId = substr($valKey, 6);
1246 $noneOptionValueSelected = FALSE;
1247 if (!$feeBlock[$priceFieldId]['is_required'] && $value == 0) {
1248 $noneOptionValueSelected = TRUE;
1249 }
1250
1251 if (
1252 !$priceFieldId ||
1253 (!$noneOptionValueSelected && !is_array($value))
1254 ) {
1255 continue;
1256 }
1257
1258 $fieldSelected[$pNum] = TRUE;
1259
1260 if (!$hasOptMaxValue || !is_array($value)) {
1261 continue;
1262 }
1263
1264 foreach ($value as $optId => $optVal) {
1265 if (CRM_Utils_Array::value('html_type', $feeBlock[$priceFieldId]) == 'Text') {
1266 $currentMaxValue = $optVal;
1267 }
1268 else {
1269 $currentMaxValue = 1;
1270 }
1271
1272 if (isset($optionsCountDetails[$priceFieldId]) && isset($optionsCountDetails[$priceFieldId]['options'][$optId])) {
1273 $currentMaxValue = $optionsCountDetails[$priceFieldId]['options'][$optId] * $optVal;
1274 }
1275 if (empty($optionMaxValues)) {
1276 $optionMaxValues[$priceFieldId][$optId] = $currentMaxValue;
1277 }
1278 else {
1279 $optionMaxValues[$priceFieldId][$optId] =
1280 $currentMaxValue + CRM_Utils_Array::value($optId, CRM_Utils_Array::value($priceFieldId, $optionMaxValues), 0);
1281 }
1282
1283 }
1284 }
1285 }
1286
1287 //validate for option max value.
1288 foreach ($optionMaxValues as $fieldId => $values) {
1289 $options = CRM_Utils_Array::value('options', $feeBlock[$fieldId], array());
1290 foreach ($values as $optId => $total) {
1291 $optMax = $optionsMaxValueDetails[$fieldId]['options'][$optId];
1292 $opDbCount = CRM_Utils_Array::value('db_total_count', $options[$optId], 0);
1293 $total += $opDbCount;
1294 if ($optMax && $total > $optMax) {
79b152ac 1295 $errors['soldOutOptions'][] = ts('Option %1 has sold out.', array(1 => $feeBlock[$fieldId]['options'][$optId]['label']));
6a488035
TO
1296 if ($opDbCount && ($opDbCount >= $optMax)) {
1297 $errors[$currentParticipantNum]["price_{$fieldId}"] =
1298 ts('Sorry, this option is currently sold out.');
1299 }
1300 elseif (($optMax - $opDbCount) == 1) {
1301 $errors[$currentParticipantNum]["price_{$fieldId}"] =
1302 ts('Sorry, currently only a single seat is available for this option.', array(1 => ($optMax - $opDbCount)));
1303 }
1304 else {
1305 $errors[$currentParticipantNum]["price_{$fieldId}"] =
1306 ts('Sorry, currently only %1 seats are available for this option.', array(1 => ($optMax - $opDbCount)));
1307 }
1308 }
1309 }
1310 }
1311
1312 //validate for price field selection.
1313 foreach ($params as $pNum => $values) {
1314 if (!is_array($values) || $values == 'skip') {
1315 continue;
1316 }
a7488080 1317 if (empty($fieldSelected[$pNum])) {
6a488035
TO
1318 $errors[$pNum]['_qf_default'] = ts('Select at least one option from Event Fee(s).');
1319 }
1320 }
1321
1322 return $errors;
1323 }
1324
1325 // set the first participant ID if not set, CRM-10032
0cf587a7 1326 /**
100fef9d 1327 * @param int $participantID
0cf587a7 1328 */
00be9182 1329 public function processFirstParticipant($participantID) {
6a488035
TO
1330 $this->_participantId = $participantID;
1331 $this->set('participantId', $this->_participantId);
1332
1333 $ids = $participantValues = array();
1334 $participantParams = array('id' => $this->_participantId);
1335 CRM_Event_BAO_Participant::getValues($participantParams, $participantValues, $ids);
1336 $this->_values['participant'] = $participantValues[$this->_participantId];
1337 $this->set('values', $this->_values);
1338
1339 // also set the allow confirmation stuff
1340 if (array_key_exists(
1341 $this->_values['participant']['status_id'],
1342 CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Pending'")
1343 )) {
1344 $this->_allowConfirmation = TRUE;
1345 $this->set('allowConfirmation', TRUE);
1346 }
1347 }
1348
e2d09ab4
EM
1349 /**
1350 * @todo - combine this with CRM_Event_BAO_Event::validRegistrationRequest
1351 * (probably extract relevant values here & call that with them & handle bounces & redirects here -as
1352 * those belong in the form layer)
1353 *
1354 * @param string $redirect
1355 */
00be9182 1356 public function checkValidEvent($redirect = NULL) {
6a488035
TO
1357 // is the event active (enabled)?
1358 if (!$this->_values['event']['is_active']) {
1359 // form is inactive, die a fatal death
1360 CRM_Core_Error::statusBounce(ts('The event you requested is currently unavailable (contact the site administrator for assistance).'));
1361 }
1362
1363 // is online registration is enabled?
1364 if (!$this->_values['event']['is_online_registration']) {
1365 CRM_Core_Error::statusBounce(ts('Online registration is not currently available for this event (contact the site administrator for assistance).'), $redirect);
1366 }
1367
1368 // is this an event template ?
a7488080 1369 if (!empty($this->_values['event']['is_template'])) {
6a488035
TO
1370 CRM_Core_Error::statusBounce(ts('Event templates are not meant to be registered.'), $redirect);
1371 }
1372
1373 $now = date('YmdHis');
1374 $startDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('registration_start_date',
1375 $this->_values['event']
1376 ));
1377
1378 if (
1379 $startDate &&
1380 $startDate >= $now
1381 ) {
1382 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);
1383 }
1384
1385 $endDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('registration_end_date',
1386 $this->_values['event']
1387 ));
4bd9b7a9 1388 $eventEndDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('event_end_date', $this->_values['event']));
6a488035
TO
1389 if (
1390 $endDate &&
1391 $endDate < $now
1392 ) {
1393 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);
1394 }
4bd9b7a9
RK
1395 if (!empty($eventEndDate) && $eventEndDate < $now) {
1396 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);
1397 }
6a488035
TO
1398 }
1399}