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