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