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