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