Merge pull request #790 from JoeMurray/CRM-12657
[civicrm-core.git] / CRM / Event / Form / Participant.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
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::locationType();
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);
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 if ($contributionTypeId) {
579 $defaults[$this->_id]['financial_type_id'] = $contributionTypeId;
580 }
581 }
582
583 if ($this->_mode) {
584 $fields["email-{$this->_bltID}"] = 1;
585 $fields['email-Primary'] = 1;
586
587 if ($this->_contactId) {
588 CRM_Core_BAO_UFGroup::setProfileDefaults($this->_contactId, $fields, $defaults);
589 }
590
591 if (empty($defaults["email-{$this->_bltID}"]) &&
592 !empty($defaults['email-Primary'])
593 ) {
594 $defaults[$this->_id]["email-{$this->_bltID}"] = $defaults['email-Primary'];
595 }
596 }
597
598 $submittedRole = $this->getElementValue('role_id');
599 if (CRM_Utils_Array::value(0, $submittedRole)) {
600 $roleID = $submittedRole[0];
601 }
602 $submittedEvent = $this->getElementValue('event_id');
603 if ($submittedEvent[0]) {
604 $eventID = $submittedEvent[0];
605 }
606 }
607 else {
608 $defaults[$this->_id]['record_contribution'] = 0;
609
610 if ($defaults[$this->_id]['participant_is_pay_later']) {
611 $this->assign('participant_is_pay_later', TRUE);
612 }
613
614 $this->assign('participant_status_id', $defaults[$this->_id]['participant_status_id']);
615 $roleID = $defaults[$this->_id]['participant_role_id'];
616 $eventID = $defaults[$this->_id]['event_id'];
617
618 $this->_eventTypeId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventID, 'event_type_id', 'id');
619
620 $this->_discountId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'discount_id');
621 if ($this->_discountId) {
622 $this->set('discountId', $this->_discountId);
623 }
624 }
625
626 list($defaults[$this->_id]['register_date'],
627 $defaults[$this->_id]['register_date_time']
628 ) = CRM_Utils_Date::setDateDefaults(
629 CRM_Utils_Array::value('register_date', $defaults[$this->_id]), 'activityDateTime'
630 );
631
632 //assign event and role id, this is needed for Custom data building
633 $sep = CRM_Core_DAO::VALUE_SEPARATOR;
634 if (CRM_Utils_Array::value('participant_role_id', $defaults[$this->_id])) {
635 $roleIDs = explode($sep, $defaults[$this->_id]['participant_role_id']);
636 }
637 if (isset($roleIDs)) {
638 $this->assign('roleID', $roleIDs);
639 }
640 if (isset($_POST['event_id'])) {
641 $eventID = $_POST['event_id'];
642 if ($eventID) {
643 $this->_eventTypeId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventID, 'event_type_id', 'id');
644 }
645 }
646
647 if (isset($eventID)) {
648 $this->assign('eventID', $eventID);
649 $this->set('eventId', $eventID);
650 }
651
652 if (isset($this->_eventTypeId)) {
653 $this->assign('eventTypeID', $this->_eventTypeId);
654 }
655
656 $this->assign('event_is_test', CRM_Utils_Array::value('event_is_test', $defaults[$this->_id]));
657 return $defaults[$this->_id];
658 }
659
660 /**
661 * Function to build the form
662 *
663 * @return None
664 * @access public
665 */
666 public function buildQuickForm() {
667 if ($this->_showFeeBlock) {
668 return CRM_Event_Form_EventFees::buildQuickForm($this);
669 }
670
671 if ($this->_cdType) {
672 return CRM_Custom_Form_CustomData::buildQuickForm($this);
673 }
674
675 //need to assign custom data type to the template
676 $this->assign('customDataType', 'Participant');
677
678 $this->applyFilter('__ALL__', 'trim');
679
680 if ($this->_action & CRM_Core_Action::DELETE) {
681 if ($this->_single) {
682 $additionalParticipant = count(CRM_Event_BAO_Event::buildCustomProfile($this->_id,
683 NULL,
684 $this->_contactId,
685 FALSE,
686 TRUE
687 )) - 1;
688 if ($additionalParticipant) {
689 $deleteParticipants = array(1 => ts('Delete this participant record along with associated participant record(s).'),
690 2 => ts('Delete only this participant record.'),
691 );
692 $this->addRadio('delete_participant', NULL, $deleteParticipants, NULL, '<br />');
693 $this->setDefaults(array('delete_participant' => 1));
694 $this->assign('additionalParticipant', $additionalParticipant);
695 }
696 }
697 $this->addButtons(array(
698 array(
699 'type' => 'next',
700 'name' => ts('Delete'),
701 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
702 'isDefault' => TRUE,
703 ),
704 array(
705 'type' => 'cancel',
706 'name' => ts('Cancel'),
707 ),
708 )
709 );
710 return;
711 }
712
713
714 if ($this->_single) {
715 $urlPath = 'civicrm/contact/view/participant';
716 $urlParams = "reset=1&cid={$this->_contactId}&context=participant";
717 if ($this->_context == 'standalone') {
718 CRM_Contact_Form_NewContact::buildQuickForm($this);
719 $urlParams = 'reset=1&context=standalone';
720 $urlPath = 'civicrm/participant/add';
721 }
722
723 if ($this->_id) {
724 $urlParams .= "&action=update&id={$this->_id}";
725 }
726 else {
727 $urlParams .= "&action=add";
728 }
729
730 if ($this->_mode) {
731 $urlParams .= "&mode={$this->_mode}";
732 }
733
734 $url = CRM_Utils_System::url($urlPath, $urlParams,
735 FALSE, NULL, FALSE
736 );
737 }
738 else {
739 $currentPath = CRM_Utils_System::currentPath();
740
741 $url = CRM_Utils_System::url($currentPath, '_qf_Participant_display=true',
742 FALSE, NULL, FALSE
743 );
744 }
745
746 $this->assign('refreshURL', $url);
747
748 $this->add('hidden', 'past_event');
749
750 $events = array();
751 if ( $this->_eID ) {
752 $eventEndDate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_eID,'end_date');
753 }
754 $this->assign('past', FALSE);
755 if ($this->_action & CRM_Core_Action::UPDATE) {
756 $events = CRM_Event_BAO_Event::getEvents(TRUE, FALSE, FALSE);
757 }
758 elseif ($this->getElementValue('past_event') || (isset($eventEndDate) && (CRM_Utils_Date::currentDBDate() > CRM_Utils_Date::processDate($eventEndDate)))) {
759 $events = CRM_Event_BAO_Event::getEvents(TRUE);
760 $this->assign('past', TRUE);
761 }
762 else {
763 $events = CRM_Event_BAO_Event::getEvents();
764 }
765
766 if ($this->_mode) {
767 //unset the event which are not monetary when credit card
768 //event registration is used
769 foreach ($events as $key => $val) {
770 $isPaid = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $key, 'is_monetary');
771 if (!$isPaid) {
772 unset($events[$key]);
773 }
774 }
775 $this->add('select', 'payment_processor_id', ts('Payment Processor'), $this->_processors, TRUE);
776 }
777
778 // build array(event -> eventType) mapper
779 $query = "
780 SELECT civicrm_event.id as id, civicrm_event.event_type_id as event_type_id
781 FROM civicrm_event
782 WHERE civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0";
783 $dao = CRM_Core_DAO::executeQuery($query);
784 $eventAndTypeMapping = array();
785 while ($dao->fetch()) {
786 $eventAndTypeMapping[$dao->id] = $dao->event_type_id;
787 }
788 $eventAndTypeMapping = json_encode($eventAndTypeMapping);
789 // building of mapping ends --
790
791 //inherit the campaign from event.
792 $eventCampaigns = array();
793 $allEventIds = array_keys($events);
794 if (!empty($allEventIds)) {
795 CRM_Core_PseudoConstant::populate($eventCampaigns,
796 'CRM_Event_DAO_Event',
797 TRUE, 'campaign_id'
798 );
799 }
800 $eventCampaigns = json_encode($eventCampaigns);
801
802 $element = $this->add('select', 'event_id', ts('Event'),
803 array(
804 '' => ts('- select -')) + $events,
805 TRUE,
806 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')
807 );
808
809 // CRM-6111
810 // note that embedding JS within PHP files is quite awful, IMO
811 // but we do the same for the onChange element and this form is complex
812 // and i did not want to break it late in the 3.2 cycle
813 $preloadJSSnippet = NULL;
814 if (CRM_Utils_Array::value('reset', $_GET) && $this->_eID) {
815 $preloadJSSnippet = "
816 cj(function() {
817 cj('#event_id').val( '{$this->_eID}' );
818 buildFeeBlock( {$this->_eID} );
819 CRM.buildCustomData( 'Participant', {$this->_eID}, {$this->_eventNameCustomDataTypeID} );
820 buildEventTypeCustomData( {$this->_eID}, {$this->_eventTypeCustomDataTypeID}, '{$eventAndTypeMapping}' );
821 loadCampaign( {$this->_eID}, {$eventCampaigns} );
822 });
823 ";
824 }
825
826 $this->assign('preloadJSSnippet', $preloadJSSnippet);
827
828
829 //frozen the field fix for CRM-4171
830 if ($this->_action & CRM_Core_Action::UPDATE && $this->_id) {
831 if (CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
832 $this->_id, 'contribution_id', 'participant_id'
833 )) {
834 $element->freeze();
835 }
836 }
837
838 //CRM-7362 --add campaigns.
839 $campaignId = NULL;
840 if ($this->_id) {
841 $campaignId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'campaign_id');
842 }
843 if (!$campaignId) {
844 $eventId = CRM_Utils_Request::retrieve('eid', 'Positive', $this);
845 if ($eventId) {
846 $campaignId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventId, 'campaign_id');
847 }
848 }
849 CRM_Campaign_BAO_Campaign::addCampaign($this, $campaignId);
850
851 $this->addDateTime('register_date', ts('Registration Date'), TRUE, array('formatType' => 'activityDateTime'));
852
853 if ($this->_id) {
854 $this->assign('entityID', $this->_id);
855 }
856
857 $roleids = CRM_Event_PseudoConstant::participantRole();
858
859 foreach ($roleids as $rolekey => $rolevalue) {
860 $roleTypes[] = $this->createElement('checkbox', $rolekey, NULL, $rolevalue,
861 array('onclick' => "showCustomData( 'Participant', {$rolekey}, {$this->_roleCustomDataTypeID} );")
862 );
863 }
864
865 $this->addGroup($roleTypes, 'role_id', ts('Participant Role'));
866 $this->addRule('role_id', ts('Role is required'), 'required');
867
868 // CRM-4395
869 $checkCancelledJs = array('onchange' => "return sendNotification( );");
870 $confirmJS = NULL;
871 if ($this->_onlinePendingContributionId) {
872 $cancelledparticipantStatusId = array_search('Cancelled', CRM_Event_PseudoConstant::participantStatus());
873 $cancelledContributionStatusId = array_search('Cancelled',
874 CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')
875 );
876 $checkCancelledJs = array(
877 'onchange' =>
878 "checkCancelled( this.value, {$cancelledparticipantStatusId},{$cancelledContributionStatusId});",
879 );
880
881 $participantStatusId = array_search('Pending from pay later',
882 CRM_Event_PseudoConstant::participantStatus()
883 );
884 $contributionStatusId = array_search('Completed',
885 CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')
886 );
887 $confirmJS = array('onclick' => "return confirmStatus( {$participantStatusId}, {$contributionStatusId} );");
888 }
889
890 $this->_participantStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label');
891 $this->add('select', 'status_id', ts('Participant Status'),
892 array(
893 '' => ts('- select -')) + $this->_participantStatuses,
894 TRUE,
895 $checkCancelledJs
896 );
897
898 $this->addElement('checkbox', 'is_notify', ts('Send Notification'), NULL);
899
900 $this->add('text', 'source', ts('Event Source'));
901 $noteAttributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_Note');
902 $this->add('textarea', 'note', ts('Notes'), $noteAttributes['note']);
903
904 $buttons[] = array(
905 'type' => 'upload',
906 'name' => ts('Save'),
907 'isDefault' => TRUE,
908 'js' => $confirmJS,
909 );
910
911 $path = CRM_Utils_System::currentPath();
912 if (strpos($path, 'civicrm/contact/search') !== 0) {
913 $buttons[] = array(
914 'type' => 'upload',
915 'name' => ts('Save and New'),
916 'subName' => 'new',
917 'js' => $confirmJS,
918 );
919 }
920 $buttons[] = array(
921 'type' => 'cancel',
922 'name' => ts('Cancel'),
923 );
924
925 $this->addButtons($buttons);
926 if ($this->_action == CRM_Core_Action::VIEW) {
927 $this->freeze();
928 }
929 }
930
931 /**
932 * Add local and global form rules
933 *
934 * @access protected
935 *
936 * @return void
937 */
938 function addRules() {
939 $this->addFormRule(array('CRM_Event_Form_Participant', 'formRule'), $this);
940 }
941
942 /**
943 * global validation rules for the form
944 *
945 * @param array $fields posted values of the form
946 *
947 * @return array list of errors to be posted back to the form
948 * @static
949 * @access public
950 */
951 static function formRule($values, $files, $self) {
952 // If $values['_qf_Participant_next'] is Delete or
953 // $values['event_id'] is empty, then return
954 // instead of proceeding further.
955
956 if ((CRM_Utils_Array::value('_qf_Participant_next', $values) == 'Delete') ||
957 (!$values['event_id'])
958 ) {
959 return TRUE;
960 }
961
962 $errorMsg = array();
963 //check if contact is selected in standalone mode
964 if (isset($values['contact_select_id'][1]) && !$values['contact_select_id'][1]) {
965 $errorMsg['contact[1]'] = ts('Please select a contact or create new contact');
966 }
967
968 if (CRM_Utils_Array::value('payment_processor_id', $values)) {
969 // make sure that credit card number and cvv are valid
970 CRM_Core_Payment_Form::validateCreditCard($values, $errorMsg);
971 }
972
973 if (CRM_Utils_Array::value('record_contribution', $values) && !CRM_Utils_Array::value('financial_type_id', $values)) {
974 $errorMsg['financial_type_id'] = ts('Please enter the associated Financial Type');
975 }
976
977 // validate contribution status for 'Failed'.
978 if ($self->_onlinePendingContributionId &&
979 CRM_Utils_Array::value('record_contribution', $values) &&
980 (CRM_Utils_Array::value('contribution_status_id', $values) ==
981 array_search('Failed', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'))
982 )
983 ) {
984 $errorMsg['contribution_status_id'] = ts('Please select a valid payment status before updating.');
985 }
986
987 // do the amount validations.
988 //skip for update mode since amount is freeze, CRM-6052
989 if ((!$self->_id &&
990 !CRM_Utils_Array::value('total_amount', $values) &&
991 empty($self->_values['line_items'])
992 ) ||
993 ($self->_id && !$self->_paymentId && isset($self->_values['line_items']) && is_array($self->_values['line_items']))
994 ) {
995 if ($priceSetId = CRM_Utils_Array::value('priceSetId', $values)) {
996 CRM_Price_BAO_Field::priceSetValidation($priceSetId, $values, $errorMsg, TRUE);
997 }
998 }
999 return CRM_Utils_Array::crmIsEmptyArray($errorMsg) ? TRUE : $errorMsg;
1000 }
1001
1002 /**
1003 * Function to process the form
1004 *
1005 * @access public
1006 */
1007 public function postProcess() {
1008 // get the submitted form values.
1009 $params = $this->controller->exportValues($this->_name);
1010
1011 if ($this->_action & CRM_Core_Action::DELETE) {
1012 if (CRM_Utils_Array::value('delete_participant', $params) == 2) {
1013 $additionalId = (CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id));
1014 $participantLinks = (CRM_Event_BAO_Participant::getAdditionalParticipantUrl($additionalId));
1015 }
1016 if (CRM_Utils_Array::value('delete_participant', $params) == 1) {
1017 $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
1018 foreach ($additionalIds as $value) {
1019 CRM_Event_BAO_Participant::deleteParticipant($value);
1020 }
1021 }
1022 CRM_Event_BAO_Participant::deleteParticipant($this->_id);
1023 CRM_Core_Session::setStatus(ts('Selected participant was deleted successfully.'), ts('Record Deleted'), 'success');
1024 if (!empty($participantLinks)) {
1025 $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;
1026 CRM_Core_Session::setStatus($status, ts('Group Payment Deleted'));
1027 }
1028 return;
1029 }
1030
1031 // set the contact, when contact is selected
1032 if (CRM_Utils_Array::value('contact_select_id', $params)) {
1033 $this->_contactId = $params['contact_select_id'][1];
1034 }
1035 if ($this->_priceSetId && $isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', $this->_priceSetId, 'is_quick_config')) {
1036 $this->_quickConfig = $isQuickConfig;
1037 }
1038
1039 if ($this->_id) {
1040 $params['id'] = $this->_id;
1041 }
1042
1043 $config = CRM_Core_Config::singleton();
1044 if ($this->_isPaidEvent) {
1045
1046 $contributionParams = array();
1047 $lineItem = array();
1048 $additionalParticipantDetails = array();
1049 if (($this->_id && $this->_action & CRM_Core_Action::UPDATE) && $this->_paymentId) {
1050 $participantBAO = new CRM_Event_BAO_Participant();
1051 $participantBAO->id = $this->_id;
1052 $participantBAO->find(TRUE);
1053 $contributionParams['total_amount'] = $participantBAO->fee_amount;
1054
1055 $params['discount_id'] = NULL;
1056 //re-enter the values for UPDATE mode
1057 $params['fee_level'] = $params['amount_level'] = $participantBAO->fee_level;
1058 $params['fee_amount'] = $participantBAO->fee_amount;
1059 if (isset($params['priceSetId'])) {
1060 $lineItem[0] = CRM_Price_BAO_LineItem::getLineItems($this->_id);
1061 }
1062 //also add additional participant's fee level/priceset
1063 if (CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
1064 $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
1065 $hasLineItems = CRM_Utils_Array::value('priceSetId', $params, FALSE);
1066 $additionalParticipantDetails = CRM_Event_BAO_Participant::getFeeDetails($additionalIds,
1067 $hasLineItems
1068 );
1069 }
1070 }
1071 else {
1072
1073 //check if discount is selected
1074 if (CRM_Utils_Array::value('discount_id', $params)) {
1075 $discountId = $params['discount_id'];
1076 }
1077 else {
1078 $discountId = $params['discount_id'] = 'null';
1079 }
1080
1081 //lets carry currency, CRM-4453
1082 $params['fee_currency'] = $config->defaultCurrency;
1083 // fix for CRM-3088
1084 if ($discountId &&
1085 !empty($this->_values['discount'][$discountId])
1086 ) {
1087 $params['amount_level'] = $this->_values['discount'][$discountId][$params['amount']]['label'];
1088 $params['amount'] = $this->_values['discount'][$discountId][$params['amount']]['value'];
1089 }
1090 elseif (!isset($params['priceSetId']) && CRM_Utils_Array::value('amount', $params)) {
1091 $params['amount_level'] = $this->_values['fee'][$params['amount']]['label'];
1092 $params['amount'] = $this->_values['fee'][$params['amount']]['value'];
1093 }
1094 else {
1095 CRM_Price_BAO_Set::processAmount($this->_values['fee'],
1096 $params, $lineItem[0]
1097 );
1098 }
1099 //CRM-11529 for quick config backoffice transactions
1100 //when financial_type_id is passed in form, update the
1101 //lineitems with the financial type selected in form
1102 $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $params);
1103 $isPaymentRecorded = CRM_Utils_Array::value('record_contribution', $params);
1104 if ($isPaymentRecorded && $this->_quickConfig && $submittedFinancialType) {
1105 foreach ($lineItem[0] as &$values) {
1106 $values['financial_type_id'] = $submittedFinancialType;
1107 }
1108 }
1109
1110 $params['fee_level'] = $params['amount_level'];
1111 $contributionParams['total_amount'] = $params['amount'];
1112 if ($this->_quickConfig && CRM_Utils_Array::value('total_amount', $params)) {
1113 $params['fee_amount'] = $params['total_amount'];
1114 } else {
1115 //fix for CRM-3086
1116 $params['fee_amount'] = $params['amount'];
1117 }
1118 }
1119
1120 if (isset($params['priceSetId'])) {
1121 if (!empty($lineItem[0])) {
1122 $this->set('lineItem', $lineItem);
1123
1124 $this->_lineItem = $lineItem;
1125 $lineItem = array_merge($lineItem, $additionalParticipantDetails);
1126
1127 $participantCount = array();
1128 foreach ($lineItem as $k) {
1129 foreach ($k as $v) {
1130 if (CRM_Utils_Array::value('participant_count', $v) > 0) {
1131 $participantCount[] = $v['participant_count'];
1132 }
1133 }
1134 }
1135 }
1136 if (isset($participantCount)) {
1137 $this->assign('pricesetFieldsCount', $participantCount);
1138 }
1139 $this->assign('lineItem', empty($lineItem[0]) || $this->_quickConfig? FALSE : $lineItem);
1140 }
1141 else {
1142 $this->assign('amount_level', $params['amount_level']);
1143 }
1144 }
1145
1146 $this->_params = $params;
1147 unset($params['amount']);
1148 $params['register_date'] = CRM_Utils_Date::processDate($params['register_date'], $params['register_date_time']);
1149 $params['receive_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $params));
1150 $params['contact_id'] = $this->_contactId;
1151
1152 // overwrite actual payment amount if entered
1153 if (CRM_Utils_Array::value('total_amount', $params)) {
1154 $contributionParams['total_amount'] = CRM_Utils_Array::value('total_amount', $params);
1155 }
1156
1157
1158 // Retrieve the name and email of the current user - this will be the FROM for the receipt email
1159 $session = CRM_Core_Session::singleton();
1160 $userID = $session->get('userID');
1161 list($userName,
1162 $userEmail
1163 ) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
1164
1165 if ($this->_contactId) {
1166 list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_contactId);
1167 }
1168
1169 if ($this->_mode) {
1170 if (!$this->_isPaidEvent) {
1171 CRM_Core_Error::fatal(ts('Selected Event is not Paid Event '));
1172 }
1173 //modify params according to parameter used in create
1174 //participant method (addParticipant)
1175 $this->_params['participant_status_id'] = $params['status_id'];
1176 $this->_params['participant_role_id'] = $params['role_id'];
1177 $this->_params['participant_register_date'] = $params['register_date'];
1178
1179 $eventTitle =
1180 CRM_Core_DAO::getFieldValue(
1181 'CRM_Event_DAO_Event',
1182 $params['event_id'],
1183 'title'
1184 );
1185
1186 // set source if not set
1187 if (empty($params['source'])) {
1188 $this->_params['participant_source'] = ts('Offline Registration for Event: %2 by: %1', array(1 => $userName, 2 => $eventTitle));
1189 }
1190 else {
1191 $this->_params['participant_source'] = $params['source'];
1192 }
1193 $this->_params['description'] = $this->_params['participant_source'];
1194
1195 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'],
1196 $this->_mode
1197 );
1198 $now = date('YmdHis');
1199 $fields = array();
1200
1201 // set email for primary location.
1202 $fields['email-Primary'] = 1;
1203 $params['email-Primary'] = $params["email-{$this->_bltID}"] = $this->_contributorEmail;
1204
1205 $params['register_date'] = $now;
1206
1207 // now set the values for the billing location.
1208 foreach ($this->_fields as $name => $dontCare) {
1209 $fields[$name] = 1;
1210 }
1211
1212 // also add location name to the array
1213 $params["address_name-{$this->_bltID}"] =
1214 CRM_Utils_Array::value('billing_first_name', $params) . ' ' .
1215 CRM_Utils_Array::value('billing_middle_name', $params) . ' ' .
1216 CRM_Utils_Array::value('billing_last_name', $params);
1217
1218 $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
1219 $fields["address_name-{$this->_bltID}"] = 1;
1220 $fields["email-{$this->_bltID}"] = 1;
1221 $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'contact_type');
1222
1223 $nameFields = array('first_name', 'middle_name', 'last_name');
1224
1225 foreach ($nameFields as $name) {
1226 $fields[$name] = 1;
1227 if (array_key_exists("billing_$name", $params)) {
1228 $params[$name] = $params["billing_{$name}"];
1229 $params['preserveDBName'] = TRUE;
1230 }
1231 }
1232 $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactId, NULL, NULL, $ctype);
1233 }
1234
1235 $roleAllIds = CRM_Utils_Array::value('role_id', $params);
1236 if ($roleAllIds) {
1237 foreach ($roleAllIds as $rkey => $rvalue) {
1238 $customFieldsRole = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, $rkey, $this->_roleCustomDataTypeID);
1239 $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant',
1240 FALSE,
1241 FALSE,
1242 CRM_Utils_Array::value('event_id', $params),
1243 $this->_eventNameCustomDataTypeID
1244 );
1245 $customFieldsEventType = CRM_Core_BAO_CustomField::getFields('Participant',
1246 FALSE,
1247 FALSE,
1248 $this->_eventTypeId,
1249 $this->_eventTypeCustomDataTypeID
1250 );
1251 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole,
1252 CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, NULL, TRUE)
1253 );
1254 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
1255 $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEventType, $customFields);
1256 $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
1257 $customFields,
1258 $this->_id,
1259 'Participant'
1260 );
1261 }
1262 }
1263
1264 //do cleanup line items if participant edit the Event Fee.
1265 if (($this->_lineItem || !isset($params['proceSetId'])) && !$this->_paymentId && $this->_id) {
1266 CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_participant');
1267 }
1268
1269 if ($this->_mode) {
1270 // add all the additioanl payment params we need
1271 $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}"]);
1272 $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
1273
1274 $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
1275 $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
1276 $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
1277 $this->_params['amount'] = $params['fee_amount'];
1278 $this->_params['amount_level'] = $params['amount_level'];
1279 $this->_params['currencyID'] = $config->defaultCurrency;
1280 $this->_params['payment_action'] = 'Sale';
1281 $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
1282
1283 // at this point we've created a contact and stored its address etc
1284 // all the payment processors expect the name and address to be in the
1285 // so we copy stuff over to first_name etc.
1286 $paymentParams = $this->_params;
1287 if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
1288 $paymentParams['email'] = $this->_contributorEmail;
1289 }
1290 CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
1291
1292 $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
1293
1294 $result = &$payment->doDirectPayment($paymentParams);
1295
1296 if (is_a($result, 'CRM_Core_Error')) {
1297 CRM_Core_Error::displaySessionError($result);
1298 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/participant',
1299 "reset=1&action=add&cid={$this->_contactId}&context=participant&mode={$this->_mode}"
1300 ));
1301 }
1302
1303 if ($result) {
1304 $this->_params = array_merge($this->_params, $result);
1305 }
1306
1307 $this->_params['receive_date'] = $now;
1308
1309 if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
1310 $this->_params['receipt_date'] = $now;
1311 }
1312 else {
1313 $this->_params['receipt_date'] = NULL;
1314 }
1315
1316 $this->set('params', $this->_params);
1317 $this->assign('trxn_id', $result['trxn_id']);
1318 $this->assign('receive_date',
1319 CRM_Utils_Date::processDate($this->_params['receive_date'])
1320 );
1321
1322 //add contribution record
1323 $this->_params['financial_type_id'] =
1324 CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'financial_type_id');
1325 $this->_params['mode'] = $this->_mode;
1326
1327 //add contribution reocord
1328 $contributions[] = $contribution = CRM_Event_Form_Registration_Confirm::processContribution($this, $this->_params, $result, $contactID, FALSE);
1329
1330 // add participant record
1331 $participants = array();
1332 if (CRM_Utils_Array::value('participant_role_id', $this->_params) && is_array($this->_params['participant_role_id'])) {
1333 $this->_params['participant_role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR,
1334 array_keys($this->_params['participant_role_id'])
1335 );
1336 }
1337 $participants[] = CRM_Event_Form_Registration::addParticipant($this->_params, $contactID);
1338
1339 //add custom data for participant
1340 CRM_Core_BAO_CustomValueTable::postProcess($this->_params,
1341 CRM_Core_DAO::$_nullArray,
1342 'civicrm_participant',
1343 $participants[0]->id,
1344 'Participant'
1345 );
1346 //add participant payment
1347 $paymentParticipant = array(
1348 'participant_id' => $participants[0]->id,
1349 'contribution_id' => $contribution->id,
1350 );
1351 $ids = array();
1352
1353 CRM_Event_BAO_ParticipantPayment::create($paymentParticipant, $ids);
1354 $this->_contactIds[] = $this->_contactId;
1355 }
1356 else {
1357 $participants = array();
1358 if ($this->_single) {
1359 if ($params['role_id']) {
1360 foreach ($params['role_id'] as $k => $v) {
1361 $rolesIDS[] = $k;
1362 }
1363 $seperator = CRM_Core_DAO::VALUE_SEPARATOR;
1364 $params['role_id'] = implode($seperator, $rolesIDS);
1365 }
1366 else {
1367 $params['role_id'] = 'NULL';
1368 }
1369 $participants[] = CRM_Event_BAO_Participant::create($params);
1370 }
1371 else {
1372 foreach ($this->_contactIds as $contactID) {
1373 $commonParams = $params;
1374 $commonParams['contact_id'] = $contactID;
1375 if ($commonParams['role_id']) {
1376 $rolesIDS = array();
1377 foreach ($commonParams['role_id'] as $k => $v) {
1378 $rolesIDS[] = $k;
1379 }
1380 $seperator = CRM_Core_DAO::VALUE_SEPARATOR;
1381 $commonParams['role_id'] = implode($seperator, $rolesIDS);
1382 $commonParams['participant_role_id'] = implode($seperator, $rolesIDS);
1383 }
1384 else {
1385 $commonParams['role_id'] = 'NULL';
1386 }
1387 $participants[] = CRM_Event_BAO_Participant::create($commonParams);
1388 }
1389 }
1390
1391 if (isset($params['event_id'])) {
1392 $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event',
1393 $params['event_id'],
1394 'title'
1395 );
1396 }
1397
1398 if ($this->_single) {
1399 $this->_contactIds[] = $this->_contactId;
1400 }
1401
1402 $contributions = array();
1403 if (CRM_Utils_Array::value('record_contribution', $params)) {
1404 if (CRM_Utils_Array::value('id', $params)) {
1405 if ($this->_onlinePendingContributionId) {
1406 $ids['contribution'] = $this->_onlinePendingContributionId;
1407 }
1408 else {
1409 $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
1410 $params['id'],
1411 'contribution_id',
1412 'participant_id'
1413 );
1414 }
1415 }
1416 unset($params['note']);
1417
1418 //build contribution params
1419 if (!$this->_onlinePendingContributionId) {
1420 $contributionParams['source'] = "{$eventTitle}: Offline registration (by {$userName})";
1421 }
1422
1423 $contributionParams['currency'] = $config->defaultCurrency;
1424 $contributionParams['non_deductible_amount'] = 'null';
1425 $contributionParams['receipt_date'] = CRM_Utils_Array::value('send_receipt', $params) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
1426
1427 $recordContribution = array( 'contact_id', 'financial_type_id',
1428 'payment_instrument_id', 'trxn_id',
1429 'contribution_status_id', 'receive_date',
1430 'check_number', 'campaign_id',
1431 );
1432
1433 foreach ($recordContribution as $f) {
1434 $contributionParams[$f] = CRM_Utils_Array::value($f, $params);
1435 if ($f == 'trxn_id') {
1436 $this->assign('trxn_id', $contributionParams[$f]);
1437 }
1438 }
1439
1440 //insert financial type name in receipt.
1441 $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionParams['financial_type_id']));
1442 $contributionParams['skipLineItem'] = 1;
1443 if ($this->_id) {
1444 $contributionParams['contribution_mode'] = 'participant';
1445 $contributionParams['participant_id'] = $this->_id;
1446 }
1447 // Set is_pay_later flag for back-office offline Pending status contributions
1448 if ($contributionParams['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
1449 $contributionParams['is_pay_later'] = 1;
1450 }
1451 if ($this->_single) {
1452 $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
1453 }
1454 else {
1455 $ids = array();
1456 foreach ($this->_contactIds as $contactID) {
1457 $contributionParams['contact_id'] = $contactID;
1458 $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
1459 }
1460 }
1461
1462 //insert payment record for this participation
1463 if (!$ids['contribution']) {
1464 foreach ($this->_contactIds as $num => $contactID) {
1465 $ppDAO = new CRM_Event_DAO_ParticipantPayment();
1466 $ppDAO->participant_id = $participants[$num]->id;
1467 $ppDAO->contribution_id = $contributions[$num]->id;
1468 $ppDAO->save();
1469 }
1470 }
1471 // next create the transaction record
1472 $transaction = new CRM_Core_Transaction();
1473
1474 // CRM-11124
1475 if ($this->_quickConfig) {
1476 if (CRM_Utils_Array::value('amount_priceset_level_radio', $this->_params)) {
1477 $feeLevel = $this->_params['amount_priceset_level_radio'];
1478 }
1479 else {
1480 $feeLevel[] = $this->_params['fee_level'] ;
1481 }
1482 CRM_Event_BAO_Participant::createDiscountTrxn($this->_eventId, $contributionParams, $feeLevel);
1483 }
1484 $transaction->commit();
1485 }
1486 }
1487
1488 // also store lineitem stuff here
1489 if ((($this->_lineItem & $this->_action & CRM_Core_Action::ADD) ||
1490 ($this->_lineItem && CRM_Core_Action::UPDATE && !$this->_paymentId))
1491 ) {
1492 foreach ($this->_contactIds as $num => $contactID) {
1493 foreach ($this->_lineItem as $key => $value) {
1494 if (is_array($value) && $value != 'skip') {
1495 foreach ($value as $lineKey => $line) {
1496 //10117 update the line items for participants if contribution amount is recorded
1497 if ($this->_quickConfig && CRM_Utils_Array::value('total_amount', $params )) {
1498 $line['unit_price'] = $line['line_total'] = $params['total_amount'];
1499 }
1500 $lineItem[$this->_priceSetId][$lineKey] = $line;
1501 }
1502 CRM_Price_BAO_LineItem::processPriceSet($participants[$num]->id, $lineItem, CRM_Utils_Array::value($num, $contributions, NULL), 'civicrm_participant');
1503 }
1504 }
1505 }
1506 }
1507
1508 $updateStatusMsg = NULL;
1509 //send mail when participant status changed, CRM-4326
1510 if ($this->_id && $this->_statusId &&
1511 $this->_statusId != CRM_Utils_Array::value('status_id', $params) &&
1512 CRM_Utils_Array::value('is_notify', $params)
1513 ) {
1514
1515 $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_id,
1516 $params['status_id'],
1517 $this->_statusId
1518 );
1519 }
1520
1521 $sent = array();
1522 $notSent = array();
1523 if (CRM_Utils_Array::value('send_receipt', $params)) {
1524 if (array_key_exists($params['from_email_address'], $this->_fromEmails['from_email_id'])) {
1525 $receiptFrom = $params['from_email_address'];
1526 }
1527
1528 $this->assign('module', 'Event Registration');
1529 //use of the message template below requires variables in different format
1530 $event = $events = array();
1531 $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
1532
1533 //get all event details.
1534 CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
1535 $event = $events[$params['event_id']];
1536 unset($event['start_date']);
1537 unset($event['end_date']);
1538
1539 $role = CRM_Event_PseudoConstant::participantRole();
1540 $participantRoles = CRM_Utils_Array::value('role_id', $params);
1541 if (is_array($participantRoles)) {
1542 $selectedRoles = array();
1543 foreach (array_keys($participantRoles) as $roleId) {
1544 $selectedRoles[] = $role[$roleId];
1545 }
1546 $event['participant_role'] = implode(', ', $selectedRoles);
1547 }
1548 else {
1549 $event['participant_role'] = CRM_Utils_Array::value($participantRoles, $role);
1550 }
1551 $event['is_monetary'] = $this->_isPaidEvent;
1552
1553 if ($params['receipt_text']) {
1554 $event['confirm_email_text'] = $params['receipt_text'];
1555 }
1556
1557 $this->assign('isAmountzero', 1);
1558 $this->assign('event', $event);
1559
1560 $this->assign('isShowLocation', $event['is_show_location']);
1561 if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
1562 $locationParams = array(
1563 'entity_id' => $params['event_id'],
1564 'entity_table' => 'civicrm_event',
1565 );
1566 $location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
1567 $this->assign('location', $location);
1568 }
1569
1570 $status = CRM_Event_PseudoConstant::participantStatus();
1571 if ($this->_isPaidEvent) {
1572 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
1573 if (!$this->_mode) {
1574 if (isset($params['payment_instrument_id'])) {
1575 $this->assign('paidBy',
1576 CRM_Utils_Array::value($params['payment_instrument_id'],
1577 $paymentInstrument
1578 )
1579 );
1580 }
1581 }
1582
1583 $this->assign('totalAmount', $contributionParams['total_amount']);
1584
1585 $this->assign('isPrimary', 1);
1586 $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
1587 }
1588 if ($this->_mode) {
1589 if (CRM_Utils_Array::value('billing_first_name', $params)) {
1590 $name = $params['billing_first_name'];
1591 }
1592
1593 if (CRM_Utils_Array::value('billing_middle_name', $params)) {
1594 $name .= " {$params['billing_middle_name']}";
1595 }
1596
1597 if (CRM_Utils_Array::value('billing_last_name', $params)) {
1598 $name .= " {$params['billing_last_name']}";
1599 }
1600 $this->assign('billingName', $name);
1601
1602 // assign the address formatted up for display
1603 $addressParts = array(
1604 "street_address-{$this->_bltID}",
1605 "city-{$this->_bltID}",
1606 "postal_code-{$this->_bltID}",
1607 "state_province-{$this->_bltID}",
1608 "country-{$this->_bltID}",
1609 );
1610 $addressFields = array();
1611 foreach ($addressParts as $part) {
1612 list($n, $id) = explode('-', $part);
1613 if (isset($this->_params['billing_' . $part])) {
1614 $addressFields[$n] = $this->_params['billing_' . $part];
1615 }
1616 }
1617 $this->assign('address', CRM_Utils_Address::format($addressFields));
1618
1619 $date = CRM_Utils_Date::format($params['credit_card_exp_date']);
1620 $date = CRM_Utils_Date::mysqlToIso($date);
1621 $this->assign('credit_card_exp_date', $date);
1622 $this->assign('credit_card_number',
1623 CRM_Utils_System::mungeCreditCard($params['credit_card_number'])
1624 );
1625 $this->assign('credit_card_type', $params['credit_card_type']);
1626 $this->assign('contributeMode', 'direct');
1627 $this->assign('isAmountzero', 0);
1628 $this->assign('is_pay_later', 0);
1629 $this->assign('isPrimary', 1);
1630 }
1631
1632 $this->assign('register_date', $params['register_date']);
1633 if ($params['receive_date']) {
1634 $this->assign('receive_date', $params['receive_date']);
1635 }
1636
1637 $participant = array(array('participant_id', '=', $participants[0]->id, 0, 0));
1638 // check whether its a test drive ref CRM-3075
1639 if (CRM_Utils_Array::value('is_test', $this->_defaultValues)) {
1640 $participant[] = array('participant_test', '=', 1, 0, 0);
1641 }
1642
1643 $template = CRM_Core_Smarty::singleton();
1644 $customGroup = array();
1645 //format submitted data
1646 foreach ($params['custom'] as $fieldID => $values) {
1647 foreach ($values as $fieldValue) {
1648 $customValue = array('data' => $fieldValue['value']);
1649 $customFields[$fieldID]['id'] = $fieldID;
1650 $formattedValue = CRM_Core_BAO_CustomGroup::formatCustomValues($customValue, $customFields[$fieldID], TRUE);
1651 $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
1652 }
1653 }
1654
1655 foreach ($this->_contactIds as $num => $contactID) {
1656 // Retrieve the name and email of the contact - this will be the TO for receipt email
1657 list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
1658
1659 $this->_contributorDisplayName = ($this->_contributorDisplayName == ' ') ? $this->_contributorEmail : $this->_contributorDisplayName;
1660
1661 $waitStatus = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
1662 if ($waitingStatus = CRM_Utils_Array::value($params['status_id'], $waitStatus)) {
1663 $this->assign('isOnWaitlist', TRUE);
1664 }
1665
1666 $this->assign('customGroup', $customGroup);
1667 $this->assign('contactID', $contactID);
1668 $this->assign('participantID', $participants[$num]->id);
1669
1670 $this->_id = $participants[$num]->id;
1671
1672 if ($this->_isPaidEvent) {
1673 // fix amount for each of participants ( for bulk mode )
1674 $eventAmount = array();
1675 if (!empty($additionalParticipantDetails)) {
1676 $params['amount_level'] = preg_replace('/\ 1/', '', $params['amount_level']) . ' - ' . $this->_contributorDisplayName;
1677 }
1678
1679 $eventAmount[$num] = array(
1680 'label' => preg_replace('/\ 1/', '', $params['amount_level']),
1681 'amount' => $params['fee_amount'],
1682 );
1683 //as we are using same template for online & offline registration.
1684 //So we have to build amount as array.
1685 $eventAmount = array_merge($eventAmount, $additionalParticipantDetails);
1686 $this->assign('amount', $eventAmount);
1687 }
1688
1689 $sendTemplateParams = array(
1690 'groupName' => 'msg_tpl_workflow_event',
1691 'valueName' => 'event_offline_receipt',
1692 'contactId' => $contactID,
1693 'isTest' => (bool) CRM_Utils_Array::value('is_test', $this->_defaultValues),
1694 );
1695
1696 // try to send emails only if email id is present
1697 // and the do-not-email option is not checked for that contact
1698 if ($this->_contributorEmail and !$this->_toDoNotEmail) {
1699 $sendTemplateParams['from'] = $receiptFrom;
1700 $sendTemplateParams['toName'] = $this->_contributorDisplayName;
1701 $sendTemplateParams['toEmail'] = $this->_contributorEmail;
1702 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc', $this->_fromEmails);
1703 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc', $this->_fromEmails);
1704 }
1705
1706 list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplates::sendTemplate($sendTemplateParams);
1707 if ($mailSent) {
1708 $sent[] = $contactID;
1709 foreach ($participants as $ids => $values) {
1710 if ($values->contact_id == $contactID) {
1711 CRM_Activity_BAO_Activity::addActivity($values, 'Email');
1712 break;
1713 }
1714 }
1715 }
1716 else {
1717 $notSent[] = $contactID;
1718 }
1719 }
1720 }
1721
1722 // set the participant id if it is not set
1723 if (!$this->_id) {
1724 $this->_id = $participants[0]->id;
1725 }
1726
1727 if (($this->_action & CRM_Core_Action::UPDATE)) {
1728 $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contributorDisplayName));
1729 if (CRM_Utils_Array::value('send_receipt', $params) && count($sent)) {
1730 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', array(1 => $this->_contributorEmail));
1731 }
1732
1733 if ($updateStatusMsg) {
1734 $statusMsg = "{$statusMsg} {$updateStatusMsg}";
1735 }
1736 }
1737 elseif ($this->_action & CRM_Core_Action::ADD) {
1738 if ($this->_single) {
1739 $statusMsg = ts('Event registration for %1 has been added.', array(1 => $this->_contributorDisplayName));
1740 if (CRM_Utils_Array::value('send_receipt', $params) && count($sent)) {
1741 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $this->_contributorEmail));
1742 }
1743 }
1744 else {
1745 $statusMsg = ts('Total Participant(s) added to event: %1.', array(1 => count($this->_contactIds)));
1746 if (count($notSent) > 0) {
1747 $statusMsg .= ' ' . ts('Email has NOT been sent to %1 contact(s) - communication preferences specify DO NOT EMAIL OR valid Email is NOT present. ', array(1 => count($notSent)));
1748 }
1749 elseif (isset($params['send_receipt'])) {
1750 $statusMsg .= ' ' . ts('A confirmation email has been sent to ALL participants');
1751 }
1752 }
1753 }
1754 CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
1755
1756 $buttonName = $this->controller->getButtonName();
1757 if ($this->_context == 'standalone') {
1758 if ($buttonName == $this->getButtonName('upload', 'new')) {
1759 $urlParams = 'reset=1&action=add&context=standalone';
1760 if ($this->_mode) {
1761 $urlParams .= '&mode=' . $this->_mode;
1762 }
1763 if ($this->_eID) {
1764 $urlParams .= '&eid=' . $this->_eID;
1765 }
1766 $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', $urlParams));
1767 }
1768 else {
1769 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
1770 "reset=1&cid={$this->_contactId}&selectedChild=participant"
1771 ));
1772 }
1773 }
1774 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1775 $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant',
1776 "reset=1&action=add&context={$this->_context}&cid={$this->_contactId}"
1777 ));
1778 }
1779 }
1780 }
1781