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