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