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