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