Allow only public custom groups to display on participants receipts
[civicrm-core.git] / CRM / Event / Form / Participant.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 *
30 *
31 * @package CRM
32 * @copyright CiviCRM LLC (c) 2004-2017
33 * $Id$
34 *
35 */
36
37 /**
38 * This class generates form components for processing a participation
39 * in an event
40 */
41 class CRM_Event_Form_Participant extends CRM_Contribute_Form_AbstractEditPayment {
42
43 public $useLivePageJS = TRUE;
44
45 /**
46 * The values for the contribution db object.
47 *
48 * @var array
49 */
50 public $_values;
51
52 /**
53 * The values for the quickconfig for priceset.
54 *
55 * @var boolean
56 */
57 public $_quickConfig = NULL;
58
59 /**
60 * Price Set ID, if the new price set method is used
61 *
62 * @var int
63 */
64 public $_priceSetId;
65
66 /**
67 * Array of fields for the price set.
68 *
69 * @var array
70 */
71 public $_priceSet;
72
73 /**
74 * The id of the participation that we are proceessing.
75 *
76 * @var int
77 */
78 public $_id;
79
80 /**
81 * The id of the note.
82 *
83 * @var int
84 */
85 protected $_noteId = NULL;
86
87 /**
88 * @deprecated
89 *
90 * Use parent $this->contactID
91 *
92 * The id of the contact associated with this participation.
93 *
94 * @var int
95 */
96 public $_contactId;
97
98 /**
99 * Array of event values.
100 *
101 * @var array
102 */
103 protected $_event;
104
105 /**
106 * Are we operating in "single mode", i.e. adding / editing only
107 * one participant record, or is this a batch add operation
108 *
109 * @var boolean
110 */
111 public $_single = FALSE;
112
113 /**
114 * If event is paid or unpaid.
115 */
116 public $_isPaidEvent;
117
118 /**
119 * Page action.
120 */
121 public $_action;
122
123 /**
124 * Role Id.
125 */
126 protected $_roleId = NULL;
127
128 /**
129 * Event Type Id.
130 */
131 protected $_eventTypeId = NULL;
132
133 /**
134 * Participant status Id.
135 */
136 protected $_statusId = NULL;
137
138 /**
139 * Cache all the participant statuses.
140 */
141 protected $_participantStatuses;
142
143 /**
144 * Participant mode.
145 */
146 public $_mode = NULL;
147
148 /**
149 * Event ID preselect.
150 */
151 public $_eID = NULL;
152
153 /**
154 * Line Item for Price Set.
155 */
156 public $_lineItem = NULL;
157
158 /**
159 * Contribution mode for event registration for offline mode.
160 *
161 * @deprecated
162 */
163 public $_contributeMode = 'direct';
164
165 public $_online;
166
167 /**
168 * Store id of role custom data type ( option value )
169 */
170 protected $_roleCustomDataTypeID;
171
172 /**
173 * Store id of event Name custom data type ( option value)
174 */
175 protected $_eventNameCustomDataTypeID;
176
177 /**
178 * Selected discount id.
179 */
180 public $_originalDiscountId = NULL;
181
182 /**
183 * Event id.
184 */
185 public $_eventId = NULL;
186
187 /**
188 * Id of payment, if any
189 */
190 public $_paymentId = NULL;
191
192 /**
193 * @todo add explanatory note about this
194 * @var null
195 */
196 public $_onlinePendingContributionId = NULL;
197
198 /**
199 * Explicitly declare the entity api name.
200 */
201 public function getDefaultEntity() {
202 return 'Participant';
203 }
204
205 /**
206 * Set variables up before form is built.
207 *
208 * @return void
209 */
210 public function preProcess() {
211 parent::preProcess();
212 $this->_showFeeBlock = CRM_Utils_Array::value('eventId', $_GET);
213 $this->assign('showFeeBlock', FALSE);
214 $this->assign('feeBlockPaid', FALSE);
215
216 // @todo eliminate this duplication.
217 $this->_contactId = $this->_contactID;
218 $this->_eID = CRM_Utils_Request::retrieve('eid', 'Positive', $this);
219 $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
220 $this->assign('context', $this->_context);
221
222 if ($this->_contactID) {
223 $this->setPageTitle(ts('Event Registration for %1', array(1 => $this->userDisplayName)));
224 }
225 else {
226 $this->setPageTitle(ts('Event Registration'));
227 }
228
229 // check the current path, if search based, then dont get participantID
230 // CRM-5792
231 $path = CRM_Utils_System::currentPath();
232 if (
233 strpos($path, 'civicrm/contact/search') === 0 ||
234 strpos($path, 'civicrm/group/search') === 0
235 ) {
236 $this->_id = NULL;
237 }
238 else {
239 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
240 }
241
242 if ($this->_id) {
243 $this->assign('participantId', $this->_id);
244
245 $this->_paymentId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
246 $this->_id, 'id', 'participant_id'
247 );
248
249 $this->assign('hasPayment', $this->_paymentId);
250 $this->assign('componentId', $this->_id);
251 $this->assign('component', 'event');
252
253 // CRM-12615 - Get payment information from the primary registration
254 if ((!$this->_paymentId) && ($this->_action == CRM_Core_Action::UPDATE)) {
255 $registered_by_id = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
256 $this->_id, 'registered_by_id', 'id'
257 );
258 if ($registered_by_id) {
259 $this->_paymentId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
260 $registered_by_id, 'id', 'participant_id'
261 );
262 $this->assign('registeredByParticipantId', $registered_by_id);
263 }
264 }
265 }
266
267 // get the option value for custom data type
268 $customDataType = CRM_Core_OptionGroup::values('custom_data_type', FALSE, FALSE, FALSE, NULL, 'name');
269 $this->_roleCustomDataTypeID = array_search('ParticipantRole', $customDataType);
270 $this->_eventNameCustomDataTypeID = array_search('ParticipantEventName', $customDataType);
271 $this->_eventTypeCustomDataTypeID = array_search('ParticipantEventType', $customDataType);
272 $this->assign('roleCustomDataTypeID', $this->_roleCustomDataTypeID);
273 $this->assign('eventNameCustomDataTypeID', $this->_eventNameCustomDataTypeID);
274 $this->assign('eventTypeCustomDataTypeID', $this->_eventTypeCustomDataTypeID);
275
276 if ($this->_mode) {
277 $this->assign('participantMode', $this->_mode);
278 }
279
280 if ($this->_showFeeBlock) {
281 $this->assign('showFeeBlock', TRUE);
282 $isMonetary = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_showFeeBlock, 'is_monetary');
283 if ($isMonetary) {
284 $this->assign('feeBlockPaid', TRUE);
285 }
286 return CRM_Event_Form_EventFees::preProcess($this);
287 }
288
289 //check the mode when this form is called either single or as
290 //search task action
291 if ($this->_id || $this->_contactId || $this->_context == 'standalone') {
292 $this->_single = TRUE;
293 $this->assign('urlPath', 'civicrm/contact/view/participant');
294 if (!$this->_id && !$this->_contactId) {
295 $breadCrumbs = array(
296 array(
297 'title' => ts('CiviEvent Dashboard'),
298 'url' => CRM_Utils_System::url('civicrm/event', 'reset=1'),
299 ),
300 );
301
302 CRM_Utils_System::appendBreadCrumb($breadCrumbs);
303 }
304 }
305 else {
306 //set the appropriate action
307 $context = $this->get('context');
308 $urlString = 'civicrm/contact/search';
309 $this->_action = CRM_Core_Action::BASIC;
310 switch ($context) {
311 case 'advanced':
312 $urlString = 'civicrm/contact/search/advanced';
313 $this->_action = CRM_Core_Action::ADVANCED;
314 break;
315
316 case 'builder':
317 $urlString = 'civicrm/contact/search/builder';
318 $this->_action = CRM_Core_Action::PROFILE;
319 break;
320
321 case 'basic':
322 $urlString = 'civicrm/contact/search/basic';
323 $this->_action = CRM_Core_Action::BASIC;
324 break;
325
326 case 'custom':
327 $urlString = 'civicrm/contact/search/custom';
328 $this->_action = CRM_Core_Action::COPY;
329 break;
330 }
331 CRM_Contact_Form_Task::preProcessCommon($this);
332
333 $this->_single = FALSE;
334 $this->_contactId = NULL;
335
336 //set ajax path, this used for custom data building
337 $this->assign('urlPath', $urlString);
338 $this->assign('urlPathVar', "_qf_Participant_display=true&qfKey={$this->controller->_key}");
339 }
340
341 $this->assign('single', $this->_single);
342
343 if (!$this->_id) {
344 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add');
345 }
346 $this->assign('action', $this->_action);
347
348 // check for edit permission
349 if (!CRM_Core_Permission::checkActionPermission('CiviEvent', $this->_action)) {
350 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
351 }
352
353 if ($this->_action & CRM_Core_Action::DELETE) {
354 // check delete permission for contribution
355 if ($this->_id && $this->_paymentId && !CRM_Core_Permission::checkActionPermission('CiviContribute', $this->_action)) {
356 CRM_Core_Error::fatal(ts("This Participant is linked to a contribution. You must have 'delete in CiviContribute' permission in order to delete this record."));
357 }
358 return;
359 }
360
361 if ($this->_id) {
362 // assign participant id to the template
363 $this->assign('participantId', $this->_id);
364 $this->_roleId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'role_id');
365 }
366
367 // when fee amount is included in form
368 if (!empty($_POST['hidden_feeblock']) || !empty($_POST['send_receipt'])) {
369 CRM_Event_Form_EventFees::preProcess($this);
370 CRM_Event_Form_EventFees::buildQuickForm($this);
371 CRM_Event_Form_EventFees::setDefaultValues($this);
372 }
373
374 // when custom data is included in this page
375 if (!empty($_POST['hidden_custom'])) {
376 // Custom data of type participant role
377 // Note: Some earlier commits imply $_POST['role_id'] could be a comma separated string,
378 // not sure if that ever really happens
379 if (!empty($_POST['role_id'])) {
380 foreach ($_POST['role_id'] as $roleID) {
381 CRM_Custom_Form_CustomData::preProcess($this, $this->_roleCustomDataTypeID, $roleID, 1, 'Participant', $this->_id);
382 CRM_Custom_Form_CustomData::buildQuickForm($this);
383 CRM_Custom_Form_CustomData::setDefaultValues($this);
384 }
385 }
386
387 //custom data of type participant event
388 CRM_Custom_Form_CustomData::preProcess($this, $this->_eventNameCustomDataTypeID, $_POST['event_id'], 1, 'Participant', $this->_id);
389 CRM_Custom_Form_CustomData::buildQuickForm($this);
390 CRM_Custom_Form_CustomData::setDefaultValues($this);
391
392 // custom data of type participant event type
393 $eventTypeId = NULL;
394 if ($eventId = CRM_Utils_Array::value('event_id', $_POST)) {
395 $eventTypeId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventId, 'event_type_id', 'id');
396 }
397 CRM_Custom_Form_CustomData::preProcess($this, $this->_eventTypeCustomDataTypeID, $eventTypeId,
398 1, 'Participant', $this->_id
399 );
400 CRM_Custom_Form_CustomData::buildQuickForm($this);
401 CRM_Custom_Form_CustomData::setDefaultValues($this);
402
403 //custom data of type participant, ( we 'null' to reset subType and subName)
404 CRM_Custom_Form_CustomData::preProcess($this, 'null', 'null', 1, 'Participant', $this->_id);
405 CRM_Custom_Form_CustomData::buildQuickForm($this);
406 CRM_Custom_Form_CustomData::setDefaultValues($this);
407 }
408
409 // CRM-4395, get the online pending contribution id.
410 $this->_onlinePendingContributionId = NULL;
411 if (!$this->_mode && $this->_id && ($this->_action & CRM_Core_Action::UPDATE)) {
412 $this->_onlinePendingContributionId = CRM_Contribute_BAO_Contribution::checkOnlinePendingContribution($this->_id,
413 'Event'
414 );
415 }
416 $this->set('onlinePendingContributionId', $this->_onlinePendingContributionId);
417 }
418
419 /**
420 * This function sets the default values for the form in edit/view mode
421 * the default values are retrieved from the database
422 *
423 *
424 * @return void
425 */
426 public function setDefaultValues() {
427 if ($this->_showFeeBlock) {
428 return CRM_Event_Form_EventFees::setDefaultValues($this);
429 }
430
431 $defaults = array();
432
433 if ($this->_action & CRM_Core_Action::DELETE) {
434 return $defaults;
435 }
436
437 if ($this->_id) {
438 $ids = array();
439 $params = array('id' => $this->_id);
440
441 CRM_Event_BAO_Participant::getValues($params, $defaults, $ids);
442 $sep = CRM_Core_DAO::VALUE_SEPARATOR;
443 if ($defaults[$this->_id]['role_id']) {
444 $roleIDs = explode($sep, $defaults[$this->_id]['role_id']);
445 }
446 $this->_contactId = $defaults[$this->_id]['contact_id'];
447 $this->_statusId = $defaults[$this->_id]['participant_status_id'];
448
449 //set defaults for note
450 $noteDetails = CRM_Core_BAO_Note::getNote($this->_id, 'civicrm_participant');
451 $defaults[$this->_id]['note'] = array_pop($noteDetails);
452
453 // Check if this is a primaryParticipant (registered for others) and retrieve additional participants if true (CRM-4859)
454 if (CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
455 $this->assign('additionalParticipants', CRM_Event_BAO_Participant::getAdditionalParticipants($this->_id));
456 }
457
458 // Get registered_by contact ID and display_name if participant was registered by someone else (CRM-4859)
459 if (!empty($defaults[$this->_id]['participant_registered_by_id'])) {
460 $registered_by_contact_id = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
461 $defaults[$this->_id]['participant_registered_by_id'],
462 'contact_id', 'id'
463 );
464 $this->assign('participant_registered_by_id', $defaults[$this->_id]['participant_registered_by_id']);
465 $this->assign('registered_by_contact_id', $registered_by_contact_id);
466 $this->assign('registered_by_display_name', CRM_Contact_BAO_Contact::displayName($registered_by_contact_id));
467 }
468 }
469
470 if ($this->_action & (CRM_Core_Action::VIEW | CRM_Core_Action::BROWSE)) {
471 $inactiveNeeded = TRUE;
472 $viewMode = TRUE;
473 }
474 else {
475 $viewMode = FALSE;
476 $inactiveNeeded = FALSE;
477 }
478
479 //setting default register date
480 if ($this->_action == CRM_Core_Action::ADD) {
481 $statuses = array_flip(CRM_Event_PseudoConstant::participantStatus());
482 $defaults[$this->_id]['status_id'] = CRM_Utils_Array::value('Registered', $statuses);
483 if (!empty($defaults[$this->_id]['event_id'])) {
484 $contributionTypeId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event',
485 $defaults[$this->_id]['event_id'],
486 'financial_type_id'
487 );
488 if ($contributionTypeId) {
489 $defaults[$this->_id]['financial_type_id'] = $contributionTypeId;
490 }
491 }
492
493 if ($this->_mode) {
494 $fields["email-{$this->_bltID}"] = 1;
495 $fields['email-Primary'] = 1;
496
497 if ($this->_contactId) {
498 CRM_Core_BAO_UFGroup::setProfileDefaults($this->_contactId, $fields, $defaults);
499 }
500
501 if (empty($defaults["email-{$this->_bltID}"]) &&
502 !empty($defaults['email-Primary'])
503 ) {
504 $defaults[$this->_id]["email-{$this->_bltID}"] = $defaults['email-Primary'];
505 }
506 }
507
508 $submittedRole = $this->getElementValue('role_id');
509 if (!empty($submittedRole[0])) {
510 $roleID = $submittedRole[0];
511 }
512 $submittedEvent = $this->getElementValue('event_id');
513 if (!empty($submittedEvent[0])) {
514 $eventID = $submittedEvent[0];
515 }
516 }
517 else {
518 $defaults[$this->_id]['record_contribution'] = 0;
519
520 if ($defaults[$this->_id]['participant_is_pay_later']) {
521 $this->assign('participant_is_pay_later', TRUE);
522 }
523
524 $this->assign('participant_status_id', $defaults[$this->_id]['participant_status_id']);
525 $eventID = $defaults[$this->_id]['event_id'];
526
527 $this->_eventTypeId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventID, 'event_type_id', 'id');
528
529 $this->_discountId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'discount_id');
530 if ($this->_discountId) {
531 $this->set('discountId', $this->_discountId);
532 }
533 }
534
535 list($defaults[$this->_id]['register_date'], $defaults[$this->_id]['register_date_time'])
536 = CRM_Utils_Date::setDateDefaults(CRM_Utils_Array::value('register_date', $defaults[$this->_id]), 'activityDateTime');
537
538 //assign event and role id, this is needed for Custom data building
539 $sep = CRM_Core_DAO::VALUE_SEPARATOR;
540 if (!empty($defaults[$this->_id]['participant_role_id'])) {
541 $roleIDs = explode($sep, $defaults[$this->_id]['participant_role_id']);
542 }
543 if (isset($_POST['event_id'])) {
544 $eventID = $_POST['event_id'];
545 }
546
547 if ($this->_eID) {
548 $eventID = $this->_eID;
549 //@todo - rationalise the $this->_eID with $POST['event_id'], $this->_eid is set when eid=x is in the url
550 $roleID = CRM_Core_DAO::getFieldValue(
551 'CRM_Event_DAO_Event',
552 $this->_eID,
553 'default_role_id'
554 );
555 if (empty($roleIDs)) {
556 $roleIDs = (array) $defaults[$this->_id]['participant_role_id'] = $roleID;
557 }
558 $defaults[$this->_id]['event_id'] = $eventID;
559 }
560 if (!empty($eventID)) {
561 $this->_eventTypeId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventID, 'event_type_id', 'id');
562 }
563 //these should take precedence so we state them last
564 $urlRoleIDS = CRM_Utils_Request::retrieve('roles', 'String');
565 if ($urlRoleIDS) {
566 $roleIDs = explode(',', $urlRoleIDS);
567 }
568 if (isset($roleIDs)) {
569 $defaults[$this->_id]['role_id'] = implode(',', $roleIDs);
570 }
571
572 if (isset($eventID)) {
573 $this->assign('eventID', $eventID);
574 $this->set('eventId', $eventID);
575 }
576
577 if (isset($this->_eventTypeId)) {
578 $this->assign('eventTypeID', $this->_eventTypeId);
579 }
580
581 $this->assign('event_is_test', CRM_Utils_Array::value('event_is_test', $defaults[$this->_id]));
582 return $defaults[$this->_id];
583 }
584
585 /**
586 * Build the form object.
587 *
588 * @return void
589 */
590 public function buildQuickForm() {
591 $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
592 $partiallyPaidStatusId = array_search('Partially paid', $participantStatuses);
593 $this->assign('partiallyPaidStatusId', $partiallyPaidStatusId);
594
595 if ($this->_showFeeBlock) {
596 return CRM_Event_Form_EventFees::buildQuickForm($this);
597 }
598
599 //need to assign custom data type to the template
600 $this->assign('customDataType', 'Participant');
601
602 $this->applyFilter('__ALL__', 'trim');
603
604 if ($this->_action & CRM_Core_Action::DELETE) {
605 if ($this->_single) {
606 $additionalParticipant = count(CRM_Event_BAO_Event::buildCustomProfile($this->_id,
607 NULL,
608 $this->_contactId,
609 FALSE,
610 TRUE
611 )) - 1;
612 if ($additionalParticipant) {
613 $deleteParticipants = array(
614 1 => ts('Delete this participant record along with associated participant record(s).'),
615 2 => ts('Delete only this participant record.'),
616 );
617 $this->addRadio('delete_participant', NULL, $deleteParticipants, NULL, '<br />');
618 $this->setDefaults(array('delete_participant' => 1));
619 $this->assign('additionalParticipant', $additionalParticipant);
620 }
621 }
622 $this->addButtons(array(
623 array(
624 'type' => 'next',
625 'name' => ts('Delete'),
626 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
627 'isDefault' => TRUE,
628 ),
629 array(
630 'type' => 'cancel',
631 'name' => ts('Cancel'),
632 ),
633 )
634 );
635 return;
636 }
637
638 if ($this->_single && $this->_context == 'standalone') {
639 $this->addEntityRef('contact_id', ts('Contact'), array(
640 'create' => TRUE,
641 'api' => array('extra' => array('email')),
642 ), TRUE);
643 }
644
645 $eventFieldParams = array(
646 'entity' => 'event',
647 'select' => array('minimumInputLength' => 0),
648 'api' => array(
649 'extra' => array('campaign_id', 'default_role_id', 'event_type_id'),
650 ),
651 );
652
653 if ($this->_mode) {
654 // exclude events which are not monetary when credit card registration is used
655 $eventFieldParams['api']['params']['is_monetary'] = 1;
656 $this->add('select', 'payment_processor_id', ts('Payment Processor'), $this->_processors, TRUE);
657 }
658
659 $element = $this->addEntityRef('event_id', ts('Event'), $eventFieldParams, TRUE);
660
661 //frozen the field fix for CRM-4171
662 if ($this->_action & CRM_Core_Action::UPDATE && $this->_id) {
663 if (CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
664 $this->_id, 'contribution_id', 'participant_id'
665 )
666 ) {
667 $element->freeze();
668 }
669 }
670
671 //CRM-7362 --add campaigns.
672 $campaignId = NULL;
673 if ($this->_id) {
674 $campaignId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'campaign_id');
675 }
676 if (!$campaignId) {
677 $eventId = CRM_Utils_Request::retrieve('eid', 'Positive', $this);
678 if ($eventId) {
679 $campaignId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventId, 'campaign_id');
680 }
681 }
682 CRM_Campaign_BAO_Campaign::addCampaign($this, $campaignId);
683
684 $this->addDateTime('register_date', ts('Registration Date'), TRUE, array('formatType' => 'activityDateTime'));
685
686 if ($this->_id) {
687 $this->assign('entityID', $this->_id);
688 }
689
690 $this->addSelect('role_id', array('multiple' => TRUE, 'class' => 'huge'), TRUE);
691
692 // CRM-4395
693 $checkCancelledJs = array('onchange' => "return sendNotification( );");
694 $confirmJS = NULL;
695 if ($this->_onlinePendingContributionId) {
696 $cancelledparticipantStatusId = array_search('Cancelled', CRM_Event_PseudoConstant::participantStatus());
697 $cancelledContributionStatusId = array_search('Cancelled',
698 CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')
699 );
700 $checkCancelledJs = array(
701 'onchange' => "checkCancelled( this.value, {$cancelledparticipantStatusId},{$cancelledContributionStatusId});",
702 );
703
704 $participantStatusId = array_search('Pending from pay later',
705 CRM_Event_PseudoConstant::participantStatus()
706 );
707 $contributionStatusId = array_search('Completed',
708 CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')
709 );
710 $confirmJS = array('onclick' => "return confirmStatus( {$participantStatusId}, {$contributionStatusId} );");
711 }
712
713 // get the participant status names to build special status array which is used to show notification
714 // checkbox below participant status select
715 $participantStatusName = CRM_Event_PseudoConstant::participantStatus();
716 $notificationStatuses = array(
717 'Cancelled',
718 'Pending from waitlist',
719 'Pending from approval',
720 'Expired',
721 );
722
723 // get the required status and then implode only ids
724 $notificationStatusIds = implode(',', array_keys(array_intersect($participantStatusName, $notificationStatuses)));
725 $this->assign('notificationStatusIds', $notificationStatusIds);
726
727 $this->_participantStatuses = $statusOptions = CRM_Event_BAO_Participant::buildOptions('status_id', 'create');
728
729 // Only show refund status when editing
730 if ($this->_action & CRM_Core_Action::ADD) {
731 $pendingRefundStatusId = array_search('Pending refund', $participantStatusName);
732 if ($pendingRefundStatusId) {
733 unset($statusOptions[$pendingRefundStatusId]);
734 }
735 }
736
737 $this->addSelect('status_id', $checkCancelledJs + array(
738 'options' => $statusOptions,
739 'option_url' => 'civicrm/admin/participant_status',
740 ), TRUE);
741
742 $this->addElement('checkbox', 'is_notify', ts('Send Notification'), NULL);
743
744 $this->add('text', 'source', ts('Event Source'));
745 $noteAttributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_Note');
746 $this->add('textarea', 'note', ts('Notes'), $noteAttributes['note']);
747
748 $buttons[] = array(
749 'type' => 'upload',
750 'name' => ts('Save'),
751 'isDefault' => TRUE,
752 'js' => $confirmJS,
753 );
754
755 $path = CRM_Utils_System::currentPath();
756 $excludeForPaths = array(
757 'civicrm/contact/search',
758 'civicrm/group/search',
759 );
760 if (!in_array($path, $excludeForPaths)) {
761 $buttons[] = array(
762 'type' => 'upload',
763 'name' => ts('Save and New'),
764 'subName' => 'new',
765 'js' => $confirmJS,
766 );
767 }
768
769 $buttons[] = array(
770 'type' => 'cancel',
771 'name' => ts('Cancel'),
772 );
773
774 $this->addButtons($buttons);
775 if ($this->_action == CRM_Core_Action::VIEW) {
776 $this->freeze();
777 }
778 }
779
780 /**
781 * Add local and global form rules.
782 *
783 *
784 * @return void
785 */
786 public function addRules() {
787 $this->addFormRule(array('CRM_Event_Form_Participant', 'formRule'), $this);
788 }
789
790 /**
791 * Global validation rules for the form.
792 *
793 * @param array $values
794 * Posted values of the form.
795 * @param $files
796 * @param $self
797 *
798 * @return array
799 * list of errors to be posted back to the form
800 */
801 public static function formRule($values, $files, $self) {
802 // If $values['_qf_Participant_next'] is Delete or
803 // $values['event_id'] is empty, then return
804 // instead of proceeding further.
805
806 if ((CRM_Utils_Array::value('_qf_Participant_next', $values) == 'Delete') ||
807 (!$values['event_id'])
808 ) {
809 return TRUE;
810 }
811
812 $errorMsg = array();
813
814 if (!empty($values['payment_processor_id'])) {
815 // make sure that payment instrument values (e.g. credit card number and cvv) are valid
816 CRM_Core_Payment_Form::validatePaymentInstrument($values['payment_processor_id'], $values, $errorMsg, NULL);
817 }
818
819 if (!empty($values['record_contribution'])) {
820 if (empty($values['financial_type_id'])) {
821 $errorMsg['financial_type_id'] = ts('Please enter the associated Financial Type');
822 }
823 if (empty($values['payment_instrument_id'])) {
824 $errorMsg['payment_instrument_id'] = ts('Payment Method is a required field.');
825 }
826 CRM_Price_BAO_PriceField::priceSetValidation($values['priceSetId'], $values, $errorMsg);
827 }
828
829 // validate contribution status for 'Failed'.
830 if ($self->_onlinePendingContributionId && !empty($values['record_contribution']) &&
831 (CRM_Utils_Array::value('contribution_status_id', $values) ==
832 array_search('Failed', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'))
833 )
834 ) {
835 $errorMsg['contribution_status_id'] = ts('Please select a valid payment status before updating.');
836 }
837
838 // do the amount validations.
839 //skip for update mode since amount is freeze, CRM-6052
840 if ((!$self->_id && empty($values['total_amount']) &&
841 empty($self->_values['line_items'])
842 ) ||
843 ($self->_id && !$self->_paymentId && isset($self->_values['line_items']) && is_array($self->_values['line_items']))
844 ) {
845 if ($priceSetId = CRM_Utils_Array::value('priceSetId', $values)) {
846 CRM_Price_BAO_PriceField::priceSetValidation($priceSetId, $values, $errorMsg, TRUE);
847 }
848 }
849 // For single additions - show validation error if the contact has already been registered
850 // for this event.
851 if ($self->_single && ($self->_action & CRM_Core_Action::ADD)) {
852 if ($self->_context == 'standalone') {
853 $contactId = CRM_Utils_Array::value('contact_id', $values);
854 }
855 else {
856 $contactId = $self->_contactId;
857 }
858
859 $eventId = CRM_Utils_Array::value('event_id', $values);
860 if (!empty($contactId) && !empty($eventId)) {
861 $dupeCheck = new CRM_Event_BAO_Participant();
862 $dupeCheck->contact_id = $contactId;
863 $dupeCheck->event_id = $eventId;
864 $dupeCheck->find(TRUE);
865 if (!empty($dupeCheck->id)) {
866 $errorMsg['event_id'] = ts("This contact has already been assigned to this event.");
867 }
868 }
869 }
870 return CRM_Utils_Array::crmIsEmptyArray($errorMsg) ? TRUE : $errorMsg;
871 }
872
873 /**
874 * Process the form submission.
875 */
876 public function postProcess() {
877 // get the submitted form values.
878 $params = $this->controller->exportValues($this->_name);
879
880 if ($this->_action & CRM_Core_Action::DELETE) {
881 if (CRM_Utils_Array::value('delete_participant', $params) == 2) {
882 $additionalId = (CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id));
883 $participantLinks = (CRM_Event_BAO_Participant::getAdditionalParticipantUrl($additionalId));
884 }
885 if (CRM_Utils_Array::value('delete_participant', $params) == 1) {
886 $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
887 foreach ($additionalIds as $value) {
888 CRM_Event_BAO_Participant::deleteParticipant($value);
889 }
890 }
891 CRM_Event_BAO_Participant::deleteParticipant($this->_id);
892 CRM_Core_Session::setStatus(ts('Selected participant was deleted successfully.'), ts('Record Deleted'), 'success');
893 if (!empty($participantLinks)) {
894 $status = ts('The following participants no longer have an event fee recorded. You can edit their registration and record a replacement contribution by clicking the links below:') . '<br/>' . $participantLinks;
895 CRM_Core_Session::setStatus($status, ts('Group Payment Deleted'));
896 }
897 return;
898 }
899 // When adding a single contact, the formRule prevents you from adding duplicates
900 // (See above in formRule()). When adding more than one contact, the duplicates are
901 // removed automatically and the user receives one notification.
902 if ($this->_action & CRM_Core_Action::ADD) {
903 $event_id = $this->_eventId;
904 if (empty($event_id) && !empty($params['event_id'])) {
905 $event_id = $params['event_id'];
906 }
907 if (!$this->_single && !empty($event_id)) {
908 $duplicateContacts = 0;
909 while (list($k, $dupeCheckContactId) = each($this->_contactIds)) {
910 // Eliminate contacts that have already been assigned to this event.
911 $dupeCheck = new CRM_Event_BAO_Participant();
912 $dupeCheck->contact_id = $dupeCheckContactId;
913 $dupeCheck->event_id = $event_id;
914 $dupeCheck->find(TRUE);
915 if (!empty($dupeCheck->id)) {
916 $duplicateContacts++;
917 unset($this->_contactIds[$k]);
918 }
919 }
920 if ($duplicateContacts > 0) {
921 $msg = ts(
922 "%1 contacts have already been assigned to this event. They were not added a second time.",
923 array(1 => $duplicateContacts)
924 );
925 CRM_Core_Session::setStatus($msg);
926 }
927 if (count($this->_contactIds) == 0) {
928 CRM_Core_Session::setStatus(ts("No participants were added."));
929 return;
930 }
931 // We have to re-key $this->_contactIds so each contact has the same
932 // key as their corresponding record in the $participants array that
933 // will be created below.
934 $this->_contactIds = array_values($this->_contactIds);
935 }
936 }
937
938 $participantStatus = CRM_Event_PseudoConstant::participantStatus();
939 // set the contact, when contact is selected
940 if (!empty($params['contact_id'])) {
941 $this->_contactID = $this->_contactId = $params['contact_id'];
942 }
943 if ($this->_priceSetId && $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
944 $this->_quickConfig = $isQuickConfig;
945 }
946
947 if ($this->_id) {
948 $params['id'] = $this->_id;
949 }
950
951 $config = CRM_Core_Config::singleton();
952 if (isset($params['total_amount'])) {
953 $params['total_amount'] = CRM_Utils_Rule::cleanMoney($params['total_amount']);
954 }
955 if ($this->_isPaidEvent) {
956
957 $contributionParams = array();
958 $lineItem = array();
959 $additionalParticipantDetails = array();
960 if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
961 $eventStartDate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_eventId, 'start_date');
962 if (strtotime($eventStartDate) > strtotime(date('Ymt'))) {
963 $contributionParams['revenue_recognition_date'] = date('Ymd', strtotime($eventStartDate));
964 }
965 }
966 if (($this->_id && $this->_action & CRM_Core_Action::UPDATE) && $this->_paymentId) {
967 $participantBAO = new CRM_Event_BAO_Participant();
968 $participantBAO->id = $this->_id;
969 $participantBAO->find(TRUE);
970 $contributionParams['total_amount'] = $participantBAO->fee_amount;
971
972 $params['discount_id'] = NULL;
973 //re-enter the values for UPDATE mode
974 $params['fee_level'] = $params['amount_level'] = $participantBAO->fee_level;
975 $params['fee_amount'] = $participantBAO->fee_amount;
976 if (isset($params['priceSetId'])) {
977 $lineItem[0] = CRM_Price_BAO_LineItem::getLineItems($this->_id);
978 }
979 //also add additional participant's fee level/priceset
980 if (CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
981 $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
982 $hasLineItems = CRM_Utils_Array::value('priceSetId', $params, FALSE);
983 $additionalParticipantDetails = CRM_Event_BAO_Participant::getFeeDetails($additionalIds,
984 $hasLineItems
985 );
986 }
987 }
988 else {
989
990 //check if discount is selected
991 if (!empty($params['discount_id'])) {
992 $discountId = $params['discount_id'];
993 }
994 else {
995 $discountId = $params['discount_id'] = 'null';
996 }
997
998 //lets carry currency, CRM-4453
999 $params['fee_currency'] = $config->defaultCurrency;
1000 CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'],
1001 $params, $lineItem[0]
1002 );
1003 //CRM-11529 for quick config backoffice transactions
1004 //when financial_type_id is passed in form, update the
1005 //lineitems with the financial type selected in form
1006 $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $params);
1007 $isPaymentRecorded = CRM_Utils_Array::value('record_contribution', $params);
1008 if ($isPaymentRecorded && $this->_quickConfig && $submittedFinancialType) {
1009 foreach ($lineItem[0] as &$values) {
1010 $values['financial_type_id'] = $submittedFinancialType;
1011 }
1012 }
1013
1014 $params['fee_level'] = $params['amount_level'];
1015 $contributionParams['total_amount'] = $params['amount'];
1016 if ($this->_quickConfig && !empty($params['total_amount']) &&
1017 $params['status_id'] != array_search('Partially paid', $participantStatus)
1018 ) {
1019 $params['fee_amount'] = $params['total_amount'];
1020 }
1021 else {
1022 //fix for CRM-3086
1023 $params['fee_amount'] = $params['amount'];
1024 }
1025 }
1026
1027 if (isset($params['priceSetId'])) {
1028 if (!empty($lineItem[0])) {
1029 $this->set('lineItem', $lineItem);
1030
1031 $this->_lineItem = $lineItem;
1032 $lineItem = array_merge($lineItem, $additionalParticipantDetails);
1033
1034 $participantCount = array();
1035 foreach ($lineItem as $k) {
1036 foreach ($k as $v) {
1037 if (CRM_Utils_Array::value('participant_count', $v) > 0) {
1038 $participantCount[] = $v['participant_count'];
1039 }
1040 }
1041 }
1042 }
1043 if (isset($participantCount)) {
1044 $this->assign('pricesetFieldsCount', $participantCount);
1045 }
1046 $this->assign('lineItem', empty($lineItem[0]) || $this->_quickConfig ? FALSE : $lineItem);
1047 }
1048 else {
1049 $this->assign('amount_level', $params['amount_level']);
1050 }
1051 }
1052
1053 $this->_params = $params;
1054 parent::beginPostProcess();
1055 $amountOwed = NULL;
1056 if (isset($params['amount'])) {
1057 $amountOwed = $params['amount'];
1058 unset($params['amount']);
1059 }
1060 $params['register_date'] = CRM_Utils_Date::processDate($params['register_date'], $params['register_date_time']);
1061 $params['receive_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $params), CRM_Utils_Array::value('receive_date_time', $params));
1062 $params['contact_id'] = $this->_contactId;
1063
1064 // overwrite actual payment amount if entered
1065 if (!empty($params['total_amount'])) {
1066 $contributionParams['total_amount'] = CRM_Utils_Array::value('total_amount', $params);
1067 }
1068
1069 // Retrieve the name and email of the current user - this will be the FROM for the receipt email
1070 $userName = CRM_Core_Session::singleton()->getLoggedInContactDisplayName();
1071
1072 if ($this->_contactId) {
1073 list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_contactId);
1074 }
1075
1076 //modify params according to parameter used in create
1077 //participant method (addParticipant)
1078 $this->_params['participant_status_id'] = $params['status_id'];
1079 $this->_params['participant_role_id'] = is_array($params['role_id']) ? $params['role_id'] : explode(',', $params['role_id']);
1080 $this->_params['participant_register_date'] = $params['register_date'];
1081 $roleIdWithSeparator = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['participant_role_id']);
1082
1083 if ($this->_mode) {
1084 if (!$this->_isPaidEvent) {
1085 CRM_Core_Error::fatal(ts('Selected Event is not Paid Event '));
1086 }
1087
1088 $eventTitle
1089 = CRM_Core_DAO::getFieldValue(
1090 'CRM_Event_DAO_Event',
1091 $params['event_id'],
1092 'title'
1093 );
1094
1095 // set source if not set
1096 if (empty($params['source'])) {
1097 $this->_params['participant_source'] = ts('Offline Registration for Event: %2 by: %1', array(
1098 1 => $userName,
1099 2 => $eventTitle,
1100 ));
1101 }
1102 else {
1103 $this->_params['participant_source'] = $params['source'];
1104 }
1105 $this->_params['description'] = $this->_params['participant_source'];
1106
1107 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'],
1108 $this->_mode
1109 );
1110 $now = date('YmdHis');
1111 $fields = array();
1112
1113 // set email for primary location.
1114 $fields['email-Primary'] = 1;
1115 $params['email-Primary'] = $params["email-{$this->_bltID}"] = $this->_contributorEmail;
1116
1117 $params['register_date'] = $now;
1118
1119 // now set the values for the billing location.
1120 foreach ($this->_fields as $name => $dontCare) {
1121 $fields[$name] = 1;
1122 }
1123
1124 // also add location name to the array
1125 $params["address_name-{$this->_bltID}"]
1126 = CRM_Utils_Array::value('billing_first_name', $params) . ' ' .
1127 CRM_Utils_Array::value('billing_middle_name', $params) . ' ' .
1128 CRM_Utils_Array::value('billing_last_name', $params);
1129
1130 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
1131 $fields["address_name-{$this->_bltID}"] = 1;
1132 $fields["email-{$this->_bltID}"] = 1;
1133 $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'contact_type');
1134
1135 $nameFields = array('first_name', 'middle_name', 'last_name');
1136
1137 foreach ($nameFields as $name) {
1138 $fields[$name] = 1;
1139 if (array_key_exists("billing_$name", $params)) {
1140 $params[$name] = $params["billing_{$name}"];
1141 $params['preserveDBName'] = TRUE;
1142 }
1143 }
1144 $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactId, NULL, NULL, $ctype);
1145 }
1146
1147 if (!empty($this->_params['participant_role_id'])) {
1148 $customFieldsRole = array();
1149 foreach ($this->_params['participant_role_id'] as $roleKey) {
1150 $customFieldsRole = CRM_Utils_Array::crmArrayMerge(CRM_Core_BAO_CustomField::getFields('Participant',
1151 FALSE, FALSE, $roleKey, $this->_roleCustomDataTypeID), $customFieldsRole);
1152 }
1153 $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant',
1154 FALSE,
1155 FALSE,
1156 CRM_Utils_Array::value('event_id', $params),
1157 $this->_eventNameCustomDataTypeID
1158 );
1159 $customFieldsEventType = CRM_Core_BAO_CustomField::getFields('Participant',
1160 FALSE,
1161 FALSE,
1162 $this->_eventTypeId,
1163 $this->_eventTypeCustomDataTypeID
1164 );
1165 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole,
1166 CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, NULL, TRUE)
1167 );
1168 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
1169 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEventType, $customFields);
1170 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
1171 $this->_id,
1172 'Participant'
1173 );
1174 }
1175
1176 //do cleanup line items if participant edit the Event Fee.
1177 if (($this->_lineItem || !isset($params['proceSetId'])) && !$this->_paymentId && $this->_id) {
1178 CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_participant');
1179 }
1180
1181 if ($this->_mode) {
1182 // add all the additional payment params we need
1183 $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
1184 $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
1185
1186 $this->_params['amount'] = $params['fee_amount'];
1187 $this->_params['amount_level'] = $params['amount_level'];
1188 $this->_params['currencyID'] = $config->defaultCurrency;
1189 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
1190
1191 // at this point we've created a contact and stored its address etc
1192 // all the payment processors expect the name and address to be in the
1193 // so we copy stuff over to first_name etc.
1194 $paymentParams = $this->_params;
1195 if (!empty($this->_params['send_receipt'])) {
1196 $paymentParams['email'] = $this->_contributorEmail;
1197 }
1198
1199 // The only reason for merging in the 'contact_id' rather than ensuring it is set
1200 // is that this patch is being done around the time of the stable release
1201 // so more conservative approach is called for.
1202 // In fact the use of $params and $this->_params & $this->_contactId vs $contactID
1203 // needs rationalising.
1204 $mapParams = array_merge(array('contact_id' => $contactID), $this->_params);
1205 CRM_Core_Payment_Form::mapParams($this->_bltID, $mapParams, $paymentParams, TRUE);
1206
1207 $payment = $this->_paymentProcessor['object'];
1208
1209 // CRM-15622: fix for incorrect contribution.fee_amount
1210 $paymentParams['fee_amount'] = NULL;
1211 $result = $payment->doPayment($paymentParams);
1212
1213 if (is_a($result, 'CRM_Core_Error')) {
1214 CRM_Core_Error::displaySessionError($result);
1215 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/participant',
1216 "reset=1&action=add&cid={$this->_contactId}&context=participant&mode={$this->_mode}"
1217 ));
1218 }
1219
1220 if ($result) {
1221 $this->_params = array_merge($this->_params, $result);
1222 }
1223
1224 $this->_params['receive_date'] = $now;
1225
1226 if (!empty($this->_params['send_receipt'])) {
1227 $this->_params['receipt_date'] = $now;
1228 }
1229 else {
1230 $this->_params['receipt_date'] = NULL;
1231 }
1232
1233 $this->set('params', $this->_params);
1234 $this->assign('trxn_id', $result['trxn_id']);
1235 $this->assign('receive_date',
1236 CRM_Utils_Date::processDate($this->_params['receive_date'])
1237 );
1238
1239 //add contribution record
1240 $this->_params['financial_type_id']
1241 = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'financial_type_id');
1242 $this->_params['mode'] = $this->_mode;
1243
1244 //add contribution record
1245 $contributions[] = $contribution = CRM_Event_Form_Registration_Confirm::processContribution($this, $this->_params, $result, $contactID, FALSE);
1246
1247 // add participant record
1248 $participants = array();
1249 if (!empty($this->_params['role_id']) && is_array($this->_params['role_id'])) {
1250 $this->_params['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR,
1251 $this->_params['role_id']
1252 );
1253 }
1254
1255 //CRM-15372 patch to fix fee amount replacing amount
1256 $this->_params['fee_amount'] = $this->_params['amount'];
1257
1258 $participants[] = CRM_Event_Form_Registration::addParticipant($this, $contactID);
1259
1260 //add custom data for participant
1261 CRM_Core_BAO_CustomValueTable::postProcess($this->_params,
1262 'civicrm_participant',
1263 $participants[0]->id,
1264 'Participant'
1265 );
1266 //add participant payment
1267 $paymentParticipant = array(
1268 'participant_id' => $participants[0]->id,
1269 'contribution_id' => $contribution->id,
1270 );
1271 $ids = array();
1272
1273 CRM_Event_BAO_ParticipantPayment::create($paymentParticipant, $ids);
1274 $this->_contactIds[] = $this->_contactId;
1275 }
1276 else {
1277 $participants = array();
1278 if ($this->_single) {
1279 if ($params['role_id']) {
1280 $params['role_id'] = $roleIdWithSeparator;
1281 }
1282 else {
1283 $params['role_id'] = 'NULL';
1284 }
1285 $participants[] = CRM_Event_BAO_Participant::create($params);
1286 }
1287 else {
1288 foreach ($this->_contactIds as $contactID) {
1289 $commonParams = $params;
1290 $commonParams['contact_id'] = $contactID;
1291 if ($commonParams['role_id']) {
1292 $commonParams['role_id'] = $commonParams['role_id'] = str_replace(',', CRM_Core_DAO::VALUE_SEPARATOR, $params['role_id']);
1293 }
1294 else {
1295 $commonParams['role_id'] = 'NULL';
1296 }
1297 $participants[] = CRM_Event_BAO_Participant::create($commonParams);
1298 }
1299 }
1300
1301 if (isset($params['event_id'])) {
1302 $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event',
1303 $params['event_id'],
1304 'title'
1305 );
1306 }
1307
1308 if ($this->_single) {
1309 $this->_contactIds[] = $this->_contactId;
1310 }
1311
1312 $contributions = array();
1313 if (!empty($params['record_contribution'])) {
1314 if (!empty($params['id'])) {
1315 if ($this->_onlinePendingContributionId) {
1316 $ids['contribution'] = $this->_onlinePendingContributionId;
1317 }
1318 else {
1319 $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
1320 $params['id'],
1321 'contribution_id',
1322 'participant_id'
1323 );
1324 }
1325 }
1326 unset($params['note']);
1327
1328 //build contribution params
1329 if (!$this->_onlinePendingContributionId) {
1330 if (empty($params['source'])) {
1331 $contributionParams['source'] = ts('%1 : Offline registration (by %2)', array(
1332 1 => $eventTitle,
1333 2 => $userName,
1334 ));
1335 }
1336 else {
1337 $contributionParams['source'] = $params['source'];
1338 }
1339 }
1340
1341 $contributionParams['currency'] = $config->defaultCurrency;
1342 $contributionParams['non_deductible_amount'] = 'null';
1343 $contributionParams['receipt_date'] = !empty($params['send_receipt']) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
1344 $contributionParams['contact_id'] = $this->_contactID;
1345 // @todo change receive_date to datepicker field. Strip out all wrangling.
1346 $contributionParams['receive_date'] = $params['receive_date'];
1347
1348 $recordContribution = array(
1349 'financial_type_id',
1350 'payment_instrument_id',
1351 'trxn_id',
1352 'contribution_status_id',
1353 'check_number',
1354 'campaign_id',
1355 'pan_truncation',
1356 'card_type_id',
1357 );
1358
1359 foreach ($recordContribution as $f) {
1360 $contributionParams[$f] = CRM_Utils_Array::value($f, $this->_params);
1361 if ($f == 'trxn_id') {
1362 $this->assign('trxn_id', $contributionParams[$f]);
1363 }
1364 }
1365
1366 //insert financial type name in receipt.
1367 $this->assign('financialTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType',
1368 $contributionParams['financial_type_id']));
1369 // legacy support
1370 $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionParams['financial_type_id']));
1371 $contributionParams['skipLineItem'] = 1;
1372 if ($this->_id) {
1373 $contributionParams['contribution_mode'] = 'participant';
1374 $contributionParams['participant_id'] = $this->_id;
1375 }
1376 // Set is_pay_later flag for back-office offline Pending status contributions
1377 if ($contributionParams['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Pending')) {
1378 $contributionParams['is_pay_later'] = 1;
1379 }
1380 elseif ($contributionParams['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Completed')) {
1381 $contributionParams['is_pay_later'] = 0;
1382 }
1383
1384 if ($params['status_id'] == array_search('Partially paid', $participantStatus)) {
1385 if (!$amountOwed && $this->_action & CRM_Core_Action::UPDATE) {
1386 $amountOwed = $params['fee_amount'];
1387 }
1388
1389 // if multiple participants are link, consider contribution total amount as the amount Owed
1390 if ($this->_id && CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
1391 $amountOwed = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
1392 $ids['contribution'],
1393 'total_amount'
1394 );
1395 }
1396
1397 // CRM-13964 partial_payment_total
1398 if ($amountOwed > $params['total_amount']) {
1399 // the owed amount
1400 $contributionParams['partial_payment_total'] = $amountOwed;
1401 // the actual amount paid
1402 $contributionParams['partial_amount_to_pay'] = $params['total_amount'];
1403 }
1404 }
1405
1406 if (CRM_Utils_Array::value('tax_amount', $this->_params)) {
1407 $contributionParams['tax_amount'] = $this->_params['tax_amount'];
1408 }
1409
1410 if ($this->_single) {
1411 if (empty($ids)) {
1412 $ids = array();
1413 }
1414 $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
1415 }
1416 else {
1417 $ids = array();
1418 foreach ($this->_contactIds as $contactID) {
1419 $contributionParams['contact_id'] = $contactID;
1420 $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
1421 }
1422 }
1423
1424 //insert payment record for this participation
1425 if (empty($ids['contribution'])) {
1426 foreach ($this->_contactIds as $num => $contactID) {
1427 $ppDAO = new CRM_Event_DAO_ParticipantPayment();
1428 $ppDAO->participant_id = $participants[$num]->id;
1429 $ppDAO->contribution_id = $contributions[$num]->id;
1430 $ppDAO->save();
1431 }
1432 }
1433 // next create the transaction record
1434 $transaction = new CRM_Core_Transaction();
1435
1436 // CRM-11124
1437 if ($this->_params['discount_id']) {
1438 CRM_Event_BAO_Participant::createDiscountTrxn(
1439 $this->_eventId,
1440 $contributionParams,
1441 NULL,
1442 CRM_Price_BAO_PriceSet::parseFirstPriceSetValueIDFromParams($this->_params)
1443 );
1444 }
1445 $transaction->commit();
1446 }
1447 }
1448
1449 // also store lineitem stuff here
1450 if ((($this->_lineItem & $this->_action & CRM_Core_Action::ADD) ||
1451 ($this->_lineItem && CRM_Core_Action::UPDATE && !$this->_paymentId))
1452 ) {
1453 foreach ($this->_contactIds as $num => $contactID) {
1454 foreach ($this->_lineItem as $key => $value) {
1455 if (is_array($value) && $value != 'skip') {
1456 foreach ($value as $lineKey => $line) {
1457 //10117 update the line items for participants if contribution amount is recorded
1458 if ($this->_quickConfig && !empty($params['total_amount']) &&
1459 ($params['status_id'] != array_search('Partially paid', $participantStatus))
1460 ) {
1461 $line['unit_price'] = $line['line_total'] = $params['total_amount'];
1462 if (!empty($params['tax_amount'])) {
1463 $line['unit_price'] = $line['unit_price'] - $params['tax_amount'];
1464 $line['line_total'] = $line['line_total'] - $params['tax_amount'];
1465 }
1466 }
1467 $lineItem[$this->_priceSetId][$lineKey] = $line;
1468 }
1469 CRM_Price_BAO_LineItem::processPriceSet($participants[$num]->id, $lineItem, CRM_Utils_Array::value($num, $contributions, NULL), 'civicrm_participant');
1470 CRM_Contribute_BAO_Contribution::addPayments($contributions);
1471 }
1472 }
1473 }
1474 }
1475
1476 $updateStatusMsg = NULL;
1477 //send mail when participant status changed, CRM-4326
1478 if ($this->_id && $this->_statusId &&
1479 $this->_statusId != CRM_Utils_Array::value('status_id', $params) && !empty($params['is_notify'])
1480 ) {
1481
1482 $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_id,
1483 $params['status_id'],
1484 $this->_statusId
1485 );
1486 }
1487
1488 $sent = array();
1489 $notSent = array();
1490 if (!empty($params['send_receipt'])) {
1491 if (array_key_exists($params['from_email_address'], $this->_fromEmails['from_email_id'])) {
1492 $receiptFrom = $params['from_email_address'];
1493 }
1494
1495 $this->assign('module', 'Event Registration');
1496 //use of the message template below requires variables in different format
1497 $event = $events = array();
1498 $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
1499
1500 //get all event details.
1501 CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
1502 $event = $events[$params['event_id']];
1503 unset($event['start_date']);
1504 unset($event['end_date']);
1505
1506 $role = CRM_Event_PseudoConstant::participantRole();
1507 $participantRoles = CRM_Utils_Array::value('role_id', $params);
1508 if (is_array($participantRoles)) {
1509 $selectedRoles = array();
1510 foreach ($participantRoles as $roleId) {
1511 $selectedRoles[] = $role[$roleId];
1512 }
1513 $event['participant_role'] = implode(', ', $selectedRoles);
1514 }
1515 else {
1516 $event['participant_role'] = CRM_Utils_Array::value($participantRoles, $role);
1517 }
1518 $event['is_monetary'] = $this->_isPaidEvent;
1519
1520 if ($params['receipt_text']) {
1521 $event['confirm_email_text'] = $params['receipt_text'];
1522 }
1523
1524 $this->assign('isAmountzero', 1);
1525 $this->assign('event', $event);
1526
1527 $this->assign('isShowLocation', $event['is_show_location']);
1528 if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
1529 $locationParams = array(
1530 'entity_id' => $params['event_id'],
1531 'entity_table' => 'civicrm_event',
1532 );
1533 $location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
1534 $this->assign('location', $location);
1535 }
1536
1537 $status = CRM_Event_PseudoConstant::participantStatus();
1538 if ($this->_isPaidEvent) {
1539 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
1540 if (!$this->_mode) {
1541 if (isset($params['payment_instrument_id'])) {
1542 $this->assign('paidBy',
1543 CRM_Utils_Array::value($params['payment_instrument_id'],
1544 $paymentInstrument
1545 )
1546 );
1547 }
1548 }
1549
1550 $this->assign('totalAmount', $contributionParams['total_amount']);
1551 if (isset($contributionParams['partial_payment_total'])) {
1552 // balance amount
1553 $balanceAmount = $contributionParams['partial_payment_total'] - $contributionParams['partial_amount_to_pay'];
1554 $this->assign('balanceAmount', $balanceAmount);
1555 }
1556 $this->assign('isPrimary', 1);
1557 $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
1558 }
1559 if ($this->_mode) {
1560 $this->assignBillingName($params);
1561 $this->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters(
1562 $this->_params,
1563 $this->_bltID
1564 ));
1565
1566 $date = CRM_Utils_Date::format($params['credit_card_exp_date']);
1567 $date = CRM_Utils_Date::mysqlToIso($date);
1568 $this->assign('credit_card_exp_date', $date);
1569 $this->assign('credit_card_number',
1570 CRM_Utils_System::mungeCreditCard($params['credit_card_number'])
1571 );
1572 $this->assign('credit_card_type', $params['credit_card_type']);
1573 // The concept of contributeMode is deprecated.
1574 $this->assign('contributeMode', 'direct');
1575 $this->assign('isAmountzero', 0);
1576 $this->assign('is_pay_later', 0);
1577 $this->assign('isPrimary', 1);
1578 }
1579
1580 $this->assign('register_date', $params['register_date']);
1581 if ($params['receive_date']) {
1582 $this->assign('receive_date', $params['receive_date']);
1583 }
1584
1585 $participant = array(array('participant_id', '=', $participants[0]->id, 0, 0));
1586 // check whether its a test drive ref CRM-3075
1587 if (!empty($this->_defaultValues['is_test'])) {
1588 $participant[] = array('participant_test', '=', 1, 0, 0);
1589 }
1590
1591 $template = CRM_Core_Smarty::singleton();
1592 $customGroup = array();
1593 //format submitted data
1594 foreach ($params['custom'] as $fieldID => $values) {
1595 foreach ($values as $fieldValue) {
1596 $isPublic = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $fieldValue['custom_group_id'], 'is_public');
1597 if ($isPublic) {
1598 $customFields[$fieldID]['id'] = $fieldID;
1599 $formattedValue = CRM_Core_BAO_CustomField::displayValue($fieldValue['value'], $fieldID, $participants[0]->id);
1600 $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
1601 }
1602 }
1603 }
1604
1605 foreach ($this->_contactIds as $num => $contactID) {
1606 // Retrieve the name and email of the contact - this will be the TO for receipt email
1607 list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
1608
1609 $this->_contributorDisplayName = ($this->_contributorDisplayName == ' ') ? $this->_contributorEmail : $this->_contributorDisplayName;
1610
1611 $waitStatus = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
1612 if ($waitingStatus = CRM_Utils_Array::value($params['status_id'], $waitStatus)) {
1613 $this->assign('isOnWaitlist', TRUE);
1614 }
1615
1616 $this->assign('customGroup', $customGroup);
1617 $this->assign('contactID', $contactID);
1618 $this->assign('participantID', $participants[$num]->id);
1619
1620 $this->_id = $participants[$num]->id;
1621
1622 if ($this->_isPaidEvent) {
1623 // fix amount for each of participants ( for bulk mode )
1624 $eventAmount = array();
1625 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
1626 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
1627 $totalTaxAmount = 0;
1628
1629 //add dataArray in the receipts in ADD and UPDATE condition
1630 $dataArray = array();
1631 if ($this->_action & CRM_Core_Action::ADD) {
1632 $line = $lineItem[0];
1633 }
1634 elseif ($this->_action & CRM_Core_Action::UPDATE) {
1635 $line = $this->_values['line_items'];
1636 }
1637 if ($invoicing) {
1638 foreach ($line as $key => $value) {
1639 if (isset($value['tax_amount'])) {
1640 $totalTaxAmount += $value['tax_amount'];
1641 if (isset($dataArray[(string) $value['tax_rate']])) {
1642 $dataArray[(string) $value['tax_rate']] = $dataArray[(string) $value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
1643 }
1644 else {
1645 $dataArray[(string) $value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
1646 }
1647 }
1648 }
1649 $this->assign('totalTaxAmount', $totalTaxAmount);
1650 $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
1651 $this->assign('dataArray', $dataArray);
1652 }
1653 if (!empty($additionalParticipantDetails)) {
1654 $params['amount_level'] = preg_replace('/\ 1/', '', $params['amount_level']) . ' - ' . $this->_contributorDisplayName;
1655 }
1656
1657 $eventAmount[$num] = array(
1658 'label' => preg_replace('/\ 1/', '', $params['amount_level']),
1659 'amount' => $params['fee_amount'],
1660 );
1661 //as we are using same template for online & offline registration.
1662 //So we have to build amount as array.
1663 $eventAmount = array_merge($eventAmount, $additionalParticipantDetails);
1664 $this->assign('amount', $eventAmount);
1665 }
1666
1667 $sendTemplateParams = array(
1668 'groupName' => 'msg_tpl_workflow_event',
1669 'valueName' => 'event_offline_receipt',
1670 'contactId' => $contactID,
1671 'isTest' => !empty($this->_defaultValues['is_test']),
1672 'PDFFilename' => ts('confirmation') . '.pdf',
1673 );
1674
1675 // try to send emails only if email id is present
1676 // and the do-not-email option is not checked for that contact
1677 if ($this->_contributorEmail and !$this->_toDoNotEmail) {
1678 $sendTemplateParams['from'] = $receiptFrom;
1679 $sendTemplateParams['toName'] = $this->_contributorDisplayName;
1680 $sendTemplateParams['toEmail'] = $this->_contributorEmail;
1681 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc', $this->_fromEmails);
1682 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc', $this->_fromEmails);
1683 }
1684
1685 //send email with pdf invoice
1686 $template = CRM_Core_Smarty::singleton();
1687 $taxAmt = $template->get_template_vars('dataArray');
1688 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
1689 $this->_id, 'contribution_id', 'participant_id'
1690 );
1691 $prefixValue = Civi::settings()->get('contribution_invoice_settings');
1692 $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
1693 if (count($taxAmt) > 0 && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
1694 $sendTemplateParams['isEmailPdf'] = TRUE;
1695 $sendTemplateParams['contributionId'] = $contributionId;
1696 }
1697 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
1698 if ($mailSent) {
1699 $sent[] = $contactID;
1700 foreach ($participants as $ids => $values) {
1701 if ($values->contact_id == $contactID) {
1702 $values->details = CRM_Utils_Array::value('receipt_text', $params);
1703 CRM_Activity_BAO_Activity::addActivity($values, 'Email');
1704 break;
1705 }
1706 }
1707 }
1708 else {
1709 $notSent[] = $contactID;
1710 }
1711 }
1712 }
1713
1714 // set the participant id if it is not set
1715 if (!$this->_id) {
1716 $this->_id = $participants[0]->id;
1717 }
1718
1719 if (($this->_action & CRM_Core_Action::UPDATE)) {
1720 $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contributorDisplayName));
1721 if (!empty($params['send_receipt']) && count($sent)) {
1722 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', array(1 => $this->_contributorEmail));
1723 }
1724
1725 if ($updateStatusMsg) {
1726 $statusMsg = "{$statusMsg} {$updateStatusMsg}";
1727 }
1728 }
1729 elseif ($this->_action & CRM_Core_Action::ADD) {
1730 if ($this->_single) {
1731 $statusMsg = ts('Event registration for %1 has been added.', array(1 => $this->_contributorDisplayName));
1732 if (!empty($params['send_receipt']) && count($sent)) {
1733 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $this->_contributorEmail));
1734 }
1735 }
1736 else {
1737 $statusMsg = ts('Total Participant(s) added to event: %1.', array(1 => count($this->_contactIds)));
1738 if (count($notSent) > 0) {
1739 $statusMsg .= ' ' . ts('Email has NOT been sent to %1 contact(s) - communication preferences specify DO NOT EMAIL OR valid Email is NOT present. ', array(1 => count($notSent)));
1740 }
1741 elseif (isset($params['send_receipt'])) {
1742 $statusMsg .= ' ' . ts('A confirmation email has been sent to ALL participants');
1743 }
1744 }
1745 }
1746 CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
1747 $session = CRM_Core_Session::singleton();
1748 $buttonName = $this->controller->getButtonName();
1749 if ($this->_context == 'standalone') {
1750 if ($buttonName == $this->getButtonName('upload', 'new')) {
1751 $urlParams = 'reset=1&action=add&context=standalone';
1752 if ($this->_mode) {
1753 $urlParams .= '&mode=' . $this->_mode;
1754 }
1755 if ($this->_eID) {
1756 $urlParams .= '&eid=' . $this->_eID;
1757 }
1758 $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', $urlParams));
1759 }
1760 else {
1761 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
1762 "reset=1&cid={$this->_contactId}&selectedChild=participant"
1763 ));
1764 }
1765 }
1766 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1767 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant',
1768 "reset=1&action=add&context={$this->_context}&cid={$this->_contactId}"
1769 ));
1770 }
1771 }
1772
1773 }