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