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