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