Merge pull request #324 from pradpnayak/CRM-12275
[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 }
237
238 // get the option value for custom data type
239 $this->_roleCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantRole', 'name');
240 $this->_eventNameCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantEventName', 'name');
241 $this->_eventTypeCustomDataTypeID = CRM_Core_OptionGroup::getValue('custom_data_type', 'ParticipantEventType', 'name');
242 $this->assign('roleCustomDataTypeID', $this->_roleCustomDataTypeID);
243 $this->assign('eventNameCustomDataTypeID', $this->_eventNameCustomDataTypeID);
244 $this->assign('eventTypeCustomDataTypeID', $this->_eventTypeCustomDataTypeID);
245
246 if ($this->_mode) {
247 $this->assign('participantMode', $this->_mode);
248
249 $this->_paymentProcessor = array('billing_mode' => 1);
250
251 $validProcessors = array();
252 $processors = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, "billing_mode IN ( 1, 3 )");
253
254 foreach ($processors as $ppID => $label) {
255 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($ppID, $this->_mode);
256 if ($paymentProcessor['payment_processor_type'] == 'PayPal' && !$paymentProcessor['user_name']) {
257 continue;
258 }
259 elseif ($paymentProcessor['payment_processor_type'] == 'Dummy' && $this->_mode == 'live') {
260 continue;
261 }
262 else {
263 $paymentObject = CRM_Core_Payment::singleton($this->_mode, $paymentProcessor, $this);
264 $error = $paymentObject->checkConfig();
265 if (empty($error)) {
266 $validProcessors[$ppID] = $label;
267 }
268 $paymentObject = NULL;
269 }
270 }
271 if (empty($validProcessors)) {
272 CRM_Core_Error::fatal(ts('Could not find valid payment processor for this page'));
273 }
274 else {
275 $this->_processors = $validProcessors;
276 }
277 // also check for billing information
278 // get the billing location type
279 $locationTypes = CRM_Core_PseudoConstant::locationType();
280 // CRM-8108 remove ts around Billing location type
281 //$this->_bltID = array_search( ts('Billing'), $locationTypes );
282 $this->_bltID = array_search('Billing', $locationTypes);
283 if (!$this->_bltID) {
284 CRM_Core_Error::fatal(ts('Please set a location type of %1', array(1 => 'Billing')));
285 }
286 $this->set('bltID', $this->_bltID);
287 $this->assign('bltID', $this->_bltID);
288
289 $this->_fields = array();
290
291 CRM_Core_Payment_Form::setCreditCardFields($this);
292
293 // this required to show billing block
294 $this->assign_by_ref('paymentProcessor', $paymentProcessor);
295 $this->assign('hidePayPalExpress', TRUE);
296 }
297
298 if ($this->_showFeeBlock) {
299 $this->assign('showFeeBlock', TRUE);
300 $isMonetary = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_showFeeBlock, 'is_monetary');
301 if ($isMonetary) {
302 $this->assign('feeBlockPaid', TRUE);
303 }
304 return CRM_Event_Form_EventFees::preProcess($this);
305 }
306
307 //custom data related code
308 $this->_cdType = CRM_Utils_Array::value('type', $_GET);
309 $this->assign('cdType', FALSE);
310 if ($this->_cdType) {
311 $this->assign('cdType', TRUE);
312 return CRM_Custom_Form_CustomData::preProcess($this);
313 }
314
315 //check the mode when this form is called either single or as
316 //search task action
317 if ($this->_id || $this->_contactId || $this->_context == 'standalone') {
318 $this->_single = TRUE;
319 $this->assign('urlPath', 'civicrm/contact/view/participant');
320 if (!$this->_id && !$this->_contactId) {
321 $breadCrumbs = array(array('title' => ts('CiviEvent Dashboard'),
322 'url' => CRM_Utils_System::url('civicrm/event', 'reset=1'),
323 ));
324
325 CRM_Utils_System::appendBreadCrumb($breadCrumbs);
326 }
327 }
328 else {
329 //set the appropriate action
330 $context = $this->get('context');
331 $urlString = 'civicrm/contact/search';
332 $this->_action = CRM_Core_Action::BASIC;
333 switch ($context) {
334 case 'advanced':
335 $urlString = 'civicrm/contact/search/advanced';
336 $this->_action = CRM_Core_Action::ADVANCED;
337 break;
338
339 case 'builder':
340 $urlString = 'civicrm/contact/search/builder';
341 $this->_action = CRM_Core_Action::PROFILE;
342 break;
343
344 case 'basic':
345 $urlString = 'civicrm/contact/search/basic';
346 $this->_action = CRM_Core_Action::BASIC;
347 break;
348
349 case 'custom':
350 $urlString = 'civicrm/contact/search/custom';
351 $this->_action = CRM_Core_Action::COPY;
352 break;
353 }
354 parent::preProcess();
355
356 $this->_single = FALSE;
357 $this->_contactId = NULL;
358
359 //set ajax path, this used for custom data building
360 $this->assign('urlPath', $urlString);
361 $this->assign('urlPathVar', "_qf_Participant_display=true&qfKey={$this->controller->_key}");
362 }
363
364 $this->assign('single', $this->_single);
365
366 if (!$this->_id) {
367 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add');
368 }
369 $this->assign('action', $this->_action);
370
371 // check for edit permission
372 if (!CRM_Core_Permission::checkActionPermission('CiviEvent', $this->_action)) {
373 CRM_Core_Error::fatal(ts('You do not have permission to access this page'));
374 }
375
376 if ($this->_action & CRM_Core_Action::DELETE) {
377 // check delete permission for contribution
378 if ($this->_id && $this->_paymentId && !CRM_Core_Permission::checkActionPermission('CiviContribute', $this->_action)) {
379 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."));
380 }
381 return;
382 }
383
384 if ($this->_id) {
385 // assign participant id to the template
386 $this->assign('participantId', $this->_id);
387 $this->_roleId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'role_id');
388 }
389
390 // when fee amount is included in form
391 if (CRM_Utils_Array::value('hidden_feeblock', $_POST)
392 || CRM_Utils_Array::value('send_receipt', $_POST)
393 ) {
394 CRM_Event_Form_EventFees::preProcess($this);
395 CRM_Event_Form_EventFees::buildQuickForm($this);
396 CRM_Event_Form_EventFees::setDefaultValues($this);
397 }
398
399 // when custom data is included in this page
400 if (CRM_Utils_Array::value('hidden_custom', $_POST)) {
401 //custom data of type participant role
402 if (CRM_Utils_Array::value('role_id', $_POST)) {
403 foreach ($_POST['role_id'] as $k => $val) {
404 $roleID = $val;
405 CRM_Custom_Form_CustomData::preProcess($this, $this->_roleCustomDataTypeID, $k, 1, 'Participant', $this->_id);
406 CRM_Custom_Form_CustomData::buildQuickForm($this);
407 CRM_Custom_Form_CustomData::setDefaultValues($this);
408 }
409 }
410
411 //custom data of type participant event
412 CRM_Custom_Form_CustomData::preProcess($this, $this->_eventNameCustomDataTypeID, $_POST['event_id'], 1, 'Participant', $this->_id);
413 CRM_Custom_Form_CustomData::buildQuickForm($this);
414 CRM_Custom_Form_CustomData::setDefaultValues($this);
415
416 // custom data of type participant event type
417 $eventTypeId = NULL;
418 if ($eventId = CRM_Utils_Array::value('event_id', $_POST)) {
419 $eventTypeId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventId, 'event_type_id', 'id');
420 }
421 CRM_Custom_Form_CustomData::preProcess($this, $this->_eventTypeCustomDataTypeID, $eventTypeId,
422 1, 'Participant', $this->_id
423 );
424 CRM_Custom_Form_CustomData::buildQuickForm($this);
425 CRM_Custom_Form_CustomData::setDefaultValues($this);
426
427 //custom data of type participant, ( we 'null' to reset subType and subName)
428 CRM_Custom_Form_CustomData::preProcess($this, 'null', 'null', 1, 'Participant', $this->_id);
429 CRM_Custom_Form_CustomData::buildQuickForm($this);
430 CRM_Custom_Form_CustomData::setDefaultValues($this);
431 }
432
433 // CRM-4395, get the online pending contribution id.
434 $this->_onlinePendingContributionId = NULL;
435 if (!$this->_mode && $this->_id && ($this->_action & CRM_Core_Action::UPDATE)) {
436 $this->_onlinePendingContributionId = CRM_Contribute_BAO_Contribution::checkOnlinePendingContribution($this->_id,
437 'Event'
438 );
439 }
440 $this->set('onlinePendingContributionId', $this->_onlinePendingContributionId);
441 $roleIds = CRM_Event_PseudoConstant::participantRole();
442
443 if (!empty($roleIds)) {
444 $query = "
445 SELECT civicrm_custom_group.name as name,
446 civicrm_custom_group.id as id,
447 extends_entity_column_value as value
448 FROM civicrm_custom_group
449 WHERE ( extends_entity_column_value REGEXP '[[:<:]]" . implode('[[:>:]]|[[:<:]]', array_keys($roleIds)) . "[[:>:]]'
450 OR extends_entity_column_value IS NULL )
451 AND extends_entity_column_id = '{$this->_roleCustomDataTypeID}'
452 AND extends = 'Participant'
453 AND is_active = 1";
454
455 $dao = CRM_Core_DAO::executeQuery($query);
456 while ($dao->fetch()) {
457 if ($dao->value) {
458 $getRole = explode(CRM_Core_DAO::VALUE_SEPARATOR, $dao->value);
459 foreach ($getRole as $r) {
460 if (!$r) {
461 continue;
462 }
463 if (isset($this->_participantRoleIds[$r])) {
464 $this->_participantRoleIds[$r] .= ',' . $dao->name;
465 }
466 else {
467 $this->_participantRoleIds[$r] = $dao->name;
468 }
469 }
470 }
471 else {
472 if (isset($this->_participantRoleIds[0])) {
473 $this->_participantRoleIds[0] .= ',' . $dao->name;
474 }
475 else {
476 $this->_participantRoleIds[0] = $dao->name;
477 }
478 }
479 }
480 $dao->free();
481 }
482 foreach ($roleIds as $k => $v) {
483 if (!isset($this->_participantRoleIds[$k])) {
484 $this->_participantRoleIds[$k] = '';
485 }
486 }
487 $this->assign('participantRoleIds', $this->_participantRoleIds);
488 }
489
490 /**
491 * This function sets the default values for the form in edit/view mode
492 * the default values are retrieved from the database
493 *
494 * @access public
495 *
496 * @return None
497 */
498 public function setDefaultValues() {
499 if ($this->_showFeeBlock) {
500 return CRM_Event_Form_EventFees::setDefaultValues($this);
501 }
502
503 if ($this->_cdType) {
504 return CRM_Custom_Form_CustomData::setDefaultValues($this);
505 }
506
507 $defaults = array();
508
509 if ($this->_action & CRM_Core_Action::DELETE) {
510 return $defaults;
511 }
512
513 if ($this->_id) {
514 $ids = array();
515 $params = array('id' => $this->_id);
516
517 CRM_Event_BAO_Participant::getValues($params, $defaults, $ids);
518 $sep = CRM_Core_DAO::VALUE_SEPARATOR;
519 if ($defaults[$this->_id]['role_id']) {
520 foreach (explode($sep, $defaults[$this->_id]['role_id']) as $k => $v) {
521 $defaults[$this->_id]["role_id[{$v}]"] = 1;
522 }
523 unset($defaults[$this->_id]['role_id']);
524 }
525 $this->_contactId = $defaults[$this->_id]['contact_id'];
526 $this->_statusId = $defaults[$this->_id]['participant_status_id'];
527
528 //set defaults for note
529 $noteDetails = CRM_Core_BAO_Note::getNote($this->_id, 'civicrm_participant');
530 $defaults[$this->_id]['note'] = array_pop($noteDetails);
531
532 // Check if this is a primaryParticipant (registered for others) and retrieve additional participants if true (CRM-4859)
533 if (CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
534 $this->assign('additionalParticipants', CRM_Event_BAO_Participant::getAdditionalParticipants($this->_id));
535 }
536
537 // Get registered_by contact ID and display_name if participant was registered by someone else (CRM-4859)
538 if (CRM_Utils_Array::value('participant_registered_by_id', $defaults[$this->_id])) {
539 $registered_by_contact_id = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
540 $defaults[$this->_id]['participant_registered_by_id'],
541 'contact_id', 'id'
542 );
543 $this->assign('participant_registered_by_id', $defaults[$this->_id]['participant_registered_by_id']);
544 $this->assign('registered_by_contact_id', $registered_by_contact_id);
545 $this->assign('registered_by_display_name', CRM_Contact_BAO_Contact::displayName($registered_by_contact_id));
546 }
547 }
548
549 if ($this->_action & (CRM_Core_Action::VIEW | CRM_Core_Action::BROWSE)) {
550 $inactiveNeeded = TRUE;
551 $viewMode = TRUE;
552 }
553 else {
554 $viewMode = FALSE;
555 $inactiveNeeded = FALSE;
556 }
557
558 //setting default register date
559 if ($this->_action == CRM_Core_Action::ADD) {
560 $statuses = array_flip($this->_participantStatuses);
561 $defaults[$this->_id]['status_id'] = CRM_Utils_Array::value(ts('Registered'), $statuses);
562 if (CRM_Utils_Array::value('event_id', $defaults[$this->_id])) {
563 $contributionTypeId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event',
564 $defaults[$this->_id]['event_id'],
565 'financial_type_id' );
566 if ($contributionTypeId) {
567 $defaults[$this->_id]['financial_type_id'] = $contributionTypeId;
568 }
569 }
570
571 if ($this->_mode) {
572 $fields["email-{$this->_bltID}"] = 1;
573 $fields['email-Primary'] = 1;
574
575 if ($this->_contactId) {
576 CRM_Core_BAO_UFGroup::setProfileDefaults($this->_contactId, $fields, $defaults);
577 }
578
579 if (empty($defaults["email-{$this->_bltID}"]) &&
580 !empty($defaults['email-Primary'])
581 ) {
582 $defaults[$this->_id]["email-{$this->_bltID}"] = $defaults['email-Primary'];
583 }
584 }
585
586 $submittedRole = $this->getElementValue('role_id');
587 if (CRM_Utils_Array::value(0, $submittedRole)) {
588 $roleID = $submittedRole[0];
589 }
590 $submittedEvent = $this->getElementValue('event_id');
591 if ($submittedEvent[0]) {
592 $eventID = $submittedEvent[0];
593 }
594 }
595 else {
596 $defaults[$this->_id]['record_contribution'] = 0;
597
598 if ($defaults[$this->_id]['participant_is_pay_later']) {
599 $this->assign('participant_is_pay_later', TRUE);
600 }
601
602 $this->assign('participant_status_id', $defaults[$this->_id]['participant_status_id']);
603 $roleID = $defaults[$this->_id]['participant_role_id'];
604 $eventID = $defaults[$this->_id]['event_id'];
605
606 $this->_eventTypeId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventID, 'event_type_id', 'id');
607
608 $this->_discountId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'discount_id');
609 if ($this->_discountId) {
610 $this->set('discountId', $this->_discountId);
611 }
612 }
613
614 list($defaults[$this->_id]['register_date'],
615 $defaults[$this->_id]['register_date_time']
616 ) = CRM_Utils_Date::setDateDefaults(
617 CRM_Utils_Array::value('register_date', $defaults[$this->_id]), 'activityDateTime'
618 );
619
620 //assign event and role id, this is needed for Custom data building
621 $sep = CRM_Core_DAO::VALUE_SEPARATOR;
622 if (CRM_Utils_Array::value('participant_role_id', $defaults[$this->_id])) {
623 $roleIDs = explode($sep, $defaults[$this->_id]['participant_role_id']);
624 }
625 if (isset($roleIDs)) {
626 $this->assign('roleID', $roleIDs);
627 }
628 if (isset($_POST['event_id'])) {
629 $eventID = $_POST['event_id'];
630 if ($eventID) {
631 $this->_eventTypeId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventID, 'event_type_id', 'id');
632 }
633 }
634
635 if (isset($eventID)) {
636 $this->assign('eventID', $eventID);
637 $this->set('eventId', $eventID);
638 }
639
640 if (isset($this->_eventTypeId)) {
641 $this->assign('eventTypeID', $this->_eventTypeId);
642 }
643
644 $this->assign('event_is_test', CRM_Utils_Array::value('event_is_test', $defaults[$this->_id]));
645 return $defaults[$this->_id];
646 }
647
648 /**
649 * Function to build the form
650 *
651 * @return None
652 * @access public
653 */
654 public function buildQuickForm() {
655 if ($this->_showFeeBlock) {
656 return CRM_Event_Form_EventFees::buildQuickForm($this);
657 }
658
659 if ($this->_cdType) {
660 return CRM_Custom_Form_CustomData::buildQuickForm($this);
661 }
662
663 //need to assign custom data type to the template
664 $this->assign('customDataType', 'Participant');
665
666 $this->applyFilter('__ALL__', 'trim');
667
668 if ($this->_action & CRM_Core_Action::DELETE) {
669 if ($this->_single) {
670 $additionalParticipant = count(CRM_Event_BAO_Event::buildCustomProfile($this->_id,
671 NULL,
672 $this->_contactId,
673 FALSE,
674 TRUE
675 )) - 1;
676 if ($additionalParticipant) {
677 $deleteParticipants = array(1 => ts('Delete this participant record along with associated participant record(s).'),
678 2 => ts('Delete only this participant record.'),
679 );
680 $this->addRadio('delete_participant', NULL, $deleteParticipants, NULL, '<br />');
681 $this->setDefaults(array('delete_participant' => 1));
682 $this->assign('additionalParticipant', $additionalParticipant);
683 }
684 }
685 $this->addButtons(array(
686 array(
687 'type' => 'next',
688 'name' => ts('Delete'),
689 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
690 'isDefault' => TRUE,
691 ),
692 array(
693 'type' => 'cancel',
694 'name' => ts('Cancel'),
695 ),
696 )
697 );
698 return;
699 }
700
701
702 if ($this->_single) {
703 $urlPath = 'civicrm/contact/view/participant';
704 $urlParams = "reset=1&cid={$this->_contactId}&context=participant";
705 if ($this->_context == 'standalone') {
706 CRM_Contact_Form_NewContact::buildQuickForm($this);
707 $urlParams = 'reset=1&context=standalone';
708 $urlPath = 'civicrm/participant/add';
709 }
710
711 if ($this->_id) {
712 $urlParams .= "&action=update&id={$this->_id}";
713 }
714 else {
715 $urlParams .= "&action=add";
716 }
717
718 if ($this->_mode) {
719 $urlParams .= "&mode={$this->_mode}";
720 }
721
722 $url = CRM_Utils_System::url($urlPath, $urlParams,
723 FALSE, NULL, FALSE
724 );
725 }
726 else {
727 $currentPath = CRM_Utils_System::currentPath();
728
729 $url = CRM_Utils_System::url($currentPath, '_qf_Participant_display=true',
730 FALSE, NULL, FALSE
731 );
732 }
733
734 $this->assign('refreshURL', $url);
735
736 $this->add('hidden', 'past_event');
737
738 $events = array();
739 if ( $this->_eID ) {
740 $eventEndDate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_eID,'end_date');
741 }
742 $this->assign('past', FALSE);
743 if ($this->_action & CRM_Core_Action::UPDATE) {
744 $events = CRM_Event_BAO_Event::getEvents(TRUE, FALSE, FALSE);
745 }
746 elseif ($this->getElementValue('past_event') || (isset($eventEndDate) && (CRM_Utils_Date::currentDBDate() > CRM_Utils_Date::processDate($eventEndDate)))) {
747 $events = CRM_Event_BAO_Event::getEvents(TRUE);
748 $this->assign('past', TRUE);
749 }
750 else {
751 $events = CRM_Event_BAO_Event::getEvents();
752 }
753
754 if ($this->_mode) {
755 //unset the event which are not monetary when credit card
756 //event registration is used
757 foreach ($events as $key => $val) {
758 $isPaid = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $key, 'is_monetary');
759 if (!$isPaid) {
760 unset($events[$key]);
761 }
762 }
763 $this->add('select', 'payment_processor_id', ts('Payment Processor'), $this->_processors, TRUE);
764 }
765
766 // build array(event -> eventType) mapper
767 $query = "
768 SELECT civicrm_event.id as id, civicrm_event.event_type_id as event_type_id
769 FROM civicrm_event
770 WHERE civicrm_event.is_template IS NULL OR civicrm_event.is_template = 0";
771 $dao = CRM_Core_DAO::executeQuery($query);
772 $eventAndTypeMapping = array();
773 while ($dao->fetch()) {
774 $eventAndTypeMapping[$dao->id] = $dao->event_type_id;
775 }
776 $eventAndTypeMapping = json_encode($eventAndTypeMapping);
777 // building of mapping ends --
778
779 //inherit the campaign from event.
780 $eventCampaigns = array();
781 $allEventIds = array_keys($events);
782 if (!empty($allEventIds)) {
783 CRM_Core_PseudoConstant::populate($eventCampaigns,
784 'CRM_Event_DAO_Event',
785 TRUE, 'campaign_id'
786 );
787 }
788 $eventCampaigns = json_encode($eventCampaigns);
789
790 $element = $this->add('select', 'event_id', ts('Event'),
791 array(
792 '' => ts('- select -')) + $events,
793 TRUE,
794 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')
795 );
796
797 // CRM-6111
798 // note that embedding JS within PHP files is quite awful, IMO
799 // but we do the same for the onChange element and this form is complex
800 // and i did not want to break it late in the 3.2 cycle
801 $preloadJSSnippet = NULL;
802 if (CRM_Utils_Array::value('reset', $_GET) && $this->_eID) {
803 $preloadJSSnippet = "
804 cj(function() {
805 cj('#event_id').val( '{$this->_eID}' );
806 buildFeeBlock( {$this->_eID} );
807 CRM.buildCustomData( 'Participant', {$this->_eID}, {$this->_eventNameCustomDataTypeID} );
808 buildEventTypeCustomData( {$this->_eID}, {$this->_eventTypeCustomDataTypeID}, '{$eventAndTypeMapping}' );
809 loadCampaign( {$this->_eID}, {$eventCampaigns} );
810 });
811 ";
812 }
813
814 $this->assign('preloadJSSnippet', $preloadJSSnippet);
815
816
817 //frozen the field fix for CRM-4171
818 if ($this->_action & CRM_Core_Action::UPDATE && $this->_id) {
819 if (CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
820 $this->_id, 'contribution_id', 'participant_id'
821 )) {
822 $element->freeze();
823 }
824 }
825
826 //CRM-7362 --add campaigns.
827 $campaignId = NULL;
828 if ($this->_id) {
829 $campaignId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'campaign_id');
830 }
831 if (!$campaignId) {
832 $eventId = CRM_Utils_Request::retrieve('eid', 'Positive', $this);
833 if ($eventId) {
834 $campaignId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventId, 'campaign_id');
835 }
836 }
837 CRM_Campaign_BAO_Campaign::addCampaign($this, $campaignId);
838
839 $this->addDateTime('register_date', ts('Registration Date'), TRUE, array('formatType' => 'activityDateTime'));
840
841 if ($this->_id) {
842 $this->assign('entityID', $this->_id);
843 }
844
845 $roleids = CRM_Event_PseudoConstant::participantRole();
846
847 foreach ($roleids as $rolekey => $rolevalue) {
848 $roleTypes[] = $this->createElement('checkbox', $rolekey, NULL, $rolevalue,
849 array('onclick' => "showCustomData( 'Participant', {$rolekey}, {$this->_roleCustomDataTypeID} );")
850 );
851 }
852
853 $this->addGroup($roleTypes, 'role_id', ts('Participant Role'));
854 $this->addRule('role_id', ts('Role is required'), 'required');
855
856 // CRM-4395
857 $checkCancelledJs = array('onchange' => "return sendNotification( );");
858 $confirmJS = NULL;
859 if ($this->_onlinePendingContributionId) {
860 $cancelledparticipantStatusId = array_search('Cancelled', CRM_Event_PseudoConstant::participantStatus());
861 $cancelledContributionStatusId = array_search('Cancelled',
862 CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')
863 );
864 $checkCancelledJs = array(
865 'onchange' =>
866 "checkCancelled( this.value, {$cancelledparticipantStatusId},{$cancelledContributionStatusId});",
867 );
868
869 $participantStatusId = array_search('Pending from pay later',
870 CRM_Event_PseudoConstant::participantStatus()
871 );
872 $contributionStatusId = array_search('Completed',
873 CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')
874 );
875 $confirmJS = array('onclick' => "return confirmStatus( {$participantStatusId}, {$contributionStatusId} );");
876 }
877
878 $this->_participantStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label');
879 $this->add('select', 'status_id', ts('Participant Status'),
880 array(
881 '' => ts('- select -')) + $this->_participantStatuses,
882 TRUE,
883 $checkCancelledJs
884 );
885
886 $this->addElement('checkbox', 'is_notify', ts('Send Notification'), NULL);
887
888 $this->add('text', 'source', ts('Event Source'));
889 $noteAttributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_Note');
890 $this->add('textarea', 'note', ts('Notes'), $noteAttributes['note']);
891
892 $buttons[] = array(
893 'type' => 'upload',
894 'name' => ts('Save'),
895 'isDefault' => TRUE,
896 'js' => $confirmJS,
897 );
898
899 $path = CRM_Utils_System::currentPath();
900 if (strpos($path, 'civicrm/contact/search') !== 0) {
901 $buttons[] = array(
902 'type' => 'upload',
903 'name' => ts('Save and New'),
904 'subName' => 'new',
905 'js' => $confirmJS,
906 );
907 }
908 $buttons[] = array(
909 'type' => 'cancel',
910 'name' => ts('Cancel'),
911 );
912
913 $this->addButtons($buttons);
914 if ($this->_action == CRM_Core_Action::VIEW) {
915 $this->freeze();
916 }
917 }
918
919 /**
920 * Add local and global form rules
921 *
922 * @access protected
923 *
924 * @return void
925 */
926 function addRules() {
927 $this->addFormRule(array('CRM_Event_Form_Participant', 'formRule'), $this);
928 }
929
930 /**
931 * global validation rules for the form
932 *
933 * @param array $fields posted values of the form
934 *
935 * @return array list of errors to be posted back to the form
936 * @static
937 * @access public
938 */
939 static function formRule($values, $files, $self) {
940 // If $values['_qf_Participant_next'] is Delete or
941 // $values['event_id'] is empty, then return
942 // instead of proceeding further.
943
944 if ((CRM_Utils_Array::value('_qf_Participant_next', $values) == 'Delete') ||
945 (!$values['event_id'])
946 ) {
947 return TRUE;
948 }
949
950 $errorMsg = array();
951 //check if contact is selected in standalone mode
952 if (isset($values['contact_select_id'][1]) && !$values['contact_select_id'][1]) {
953 $errorMsg['contact[1]'] = ts('Please select a contact or create new contact');
954 }
955
956 if (CRM_Utils_Array::value('payment_processor_id', $values)) {
957 // make sure that credit card number and cvv are valid
958 if (CRM_Utils_Array::value('credit_card_type', $values)) {
959 if (CRM_Utils_Array::value('credit_card_number', $values) &&
960 !CRM_Utils_Rule::creditCardNumber($values['credit_card_number'], $values['credit_card_type'])
961 ) {
962 $errorMsg['credit_card_number'] = ts('Please enter a valid Credit Card Number');
963 }
964
965 if (CRM_Utils_Array::value('cvv2', $values) &&
966 !CRM_Utils_Rule::cvv($values['cvv2'], $values['credit_card_type'])
967 ) {
968 $errorMsg['cvv2'] = ts('Please enter a valid Credit Card Verification Number');
969 }
970 }
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