Merge pull request #12648 from civicrm/5.5
[civicrm-core.git] / CRM / Event / Form / Participant.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
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 processing.
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 * Default form context used as part of addField()
207 */
208 public function getDefaultContext() {
209 return 'create';
210 }
211
212 /**
213 * Set variables up before form is built.
214 *
215 * @return void
216 */
217 public function preProcess() {
218 parent::preProcess();
219 $this->_showFeeBlock = CRM_Utils_Array::value('eventId', $_GET);
220 $this->assign('showFeeBlock', FALSE);
221 $this->assign('feeBlockPaid', FALSE);
222
223 // @todo eliminate this duplication.
224 $this->_contactId = $this->_contactID;
225 $this->_eID = CRM_Utils_Request::retrieve('eid', 'Positive', $this);
226 $this->_context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this);
227 $this->assign('context', $this->_context);
228
229 if ($this->_contactID) {
230 $this->setPageTitle(ts('Event Registration for %1', array(1 => $this->userDisplayName)));
231 }
232 else {
233 $this->setPageTitle(ts('Event Registration'));
234 }
235
236 // check the current path, if search based, then dont get participantID
237 // CRM-5792
238 $path = CRM_Utils_System::currentPath();
239 if (
240 strpos($path, 'civicrm/contact/search') === 0 ||
241 strpos($path, 'civicrm/group/search') === 0
242 ) {
243 $this->_id = NULL;
244 }
245 else {
246 $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
247 }
248
249 if ($this->_id) {
250 $this->assign('participantId', $this->_id);
251
252 $this->_paymentId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
253 $this->_id, 'id', 'participant_id'
254 );
255
256 $this->assign('hasPayment', $this->_paymentId);
257 $this->assign('componentId', $this->_id);
258 $this->assign('component', 'event');
259
260 // CRM-12615 - Get payment information from the primary registration
261 if ((!$this->_paymentId) && ($this->_action == CRM_Core_Action::UPDATE)) {
262 $registered_by_id = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
263 $this->_id, 'registered_by_id', 'id'
264 );
265 if ($registered_by_id) {
266 $this->_paymentId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
267 $registered_by_id, 'id', 'participant_id'
268 );
269 $this->assign('registeredByParticipantId', $registered_by_id);
270 }
271 }
272 }
273 $this->setCustomDataTypes();
274
275 if ($this->_mode) {
276 $this->assign('participantMode', $this->_mode);
277 }
278
279 if ($this->_showFeeBlock) {
280 $this->assign('showFeeBlock', TRUE);
281 $isMonetary = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_showFeeBlock, 'is_monetary');
282 if ($isMonetary) {
283 $this->assign('feeBlockPaid', TRUE);
284 }
285 return CRM_Event_Form_EventFees::preProcess($this);
286 }
287
288 //check the mode when this form is called either single or as
289 //search task action
290 if ($this->_id || $this->_contactId || $this->_context == 'standalone') {
291 $this->_single = TRUE;
292 $this->assign('urlPath', 'civicrm/contact/view/participant');
293 if (!$this->_id && !$this->_contactId) {
294 $breadCrumbs = array(
295 array(
296 'title' => ts('CiviEvent Dashboard'),
297 'url' => CRM_Utils_System::url('civicrm/event', 'reset=1'),
298 ),
299 );
300
301 CRM_Utils_System::appendBreadCrumb($breadCrumbs);
302 }
303 }
304 else {
305 //set the appropriate action
306 $context = $this->get('context');
307 $urlString = 'civicrm/contact/search';
308 $this->_action = CRM_Core_Action::BASIC;
309 switch ($context) {
310 case 'advanced':
311 $urlString = 'civicrm/contact/search/advanced';
312 $this->_action = CRM_Core_Action::ADVANCED;
313 break;
314
315 case 'builder':
316 $urlString = 'civicrm/contact/search/builder';
317 $this->_action = CRM_Core_Action::PROFILE;
318 break;
319
320 case 'basic':
321 $urlString = 'civicrm/contact/search/basic';
322 $this->_action = CRM_Core_Action::BASIC;
323 break;
324
325 case 'custom':
326 $urlString = 'civicrm/contact/search/custom';
327 $this->_action = CRM_Core_Action::COPY;
328 break;
329 }
330 CRM_Contact_Form_Task::preProcessCommon($this);
331
332 $this->_single = FALSE;
333 $this->_contactId = NULL;
334
335 //set ajax path, this used for custom data building
336 $this->assign('urlPath', $urlString);
337 $this->assign('urlPathVar', "_qf_Participant_display=true&qfKey={$this->controller->_key}");
338 }
339
340 $this->assign('single', $this->_single);
341
342 if (!$this->_id) {
343 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add');
344 }
345 $this->assign('action', $this->_action);
346
347 // check for edit permission
348 if (!CRM_Core_Permission::checkActionPermission('CiviEvent', $this->_action)) {
349 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
350 }
351
352 if ($this->_action & CRM_Core_Action::DELETE) {
353 // check delete permission for contribution
354 if ($this->_id && $this->_paymentId && !CRM_Core_Permission::checkActionPermission('CiviContribute', $this->_action)) {
355 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."));
356 }
357 return;
358 }
359
360 if ($this->_id) {
361 // assign participant id to the template
362 $this->assign('participantId', $this->_id);
363 $this->_roleId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'role_id');
364 }
365
366 // when fee amount is included in form
367 if (!empty($_POST['hidden_feeblock']) || !empty($_POST['send_receipt'])) {
368 CRM_Event_Form_EventFees::preProcess($this);
369 CRM_Event_Form_EventFees::buildQuickForm($this);
370 CRM_Event_Form_EventFees::setDefaultValues($this);
371 }
372
373 // when custom data is included in this page
374 if (!empty($_POST['hidden_custom'])) {
375 $eventId = (int) CRM_Utils_Array::value('event_id', $_POST);
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, $eventId, 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) {
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 }
657 $this->addPaymentProcessorSelect(TRUE, FALSE, FALSE);
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->addField('source', array('entity' => 'Participant', 'name' => '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 if (!empty($values['priceSetId'])) {
827 CRM_Price_BAO_PriceField::priceSetValidation($values['priceSetId'], $values, $errorMsg);
828 }
829 }
830
831 // validate contribution status for 'Failed'.
832 if ($self->_onlinePendingContributionId && !empty($values['record_contribution']) &&
833 (CRM_Utils_Array::value('contribution_status_id', $values) ==
834 array_search('Failed', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'))
835 )
836 ) {
837 $errorMsg['contribution_status_id'] = ts('Please select a valid payment status before updating.');
838 }
839
840 // do the amount validations.
841 //skip for update mode since amount is freeze, CRM-6052
842 if ((!$self->_id && empty($values['total_amount']) &&
843 empty($self->_values['line_items'])
844 ) ||
845 ($self->_id && !$self->_paymentId && isset($self->_values['line_items']) && is_array($self->_values['line_items']))
846 ) {
847 if ($priceSetId = CRM_Utils_Array::value('priceSetId', $values)) {
848 CRM_Price_BAO_PriceField::priceSetValidation($priceSetId, $values, $errorMsg, TRUE);
849 }
850 }
851 // For single additions - show validation error if the contact has already been registered
852 // for this event.
853 if ($self->_single && ($self->_action & CRM_Core_Action::ADD)) {
854 if ($self->_context == 'standalone') {
855 $contactId = CRM_Utils_Array::value('contact_id', $values);
856 }
857 else {
858 $contactId = $self->_contactId;
859 }
860
861 $eventId = CRM_Utils_Array::value('event_id', $values);
862 if (!empty($contactId) && !empty($eventId)) {
863 $cancelledStatusID = CRM_Core_PseudoConstant::getKey('CRM_Event_BAO_Participant', 'status_id', 'Cancelled');
864 $dupeCheck = new CRM_Event_BAO_Participant();
865 $dupeCheck->contact_id = $contactId;
866 $dupeCheck->event_id = $eventId;
867 $dupeCheck->whereAdd("status_id != {$cancelledStatusID} ");
868 $dupeCheck->find(TRUE);
869 if (!empty($dupeCheck->id)) {
870 $errorMsg['event_id'] = ts("This contact has already been assigned to this event.");
871 }
872 }
873 }
874 return CRM_Utils_Array::crmIsEmptyArray($errorMsg) ? TRUE : $errorMsg;
875 }
876
877 /**
878 * Process the form submission.
879 */
880 public function postProcess() {
881 // get the submitted form values.
882 $params = $this->controller->exportValues($this->_name);
883
884 if ($this->_action & CRM_Core_Action::DELETE) {
885 if (CRM_Utils_Array::value('delete_participant', $params) == 2) {
886 $additionalId = (CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id));
887 $participantLinks = (CRM_Event_BAO_Participant::getAdditionalParticipantUrl($additionalId));
888 }
889 if (CRM_Utils_Array::value('delete_participant', $params) == 1) {
890 $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
891 foreach ($additionalIds as $value) {
892 CRM_Event_BAO_Participant::deleteParticipant($value);
893 }
894 }
895 CRM_Event_BAO_Participant::deleteParticipant($this->_id);
896 CRM_Core_Session::setStatus(ts('Selected participant was deleted successfully.'), ts('Record Deleted'), 'success');
897 if (!empty($participantLinks)) {
898 $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;
899 CRM_Core_Session::setStatus($status, ts('Group Payment Deleted'));
900 }
901 return;
902 }
903 // When adding a single contact, the formRule prevents you from adding duplicates
904 // (See above in formRule()). When adding more than one contact, the duplicates are
905 // removed automatically and the user receives one notification.
906 if ($this->_action & CRM_Core_Action::ADD) {
907 $event_id = $this->_eventId;
908 if (empty($event_id) && !empty($params['event_id'])) {
909 $event_id = $params['event_id'];
910 }
911 if (!$this->_single && !empty($event_id)) {
912 $duplicateContacts = 0;
913 foreach ($this->_contactIds as $k => $dupeCheckContactId) {
914 // Eliminate contacts that have already been assigned to this event.
915 $dupeCheck = new CRM_Event_BAO_Participant();
916 $dupeCheck->contact_id = $dupeCheckContactId;
917 $dupeCheck->event_id = $event_id;
918 $dupeCheck->find(TRUE);
919 if (!empty($dupeCheck->id)) {
920 $duplicateContacts++;
921 unset($this->_contactIds[$k]);
922 }
923 }
924 if ($duplicateContacts > 0) {
925 $msg = ts(
926 "%1 contacts have already been assigned to this event. They were not added a second time.",
927 array(1 => $duplicateContacts)
928 );
929 CRM_Core_Session::setStatus($msg);
930 }
931 if (count($this->_contactIds) == 0) {
932 CRM_Core_Session::setStatus(ts("No participants were added."));
933 return;
934 }
935 // We have to re-key $this->_contactIds so each contact has the same
936 // key as their corresponding record in the $participants array that
937 // will be created below.
938 $this->_contactIds = array_values($this->_contactIds);
939 }
940 }
941
942 $statusMsg = $this->submit($params);
943 CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
944 $session = CRM_Core_Session::singleton();
945 $buttonName = $this->controller->getButtonName();
946 if ($this->_context == 'standalone') {
947 if ($buttonName == $this->getButtonName('upload', 'new')) {
948 $urlParams = 'reset=1&action=add&context=standalone';
949 if ($this->_mode) {
950 $urlParams .= '&mode=' . $this->_mode;
951 }
952 if ($this->_eID) {
953 $urlParams .= '&eid=' . $this->_eID;
954 }
955 $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', $urlParams));
956 }
957 else {
958 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
959 "reset=1&cid={$this->_contactId}&selectedChild=participant"
960 ));
961 }
962 }
963 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
964 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant',
965 "reset=1&action=add&context={$this->_context}&cid={$this->_contactId}"
966 ));
967 }
968 }
969
970 /**
971 * Submit form.
972 *
973 * @param array $params
974 *
975 * @return array
976 */
977 public function submit($params) {
978 $participantStatus = CRM_Event_PseudoConstant::participantStatus();
979 // set the contact, when contact is selected
980 if (!empty($params['contact_id'])) {
981 $this->_contactID = $this->_contactId = $params['contact_id'];
982 }
983 if ($this->_priceSetId && $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
984 $this->_quickConfig = $isQuickConfig;
985 }
986
987 if ($this->_id) {
988 $params['id'] = $this->_id;
989 }
990
991 $config = CRM_Core_Config::singleton();
992 if (isset($params['total_amount'])) {
993 $params['total_amount'] = CRM_Utils_Rule::cleanMoney($params['total_amount']);
994 }
995 if ($this->_isPaidEvent) {
996
997 $contributionParams = array('skipCleanMoney' => TRUE);
998 $lineItem = array();
999 $additionalParticipantDetails = array();
1000 if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
1001 $eventStartDate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_eventId, 'start_date');
1002 if (strtotime($eventStartDate) > strtotime(date('Ymt'))) {
1003 $contributionParams['revenue_recognition_date'] = date('Ymd', strtotime($eventStartDate));
1004 }
1005 }
1006 if (($this->_id && $this->_action & CRM_Core_Action::UPDATE) && $this->_paymentId) {
1007 $participantBAO = new CRM_Event_BAO_Participant();
1008 $participantBAO->id = $this->_id;
1009 $participantBAO->find(TRUE);
1010 $contributionParams['total_amount'] = $participantBAO->fee_amount;
1011
1012 $params['discount_id'] = NULL;
1013 //re-enter the values for UPDATE mode
1014 $params['fee_level'] = $params['amount_level'] = $participantBAO->fee_level;
1015 $params['fee_amount'] = $participantBAO->fee_amount;
1016 if (isset($params['priceSetId'])) {
1017 $lineItem[0] = CRM_Price_BAO_LineItem::getLineItems($this->_id);
1018 }
1019 //also add additional participant's fee level/priceset
1020 if (CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
1021 $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
1022 $hasLineItems = CRM_Utils_Array::value('priceSetId', $params, FALSE);
1023 $additionalParticipantDetails = CRM_Event_BAO_Participant::getFeeDetails($additionalIds,
1024 $hasLineItems
1025 );
1026 }
1027 }
1028 else {
1029
1030 //check if discount is selected
1031 if (!empty($params['discount_id'])) {
1032 $discountId = $params['discount_id'];
1033 }
1034 else {
1035 $discountId = $params['discount_id'] = 'null';
1036 }
1037
1038 //lets carry currency, CRM-4453
1039 $params['fee_currency'] = $config->defaultCurrency;
1040 if (!isset($lineItem[0])) {
1041 $lineItem[0] = array();
1042 }
1043 CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'],
1044 $params, $lineItem[0]
1045 );
1046 //CRM-11529 for quick config backoffice transactions
1047 //when financial_type_id is passed in form, update the
1048 //lineitems with the financial type selected in form
1049 $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $params);
1050 $isPaymentRecorded = CRM_Utils_Array::value('record_contribution', $params);
1051 if ($isPaymentRecorded && $this->_quickConfig && $submittedFinancialType) {
1052 foreach ($lineItem[0] as &$values) {
1053 $values['financial_type_id'] = $submittedFinancialType;
1054 }
1055 }
1056
1057 $params['fee_level'] = $params['amount_level'];
1058 $contributionParams['total_amount'] = $params['amount'];
1059 if ($this->_quickConfig && !empty($params['total_amount']) &&
1060 $params['status_id'] != array_search('Partially paid', $participantStatus)
1061 ) {
1062 $params['fee_amount'] = $params['total_amount'];
1063 }
1064 else {
1065 //fix for CRM-3086
1066 $params['fee_amount'] = $params['amount'];
1067 }
1068 }
1069
1070 if (isset($params['priceSetId'])) {
1071 if (!empty($lineItem[0])) {
1072 $this->set('lineItem', $lineItem);
1073
1074 $this->_lineItem = $lineItem;
1075 $lineItem = array_merge($lineItem, $additionalParticipantDetails);
1076
1077 $participantCount = array();
1078 foreach ($lineItem as $k) {
1079 foreach ($k as $v) {
1080 if (CRM_Utils_Array::value('participant_count', $v) > 0) {
1081 $participantCount[] = $v['participant_count'];
1082 }
1083 }
1084 }
1085 }
1086 if (isset($participantCount)) {
1087 $this->assign('pricesetFieldsCount', $participantCount);
1088 }
1089 $this->assign('lineItem', empty($lineItem[0]) || $this->_quickConfig ? FALSE : $lineItem);
1090 }
1091 else {
1092 $this->assign('amount_level', $params['amount_level']);
1093 }
1094 }
1095
1096 $this->_params = $params;
1097 parent::beginPostProcess();
1098 $amountOwed = NULL;
1099 if (isset($params['amount'])) {
1100 $amountOwed = $params['amount'];
1101 unset($params['amount']);
1102 }
1103 $params['register_date'] = CRM_Utils_Date::processDate($params['register_date'], $params['register_date_time']);
1104 $params['receive_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $params), CRM_Utils_Array::value('receive_date_time', $params));
1105 $params['contact_id'] = $this->_contactId;
1106
1107 // overwrite actual payment amount if entered
1108 if (!empty($params['total_amount'])) {
1109 $contributionParams['total_amount'] = CRM_Utils_Array::value('total_amount', $params);
1110 }
1111
1112 // Retrieve the name and email of the current user - this will be the FROM for the receipt email
1113 $userName = CRM_Core_Session::singleton()->getLoggedInContactDisplayName();
1114
1115 if ($this->_contactId) {
1116 list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_contactId);
1117 }
1118
1119 //modify params according to parameter used in create
1120 //participant method (addParticipant)
1121 $this->_params['participant_status_id'] = $params['status_id'];
1122 $this->_params['participant_role_id'] = is_array($params['role_id']) ? $params['role_id'] : explode(',', $params['role_id']);
1123 $this->_params['participant_register_date'] = $params['register_date'];
1124 $roleIdWithSeparator = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['participant_role_id']);
1125
1126 if ($this->_mode) {
1127 if (!$this->_isPaidEvent) {
1128 CRM_Core_Error::fatal(ts('Selected Event is not Paid Event '));
1129 }
1130
1131 $eventTitle
1132 = CRM_Core_DAO::getFieldValue(
1133 'CRM_Event_DAO_Event',
1134 $params['event_id'],
1135 'title'
1136 );
1137
1138 // set source if not set
1139 if (empty($params['source'])) {
1140 $this->_params['participant_source'] = ts('Offline Registration for Event: %2 by: %1', array(
1141 1 => $userName,
1142 2 => $eventTitle,
1143 ));
1144 }
1145 else {
1146 $this->_params['participant_source'] = $params['source'];
1147 }
1148 $this->_params['description'] = $this->_params['participant_source'];
1149
1150 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'],
1151 $this->_mode
1152 );
1153 $now = date('YmdHis');
1154 $fields = array();
1155
1156 // set email for primary location.
1157 $fields['email-Primary'] = 1;
1158 $params['email-Primary'] = $params["email-{$this->_bltID}"] = $this->_contributorEmail;
1159
1160 $params['register_date'] = $now;
1161
1162 // now set the values for the billing location.
1163 foreach ($this->_fields as $name => $dontCare) {
1164 $fields[$name] = 1;
1165 }
1166
1167 // also add location name to the array
1168 $params["address_name-{$this->_bltID}"]
1169 = CRM_Utils_Array::value('billing_first_name', $params) . ' ' .
1170 CRM_Utils_Array::value('billing_middle_name', $params) . ' ' .
1171 CRM_Utils_Array::value('billing_last_name', $params);
1172
1173 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
1174 $fields["address_name-{$this->_bltID}"] = 1;
1175 $fields["email-{$this->_bltID}"] = 1;
1176 $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'contact_type');
1177
1178 $nameFields = array('first_name', 'middle_name', 'last_name');
1179
1180 foreach ($nameFields as $name) {
1181 $fields[$name] = 1;
1182 if (array_key_exists("billing_$name", $params)) {
1183 $params[$name] = $params["billing_{$name}"];
1184 $params['preserveDBName'] = TRUE;
1185 }
1186 }
1187 $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactId, NULL, NULL, $ctype);
1188 }
1189
1190 if (!empty($this->_params['participant_role_id'])) {
1191 $customFieldsRole = array();
1192 foreach ($this->_params['participant_role_id'] as $roleKey) {
1193 $customFieldsRole = CRM_Utils_Array::crmArrayMerge(CRM_Core_BAO_CustomField::getFields('Participant',
1194 FALSE, FALSE, $roleKey, $this->_roleCustomDataTypeID), $customFieldsRole);
1195 }
1196 $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant',
1197 FALSE,
1198 FALSE,
1199 CRM_Utils_Array::value('event_id', $params),
1200 $this->_eventNameCustomDataTypeID
1201 );
1202 $customFieldsEventType = CRM_Core_BAO_CustomField::getFields('Participant',
1203 FALSE,
1204 FALSE,
1205 $this->_eventTypeId,
1206 $this->_eventTypeCustomDataTypeID
1207 );
1208 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole,
1209 CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, NULL, TRUE)
1210 );
1211 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
1212 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEventType, $customFields);
1213
1214 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->_id, $this->getDefaultEntity());
1215 }
1216
1217 //do cleanup line items if participant edit the Event Fee.
1218 if (($this->_lineItem || !isset($params['proceSetId'])) && !$this->_paymentId && $this->_id) {
1219 CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_participant');
1220 }
1221
1222 if ($this->_mode) {
1223 // add all the additional payment params we need
1224 $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}"]);
1225 $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
1226
1227 $this->_params['amount'] = $params['fee_amount'];
1228 $this->_params['amount_level'] = $params['amount_level'];
1229 $this->_params['currencyID'] = $config->defaultCurrency;
1230 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
1231
1232 // at this point we've created a contact and stored its address etc
1233 // all the payment processors expect the name and address to be in the
1234 // so we copy stuff over to first_name etc.
1235 $paymentParams = $this->_params;
1236 if (!empty($this->_params['send_receipt'])) {
1237 $paymentParams['email'] = $this->_contributorEmail;
1238 }
1239
1240 // The only reason for merging in the 'contact_id' rather than ensuring it is set
1241 // is that this patch is being done around the time of the stable release
1242 // so more conservative approach is called for.
1243 // In fact the use of $params and $this->_params & $this->_contactId vs $contactID
1244 // needs rationalising.
1245 $mapParams = array_merge(array('contact_id' => $contactID), $this->_params);
1246 CRM_Core_Payment_Form::mapParams($this->_bltID, $mapParams, $paymentParams, TRUE);
1247
1248 $payment = $this->_paymentProcessor['object'];
1249
1250 // CRM-15622: fix for incorrect contribution.fee_amount
1251 $paymentParams['fee_amount'] = NULL;
1252 $result = $payment->doPayment($paymentParams);
1253
1254 if (is_a($result, 'CRM_Core_Error')) {
1255 CRM_Core_Error::displaySessionError($result);
1256 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/participant',
1257 "reset=1&action=add&cid={$this->_contactId}&context=participant&mode={$this->_mode}"
1258 ));
1259 }
1260
1261 if ($result) {
1262 $this->_params = array_merge($this->_params, $result);
1263 }
1264
1265 $this->_params['receive_date'] = $now;
1266
1267 if (!empty($this->_params['send_receipt'])) {
1268 $this->_params['receipt_date'] = $now;
1269 }
1270 else {
1271 $this->_params['receipt_date'] = NULL;
1272 }
1273
1274 $this->set('params', $this->_params);
1275 $this->assign('trxn_id', $result['trxn_id']);
1276 $this->assign('receive_date',
1277 CRM_Utils_Date::processDate($this->_params['receive_date'])
1278 );
1279
1280 //add contribution record
1281 $this->_params['financial_type_id']
1282 = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'financial_type_id');
1283 $this->_params['mode'] = $this->_mode;
1284
1285 //add contribution record
1286 $contributions[] = $contribution = CRM_Event_Form_Registration_Confirm::processContribution(
1287 $this, $this->_params,
1288 $result, $contactID,
1289 FALSE, FALSE,
1290 $this->_paymentProcessor
1291 );
1292
1293 // add participant record
1294 $participants = array();
1295 if (!empty($this->_params['role_id']) && is_array($this->_params['role_id'])) {
1296 $this->_params['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR,
1297 $this->_params['role_id']
1298 );
1299 }
1300
1301 //CRM-15372 patch to fix fee amount replacing amount
1302 $this->_params['fee_amount'] = $this->_params['amount'];
1303
1304 $participants[] = CRM_Event_Form_Registration::addParticipant($this, $contactID);
1305
1306 //add custom data for participant
1307 CRM_Core_BAO_CustomValueTable::postProcess($this->_params,
1308 'civicrm_participant',
1309 $participants[0]->id,
1310 'Participant'
1311 );
1312 //add participant payment
1313 $paymentParticipant = array(
1314 'participant_id' => $participants[0]->id,
1315 'contribution_id' => $contribution->id,
1316 );
1317
1318 CRM_Event_BAO_ParticipantPayment::create($paymentParticipant);
1319 $this->_contactIds[] = $this->_contactId;
1320 }
1321 else {
1322 $participants = array();
1323 if ($this->_single) {
1324 if ($params['role_id']) {
1325 $params['role_id'] = $roleIdWithSeparator;
1326 }
1327 else {
1328 $params['role_id'] = 'NULL';
1329 }
1330 $participants[] = CRM_Event_BAO_Participant::create($params);
1331 }
1332 else {
1333 foreach ($this->_contactIds as $contactID) {
1334 $commonParams = $params;
1335 $commonParams['contact_id'] = $contactID;
1336 if ($commonParams['role_id']) {
1337 $commonParams['role_id'] = $commonParams['role_id'] = str_replace(',', CRM_Core_DAO::VALUE_SEPARATOR, $params['role_id']);
1338 }
1339 else {
1340 $commonParams['role_id'] = 'NULL';
1341 }
1342 $participants[] = CRM_Event_BAO_Participant::create($commonParams);
1343 }
1344 }
1345
1346 if (isset($params['event_id'])) {
1347 $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event',
1348 $params['event_id'],
1349 'title'
1350 );
1351 }
1352
1353 if ($this->_single) {
1354 $this->_contactIds[] = $this->_contactId;
1355 }
1356
1357 $contributions = array();
1358 if (!empty($params['record_contribution'])) {
1359 if (!empty($params['id'])) {
1360 if ($this->_onlinePendingContributionId) {
1361 $ids['contribution'] = $this->_onlinePendingContributionId;
1362 }
1363 else {
1364 $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
1365 $params['id'],
1366 'contribution_id',
1367 'participant_id'
1368 );
1369 }
1370 }
1371 unset($params['note']);
1372
1373 //build contribution params
1374 if (!$this->_onlinePendingContributionId) {
1375 if (empty($params['source'])) {
1376 $contributionParams['source'] = ts('%1 : Offline registration (by %2)', array(
1377 1 => $eventTitle,
1378 2 => $userName,
1379 ));
1380 }
1381 else {
1382 $contributionParams['source'] = $params['source'];
1383 }
1384 }
1385
1386 $contributionParams['currency'] = $config->defaultCurrency;
1387 $contributionParams['non_deductible_amount'] = 'null';
1388 $contributionParams['receipt_date'] = !empty($params['send_receipt']) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
1389 $contributionParams['contact_id'] = $this->_contactID;
1390 // @todo change receive_date to datepicker field. Strip out all wrangling.
1391 $contributionParams['receive_date'] = $params['receive_date'];
1392
1393 $recordContribution = array(
1394 'financial_type_id',
1395 'payment_instrument_id',
1396 'trxn_id',
1397 'contribution_status_id',
1398 'check_number',
1399 'campaign_id',
1400 'pan_truncation',
1401 'card_type_id',
1402 );
1403
1404 foreach ($recordContribution as $f) {
1405 $contributionParams[$f] = CRM_Utils_Array::value($f, $this->_params);
1406 if ($f == 'trxn_id') {
1407 $this->assign('trxn_id', $contributionParams[$f]);
1408 }
1409 }
1410
1411 //insert financial type name in receipt.
1412 $this->assign('financialTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType',
1413 $contributionParams['financial_type_id']));
1414 // legacy support
1415 $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionParams['financial_type_id']));
1416 $contributionParams['skipLineItem'] = 1;
1417 if ($this->_id) {
1418 $contributionParams['contribution_mode'] = 'participant';
1419 $contributionParams['participant_id'] = $this->_id;
1420 }
1421 // Set is_pay_later flag for back-office offline Pending status contributions
1422 if ($contributionParams['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Pending')) {
1423 $contributionParams['is_pay_later'] = 1;
1424 }
1425 elseif ($contributionParams['contribution_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_DAO_Contribution', 'contribution_status_id', 'Completed')) {
1426 $contributionParams['is_pay_later'] = 0;
1427 }
1428
1429 if ($params['status_id'] == array_search('Partially paid', $participantStatus)) {
1430 if (!$amountOwed && $this->_action & CRM_Core_Action::UPDATE) {
1431 $amountOwed = $params['fee_amount'];
1432 }
1433
1434 // if multiple participants are link, consider contribution total amount as the amount Owed
1435 if ($this->_id && CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
1436 $amountOwed = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
1437 $ids['contribution'],
1438 'total_amount'
1439 );
1440 }
1441
1442 // CRM-13964 partial_payment_total
1443 if ($amountOwed > $params['total_amount']) {
1444 // the owed amount
1445 $contributionParams['partial_payment_total'] = $amountOwed;
1446 // the actual amount paid
1447 $contributionParams['partial_amount_to_pay'] = $params['total_amount'];
1448 }
1449 }
1450
1451 if (CRM_Utils_Array::value('tax_amount', $this->_params)) {
1452 $contributionParams['tax_amount'] = $this->_params['tax_amount'];
1453 }
1454
1455 if ($this->_single) {
1456 if (empty($ids)) {
1457 $ids = array();
1458 }
1459 $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
1460 }
1461 else {
1462 $ids = array();
1463 foreach ($this->_contactIds as $contactID) {
1464 $contributionParams['contact_id'] = $contactID;
1465 $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
1466 }
1467 }
1468
1469 //insert payment record for this participation
1470 if (empty($ids['contribution'])) {
1471 foreach ($this->_contactIds as $num => $contactID) {
1472 $ppDAO = new CRM_Event_DAO_ParticipantPayment();
1473 $ppDAO->participant_id = $participants[$num]->id;
1474 $ppDAO->contribution_id = $contributions[$num]->id;
1475 $ppDAO->save();
1476 }
1477 }
1478 // next create the transaction record
1479 $transaction = new CRM_Core_Transaction();
1480
1481 // CRM-11124
1482 if ($this->_params['discount_id']) {
1483 CRM_Event_BAO_Participant::createDiscountTrxn(
1484 $this->_eventId,
1485 $contributionParams,
1486 NULL,
1487 CRM_Price_BAO_PriceSet::parseFirstPriceSetValueIDFromParams($this->_params)
1488 );
1489 }
1490 $transaction->commit();
1491 }
1492 }
1493
1494 // also store lineitem stuff here
1495 if ((($this->_lineItem & $this->_action & CRM_Core_Action::ADD) ||
1496 ($this->_lineItem && CRM_Core_Action::UPDATE && !$this->_paymentId))
1497 ) {
1498 foreach ($this->_contactIds as $num => $contactID) {
1499 foreach ($this->_lineItem as $key => $value) {
1500 if (is_array($value) && $value != 'skip') {
1501 foreach ($value as $lineKey => $line) {
1502 //10117 update the line items for participants if contribution amount is recorded
1503 if ($this->_quickConfig && !empty($params['total_amount']) &&
1504 ($params['status_id'] != array_search('Partially paid', $participantStatus))
1505 ) {
1506 $line['unit_price'] = $line['line_total'] = $params['total_amount'];
1507 if (!empty($params['tax_amount'])) {
1508 $line['unit_price'] = $line['unit_price'] - $params['tax_amount'];
1509 $line['line_total'] = $line['line_total'] - $params['tax_amount'];
1510 }
1511 }
1512 $lineItem[$this->_priceSetId][$lineKey] = $line;
1513 }
1514 CRM_Price_BAO_LineItem::processPriceSet($participants[$num]->id, $lineItem, CRM_Utils_Array::value($num, $contributions, NULL), 'civicrm_participant');
1515 CRM_Contribute_BAO_Contribution::addPayments($contributions);
1516 }
1517 }
1518 }
1519 }
1520
1521 $updateStatusMsg = NULL;
1522 //send mail when participant status changed, CRM-4326
1523 if ($this->_id && $this->_statusId &&
1524 $this->_statusId != CRM_Utils_Array::value('status_id', $params) && !empty($params['is_notify'])
1525 ) {
1526
1527 $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_id,
1528 $params['status_id'],
1529 $this->_statusId
1530 );
1531 }
1532
1533 $sent = array();
1534 $notSent = array();
1535 if (!empty($params['send_receipt'])) {
1536 if (array_key_exists($params['from_email_address'], $this->_fromEmails['from_email_id'])) {
1537 $receiptFrom = $params['from_email_address'];
1538 }
1539
1540 $this->assign('module', 'Event Registration');
1541 //use of the message template below requires variables in different format
1542 $event = $events = array();
1543 $returnProperties = array('event_type_id', 'fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
1544
1545 //get all event details.
1546 CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
1547 $event = $events[$params['event_id']];
1548 unset($event['start_date']);
1549 unset($event['end_date']);
1550
1551 $role = CRM_Event_PseudoConstant::participantRole();
1552 $participantRoles = CRM_Utils_Array::value('role_id', $params);
1553 if (is_array($participantRoles)) {
1554 $selectedRoles = array();
1555 foreach ($participantRoles as $roleId) {
1556 $selectedRoles[] = $role[$roleId];
1557 }
1558 $event['participant_role'] = implode(', ', $selectedRoles);
1559 }
1560 else {
1561 $event['participant_role'] = CRM_Utils_Array::value($participantRoles, $role);
1562 }
1563 $event['is_monetary'] = $this->_isPaidEvent;
1564
1565 if ($params['receipt_text']) {
1566 $event['confirm_email_text'] = $params['receipt_text'];
1567 }
1568
1569 $this->assign('isAmountzero', 1);
1570 $this->assign('event', $event);
1571
1572 $this->assign('isShowLocation', $event['is_show_location']);
1573 if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
1574 $locationParams = array(
1575 'entity_id' => $params['event_id'],
1576 'entity_table' => 'civicrm_event',
1577 );
1578 $location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
1579 $this->assign('location', $location);
1580 }
1581
1582 $status = CRM_Event_PseudoConstant::participantStatus();
1583 if ($this->_isPaidEvent) {
1584 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
1585 if (!$this->_mode) {
1586 if (isset($params['payment_instrument_id'])) {
1587 $this->assign('paidBy',
1588 CRM_Utils_Array::value($params['payment_instrument_id'],
1589 $paymentInstrument
1590 )
1591 );
1592 }
1593 }
1594
1595 $this->assign('totalAmount', $contributionParams['total_amount']);
1596 if (isset($contributionParams['partial_payment_total'])) {
1597 // balance amount
1598 $balanceAmount = $contributionParams['partial_payment_total'] - $contributionParams['partial_amount_to_pay'];
1599 $this->assign('balanceAmount', $balanceAmount);
1600 }
1601 $this->assign('isPrimary', 1);
1602 $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
1603 }
1604 if ($this->_mode) {
1605 $this->assignBillingName($params);
1606 $this->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters(
1607 $this->_params,
1608 $this->_bltID
1609 ));
1610
1611 $date = CRM_Utils_Date::format($params['credit_card_exp_date']);
1612 $date = CRM_Utils_Date::mysqlToIso($date);
1613 $this->assign('credit_card_exp_date', $date);
1614 $this->assign('credit_card_number',
1615 CRM_Utils_System::mungeCreditCard($params['credit_card_number'])
1616 );
1617 $this->assign('credit_card_type', $params['credit_card_type']);
1618 // The concept of contributeMode is deprecated.
1619 $this->assign('contributeMode', 'direct');
1620 $this->assign('isAmountzero', 0);
1621 $this->assign('is_pay_later', 0);
1622 $this->assign('isPrimary', 1);
1623 }
1624
1625 $this->assign('register_date', $params['register_date']);
1626 if ($params['receive_date']) {
1627 $this->assign('receive_date', $params['receive_date']);
1628 }
1629
1630 $participant = array(array('participant_id', '=', $participants[0]->id, 0, 0));
1631 // check whether its a test drive ref CRM-3075
1632 if (!empty($this->_defaultValues['is_test'])) {
1633 $participant[] = array('participant_test', '=', 1, 0, 0);
1634 }
1635
1636 $template = CRM_Core_Smarty::singleton();
1637 $customGroup = array();
1638 //format submitted data
1639 foreach ($params['custom'] as $fieldID => $values) {
1640 foreach ($values as $fieldValue) {
1641 $isPublic = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $fieldValue['custom_group_id'], 'is_public');
1642 if ($isPublic) {
1643 $customFields[$fieldID]['id'] = $fieldID;
1644 $formattedValue = CRM_Core_BAO_CustomField::displayValue($fieldValue['value'], $fieldID, $participants[0]->id);
1645 $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
1646 }
1647 }
1648 }
1649
1650 foreach ($this->_contactIds as $num => $contactID) {
1651 // Retrieve the name and email of the contact - this will be the TO for receipt email
1652 list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
1653
1654 $this->_contributorDisplayName = ($this->_contributorDisplayName == ' ') ? $this->_contributorEmail : $this->_contributorDisplayName;
1655
1656 $waitStatus = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
1657 if ($waitingStatus = CRM_Utils_Array::value($params['status_id'], $waitStatus)) {
1658 $this->assign('isOnWaitlist', TRUE);
1659 }
1660
1661 $this->assign('customGroup', $customGroup);
1662 $this->assign('contactID', $contactID);
1663 $this->assign('participantID', $participants[$num]->id);
1664
1665 $this->_id = $participants[$num]->id;
1666
1667 if ($this->_isPaidEvent) {
1668 // fix amount for each of participants ( for bulk mode )
1669 $eventAmount = array();
1670 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
1671 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
1672 $totalTaxAmount = 0;
1673
1674 //add dataArray in the receipts in ADD and UPDATE condition
1675 $dataArray = array();
1676 if ($this->_action & CRM_Core_Action::ADD) {
1677 $line = isset($lineItem[0]) ? $lineItem[0] : array();
1678 }
1679 elseif ($this->_action & CRM_Core_Action::UPDATE) {
1680 $line = $this->_values['line_items'];
1681 }
1682 if ($invoicing) {
1683 foreach ($line as $key => $value) {
1684 if (isset($value['tax_amount'])) {
1685 $totalTaxAmount += $value['tax_amount'];
1686 if (isset($dataArray[(string) $value['tax_rate']])) {
1687 $dataArray[(string) $value['tax_rate']] = $dataArray[(string) $value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
1688 }
1689 else {
1690 $dataArray[(string) $value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
1691 }
1692 }
1693 }
1694 $this->assign('totalTaxAmount', $totalTaxAmount);
1695 $this->assign('taxTerm', $this->getSalesTaxTerm());
1696 $this->assign('dataArray', $dataArray);
1697 }
1698 if (!empty($additionalParticipantDetails)) {
1699 $params['amount_level'] = preg_replace('/\ 1/', '', $params['amount_level']) . ' - ' . $this->_contributorDisplayName;
1700 }
1701
1702 $eventAmount[$num] = array(
1703 'label' => preg_replace('/\ 1/', '', $params['amount_level']),
1704 'amount' => $params['fee_amount'],
1705 );
1706 //as we are using same template for online & offline registration.
1707 //So we have to build amount as array.
1708 $eventAmount = array_merge($eventAmount, $additionalParticipantDetails);
1709 $this->assign('amount', $eventAmount);
1710 }
1711
1712 $sendTemplateParams = array(
1713 'groupName' => 'msg_tpl_workflow_event',
1714 'valueName' => 'event_offline_receipt',
1715 'contactId' => $contactID,
1716 'isTest' => !empty($this->_defaultValues['is_test']),
1717 'PDFFilename' => ts('confirmation') . '.pdf',
1718 );
1719
1720 // try to send emails only if email id is present
1721 // and the do-not-email option is not checked for that contact
1722 if ($this->_contributorEmail and !$this->_toDoNotEmail) {
1723 $sendTemplateParams['from'] = $receiptFrom;
1724 $sendTemplateParams['toName'] = $this->_contributorDisplayName;
1725 $sendTemplateParams['toEmail'] = $this->_contributorEmail;
1726 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc', $this->_fromEmails);
1727 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc', $this->_fromEmails);
1728 }
1729
1730 //send email with pdf invoice
1731 $template = CRM_Core_Smarty::singleton();
1732 $taxAmt = $template->get_template_vars('dataArray');
1733 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
1734 $this->_id, 'contribution_id', 'participant_id'
1735 );
1736 $prefixValue = Civi::settings()->get('contribution_invoice_settings');
1737 $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
1738 if (count($taxAmt) > 0 && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
1739 $sendTemplateParams['isEmailPdf'] = TRUE;
1740 $sendTemplateParams['contributionId'] = $contributionId;
1741 }
1742 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
1743 if ($mailSent) {
1744 $sent[] = $contactID;
1745 foreach ($participants as $ids => $values) {
1746 if ($values->contact_id == $contactID) {
1747 $values->details = CRM_Utils_Array::value('receipt_text', $params);
1748 CRM_Activity_BAO_Activity::addActivity($values, 'Email');
1749 break;
1750 }
1751 }
1752 }
1753 else {
1754 $notSent[] = $contactID;
1755 }
1756 }
1757 }
1758
1759 // set the participant id if it is not set
1760 if (!$this->_id) {
1761 $this->_id = $participants[0]->id;
1762 }
1763
1764 return $this->getStatusMsg($params, $sent, $updateStatusMsg, $notSent);
1765 }
1766
1767 /**
1768 * Set the various IDs relating to custom data types.
1769 */
1770 public function setCustomDataTypes() {
1771 $customDataType = CRM_Core_OptionGroup::values('custom_data_type', FALSE, FALSE, FALSE, NULL, 'name');
1772 $this->_roleCustomDataTypeID = array_search('ParticipantRole', $customDataType);
1773 $this->_eventNameCustomDataTypeID = array_search('ParticipantEventName', $customDataType);
1774 $this->_eventTypeCustomDataTypeID = array_search('ParticipantEventType', $customDataType);
1775 $this->assign('roleCustomDataTypeID', $this->_roleCustomDataTypeID);
1776 $this->assign('eventNameCustomDataTypeID', $this->_eventNameCustomDataTypeID);
1777 $this->assign('eventTypeCustomDataTypeID', $this->_eventTypeCustomDataTypeID);
1778 }
1779
1780 /**
1781 * Get status message
1782 *
1783 * @param array $params
1784 * @param int $sent
1785 * @param string $updateStatusMsg
1786 * @param int $notSent
1787 *
1788 * @return string
1789 */
1790 protected function getStatusMsg($params, $sent, $updateStatusMsg, $notSent) {
1791 $statusMsg = '';
1792 if (($this->_action & CRM_Core_Action::UPDATE)) {
1793 $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contributorDisplayName));
1794 if (!empty($params['send_receipt']) && count($sent)) {
1795 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', array(1 => $this->_contributorEmail));
1796 }
1797
1798 if ($updateStatusMsg) {
1799 $statusMsg = "{$statusMsg} {$updateStatusMsg}";
1800 }
1801 }
1802 elseif ($this->_action & CRM_Core_Action::ADD) {
1803 if ($this->_single) {
1804 $statusMsg = ts('Event registration for %1 has been added.', array(1 => $this->_contributorDisplayName));
1805 if (!empty($params['send_receipt']) && count($sent)) {
1806 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $this->_contributorEmail));
1807 }
1808 }
1809 else {
1810 $statusMsg = ts('Total Participant(s) added to event: %1.', array(1 => count($this->_contactIds)));
1811 if (count($notSent) > 0) {
1812 $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)));
1813 }
1814 elseif (isset($params['send_receipt'])) {
1815 $statusMsg .= ' ' . ts('A confirmation email has been sent to ALL participants');
1816 }
1817 }
1818 }
1819 return $statusMsg;
1820 }
1821
1822 }