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