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