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