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