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