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