CRM-16761 - User message improvements.
[civicrm-core.git] / CRM / Event / Form / Participant.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 *
31 * @package CRM
32 * @copyright CiviCRM LLC (c) 2004-2015
33 * $Id$
34 *
35 */
36
37 /**
38 * This class generates form components for processing a participation
39 * in an event
40 */
41 class CRM_Event_Form_Participant extends CRM_Contribute_Form_AbstractEditPayment {
42
43 public $useLivePageJS = TRUE;
44
45 /**
46 * The values for the contribution db object.
47 *
48 * @var array
49 */
50 public $_values;
51
52 /**
53 * The values for the quickconfig for priceset.
54 *
55 * @var boolean
56 */
57 public $_quickConfig = NULL;
58
59 /**
60 * Price Set ID, if the new price set method is used
61 *
62 * @var int
63 */
64 public $_priceSetId;
65
66 /**
67 * Array of fields for the price set.
68 *
69 * @var array
70 */
71 public $_priceSet;
72
73 /**
74 * The id of the participation that we are proceessing.
75 *
76 * @var int
77 */
78 public $_id;
79
80 /**
81 * The id of the note.
82 *
83 * @var int
84 */
85 protected $_noteId = NULL;
86
87 /**
88 * The id of the contact associated with this participation.
89 *
90 * @var int
91 */
92 public $_contactId;
93
94 /**
95 * Array of event values.
96 *
97 * @var array
98 */
99 protected $_event;
100
101 /**
102 * Are we operating in "single mode", i.e. adding / editing only
103 * one participant record, or is this a batch add operation
104 *
105 * @var boolean
106 */
107 public $_single = FALSE;
108
109 /**
110 * If event is paid or unpaid.
111 */
112 public $_isPaidEvent;
113
114 /**
115 * Page action.
116 */
117 public $_action;
118
119 /**
120 * Role Id.
121 */
122 protected $_roleId = NULL;
123
124 /**
125 * Event Type Id.
126 */
127 protected $_eventTypeId = NULL;
128
129 /**
130 * Participant status Id.
131 */
132 protected $_statusId = NULL;
133
134 /**
135 * Cache all the participant statuses.
136 */
137 protected $_participantStatuses;
138
139 /**
140 * Participant mode.
141 */
142 public $_mode = NULL;
143
144 /**
145 * Event ID preselect.
146 */
147 public $_eID = NULL;
148
149 /**
150 * Line Item for Price Set.
151 */
152 public $_lineItem = NULL;
153
154 /**
155 * Contribution mode for event registration for offline mode.
156 *
157 * @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 (($this->_id && $this->_action & CRM_Core_Action::UPDATE) && $this->_paymentId) {
946 $participantBAO = new CRM_Event_BAO_Participant();
947 $participantBAO->id = $this->_id;
948 $participantBAO->find(TRUE);
949 $contributionParams['total_amount'] = $participantBAO->fee_amount;
950
951 $params['discount_id'] = NULL;
952 //re-enter the values for UPDATE mode
953 $params['fee_level'] = $params['amount_level'] = $participantBAO->fee_level;
954 $params['fee_amount'] = $participantBAO->fee_amount;
955 if (isset($params['priceSetId'])) {
956 $lineItem[0] = CRM_Price_BAO_LineItem::getLineItems($this->_id);
957 }
958 //also add additional participant's fee level/priceset
959 if (CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
960 $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
961 $hasLineItems = CRM_Utils_Array::value('priceSetId', $params, FALSE);
962 $additionalParticipantDetails = CRM_Event_BAO_Participant::getFeeDetails($additionalIds,
963 $hasLineItems
964 );
965 }
966 }
967 else {
968
969 //check if discount is selected
970 if (!empty($params['discount_id'])) {
971 $discountId = $params['discount_id'];
972 }
973 else {
974 $discountId = $params['discount_id'] = 'null';
975 }
976
977 //lets carry currency, CRM-4453
978 $params['fee_currency'] = $config->defaultCurrency;
979 CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'],
980 $params, $lineItem[0]
981 );
982 //CRM-11529 for quick config backoffice transactions
983 //when financial_type_id is passed in form, update the
984 //lineitems with the financial type selected in form
985 $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $params);
986 $isPaymentRecorded = CRM_Utils_Array::value('record_contribution', $params);
987 if ($isPaymentRecorded && $this->_quickConfig && $submittedFinancialType) {
988 foreach ($lineItem[0] as &$values) {
989 $values['financial_type_id'] = $submittedFinancialType;
990 }
991 }
992
993 $params['fee_level'] = $params['amount_level'];
994 $contributionParams['total_amount'] = $params['amount'];
995 if ($this->_quickConfig && !empty($params['total_amount']) &&
996 $params['status_id'] != array_search('Partially paid', $participantStatus)
997 ) {
998 $params['fee_amount'] = $params['total_amount'];
999 }
1000 else {
1001 //fix for CRM-3086
1002 $params['fee_amount'] = $params['amount'];
1003 }
1004 }
1005
1006 if (isset($params['priceSetId'])) {
1007 if (!empty($lineItem[0])) {
1008 $this->set('lineItem', $lineItem);
1009
1010 $this->_lineItem = $lineItem;
1011 $lineItem = array_merge($lineItem, $additionalParticipantDetails);
1012
1013 $participantCount = array();
1014 foreach ($lineItem as $k) {
1015 foreach ($k as $v) {
1016 if (CRM_Utils_Array::value('participant_count', $v) > 0) {
1017 $participantCount[] = $v['participant_count'];
1018 }
1019 }
1020 }
1021 }
1022 if (isset($participantCount)) {
1023 $this->assign('pricesetFieldsCount', $participantCount);
1024 }
1025 $this->assign('lineItem', empty($lineItem[0]) || $this->_quickConfig ? FALSE : $lineItem);
1026 }
1027 else {
1028 $this->assign('amount_level', $params['amount_level']);
1029 }
1030 }
1031
1032 $this->_params = $params;
1033 $amountOwed = NULL;
1034 if (isset($params['amount'])) {
1035 $amountOwed = $params['amount'];
1036 unset($params['amount']);
1037 }
1038 $params['register_date'] = CRM_Utils_Date::processDate($params['register_date'], $params['register_date_time']);
1039 $params['receive_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $params), CRM_Utils_Array::value('receive_date_time', $params));
1040 $params['contact_id'] = $this->_contactId;
1041
1042 // overwrite actual payment amount if entered
1043 if (!empty($params['total_amount'])) {
1044 $contributionParams['total_amount'] = CRM_Utils_Array::value('total_amount', $params);
1045 }
1046
1047 // Retrieve the name and email of the current user - this will be the FROM for the receipt email
1048 $session = CRM_Core_Session::singleton();
1049 $userID = $session->get('userID');
1050 list($userName,
1051 $userEmail
1052 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
1053
1054 if ($this->_contactId) {
1055 list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_contactId);
1056 }
1057
1058 //modify params according to parameter used in create
1059 //participant method (addParticipant)
1060 $this->_params['participant_status_id'] = $params['status_id'];
1061 $this->_params['participant_role_id'] = is_array($params['role_id']) ? $params['role_id'] : explode(',', $params['role_id']);
1062 $this->_params['participant_register_date'] = $params['register_date'];
1063 $roleIdWithSeparator = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['participant_role_id']);
1064
1065 if ($this->_mode) {
1066 if (!$this->_isPaidEvent) {
1067 CRM_Core_Error::fatal(ts('Selected Event is not Paid Event '));
1068 }
1069
1070 $eventTitle
1071 = CRM_Core_DAO::getFieldValue(
1072 'CRM_Event_DAO_Event',
1073 $params['event_id'],
1074 'title'
1075 );
1076
1077 // set source if not set
1078 if (empty($params['source'])) {
1079 $this->_params['participant_source'] = ts('Offline Registration for Event: %2 by: %1', array(
1080 1 => $userName,
1081 2 => $eventTitle,
1082 ));
1083 }
1084 else {
1085 $this->_params['participant_source'] = $params['source'];
1086 }
1087 $this->_params['description'] = $this->_params['participant_source'];
1088
1089 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'],
1090 $this->_mode
1091 );
1092 $now = date('YmdHis');
1093 $fields = array();
1094
1095 // set email for primary location.
1096 $fields['email-Primary'] = 1;
1097 $params['email-Primary'] = $params["email-{$this->_bltID}"] = $this->_contributorEmail;
1098
1099 $params['register_date'] = $now;
1100
1101 // now set the values for the billing location.
1102 foreach ($this->_fields as $name => $dontCare) {
1103 $fields[$name] = 1;
1104 }
1105
1106 // also add location name to the array
1107 $params["address_name-{$this->_bltID}"]
1108 = CRM_Utils_Array::value('billing_first_name', $params) . ' ' .
1109 CRM_Utils_Array::value('billing_middle_name', $params) . ' ' .
1110 CRM_Utils_Array::value('billing_last_name', $params);
1111
1112 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
1113 $fields["address_name-{$this->_bltID}"] = 1;
1114 $fields["email-{$this->_bltID}"] = 1;
1115 $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'contact_type');
1116
1117 $nameFields = array('first_name', 'middle_name', 'last_name');
1118
1119 foreach ($nameFields as $name) {
1120 $fields[$name] = 1;
1121 if (array_key_exists("billing_$name", $params)) {
1122 $params[$name] = $params["billing_{$name}"];
1123 $params['preserveDBName'] = TRUE;
1124 }
1125 }
1126 $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactId, NULL, NULL, $ctype);
1127 }
1128
1129 if (!empty($this->_params['participant_role_id'])) {
1130 $customFieldsRole = array();
1131 foreach ($this->_params['participant_role_id'] as $roleKey) {
1132 $customFieldsRole = CRM_Utils_Array::crmArrayMerge(CRM_Core_BAO_CustomField::getFields('Participant',
1133 FALSE, FALSE, $roleKey, $this->_roleCustomDataTypeID), $customFieldsRole);
1134 }
1135 $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant',
1136 FALSE,
1137 FALSE,
1138 CRM_Utils_Array::value('event_id', $params),
1139 $this->_eventNameCustomDataTypeID
1140 );
1141 $customFieldsEventType = CRM_Core_BAO_CustomField::getFields('Participant',
1142 FALSE,
1143 FALSE,
1144 $this->_eventTypeId,
1145 $this->_eventTypeCustomDataTypeID
1146 );
1147 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole,
1148 CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, NULL, TRUE)
1149 );
1150 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
1151 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEventType, $customFields);
1152 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
1153 $this->_id,
1154 'Participant'
1155 );
1156 }
1157
1158 //do cleanup line items if participant edit the Event Fee.
1159 if (($this->_lineItem || !isset($params['proceSetId'])) && !$this->_paymentId && $this->_id) {
1160 CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_participant');
1161 }
1162
1163 if ($this->_mode) {
1164 // add all the additional payment params we need
1165 $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}"]);
1166 $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
1167
1168 $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
1169 $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
1170 $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
1171 $this->_params['amount'] = $params['fee_amount'];
1172 $this->_params['amount_level'] = $params['amount_level'];
1173 $this->_params['currencyID'] = $config->defaultCurrency;
1174 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
1175
1176 // at this point we've created a contact and stored its address etc
1177 // all the payment processors expect the name and address to be in the
1178 // so we copy stuff over to first_name etc.
1179 $paymentParams = $this->_params;
1180 if (!empty($this->_params['send_receipt'])) {
1181 $paymentParams['email'] = $this->_contributorEmail;
1182 }
1183
1184 // The only reason for merging in the 'contact_id' rather than ensuring it is set
1185 // is that this patch is being done around the time of the stable release
1186 // so more conservative approach is called for.
1187 // In fact the use of $params and $this->_params & $this->_contactId vs $contactID
1188 // needs rationalising.
1189 $mapParams = array_merge(array('contact_id' => $contactID), $this->_params);
1190 CRM_Core_Payment_Form::mapParams($this->_bltID, $mapParams, $paymentParams, TRUE);
1191
1192 $payment = $this->_paymentProcessor['object'];
1193
1194 // CRM-15622: fix for incorrect contribution.fee_amount
1195 $paymentParams['fee_amount'] = NULL;
1196 $result = $payment->doPayment($paymentParams);
1197
1198 if (is_a($result, 'CRM_Core_Error')) {
1199 CRM_Core_Error::displaySessionError($result);
1200 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/participant',
1201 "reset=1&action=add&cid={$this->_contactId}&context=participant&mode={$this->_mode}"
1202 ));
1203 }
1204
1205 if ($result) {
1206 $this->_params = array_merge($this->_params, $result);
1207 }
1208
1209 $this->_params['receive_date'] = $now;
1210
1211 if (!empty($this->_params['send_receipt'])) {
1212 $this->_params['receipt_date'] = $now;
1213 }
1214 else {
1215 $this->_params['receipt_date'] = NULL;
1216 }
1217
1218 $this->set('params', $this->_params);
1219 $this->assign('trxn_id', $result['trxn_id']);
1220 $this->assign('receive_date',
1221 CRM_Utils_Date::processDate($this->_params['receive_date'])
1222 );
1223
1224 //add contribution record
1225 $this->_params['financial_type_id']
1226 = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'financial_type_id');
1227 $this->_params['mode'] = $this->_mode;
1228
1229 //add contribution record
1230 $contributions[] = $contribution = CRM_Event_Form_Registration_Confirm::processContribution($this, $this->_params, $result, $contactID, FALSE);
1231
1232 // add participant record
1233 $participants = array();
1234 if (!empty($this->_params['role_id']) && is_array($this->_params['role_id'])) {
1235 $this->_params['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR,
1236 $this->_params['role_id']
1237 );
1238 }
1239
1240 //CRM-15372 patch to fix fee amount replacing amount
1241 $this->_params['fee_amount'] = $this->_params['amount'];
1242
1243 $participants[] = CRM_Event_Form_Registration::addParticipant($this, $contactID);
1244
1245 //add custom data for participant
1246 CRM_Core_BAO_CustomValueTable::postProcess($this->_params,
1247 'civicrm_participant',
1248 $participants[0]->id,
1249 'Participant'
1250 );
1251 //add participant payment
1252 $paymentParticipant = array(
1253 'participant_id' => $participants[0]->id,
1254 'contribution_id' => $contribution->id,
1255 );
1256 $ids = array();
1257
1258 CRM_Event_BAO_ParticipantPayment::create($paymentParticipant, $ids);
1259 $this->_contactIds[] = $this->_contactId;
1260 }
1261 else {
1262 $participants = array();
1263 if ($this->_single) {
1264 if ($params['role_id']) {
1265 $params['role_id'] = $roleIdWithSeparator;
1266 }
1267 else {
1268 $params['role_id'] = 'NULL';
1269 }
1270 $participants[] = CRM_Event_BAO_Participant::create($params);
1271 }
1272 else {
1273 foreach ($this->_contactIds as $contactID) {
1274 $commonParams = $params;
1275 $commonParams['contact_id'] = $contactID;
1276 if ($commonParams['role_id']) {
1277 $commonParams['role_id'] = $commonParams['role_id'] = str_replace(',', CRM_Core_DAO::VALUE_SEPARATOR, $params['role_id']);
1278 }
1279 else {
1280 $commonParams['role_id'] = 'NULL';
1281 }
1282 $participants[] = CRM_Event_BAO_Participant::create($commonParams);
1283 }
1284 }
1285
1286 if (isset($params['event_id'])) {
1287 $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event',
1288 $params['event_id'],
1289 'title'
1290 );
1291 }
1292
1293 if ($this->_single) {
1294 $this->_contactIds[] = $this->_contactId;
1295 }
1296
1297 $contributions = array();
1298 if (!empty($params['record_contribution'])) {
1299 if (!empty($params['id'])) {
1300 if ($this->_onlinePendingContributionId) {
1301 $ids['contribution'] = $this->_onlinePendingContributionId;
1302 }
1303 else {
1304 $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
1305 $params['id'],
1306 'contribution_id',
1307 'participant_id'
1308 );
1309 }
1310 }
1311 unset($params['note']);
1312
1313 //build contribution params
1314 if (!$this->_onlinePendingContributionId) {
1315 if (empty($params['source'])) {
1316 $contributionParams['source'] = ts('%1 : Offline registration (by %2)', array(
1317 1 => $eventTitle,
1318 2 => $userName,
1319 ));
1320 }
1321 else {
1322 $contributionParams['source'] = $params['source'];
1323 }
1324 }
1325
1326 $contributionParams['currency'] = $config->defaultCurrency;
1327 $contributionParams['non_deductible_amount'] = 'null';
1328 $contributionParams['receipt_date'] = !empty($params['send_receipt']) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
1329
1330 $recordContribution = array(
1331 'contact_id',
1332 'financial_type_id',
1333 'payment_instrument_id',
1334 'trxn_id',
1335 'contribution_status_id',
1336 'receive_date',
1337 'check_number',
1338 'campaign_id',
1339 );
1340
1341 foreach ($recordContribution as $f) {
1342 $contributionParams[$f] = CRM_Utils_Array::value($f, $params);
1343 if ($f == 'trxn_id') {
1344 $this->assign('trxn_id', $contributionParams[$f]);
1345 }
1346 }
1347
1348 //insert financial type name in receipt.
1349 $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionParams['financial_type_id']));
1350 $contributionParams['skipLineItem'] = 1;
1351 if ($this->_id) {
1352 $contributionParams['contribution_mode'] = 'participant';
1353 $contributionParams['participant_id'] = $this->_id;
1354 }
1355 // Set is_pay_later flag for back-office offline Pending status contributions
1356 if ($contributionParams['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
1357 $contributionParams['is_pay_later'] = 1;
1358 }
1359 elseif ($contributionParams['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
1360 $contributionParams['is_pay_later'] = 0;
1361 }
1362
1363 if ($params['status_id'] == array_search('Partially paid', $participantStatus)) {
1364 if (!$amountOwed && $this->_action & CRM_Core_Action::UPDATE) {
1365 $amountOwed = $params['fee_amount'];
1366 }
1367
1368 // if multiple participants are link, consider contribution total amount as the amount Owed
1369 if ($this->_id && CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
1370 $amountOwed = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
1371 $ids['contribution'],
1372 'total_amount'
1373 );
1374 }
1375
1376 // CRM-13964 partial_payment_total
1377 if ($amountOwed > $params['total_amount']) {
1378 // the owed amount
1379 $contributionParams['partial_payment_total'] = $amountOwed;
1380 // the actual amount paid
1381 $contributionParams['partial_amount_pay'] = $params['total_amount'];
1382 }
1383 }
1384
1385 if (CRM_Utils_Array::value('tax_amount', $this->_params)) {
1386 $contributionParams['tax_amount'] = $this->_params['tax_amount'];
1387 }
1388
1389 if ($this->_single) {
1390 if (empty($ids)) {
1391 $ids = array();
1392 }
1393 $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
1394 }
1395 else {
1396 $ids = array();
1397 foreach ($this->_contactIds as $contactID) {
1398 $contributionParams['contact_id'] = $contactID;
1399 $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
1400 }
1401 }
1402
1403 //insert payment record for this participation
1404 if (empty($ids['contribution'])) {
1405 foreach ($this->_contactIds as $num => $contactID) {
1406 $ppDAO = new CRM_Event_DAO_ParticipantPayment();
1407 $ppDAO->participant_id = $participants[$num]->id;
1408 $ppDAO->contribution_id = $contributions[$num]->id;
1409 $ppDAO->save();
1410 }
1411 }
1412 // next create the transaction record
1413 $transaction = new CRM_Core_Transaction();
1414
1415 // CRM-11124
1416 if ($this->_quickConfig) {
1417 if (!empty($this->_params['amount_priceset_level_radio'])) {
1418 $feeLevel = $this->_params['amount_priceset_level_radio'];
1419 }
1420 else {
1421 $feeLevel[] = $this->_params['fee_level'];
1422 }
1423 CRM_Event_BAO_Participant::createDiscountTrxn($this->_eventId, $contributionParams, $feeLevel);
1424 }
1425 $transaction->commit();
1426 }
1427 }
1428
1429 // also store lineitem stuff here
1430 if ((($this->_lineItem & $this->_action & CRM_Core_Action::ADD) ||
1431 ($this->_lineItem && CRM_Core_Action::UPDATE && !$this->_paymentId))
1432 ) {
1433 foreach ($this->_contactIds as $num => $contactID) {
1434 foreach ($this->_lineItem as $key => $value) {
1435 if (is_array($value) && $value != 'skip') {
1436 foreach ($value as $lineKey => $line) {
1437 //10117 update the line items for participants if contribution amount is recorded
1438 if ($this->_quickConfig && !empty($params['total_amount']) &&
1439 ($params['status_id'] != array_search('Partially paid', $participantStatus))
1440 ) {
1441 $line['unit_price'] = $line['line_total'] = $params['total_amount'];
1442 if (!empty($params['tax_amount'])) {
1443 $line['unit_price'] = $line['unit_price'] - $params['tax_amount'];
1444 $line['line_total'] = $line['line_total'] - $params['tax_amount'];
1445 }
1446 }
1447 $lineItem[$this->_priceSetId][$lineKey] = $line;
1448 }
1449 CRM_Price_BAO_LineItem::processPriceSet($participants[$num]->id, $lineItem, CRM_Utils_Array::value($num, $contributions, NULL), 'civicrm_participant');
1450 }
1451 }
1452 }
1453 }
1454
1455 $updateStatusMsg = NULL;
1456 //send mail when participant status changed, CRM-4326
1457 if ($this->_id && $this->_statusId &&
1458 $this->_statusId != CRM_Utils_Array::value('status_id', $params) && !empty($params['is_notify'])
1459 ) {
1460
1461 $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_id,
1462 $params['status_id'],
1463 $this->_statusId
1464 );
1465 }
1466
1467 $sent = array();
1468 $notSent = array();
1469 if (!empty($params['send_receipt'])) {
1470 if (array_key_exists($params['from_email_address'], $this->_fromEmails['from_email_id'])) {
1471 $receiptFrom = $params['from_email_address'];
1472 }
1473
1474 $this->assign('module', 'Event Registration');
1475 //use of the message template below requires variables in different format
1476 $event = $events = array();
1477 $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
1478
1479 //get all event details.
1480 CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
1481 $event = $events[$params['event_id']];
1482 unset($event['start_date']);
1483 unset($event['end_date']);
1484
1485 $role = CRM_Event_PseudoConstant::participantRole();
1486 $participantRoles = CRM_Utils_Array::value('role_id', $params);
1487 if (is_array($participantRoles)) {
1488 $selectedRoles = array();
1489 foreach ($participantRoles as $roleId) {
1490 $selectedRoles[] = $role[$roleId];
1491 }
1492 $event['participant_role'] = implode(', ', $selectedRoles);
1493 }
1494 else {
1495 $event['participant_role'] = CRM_Utils_Array::value($participantRoles, $role);
1496 }
1497 $event['is_monetary'] = $this->_isPaidEvent;
1498
1499 if ($params['receipt_text']) {
1500 $event['confirm_email_text'] = $params['receipt_text'];
1501 }
1502
1503 $this->assign('isAmountzero', 1);
1504 $this->assign('event', $event);
1505
1506 $this->assign('isShowLocation', $event['is_show_location']);
1507 if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
1508 $locationParams = array(
1509 'entity_id' => $params['event_id'],
1510 'entity_table' => 'civicrm_event',
1511 );
1512 $location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
1513 $this->assign('location', $location);
1514 }
1515
1516 $status = CRM_Event_PseudoConstant::participantStatus();
1517 if ($this->_isPaidEvent) {
1518 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
1519 if (!$this->_mode) {
1520 if (isset($params['payment_instrument_id'])) {
1521 $this->assign('paidBy',
1522 CRM_Utils_Array::value($params['payment_instrument_id'],
1523 $paymentInstrument
1524 )
1525 );
1526 }
1527 }
1528
1529 $this->assign('totalAmount', $contributionParams['total_amount']);
1530 if (isset($contributionParams['partial_payment_total'])) {
1531 // balance amount
1532 $balanceAmount = $contributionParams['partial_payment_total'] - $contributionParams['partial_amount_pay'];
1533 $this->assign('balanceAmount', $balanceAmount);
1534 }
1535 $this->assign('isPrimary', 1);
1536 $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
1537 }
1538 if ($this->_mode) {
1539 if (!empty($params['billing_first_name'])) {
1540 $name = $params['billing_first_name'];
1541 }
1542
1543 if (!empty($params['billing_middle_name'])) {
1544 $name .= " {$params['billing_middle_name']}";
1545 }
1546
1547 if (!empty($params['billing_last_name'])) {
1548 $name .= " {$params['billing_last_name']}";
1549 }
1550 $this->assign('billingName', $name);
1551
1552 // assign the address formatted up for display
1553 $addressParts = array(
1554 "street_address-{$this->_bltID}",
1555 "city-{$this->_bltID}",
1556 "postal_code-{$this->_bltID}",
1557 "state_province-{$this->_bltID}",
1558 "country-{$this->_bltID}",
1559 );
1560 $addressFields = array();
1561 foreach ($addressParts as $part) {
1562 list($n, $id) = explode('-', $part);
1563 if (isset($this->_params['billing_' . $part])) {
1564 $addressFields[$n] = $this->_params['billing_' . $part];
1565 }
1566 }
1567 $this->assign('address', CRM_Utils_Address::format($addressFields));
1568
1569 $date = CRM_Utils_Date::format($params['credit_card_exp_date']);
1570 $date = CRM_Utils_Date::mysqlToIso($date);
1571 $this->assign('credit_card_exp_date', $date);
1572 $this->assign('credit_card_number',
1573 CRM_Utils_System::mungeCreditCard($params['credit_card_number'])
1574 );
1575 $this->assign('credit_card_type', $params['credit_card_type']);
1576 // The concept of contributeMode is deprecated.
1577 $this->assign('contributeMode', 'direct');
1578 $this->assign('isAmountzero', 0);
1579 $this->assign('is_pay_later', 0);
1580 $this->assign('isPrimary', 1);
1581 }
1582
1583 $this->assign('register_date', $params['register_date']);
1584 if ($params['receive_date']) {
1585 $this->assign('receive_date', $params['receive_date']);
1586 }
1587
1588 $participant = array(array('participant_id', '=', $participants[0]->id, 0, 0));
1589 // check whether its a test drive ref CRM-3075
1590 if (!empty($this->_defaultValues['is_test'])) {
1591 $participant[] = array('participant_test', '=', 1, 0, 0);
1592 }
1593
1594 $template = CRM_Core_Smarty::singleton();
1595 $customGroup = array();
1596 //format submitted data
1597 foreach ($params['custom'] as $fieldID => $values) {
1598 foreach ($values as $fieldValue) {
1599 $customValue = array('data' => $fieldValue['value']);
1600 $customFields[$fieldID]['id'] = $fieldID;
1601 $formattedValue = CRM_Core_BAO_CustomGroup::formatCustomValues($customValue, $customFields[$fieldID], TRUE);
1602 $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
1603 }
1604 }
1605
1606 foreach ($this->_contactIds as $num => $contactID) {
1607 // Retrieve the name and email of the contact - this will be the TO for receipt email
1608 list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
1609
1610 $this->_contributorDisplayName = ($this->_contributorDisplayName == ' ') ? $this->_contributorEmail : $this->_contributorDisplayName;
1611
1612 $waitStatus = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
1613 if ($waitingStatus = CRM_Utils_Array::value($params['status_id'], $waitStatus)) {
1614 $this->assign('isOnWaitlist', TRUE);
1615 }
1616
1617 $this->assign('customGroup', $customGroup);
1618 $this->assign('contactID', $contactID);
1619 $this->assign('participantID', $participants[$num]->id);
1620
1621 $this->_id = $participants[$num]->id;
1622
1623 if ($this->_isPaidEvent) {
1624 // fix amount for each of participants ( for bulk mode )
1625 $eventAmount = array();
1626 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
1627 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
1628 $totalTaxAmount = 0;
1629
1630 //add dataArray in the receipts in ADD and UPDATE condition
1631 $dataArray = array();
1632 if ($this->_action & CRM_Core_Action::ADD) {
1633 $line = $lineItem[0];
1634 }
1635 elseif ($this->_action & CRM_Core_Action::UPDATE) {
1636 $line = $this->_values['line_items'];
1637 }
1638 if ($invoicing) {
1639 foreach ($line as $key => $value) {
1640 if (isset($value['tax_amount'])) {
1641 $totalTaxAmount += $value['tax_amount'];
1642 if (isset($dataArray[(string) $value['tax_rate']])) {
1643 $dataArray[(string) $value['tax_rate']] = $dataArray[(string) $value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
1644 }
1645 else {
1646 $dataArray[(string) $value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
1647 }
1648 }
1649 }
1650 $this->assign('totalTaxAmount', $totalTaxAmount);
1651 $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
1652 $this->assign('dataArray', $dataArray);
1653 }
1654 if (!empty($additionalParticipantDetails)) {
1655 $params['amount_level'] = preg_replace('/\ 1/', '', $params['amount_level']) . ' - ' . $this->_contributorDisplayName;
1656 }
1657
1658 $eventAmount[$num] = array(
1659 'label' => preg_replace('/\ 1/', '', $params['amount_level']),
1660 'amount' => $params['fee_amount'],
1661 );
1662 //as we are using same template for online & offline registration.
1663 //So we have to build amount as array.
1664 $eventAmount = array_merge($eventAmount, $additionalParticipantDetails);
1665 $this->assign('amount', $eventAmount);
1666 }
1667
1668 $sendTemplateParams = array(
1669 'groupName' => 'msg_tpl_workflow_event',
1670 'valueName' => 'event_offline_receipt',
1671 'contactId' => $contactID,
1672 'isTest' => (bool) CRM_Utils_Array::value('is_test', $this->_defaultValues),
1673 'PDFFilename' => ts('confirmation') . '.pdf',
1674 );
1675
1676 // try to send emails only if email id is present
1677 // and the do-not-email option is not checked for that contact
1678 if ($this->_contributorEmail and !$this->_toDoNotEmail) {
1679 $sendTemplateParams['from'] = $receiptFrom;
1680 $sendTemplateParams['toName'] = $this->_contributorDisplayName;
1681 $sendTemplateParams['toEmail'] = $this->_contributorEmail;
1682 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc', $this->_fromEmails);
1683 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc', $this->_fromEmails);
1684 }
1685
1686 //send email with pdf invoice
1687 $template = CRM_Core_Smarty::singleton();
1688 $taxAmt = $template->get_template_vars('dataArray');
1689 $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
1690 $this->_id, 'contribution_id', 'participant_id'
1691 );
1692 $prefixValue = Civi::settings()->get('contribution_invoice_settings');
1693 $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
1694 if (count($taxAmt) > 0 && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
1695 $sendTemplateParams['isEmailPdf'] = TRUE;
1696 $sendTemplateParams['contributionId'] = $contributionId;
1697 }
1698 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
1699 if ($mailSent) {
1700 $sent[] = $contactID;
1701 foreach ($participants as $ids => $values) {
1702 if ($values->contact_id == $contactID) {
1703 $values->details = CRM_Utils_Array::value('receipt_text', $params);
1704 CRM_Activity_BAO_Activity::addActivity($values, 'Email');
1705 break;
1706 }
1707 }
1708 }
1709 else {
1710 $notSent[] = $contactID;
1711 }
1712 }
1713 }
1714
1715 // set the participant id if it is not set
1716 if (!$this->_id) {
1717 $this->_id = $participants[0]->id;
1718 }
1719
1720 if (($this->_action & CRM_Core_Action::UPDATE)) {
1721 $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contributorDisplayName));
1722 if (!empty($params['send_receipt']) && count($sent)) {
1723 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', array(1 => $this->_contributorEmail));
1724 }
1725
1726 if ($updateStatusMsg) {
1727 $statusMsg = "{$statusMsg} {$updateStatusMsg}";
1728 }
1729 }
1730 elseif ($this->_action & CRM_Core_Action::ADD) {
1731 if ($this->_single) {
1732 $statusMsg = ts('Event registration for %1 has been added.', array(1 => $this->_contributorDisplayName));
1733 if (!empty($params['send_receipt']) && count($sent)) {
1734 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $this->_contributorEmail));
1735 }
1736 }
1737 else {
1738 $statusMsg = ts('Total Participant(s) added to event: %1.', array(1 => count($this->_contactIds)));
1739 if (count($notSent) > 0) {
1740 $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)));
1741 }
1742 elseif (isset($params['send_receipt'])) {
1743 $statusMsg .= ' ' . ts('A confirmation email has been sent to ALL participants');
1744 }
1745 }
1746 }
1747 CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
1748
1749 $buttonName = $this->controller->getButtonName();
1750 if ($this->_context == 'standalone') {
1751 if ($buttonName == $this->getButtonName('upload', 'new')) {
1752 $urlParams = 'reset=1&action=add&context=standalone';
1753 if ($this->_mode) {
1754 $urlParams .= '&mode=' . $this->_mode;
1755 }
1756 if ($this->_eID) {
1757 $urlParams .= '&eid=' . $this->_eID;
1758 }
1759 $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', $urlParams));
1760 }
1761 else {
1762 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
1763 "reset=1&cid={$this->_contactId}&selectedChild=participant"
1764 ));
1765 }
1766 }
1767 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1768 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant',
1769 "reset=1&action=add&context={$this->_context}&cid={$this->_contactId}"
1770 ));
1771 }
1772 }
1773
1774 }