Merge pull request #9296 from michaelmcandrew/grant-api-contact-required
[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);
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();
8cf6bd83
PN
945 if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
946 $eventStartDate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_eventId, 'start_date');
947 if ($eventStartDate) {
948 $contributionParams['revenue_recognition_date'] = date('Ymd', strtotime($eventStartDate));
949 }
950 }
6a488035
TO
951 if (($this->_id && $this->_action & CRM_Core_Action::UPDATE) && $this->_paymentId) {
952 $participantBAO = new CRM_Event_BAO_Participant();
953 $participantBAO->id = $this->_id;
954 $participantBAO->find(TRUE);
955 $contributionParams['total_amount'] = $participantBAO->fee_amount;
956
957 $params['discount_id'] = NULL;
958 //re-enter the values for UPDATE mode
959 $params['fee_level'] = $params['amount_level'] = $participantBAO->fee_level;
960 $params['fee_amount'] = $participantBAO->fee_amount;
961 if (isset($params['priceSetId'])) {
962 $lineItem[0] = CRM_Price_BAO_LineItem::getLineItems($this->_id);
963 }
964 //also add additional participant's fee level/priceset
965 if (CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
966 $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
967 $hasLineItems = CRM_Utils_Array::value('priceSetId', $params, FALSE);
968 $additionalParticipantDetails = CRM_Event_BAO_Participant::getFeeDetails($additionalIds,
969 $hasLineItems
970 );
971 }
972 }
973 else {
974
975 //check if discount is selected
a7488080 976 if (!empty($params['discount_id'])) {
6a488035
TO
977 $discountId = $params['discount_id'];
978 }
979 else {
980 $discountId = $params['discount_id'] = 'null';
981 }
982
983 //lets carry currency, CRM-4453
984 $params['fee_currency'] = $config->defaultCurrency;
9da8dc8c 985 CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'],
8567d0f8
PN
986 $params, $lineItem[0]
987 );
6a488035
TO
988 //CRM-11529 for quick config backoffice transactions
989 //when financial_type_id is passed in form, update the
990 //lineitems with the financial type selected in form
991 $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $params);
992 $isPaymentRecorded = CRM_Utils_Array::value('record_contribution', $params);
993 if ($isPaymentRecorded && $this->_quickConfig && $submittedFinancialType) {
994 foreach ($lineItem[0] as &$values) {
995 $values['financial_type_id'] = $submittedFinancialType;
996 }
997 }
998
999 $params['fee_level'] = $params['amount_level'];
1000 $contributionParams['total_amount'] = $params['amount'];
f6bae84f 1001 if ($this->_quickConfig && !empty($params['total_amount']) &&
353ffa53
TO
1002 $params['status_id'] != array_search('Partially paid', $participantStatus)
1003 ) {
6a488035 1004 $params['fee_amount'] = $params['total_amount'];
0db6c3e1
TO
1005 }
1006 else {
6a488035
TO
1007 //fix for CRM-3086
1008 $params['fee_amount'] = $params['amount'];
1009 }
1010 }
1011
1012 if (isset($params['priceSetId'])) {
1013 if (!empty($lineItem[0])) {
1014 $this->set('lineItem', $lineItem);
1015
353ffa53
TO
1016 $this->_lineItem = $lineItem;
1017 $lineItem = array_merge($lineItem, $additionalParticipantDetails);
6a488035
TO
1018
1019 $participantCount = array();
1020 foreach ($lineItem as $k) {
1021 foreach ($k as $v) {
1022 if (CRM_Utils_Array::value('participant_count', $v) > 0) {
1023 $participantCount[] = $v['participant_count'];
1024 }
1025 }
1026 }
1027 }
1028 if (isset($participantCount)) {
1029 $this->assign('pricesetFieldsCount', $participantCount);
1030 }
0479b4c8 1031 $this->assign('lineItem', empty($lineItem[0]) || $this->_quickConfig ? FALSE : $lineItem);
6a488035
TO
1032 }
1033 else {
1034 $this->assign('amount_level', $params['amount_level']);
1035 }
1036 }
1037
1038 $this->_params = $params;
fbc54416
PJ
1039 $amountOwed = NULL;
1040 if (isset($params['amount'])) {
1041 $amountOwed = $params['amount'];
1042 unset($params['amount']);
1043 }
6a488035 1044 $params['register_date'] = CRM_Utils_Date::processDate($params['register_date'], $params['register_date_time']);
53f56880 1045 $params['receive_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $params), CRM_Utils_Array::value('receive_date_time', $params));
6a488035
TO
1046 $params['contact_id'] = $this->_contactId;
1047
1048 // overwrite actual payment amount if entered
a7488080 1049 if (!empty($params['total_amount'])) {
6a488035
TO
1050 $contributionParams['total_amount'] = CRM_Utils_Array::value('total_amount', $params);
1051 }
1052
6a488035 1053 // Retrieve the name and email of the current user - this will be the FROM for the receipt email
46929486 1054 $userName = CRM_Core_Session::singleton()->getLoggedInContactDisplayName();
6a488035
TO
1055
1056 if ($this->_contactId) {
1057 list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_contactId);
1058 }
1059
7df021e5 1060 //modify params according to parameter used in create
1061 //participant method (addParticipant)
1062 $this->_params['participant_status_id'] = $params['status_id'];
1063 $this->_params['participant_role_id'] = is_array($params['role_id']) ? $params['role_id'] : explode(',', $params['role_id']);
1064 $this->_params['participant_register_date'] = $params['register_date'];
1065 $roleIdWithSeparator = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['participant_role_id']);
1066
6a488035
TO
1067 if ($this->_mode) {
1068 if (!$this->_isPaidEvent) {
1069 CRM_Core_Error::fatal(ts('Selected Event is not Paid Event '));
1070 }
6a488035 1071
a130e045
DG
1072 $eventTitle
1073 = CRM_Core_DAO::getFieldValue(
6a488035
TO
1074 'CRM_Event_DAO_Event',
1075 $params['event_id'],
1076 'title'
1077 );
1078
1079 // set source if not set
1080 if (empty($params['source'])) {
353ffa53
TO
1081 $this->_params['participant_source'] = ts('Offline Registration for Event: %2 by: %1', array(
1082 1 => $userName,
a130e045 1083 2 => $eventTitle,
353ffa53 1084 ));
6a488035
TO
1085 }
1086 else {
03e04002 1087 $this->_params['participant_source'] = $params['source'];
6a488035
TO
1088 }
1089 $this->_params['description'] = $this->_params['participant_source'];
1090
1091 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'],
1092 $this->_mode
1093 );
1094 $now = date('YmdHis');
1095 $fields = array();
1096
1097 // set email for primary location.
1098 $fields['email-Primary'] = 1;
1099 $params['email-Primary'] = $params["email-{$this->_bltID}"] = $this->_contributorEmail;
1100
1101 $params['register_date'] = $now;
1102
1103 // now set the values for the billing location.
1104 foreach ($this->_fields as $name => $dontCare) {
1105 $fields[$name] = 1;
1106 }
1107
1108 // also add location name to the array
a130e045
DG
1109 $params["address_name-{$this->_bltID}"]
1110 = CRM_Utils_Array::value('billing_first_name', $params) . ' ' .
6a488035
TO
1111 CRM_Utils_Array::value('billing_middle_name', $params) . ' ' .
1112 CRM_Utils_Array::value('billing_last_name', $params);
1113
1114 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
1115 $fields["address_name-{$this->_bltID}"] = 1;
1116 $fields["email-{$this->_bltID}"] = 1;
1117 $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'contact_type');
1118
1119 $nameFields = array('first_name', 'middle_name', 'last_name');
1120
1121 foreach ($nameFields as $name) {
1122 $fields[$name] = 1;
1123 if (array_key_exists("billing_$name", $params)) {
1124 $params[$name] = $params["billing_{$name}"];
1125 $params['preserveDBName'] = TRUE;
1126 }
1127 }
1128 $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactId, NULL, NULL, $ctype);
1129 }
1130
e03317f1 1131 if (!empty($this->_params['participant_role_id'])) {
7df021e5 1132 $customFieldsRole = array();
1133 foreach ($this->_params['participant_role_id'] as $roleKey) {
1134 $customFieldsRole = CRM_Utils_Array::crmArrayMerge(CRM_Core_BAO_CustomField::getFields('Participant',
1135 FALSE, FALSE, $roleKey, $this->_roleCustomDataTypeID), $customFieldsRole);
6a488035 1136 }
7df021e5 1137 $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant',
1138 FALSE,
1139 FALSE,
1140 CRM_Utils_Array::value('event_id', $params),
1141 $this->_eventNameCustomDataTypeID
1142 );
1143 $customFieldsEventType = CRM_Core_BAO_CustomField::getFields('Participant',
1144 FALSE,
1145 FALSE,
1146 $this->_eventTypeId,
1147 $this->_eventTypeCustomDataTypeID
1148 );
1149 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole,
1150 CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, NULL, TRUE)
1151 );
1152 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
1153 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEventType, $customFields);
1154 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
7df021e5 1155 $this->_id,
1156 'Participant'
1157 );
6a488035
TO
1158 }
1159
1160 //do cleanup line items if participant edit the Event Fee.
0479b4c8 1161 if (($this->_lineItem || !isset($params['proceSetId'])) && !$this->_paymentId && $this->_id) {
6a488035
TO
1162 CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_participant');
1163 }
03e04002 1164
6a488035 1165 if ($this->_mode) {
dc8cdf3a 1166 // add all the additional payment params we need
6a488035
TO
1167 $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}"]);
1168 $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
1169
1170 $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
1171 $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
1172 $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
1173 $this->_params['amount'] = $params['fee_amount'];
1174 $this->_params['amount_level'] = $params['amount_level'];
1175 $this->_params['currencyID'] = $config->defaultCurrency;
6a488035
TO
1176 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
1177
1178 // at this point we've created a contact and stored its address etc
1179 // all the payment processors expect the name and address to be in the
1180 // so we copy stuff over to first_name etc.
1181 $paymentParams = $this->_params;
a7488080 1182 if (!empty($this->_params['send_receipt'])) {
6a488035
TO
1183 $paymentParams['email'] = $this->_contributorEmail;
1184 }
e7309307
EM
1185
1186 // The only reason for merging in the 'contact_id' rather than ensuring it is set
1187 // is that this patch is being done around the time of the stable release
1188 // so more conservative approach is called for.
1189 // In fact the use of $params and $this->_params & $this->_contactId vs $contactID
1190 // needs rationalising.
1191 $mapParams = array_merge(array('contact_id' => $contactID), $this->_params);
1192 CRM_Core_Payment_Form::mapParams($this->_bltID, $mapParams, $paymentParams, TRUE);
6a488035 1193
077017db 1194 $payment = $this->_paymentProcessor['object'];
6a488035 1195
9b7e7d4c
PH
1196 // CRM-15622: fix for incorrect contribution.fee_amount
1197 $paymentParams['fee_amount'] = NULL;
ce2511f7 1198 $result = $payment->doPayment($paymentParams);
6a488035
TO
1199
1200 if (is_a($result, 'CRM_Core_Error')) {
1201 CRM_Core_Error::displaySessionError($result);
1202 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/participant',
353ffa53
TO
1203 "reset=1&action=add&cid={$this->_contactId}&context=participant&mode={$this->_mode}"
1204 ));
6a488035
TO
1205 }
1206
1207 if ($result) {
1208 $this->_params = array_merge($this->_params, $result);
1209 }
1210
1211 $this->_params['receive_date'] = $now;
1212
a7488080 1213 if (!empty($this->_params['send_receipt'])) {
6a488035
TO
1214 $this->_params['receipt_date'] = $now;
1215 }
1216 else {
1217 $this->_params['receipt_date'] = NULL;
1218 }
1219
1220 $this->set('params', $this->_params);
1221 $this->assign('trxn_id', $result['trxn_id']);
1222 $this->assign('receive_date',
1223 CRM_Utils_Date::processDate($this->_params['receive_date'])
1224 );
1225
1226 //add contribution record
a130e045
DG
1227 $this->_params['financial_type_id']
1228 = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'financial_type_id');
6a488035
TO
1229 $this->_params['mode'] = $this->_mode;
1230
431c430b 1231 //add contribution record
6a488035
TO
1232 $contributions[] = $contribution = CRM_Event_Form_Registration_Confirm::processContribution($this, $this->_params, $result, $contactID, FALSE);
1233
1234 // add participant record
1235 $participants = array();
dc8cdf3a
K
1236 if (!empty($this->_params['role_id']) && is_array($this->_params['role_id'])) {
1237 $this->_params['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR,
1238 $this->_params['role_id']
6a488035
TO
1239 );
1240 }
0e81467c 1241
5c320924 1242 //CRM-15372 patch to fix fee amount replacing amount
0479b4c8 1243 $this->_params['fee_amount'] = $this->_params['amount'];
5c320924 1244
bf2c70af 1245 $participants[] = CRM_Event_Form_Registration::addParticipant($this, $contactID);
6a488035
TO
1246
1247 //add custom data for participant
1248 CRM_Core_BAO_CustomValueTable::postProcess($this->_params,
6a488035
TO
1249 'civicrm_participant',
1250 $participants[0]->id,
1251 'Participant'
1252 );
1253 //add participant payment
1254 $paymentParticipant = array(
1255 'participant_id' => $participants[0]->id,
1256 'contribution_id' => $contribution->id,
1257 );
1258 $ids = array();
1259
1260 CRM_Event_BAO_ParticipantPayment::create($paymentParticipant, $ids);
1261 $this->_contactIds[] = $this->_contactId;
1262 }
1263 else {
1264 $participants = array();
1265 if ($this->_single) {
1266 if ($params['role_id']) {
7df021e5 1267 $params['role_id'] = $roleIdWithSeparator;
6a488035
TO
1268 }
1269 else {
1270 $params['role_id'] = 'NULL';
1271 }
1272 $participants[] = CRM_Event_BAO_Participant::create($params);
1273 }
1274 else {
1275 foreach ($this->_contactIds as $contactID) {
1276 $commonParams = $params;
1277 $commonParams['contact_id'] = $contactID;
1278 if ($commonParams['role_id']) {
dc8cdf3a 1279 $commonParams['role_id'] = $commonParams['role_id'] = str_replace(',', CRM_Core_DAO::VALUE_SEPARATOR, $params['role_id']);
6a488035
TO
1280 }
1281 else {
1282 $commonParams['role_id'] = 'NULL';
1283 }
1284 $participants[] = CRM_Event_BAO_Participant::create($commonParams);
1285 }
1286 }
1287
1288 if (isset($params['event_id'])) {
1289 $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event',
1290 $params['event_id'],
1291 'title'
1292 );
1293 }
1294
1295 if ($this->_single) {
1296 $this->_contactIds[] = $this->_contactId;
1297 }
1298
1299 $contributions = array();
a7488080
CW
1300 if (!empty($params['record_contribution'])) {
1301 if (!empty($params['id'])) {
6a488035
TO
1302 if ($this->_onlinePendingContributionId) {
1303 $ids['contribution'] = $this->_onlinePendingContributionId;
1304 }
1305 else {
1306 $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
1307 $params['id'],
1308 'contribution_id',
1309 'participant_id'
1310 );
1311 }
1312 }
1313 unset($params['note']);
1314
1315 //build contribution params
1316 if (!$this->_onlinePendingContributionId) {
0e81467c 1317 if (empty($params['source'])) {
353ffa53
TO
1318 $contributionParams['source'] = ts('%1 : Offline registration (by %2)', array(
1319 1 => $eventTitle,
a130e045 1320 2 => $userName,
353ffa53 1321 ));
0e81467c
EM
1322 }
1323 else {
1324 $contributionParams['source'] = $params['source'];
1325 }
1326 }
6a488035
TO
1327
1328 $contributionParams['currency'] = $config->defaultCurrency;
1329 $contributionParams['non_deductible_amount'] = 'null';
0d8afee2 1330 $contributionParams['receipt_date'] = !empty($params['send_receipt']) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
6a488035 1331
353ffa53
TO
1332 $recordContribution = array(
1333 'contact_id',
1334 'financial_type_id',
1335 'payment_instrument_id',
1336 'trxn_id',
1337 'contribution_status_id',
1338 'receive_date',
1339 'check_number',
1340 'campaign_id',
6a488035
TO
1341 );
1342
1343 foreach ($recordContribution as $f) {
1344 $contributionParams[$f] = CRM_Utils_Array::value($f, $params);
1345 if ($f == 'trxn_id') {
1346 $this->assign('trxn_id', $contributionParams[$f]);
1347 }
1348 }
1349
1350 //insert financial type name in receipt.
b956b310 1351 $this->assign('financialTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType',
1352 $contributionParams['financial_type_id']));
1353 // legacy support
6a488035
TO
1354 $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionParams['financial_type_id']));
1355 $contributionParams['skipLineItem'] = 1;
7030a002
PN
1356 if ($this->_id) {
1357 $contributionParams['contribution_mode'] = 'participant';
1358 $contributionParams['participant_id'] = $this->_id;
1359 }
6a488035
TO
1360 // Set is_pay_later flag for back-office offline Pending status contributions
1361 if ($contributionParams['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
1362 $contributionParams['is_pay_later'] = 1;
1363 }
d6dce594 1364 elseif ($contributionParams['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
d75f2f47
EM
1365 $contributionParams['is_pay_later'] = 0;
1366 }
f8325309 1367
aac57c29 1368 if ($params['status_id'] == array_search('Partially paid', $participantStatus)) {
5e494d5c
PJ
1369 if (!$amountOwed && $this->_action & CRM_Core_Action::UPDATE) {
1370 $amountOwed = $params['fee_amount'];
1371 }
1372
356579e9 1373 // if multiple participants are link, consider contribution total amount as the amount Owed
ea707c1b 1374 if ($this->_id && CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
356579e9
PJ
1375 $amountOwed = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
1376 $ids['contribution'],
1377 'total_amount'
1378 );
1379 }
1380
aac57c29
PJ
1381 // CRM-13964 partial_payment_total
1382 if ($amountOwed > $params['total_amount']) {
1383 // the owed amount
1384 $contributionParams['partial_payment_total'] = $amountOwed;
1385 // the actual amount paid
1386 $contributionParams['partial_amount_pay'] = $params['total_amount'];
1387 }
f8325309 1388 }
372ad74d 1389
d91b8b33 1390 if (CRM_Utils_Array::value('tax_amount', $this->_params)) {
1391 $contributionParams['tax_amount'] = $this->_params['tax_amount'];
1392 }
1393
6a488035 1394 if ($this->_single) {
dbd48d4e 1395 if (empty($ids)) {
1396 $ids = array();
1397 }
6a488035
TO
1398 $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
1399 }
1400 else {
1401 $ids = array();
1402 foreach ($this->_contactIds as $contactID) {
1403 $contributionParams['contact_id'] = $contactID;
1404 $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
1405 }
1406 }
1407
1408 //insert payment record for this participation
dbd48d4e 1409 if (empty($ids['contribution'])) {
6a488035
TO
1410 foreach ($this->_contactIds as $num => $contactID) {
1411 $ppDAO = new CRM_Event_DAO_ParticipantPayment();
1412 $ppDAO->participant_id = $participants[$num]->id;
1413 $ppDAO->contribution_id = $contributions[$num]->id;
1414 $ppDAO->save();
1415 }
1416 }
1417 // next create the transaction record
1418 $transaction = new CRM_Core_Transaction();
1419
1420 // CRM-11124
362bd1b7 1421 if ($this->_params['discount_id']) {
1422 CRM_Event_BAO_Participant::createDiscountTrxn(
1423 $this->_eventId,
1424 $contributionParams,
1425 NULL,
1426 CRM_Price_BAO_PriceSet::parseFirstPriceSetValueIDFromParams($this->_params)
1427 );
6a488035
TO
1428 }
1429 $transaction->commit();
1430 }
1431 }
1432
1433 // also store lineitem stuff here
1434 if ((($this->_lineItem & $this->_action & CRM_Core_Action::ADD) ||
1435 ($this->_lineItem && CRM_Core_Action::UPDATE && !$this->_paymentId))
1436 ) {
1437 foreach ($this->_contactIds as $num => $contactID) {
1438 foreach ($this->_lineItem as $key => $value) {
1439 if (is_array($value) && $value != 'skip') {
1440 foreach ($value as $lineKey => $line) {
aac57c29 1441 //10117 update the line items for participants if contribution amount is recorded
f6bae84f 1442 if ($this->_quickConfig && !empty($params['total_amount']) &&
372ad74d 1443 ($params['status_id'] != array_search('Partially paid', $participantStatus))
aac57c29
PJ
1444 ) {
1445 $line['unit_price'] = $line['line_total'] = $params['total_amount'];
d91b8b33 1446 if (!empty($params['tax_amount'])) {
1447 $line['unit_price'] = $line['unit_price'] - $params['tax_amount'];
ff9b6b50 1448 $line['line_total'] = $line['line_total'] - $params['tax_amount'];
d91b8b33 1449 }
aac57c29 1450 }
6a488035
TO
1451 $lineItem[$this->_priceSetId][$lineKey] = $line;
1452 }
1453 CRM_Price_BAO_LineItem::processPriceSet($participants[$num]->id, $lineItem, CRM_Utils_Array::value($num, $contributions, NULL), 'civicrm_participant');
81caebc8 1454 CRM_Contribute_BAO_Contribution::addPayments($value, $contributions);
6a488035
TO
1455 }
1456 }
1457 }
1458 }
1459
1460 $updateStatusMsg = NULL;
1461 //send mail when participant status changed, CRM-4326
1462 if ($this->_id && $this->_statusId &&
353ffa53
TO
1463 $this->_statusId != CRM_Utils_Array::value('status_id', $params) && !empty($params['is_notify'])
1464 ) {
6a488035
TO
1465
1466 $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_id,
1467 $params['status_id'],
1468 $this->_statusId
1469 );
1470 }
1471
1472 $sent = array();
1473 $notSent = array();
a7488080 1474 if (!empty($params['send_receipt'])) {
6a488035
TO
1475 if (array_key_exists($params['from_email_address'], $this->_fromEmails['from_email_id'])) {
1476 $receiptFrom = $params['from_email_address'];
1477 }
1478
1479 $this->assign('module', 'Event Registration');
1480 //use of the message template below requires variables in different format
1481 $event = $events = array();
1482 $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
1483
1484 //get all event details.
1485 CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
1486 $event = $events[$params['event_id']];
1487 unset($event['start_date']);
1488 unset($event['end_date']);
1489
1490 $role = CRM_Event_PseudoConstant::participantRole();
1491 $participantRoles = CRM_Utils_Array::value('role_id', $params);
1492 if (is_array($participantRoles)) {
1493 $selectedRoles = array();
c7101803 1494 foreach ($participantRoles as $roleId) {
6a488035
TO
1495 $selectedRoles[] = $role[$roleId];
1496 }
1497 $event['participant_role'] = implode(', ', $selectedRoles);
1498 }
1499 else {
1500 $event['participant_role'] = CRM_Utils_Array::value($participantRoles, $role);
1501 }
1502 $event['is_monetary'] = $this->_isPaidEvent;
1503
1504 if ($params['receipt_text']) {
1505 $event['confirm_email_text'] = $params['receipt_text'];
1506 }
1507
1508 $this->assign('isAmountzero', 1);
1509 $this->assign('event', $event);
1510
1511 $this->assign('isShowLocation', $event['is_show_location']);
1512 if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
1513 $locationParams = array(
1514 'entity_id' => $params['event_id'],
1515 'entity_table' => 'civicrm_event',
1516 );
1517 $location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
1518 $this->assign('location', $location);
1519 }
1520
1521 $status = CRM_Event_PseudoConstant::participantStatus();
1522 if ($this->_isPaidEvent) {
1523 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
1524 if (!$this->_mode) {
1525 if (isset($params['payment_instrument_id'])) {
1526 $this->assign('paidBy',
1527 CRM_Utils_Array::value($params['payment_instrument_id'],
1528 $paymentInstrument
1529 )
1530 );
1531 }
1532 }
1533
1534 $this->assign('totalAmount', $contributionParams['total_amount']);
81f3d017
PJ
1535 if (isset($contributionParams['partial_payment_total'])) {
1536 // balance amount
1537 $balanceAmount = $contributionParams['partial_payment_total'] - $contributionParams['partial_amount_pay'];
481a74f4 1538 $this->assign('balanceAmount', $balanceAmount);
81f3d017 1539 }
6a488035
TO
1540 $this->assign('isPrimary', 1);
1541 $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
1542 }
1543 if ($this->_mode) {
0b50eca0 1544 $this->assignBillingName($params);
1545 $this->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters(
1546 $this->_params,
1547 $this->_bltID
1548 ));
6a488035
TO
1549
1550 $date = CRM_Utils_Date::format($params['credit_card_exp_date']);
1551 $date = CRM_Utils_Date::mysqlToIso($date);
1552 $this->assign('credit_card_exp_date', $date);
1553 $this->assign('credit_card_number',
1554 CRM_Utils_System::mungeCreditCard($params['credit_card_number'])
1555 );
1556 $this->assign('credit_card_type', $params['credit_card_type']);
0f2b049e 1557 // The concept of contributeMode is deprecated.
6a488035
TO
1558 $this->assign('contributeMode', 'direct');
1559 $this->assign('isAmountzero', 0);
1560 $this->assign('is_pay_later', 0);
1561 $this->assign('isPrimary', 1);
1562 }
1563
1564 $this->assign('register_date', $params['register_date']);
1565 if ($params['receive_date']) {
1566 $this->assign('receive_date', $params['receive_date']);
1567 }
1568
1569 $participant = array(array('participant_id', '=', $participants[0]->id, 0, 0));
1570 // check whether its a test drive ref CRM-3075
a7488080 1571 if (!empty($this->_defaultValues['is_test'])) {
6a488035
TO
1572 $participant[] = array('participant_test', '=', 1, 0, 0);
1573 }
1574
1575 $template = CRM_Core_Smarty::singleton();
1576 $customGroup = array();
1577 //format submitted data
1578 foreach ($params['custom'] as $fieldID => $values) {
1579 foreach ($values as $fieldValue) {
6a488035 1580 $customFields[$fieldID]['id'] = $fieldID;
ba475058 1581 $formattedValue = CRM_Core_BAO_CustomField::displayValue($fieldValue['value'], $fieldID, $participants[0]->id);
6a488035
TO
1582 $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
1583 }
1584 }
1585
1586 foreach ($this->_contactIds as $num => $contactID) {
1587 // Retrieve the name and email of the contact - this will be the TO for receipt email
1588 list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
1589
1590 $this->_contributorDisplayName = ($this->_contributorDisplayName == ' ') ? $this->_contributorEmail : $this->_contributorDisplayName;
1591
1592 $waitStatus = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
1593 if ($waitingStatus = CRM_Utils_Array::value($params['status_id'], $waitStatus)) {
1594 $this->assign('isOnWaitlist', TRUE);
1595 }
1596
1597 $this->assign('customGroup', $customGroup);
1598 $this->assign('contactID', $contactID);
1599 $this->assign('participantID', $participants[$num]->id);
1600
1601 $this->_id = $participants[$num]->id;
1602
1603 if ($this->_isPaidEvent) {
1604 // fix amount for each of participants ( for bulk mode )
1605 $eventAmount = array();
aaffa79f 1606 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
03b412ae 1607 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
79d001a2 1608 $totalTaxAmount = 0;
0e81467c 1609
03b412ae 1610 //add dataArray in the receipts in ADD and UPDATE condition
79d001a2
PB
1611 $dataArray = array();
1612 if ($this->_action & CRM_Core_Action::ADD) {
1613 $line = $lineItem[0];
1614 }
1615 elseif ($this->_action & CRM_Core_Action::UPDATE) {
1616 $line = $this->_values['line_items'];
1617 }
03b412ae
PB
1618 if ($invoicing) {
1619 foreach ($line as $key => $value) {
1620 if (isset($value['tax_amount'])) {
1621 $totalTaxAmount += $value['tax_amount'];
288ec043
PB
1622 if (isset($dataArray[(string) $value['tax_rate']])) {
1623 $dataArray[(string) $value['tax_rate']] = $dataArray[(string) $value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
03b412ae
PB
1624 }
1625 else {
288ec043 1626 $dataArray[(string) $value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
03b412ae 1627 }
79d001a2
PB
1628 }
1629 }
03b412ae 1630 $this->assign('totalTaxAmount', $totalTaxAmount);
01604562 1631 $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
03b412ae 1632 $this->assign('dataArray', $dataArray);
79d001a2 1633 }
6a488035
TO
1634 if (!empty($additionalParticipantDetails)) {
1635 $params['amount_level'] = preg_replace('/\ 1/', '', $params['amount_level']) . ' - ' . $this->_contributorDisplayName;
1636 }
1637
1638 $eventAmount[$num] = array(
1639 'label' => preg_replace('/\ 1/', '', $params['amount_level']),
1640 'amount' => $params['fee_amount'],
1641 );
1642 //as we are using same template for online & offline registration.
1643 //So we have to build amount as array.
1644 $eventAmount = array_merge($eventAmount, $additionalParticipantDetails);
1645 $this->assign('amount', $eventAmount);
1646 }
1647
1648 $sendTemplateParams = array(
1649 'groupName' => 'msg_tpl_workflow_event',
1650 'valueName' => 'event_offline_receipt',
1651 'contactId' => $contactID,
52f3b44b 1652 'isTest' => !empty($this->_defaultValues['is_test']),
92fcb95f 1653 'PDFFilename' => ts('confirmation') . '.pdf',
6a488035
TO
1654 );
1655
1656 // try to send emails only if email id is present
1657 // and the do-not-email option is not checked for that contact
1658 if ($this->_contributorEmail and !$this->_toDoNotEmail) {
1659 $sendTemplateParams['from'] = $receiptFrom;
1660 $sendTemplateParams['toName'] = $this->_contributorDisplayName;
1661 $sendTemplateParams['toEmail'] = $this->_contributorEmail;
1662 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc', $this->_fromEmails);
1663 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc', $this->_fromEmails);
1664 }
1665
9161952c 1666 //send email with pdf invoice
481a74f4 1667 $template = CRM_Core_Smarty::singleton();
9161952c
PD
1668 $taxAmt = $template->get_template_vars('dataArray');
1669 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
353ffa53
TO
1670 $this->_id, 'contribution_id', 'participant_id'
1671 );
aaffa79f 1672 $prefixValue = Civi::settings()->get('contribution_invoice_settings');
9161952c
PD
1673 $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
1674 if (count($taxAmt) > 0 && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
0479b4c8 1675 $sendTemplateParams['isEmailPdf'] = TRUE;
0e81467c 1676 $sendTemplateParams['contributionId'] = $contributionId;
9161952c 1677 }
c6327d7d 1678 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
6a488035
TO
1679 if ($mailSent) {
1680 $sent[] = $contactID;
1681 foreach ($participants as $ids => $values) {
1682 if ($values->contact_id == $contactID) {
641f812f 1683 $values->details = CRM_Utils_Array::value('receipt_text', $params);
6a488035
TO
1684 CRM_Activity_BAO_Activity::addActivity($values, 'Email');
1685 break;
1686 }
1687 }
1688 }
1689 else {
1690 $notSent[] = $contactID;
1691 }
1692 }
1693 }
1694
1695 // set the participant id if it is not set
1696 if (!$this->_id) {
1697 $this->_id = $participants[0]->id;
1698 }
1699
1700 if (($this->_action & CRM_Core_Action::UPDATE)) {
1701 $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contributorDisplayName));
a7488080 1702 if (!empty($params['send_receipt']) && count($sent)) {
6a488035
TO
1703 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', array(1 => $this->_contributorEmail));
1704 }
1705
1706 if ($updateStatusMsg) {
1707 $statusMsg = "{$statusMsg} {$updateStatusMsg}";
1708 }
1709 }
1710 elseif ($this->_action & CRM_Core_Action::ADD) {
1711 if ($this->_single) {
1712 $statusMsg = ts('Event registration for %1 has been added.', array(1 => $this->_contributorDisplayName));
a7488080 1713 if (!empty($params['send_receipt']) && count($sent)) {
6a488035
TO
1714 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $this->_contributorEmail));
1715 }
1716 }
1717 else {
1718 $statusMsg = ts('Total Participant(s) added to event: %1.', array(1 => count($this->_contactIds)));
1719 if (count($notSent) > 0) {
1720 $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)));
1721 }
1722 elseif (isset($params['send_receipt'])) {
1723 $statusMsg .= ' ' . ts('A confirmation email has been sent to ALL participants');
1724 }
1725 }
1726 }
1727 CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
3748c4b7 1728 $session = CRM_Core_Session::singleton();
6a488035
TO
1729 $buttonName = $this->controller->getButtonName();
1730 if ($this->_context == 'standalone') {
1731 if ($buttonName == $this->getButtonName('upload', 'new')) {
1732 $urlParams = 'reset=1&action=add&context=standalone';
1733 if ($this->_mode) {
1734 $urlParams .= '&mode=' . $this->_mode;
1735 }
1736 if ($this->_eID) {
1737 $urlParams .= '&eid=' . $this->_eID;
1738 }
1739 $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', $urlParams));
1740 }
1741 else {
1742 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
353ffa53
TO
1743 "reset=1&cid={$this->_contactId}&selectedChild=participant"
1744 ));
6a488035
TO
1745 }
1746 }
1747 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1748 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant',
353ffa53
TO
1749 "reset=1&action=add&context={$this->_context}&cid={$this->_contactId}"
1750 ));
6a488035
TO
1751 }
1752 }
96025800 1753
6a488035 1754}