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