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