First commit

This commit is contained in:
Theodotos Andreou 2018-01-14 13:10:16 +00:00
commit c6e2478c40
13918 changed files with 2303184 additions and 0 deletions

View file

@ -0,0 +1,193 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
use Civi\ActionSchedule\RecipientBuilder;
/**
* Class CRM_Event_ActionMapping
*
* This defines the scheduled-reminder functionality for CiviEvent
* participants. It allows one to target messages on the
* event's start-date/end-date, with additional filtering by
* event-type, event-template, or event-id.
*/
class CRM_Event_ActionMapping extends \Civi\ActionSchedule\Mapping {
/**
* The value for civicrm_action_schedule.mapping_id which identifies the
* "Event Type" mapping.
*
* Note: This value is chosen to match legacy DB IDs.
*/
const EVENT_TYPE_MAPPING_ID = 2;
const EVENT_NAME_MAPPING_ID = 3;
const EVENT_TPL_MAPPING_ID = 5;
/**
* Register CiviEvent-related action mappings.
*
* @param \Civi\ActionSchedule\Event\MappingRegisterEvent $registrations
*/
public static function onRegisterActionMappings(\Civi\ActionSchedule\Event\MappingRegisterEvent $registrations) {
$registrations->register(CRM_Event_ActionMapping::create(array(
'id' => CRM_Event_ActionMapping::EVENT_TYPE_MAPPING_ID,
'entity' => 'civicrm_participant',
'entity_label' => ts('Event Type'),
'entity_value' => 'event_type',
'entity_value_label' => ts('Event Type'),
'entity_status' => 'civicrm_participant_status_type',
'entity_status_label' => ts('Participant Status'),
'entity_date_start' => 'event_start_date',
'entity_date_end' => 'event_end_date',
)));
$registrations->register(CRM_Event_ActionMapping::create(array(
'id' => CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID,
'entity' => 'civicrm_participant',
'entity_label' => ts('Event Name'),
'entity_value' => 'civicrm_event',
'entity_value_label' => ts('Event Name'),
'entity_status' => 'civicrm_participant_status_type',
'entity_status_label' => ts('Participant Status'),
'entity_date_start' => 'event_start_date',
'entity_date_end' => 'event_end_date',
)));
$registrations->register(CRM_Event_ActionMapping::create(array(
'id' => CRM_Event_ActionMapping::EVENT_TPL_MAPPING_ID,
'entity' => 'civicrm_participant',
'entity_label' => ts('Event Template'),
'entity_value' => 'event_template',
'entity_value_label' => ts('Event Template'),
'entity_status' => 'civicrm_participant_status_type',
'entity_status_label' => ts('Participant Status'),
'entity_date_start' => 'event_start_date',
'entity_date_end' => 'event_end_date',
)));
}
/**
* Get a list of recipient types.
*
* Note: A single schedule may filter on *zero* or *one* recipient types.
* When an admin chooses a value, it's stored in $schedule->recipient.
*
* @return array
* array(string $value => string $label).
* Ex: array('assignee' => 'Activity Assignee').
*/
public function getRecipientTypes() {
return \CRM_Core_OptionGroup::values('event_contacts', FALSE, FALSE, FALSE, NULL, 'label', TRUE, FALSE, 'name');
}
/**
* Get a list of recipients which match the given type.
*
* Note: A single schedule may filter on *multiple* recipients.
* When an admin chooses value(s), it's stored in $schedule->recipient_listing.
*
* @param string $recipientType
* Ex: 'participant_role'.
* @return array
* Array(mixed $name => string $label).
* Ex: array(1 => 'Attendee', 2 => 'Volunteer').
* @see getRecipientTypes
*/
public function getRecipientListing($recipientType) {
switch ($recipientType) {
case 'participant_role':
return \CRM_Event_PseudoConstant::participantRole();
default:
return array();
}
}
/**
* Generate a query to locate recipients who match the given
* schedule.
*
* @param \CRM_Core_DAO_ActionSchedule $schedule
* The schedule as configured by the administrator.
* @param string $phase
* See, e.g., RecipientBuilder::PHASE_RELATION_FIRST.
* @param array $defaultParams
*
* @return \CRM_Utils_SQL_Select
* @see RecipientBuilder
*/
public function createQuery($schedule, $phase, $defaultParams) {
$selectedValues = (array) \CRM_Utils_Array::explodePadded($schedule->entity_value);
$selectedStatuses = (array) \CRM_Utils_Array::explodePadded($schedule->entity_status);
$query = \CRM_Utils_SQL_Select::from("{$this->entity} e")->param($defaultParams);;
$query['casAddlCheckFrom'] = 'civicrm_event r';
$query['casContactIdField'] = 'e.contact_id';
$query['casEntityIdField'] = 'e.id';
$query['casContactTableAlias'] = NULL;
$query['casDateField'] = str_replace('event_', 'r.', $schedule->start_action_date);
$query->join('r', 'INNER JOIN civicrm_event r ON e.event_id = r.id');
if ($schedule->recipient_listing && $schedule->limit_to) {
switch ($schedule->recipient) {
case 'participant_role':
$query->where("e.role_id IN (#recipList)")
->param('recipList', \CRM_Utils_Array::explodePadded($schedule->recipient_listing));
break;
default:
break;
}
}
// build where clause
if (!empty($selectedValues)) {
$valueField = ($this->id == \CRM_Event_ActionMapping::EVENT_TYPE_MAPPING_ID) ? 'event_type_id' : 'id';
$query->where("r.{$valueField} IN (@selectedValues)")
->param('selectedValues', $selectedValues);
}
else {
$query->where(($this->id == \CRM_Event_ActionMapping::EVENT_TYPE_MAPPING_ID) ? "r.event_type_id IS NULL" : "r.id IS NULL");
}
$query->where('r.is_active = 1');
$query->where('r.is_template = 0');
// participant status criteria not to be implemented for additional recipients
// ... why not?
if (!empty($selectedStatuses)) {
switch ($phase) {
case RecipientBuilder::PHASE_RELATION_FIRST:
case RecipientBuilder::PHASE_RELATION_REPEAT:
$query->where("e.status_id IN (#selectedStatuses)")
->param('selectedStatuses', $selectedStatuses);
break;
}
}
return $query;
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,130 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
class CRM_Event_BAO_ParticipantPayment extends CRM_Event_DAO_ParticipantPayment {
/**
* Creates or updates a participant payment record.
*
* @param array $params
* of values to initialize the record with.
* @param array $ids
* with one values of id for this participantPayment record (for update).
*
* @return object
* the partcipant payment record
*/
public static function create(&$params, &$ids) {
if (isset($ids['id'])) {
CRM_Utils_Hook::pre('edit', 'ParticipantPayment', $ids['id'], $params);
}
else {
CRM_Utils_Hook::pre('create', 'ParticipantPayment', NULL, $params);
}
$participantPayment = new CRM_Event_BAO_ParticipantPayment();
$participantPayment->copyValues($params);
if (isset($ids['id'])) {
$participantPayment->id = CRM_Utils_Array::value('id', $ids);
}
else {
$participantPayment->find(TRUE);
}
$participantPayment->save();
if (isset($ids['id'])) {
CRM_Utils_Hook::post('edit', 'ParticipantPayment', $ids['id'], $participantPayment);
}
else {
CRM_Utils_Hook::post('create', 'ParticipantPayment', NULL, $participantPayment);
}
//generally if people are creating participant_payments via the api they won't be setting the line item correctly - we can't help them if they are doing complex transactions
// but if they have a single line item for the contribution we can assume it should refer to the participant line
$lineItemCount = CRM_Core_DAO::singleValueQuery("select count(*) FROM civicrm_line_item WHERE contribution_id = %1", array(
1 => array(
$participantPayment->contribution_id,
'Integer',
),
));
if ($lineItemCount == 1) {
$sql = "UPDATE civicrm_line_item li
SET entity_table = 'civicrm_participant', entity_id = %1
WHERE contribution_id = %2 AND entity_table = 'civicrm_contribution'";
CRM_Core_DAO::executeQuery($sql, array(
1 => array($participantPayment->participant_id, 'Integer'),
2 => array($participantPayment->contribution_id, 'Integer'),
));
}
return $participantPayment;
}
/**
* Delete the record that are associated with this ParticipantPayment.
* Also deletes the associated contribution for this participant
*
* @param array $params
* Associative array whose values match the record to be deleted.
*
* @return bool
* true if deleted false otherwise
*/
public static function deleteParticipantPayment($params) {
$participantPayment = new CRM_Event_DAO_ParticipantPayment();
$valid = FALSE;
foreach ($params as $field => $value) {
if (!empty($value)) {
$participantPayment->$field = $value;
$valid = TRUE;
}
}
if (!$valid) {
CRM_Core_Error::fatal();
}
if ($participantPayment->find(TRUE)) {
CRM_Utils_Hook::pre('delete', 'ParticipantPayment', $participantPayment->id, $params);
CRM_Contribute_BAO_Contribution::deleteContribution($participantPayment->contribution_id);
$participantPayment->delete();
CRM_Utils_Hook::post('delete', 'ParticipantPayment', $participantPayment->id, $participantPayment);
return $participantPayment;
}
return FALSE;
}
}

View file

@ -0,0 +1,327 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
class CRM_Event_BAO_ParticipantStatusType extends CRM_Event_DAO_ParticipantStatusType {
/**
* @param array $params
*
* @return this|null
*/
public static function add(&$params) {
if (empty($params)) {
return NULL;
}
$dao = new CRM_Event_DAO_ParticipantStatusType();
$dao->copyValues($params);
return $dao->save();
}
/**
* @param array $params
*
* @return this|null
*/
public static function &create(&$params) {
$transaction = new CRM_Core_Transaction();
$statusType = self::add($params);
if (is_a($statusType, 'CRM_Core_Error')) {
$transaction->rollback();
return $statusType;
}
$transaction->commit();
return $statusType;
}
/**
* @param int $id
*
* @return bool
*/
public static function deleteParticipantStatusType($id) {
// return early if there are participants with this status
$participant = new CRM_Event_DAO_Participant();
$participant->status_id = $id;
if ($participant->find()) {
return FALSE;
}
CRM_Utils_Weight::delWeight('CRM_Event_DAO_ParticipantStatusType', $id);
$dao = new CRM_Event_DAO_ParticipantStatusType();
$dao->id = $id;
if (!$dao->find()) {
return FALSE;
}
$dao->delete();
return TRUE;
}
/**
* @param array $params
* @param $defaults
*
* @return CRM_Event_DAO_ParticipantStatusType|null
*/
public static function retrieve(&$params, &$defaults) {
$result = NULL;
$dao = new CRM_Event_DAO_ParticipantStatusType();
$dao->copyValues($params);
if ($dao->find(TRUE)) {
CRM_Core_DAO::storeValues($dao, $defaults);
$result = $dao;
}
return $result;
}
/**
* @param int $id
* @param $isActive
*
* @return bool
*/
public static function setIsActive($id, $isActive) {
return CRM_Core_DAO::setFieldValue('CRM_Event_BAO_ParticipantStatusType', $id, 'is_active', $isActive);
}
/**
* @param array $params
*
* @return array
*/
public static function process($params) {
$returnMessages = array();
$participantRole = CRM_Event_PseudoConstant::participantRole();
$pendingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Pending'");
$expiredStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'");
$waitingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
//build the required status ids.
$statusIds = '(' . implode(',', array_merge(array_keys($pendingStatuses), array_keys($waitingStatuses))) . ')';
$participantDetails = $fullEvents = array();
$expiredParticipantCount = $waitingConfirmCount = $waitingApprovalCount = 0;
//get all participant who's status in class pending and waiting
$query = "SELECT * FROM civicrm_participant WHERE status_id IN {$statusIds} ORDER BY register_date";
$query = "
SELECT participant.id,
participant.contact_id,
participant.status_id,
participant.register_date,
participant.registered_by_id,
participant.event_id,
event.title as eventTitle,
event.registration_start_date,
event.registration_end_date,
event.end_date,
event.expiration_time,
event.requires_approval
FROM civicrm_participant participant
LEFT JOIN civicrm_event event ON ( event.id = participant.event_id )
WHERE participant.status_id IN {$statusIds}
AND (event.end_date > now() OR event.end_date IS NULL)
AND event.is_active = 1
ORDER BY participant.register_date, participant.id
";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$participantDetails[$dao->id] = array(
'id' => $dao->id,
'event_id' => $dao->event_id,
'status_id' => $dao->status_id,
'contact_id' => $dao->contact_id,
'register_date' => $dao->register_date,
'registered_by_id' => $dao->registered_by_id,
'eventTitle' => $dao->eventTitle,
'registration_start_date' => $dao->registration_start_date,
'registration_end_date' => $dao->registration_end_date,
'end_date' => $dao->end_date,
'expiration_time' => $dao->expiration_time,
'requires_approval' => $dao->requires_approval,
);
}
if (!empty($participantDetails)) {
//cron 1. move participant from pending to expire if needed
foreach ($participantDetails as $participantId => $values) {
//process the additional participant at the time of
//primary participant, don't process separately.
if (!empty($values['registered_by_id'])) {
continue;
}
$expirationTime = CRM_Utils_Array::value('expiration_time', $values);
if ($expirationTime && array_key_exists($values['status_id'], $pendingStatuses)) {
//get the expiration and registration pending time.
$expirationSeconds = $expirationTime * 3600;
$registrationPendingSeconds = CRM_Utils_Date::unixTime($values['register_date']);
// expired registration since registration cross allow confirmation time.
if (($expirationSeconds + $registrationPendingSeconds) < time()) {
//lets get the transaction mechanism.
$transaction = new CRM_Core_Transaction();
$ids = array($participantId);
$expiredId = array_search('Expired', $expiredStatuses);
$results = CRM_Event_BAO_Participant::transitionParticipants($ids, $expiredId, $values['status_id'], TRUE, TRUE);
$transaction->commit();
if (!empty($results)) {
//diaplay updated participants
if (is_array($results['updatedParticipantIds']) && !empty($results['updatedParticipantIds'])) {
foreach ($results['updatedParticipantIds'] as $processedId) {
$expiredParticipantCount += 1;
$returnMessages[] .= "<br />Status updated to: Expired";
//mailed participants.
if (is_array($results['mailedParticipants']) &&
array_key_exists($processedId, $results['mailedParticipants'])
) {
$returnMessages[] .= "<br />Expiration Mail sent to: {$results['mailedParticipants'][$processedId]}";
}
}
}
}
}
}
}
//cron 1 end.
//cron 2. lets move participants from waiting list to pending status
foreach ($participantDetails as $participantId => $values) {
//process the additional participant at the time of
//primary participant, don't process separately.
if (!empty($values['registered_by_id'])) {
continue;
}
if (array_key_exists($values['status_id'], $waitingStatuses) &&
!array_key_exists($values['event_id'], $fullEvents)
) {
if ($waitingStatuses[$values['status_id']] == 'On waitlist' &&
CRM_Event_BAO_Event::validRegistrationDate($values)
) {
//check the target event having space.
$eventOpenSpaces = CRM_Event_BAO_Participant::eventFull($values['event_id'], TRUE, FALSE);
if ($eventOpenSpaces && is_numeric($eventOpenSpaces) || ($eventOpenSpaces === NULL)) {
//get the additional participant if any.
$additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($participantId);
$allIds = array($participantId);
if (!empty($additionalIds)) {
$allIds = array_merge($allIds, $additionalIds);
}
$pClause = ' participant.id IN ( ' . implode(' , ', $allIds) . ' )';
$requiredSpaces = CRM_Event_BAO_Event::eventTotalSeats($values['event_id'], $pClause);
//need to check as to see if event has enough speces
if (($requiredSpaces <= $eventOpenSpaces) || ($eventOpenSpaces === NULL)) {
$transaction = new CRM_Core_Transaction();
$ids = array($participantId);
$updateStatusId = array_search('Pending from waitlist', $pendingStatuses);
//lets take a call to make pending or need approval
if ($values['requires_approval']) {
$updateStatusId = array_search('Awaiting approval', $waitingStatuses);
}
$results = CRM_Event_BAO_Participant::transitionParticipants($ids, $updateStatusId,
$values['status_id'], TRUE, TRUE
);
//commit the transaction.
$transaction->commit();
if (!empty($results)) {
//diaplay updated participants
if (is_array($results['updatedParticipantIds']) &&
!empty($results['updatedParticipantIds'])
) {
foreach ($results['updatedParticipantIds'] as $processedId) {
if ($values['requires_approval']) {
$waitingApprovalCount += 1;
$returnMessages[] .= "<br /><br />- status updated to: Awaiting approval";
$returnMessages[] .= "<br />Will send you Confirmation Mail when registration gets approved.";
}
else {
$waitingConfirmCount += 1;
$returnMessages[] .= "<br /><br />- status updated to: Pending from waitlist";
if (is_array($results['mailedParticipants']) &&
array_key_exists($processedId, $results['mailedParticipants'])
) {
$returnMessages[] .= "<br />Confirmation Mail sent to: {$results['mailedParticipants'][$processedId]}";
}
}
}
}
}
}
else {
//target event is full.
$fullEvents[$values['event_id']] = $values['eventTitle'];
}
}
else {
//target event is full.
$fullEvents[$values['event_id']] = $values['eventTitle'];
}
}
}
}
//cron 2 ends.
}
$returnMessages[] .= "<br /><br />Number of Expired registration(s) = {$expiredParticipantCount}";
$returnMessages[] .= "<br />Number of registration(s) require approval = {$waitingApprovalCount}";
$returnMessages[] .= "<br />Number of registration changed to Pending from waitlist = {$waitingConfirmCount}<br /><br />";
if (!empty($fullEvents)) {
foreach ($fullEvents as $eventId => $title) {
$returnMessages[] .= "Full Event : {$title}<br />";
}
}
return array('is_error' => 0, 'messages' => $returnMessages);
}
}

View file

@ -0,0 +1,695 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
class CRM_Event_BAO_Query extends CRM_Core_BAO_Query {
/**
* Function get the import/export fields for contribution.
*
* @param bool $checkPermission
*
* @return array
* Associative array of contribution fields
*/
public static function &getFields($checkPermission = TRUE) {
$fields = array();
$fields = array_merge($fields, CRM_Event_DAO_Event::import());
$fields = array_merge($fields, self::getParticipantFields());
$fields = array_merge($fields, CRM_Core_DAO_Discount::export());
return $fields;
}
/**
* @return array
*/
public static function &getParticipantFields() {
$fields = CRM_Event_BAO_Participant::importableFields('Individual', TRUE, TRUE);
return $fields;
}
/**
* Build select for CiviEvent.
*
* @param $query
*/
public static function select(&$query) {
if (($query->_mode & CRM_Contact_BAO_Query::MODE_EVENT) ||
CRM_Contact_BAO_Query::componentPresent($query->_returnProperties, 'participant_')
) {
$query->_select['participant_id'] = "civicrm_participant.id as participant_id";
$query->_element['participant_id'] = 1;
$query->_tables['civicrm_participant'] = $query->_whereTables['civicrm_participant'] = 1;
//add fee level
if (!empty($query->_returnProperties['participant_fee_level'])) {
$query->_select['participant_fee_level'] = "civicrm_participant.fee_level as participant_fee_level";
$query->_element['participant_fee_level'] = 1;
}
//add participant contact ID
if (!empty($query->_returnProperties['participant_contact_id'])) {
$query->_select['participant_contact_id'] = "civicrm_participant.contact_id as participant_contact_id";
$query->_element['participant_contact_id'] = 1;
}
//add fee amount
if (!empty($query->_returnProperties['participant_fee_amount'])) {
$query->_select['participant_fee_amount'] = "civicrm_participant.fee_amount as participant_fee_amount";
$query->_element['participant_fee_amount'] = 1;
}
//add fee currency
if (!empty($query->_returnProperties['participant_fee_currency'])) {
$query->_select['participant_fee_currency'] = "civicrm_participant.fee_currency as participant_fee_currency";
$query->_element['participant_fee_currency'] = 1;
}
//add event title also if event id is select
if (!empty($query->_returnProperties['event_id']) || !empty($query->_returnProperties['event_title'])) {
$query->_select['event_id'] = "civicrm_event.id as event_id";
$query->_select['event_title'] = "civicrm_event.title as event_title";
$query->_element['event_id'] = 1;
$query->_element['event_title'] = 1;
$query->_tables['civicrm_event'] = 1;
$query->_whereTables['civicrm_event'] = 1;
}
//add start date / end date
if (!empty($query->_returnProperties['event_start_date'])) {
$query->_select['event_start_date'] = "civicrm_event.start_date as event_start_date";
$query->_element['event_start_date'] = 1;
}
if (!empty($query->_returnProperties['event_end_date'])) {
$query->_select['event_end_date'] = "civicrm_event.end_date as event_end_date";
$query->_element['event_end_date'] = 1;
}
//event type
if (!empty($query->_returnProperties['event_type'])) {
$query->_select['event_type'] = "event_type.label as event_type";
$query->_element['event_type'] = 1;
$query->_tables['event_type'] = 1;
$query->_whereTables['event_type'] = 1;
}
if (!empty($query->_returnProperties['event_type_id'])) {
$query->_select['event_type_id'] = "event_type.id as event_type_id";
$query->_element['event_type_id'] = 1;
$query->_tables['event_type'] = 1;
$query->_whereTables['event_type'] = 1;
}
//add status_id
if (!empty($query->_returnProperties['participant_status_id'])) {
$query->_select['participant_status_id'] = "civicrm_participant.status_id as participant_status_id";
$query->_element['participant_status_id'] = 1;
$query->_tables['civicrm_participant'] = 1;
$query->_whereTables['civicrm_participant'] = 1;
}
// get particupant_status label
if (!empty($query->_returnProperties['participant_status'])) {
$query->_select['participant_status'] = "participant_status.label as participant_status";
$query->_element['participant_status'] = 1;
$query->_tables['participant_status'] = 1;
$query->_whereTables['civicrm_participant'] = 1;
}
//add participant_role_id
if (!empty($query->_returnProperties['participant_role_id'])) {
$query->_select['participant_role_id'] = "civicrm_participant.role_id as participant_role_id";
$query->_element['participant_role_id'] = 1;
$query->_tables['civicrm_participant'] = 1;
$query->_whereTables['civicrm_participant'] = 1;
$query->_pseudoConstantsSelect['participant_role_id'] = array(
'pseudoField' => 'participant_role_id',
'idCol' => 'participant_role_id',
);
}
//add participant_role
if (!empty($query->_returnProperties['participant_role'])) {
$query->_select['participant_role'] = "civicrm_participant.role_id as participant_role";
$query->_element['participant_role'] = 1;
$query->_tables['participant_role'] = 1;
$query->_whereTables['civicrm_participant'] = 1;
$query->_pseudoConstantsSelect['participant_role'] = array(
'pseudoField' => 'participant_role',
'idCol' => 'participant_role',
);
}
//add register date
if (!empty($query->_returnProperties['participant_register_date'])) {
$query->_select['participant_register_date'] = "civicrm_participant.register_date as participant_register_date";
$query->_element['participant_register_date'] = 1;
}
//add source
if (!empty($query->_returnProperties['participant_source'])) {
$query->_select['participant_source'] = "civicrm_participant.source as participant_source";
$query->_element['participant_source'] = 1;
$query->_tables['civicrm_participant'] = $query->_whereTables['civicrm_participant'] = 1;
}
//participant note
if (!empty($query->_returnProperties['participant_note'])) {
$query->_select['participant_note'] = "civicrm_note.note as participant_note";
$query->_element['participant_note'] = 1;
$query->_tables['participant_note'] = 1;
$query->_whereTables['civicrm_note'] = 1;
}
if (!empty($query->_returnProperties['participant_is_pay_later'])) {
$query->_select['participant_is_pay_later'] = "civicrm_participant.is_pay_later as participant_is_pay_later";
$query->_element['participant_is_pay_later'] = 1;
}
if (!empty($query->_returnProperties['participant_is_test'])) {
$query->_select['participant_is_test'] = "civicrm_participant.is_test as participant_is_test";
$query->_element['participant_is_test'] = 1;
}
if (!empty($query->_returnProperties['participant_registered_by_id'])) {
$query->_select['participant_registered_by_id'] = "civicrm_participant.registered_by_id as participant_registered_by_id";
$query->_element['participant_registered_by_id'] = 1;
}
// get discount name
if (!empty($query->_returnProperties['participant_discount_name'])) {
$query->_select['participant_discount_name'] = "discount_name.title as participant_discount_name";
$query->_element['participant_discount_name'] = 1;
$query->_tables['civicrm_discount'] = 1;
$query->_tables['participant_discount_name'] = 1;
$query->_whereTables['civicrm_discount'] = 1;
$query->_whereTables['participant_discount_name'] = 1;
}
//carry campaign id to selectors.
if (!empty($query->_returnProperties['participant_campaign_id'])) {
$query->_select['participant_campaign_id'] = 'civicrm_participant.campaign_id as participant_campaign_id';
$query->_element['participant_campaign_id'] = 1;
}
}
}
/**
* @param $query
*/
public static function where(&$query) {
$grouping = NULL;
foreach (array_keys($query->_params) as $id) {
if (empty($query->_params[$id][0])) {
continue;
}
if (substr($query->_params[$id][0], 0, 6) == 'event_' ||
substr($query->_params[$id][0], 0, 12) == 'participant_'
) {
if ($query->_mode == CRM_Contact_BAO_QUERY::MODE_CONTACTS) {
$query->_useDistinct = TRUE;
}
$grouping = $query->_params[$id][3];
self::whereClauseSingle($query->_params[$id], $query);
}
}
}
/**
* @param $values
* @param $query
*/
public static function whereClauseSingle(&$values, &$query) {
$checkPermission = empty($query->_skipPermission);
list($name, $op, $value, $grouping, $wildcard) = $values;
$fields = array_merge(CRM_Event_BAO_Event::fields(), CRM_Event_BAO_Participant::exportableFields());
switch ($name) {
case 'event_start_date_low':
case 'event_start_date_high':
$query->dateQueryBuilder($values,
'civicrm_event', 'event_start_date', 'start_date', 'Start Date'
);
return;
case 'event_end_date_low':
case 'event_end_date_high':
$query->dateQueryBuilder($values,
'civicrm_event', 'event_end_date', 'end_date', 'End Date'
);
return;
case 'event_include_repeating_events':
/**
* Include Repeating Events
*/
//Get parent of this event
$exEventId = '';
if ($query->_where[$grouping]) {
foreach ($query->_where[$grouping] as $key => $val) {
if (strstr($val, 'civicrm_event.id =')) {
$exEventId = $val;
$extractEventId = explode(" ", $val);
$value = $extractEventId[2];
$where = $query->_where[$grouping][$key];
}
elseif (strstr($val, 'civicrm_event.id IN')) {
//extract the first event id if multiple events are selected
preg_match('/civicrm_event.id IN \(\"(\d+)/', $val, $matches);
$value = $matches[1];
$where = $query->_where[$grouping][$key];
}
}
if ($exEventId) {
$extractEventId = explode(" ", $exEventId);
$value = $extractEventId[2];
}
elseif (!empty($matches[1])) {
$value = $matches[1];
}
$where = $query->_where[$grouping][$key];
}
$thisEventHasParent = CRM_Core_BAO_RecurringEntity::getParentFor($value, 'civicrm_event');
if ($thisEventHasParent) {
$getAllConnections = CRM_Core_BAO_RecurringEntity::getEntitiesForParent($thisEventHasParent, 'civicrm_event');
$allEventIds = array();
foreach ($getAllConnections as $key => $val) {
$allEventIds[] = $val['id'];
}
if (!empty($allEventIds)) {
$op = "IN";
$value = "(" . implode(",", $allEventIds) . ")";
}
}
$query->_where[$grouping][] = "{$where} OR civicrm_event.id $op {$value}";
$query->_qill[$grouping][] = ts('Include Repeating Events');
$query->_tables['civicrm_event'] = $query->_whereTables['civicrm_event'] = 1;
return;
case 'participant_is_test':
$key = array_search('civicrm_participant.is_test = 0', $query->_where[$grouping]);
if (!empty($key)) {
unset($query->_where[$grouping][$key]);
}
case 'participant_test':
// We dont want to include all tests for sql OR CRM-7827
if (!$value || $query->getOperator() != 'OR') {
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_participant.is_test",
$op,
$value,
"Boolean"
);
$isTest = $value ? 'a Test' : 'not a Test';
$query->_qill[$grouping][] = ts("Participant is %1", array(1 => $isTest));
$query->_tables['civicrm_participant'] = $query->_whereTables['civicrm_participant'] = 1;
}
return;
case 'participant_fee_id':
foreach ($value as $k => &$val) {
$val = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $val, 'label');
$val = CRM_Core_DAO::escapeString(trim($val));
}
$feeLabel = implode('|', $value);
$query->_where[$grouping][] = "civicrm_participant.fee_level REGEXP '{$feeLabel}'";
$query->_qill[$grouping][] = ts("Fee level") . " IN " . implode(', ', $value);
$query->_tables['civicrm_participant'] = $query->_whereTables['civicrm_participant'] = 1;
return;
case 'participant_fee_amount_high':
case 'participant_fee_amount_low':
$query->numberRangeBuilder($values,
'civicrm_participant', 'participant_fee_amount', 'fee_amount', 'Fee Amount'
);
return;
case 'participant_status_id':
if ($value && is_array($value) && strpos($op, 'IN') === FALSE) {
$op = 'IN';
}
case 'participant_status':
case 'participant_source':
case 'participant_id':
case 'participant_contact_id':
case 'participant_is_pay_later':
case 'participant_fee_amount':
case 'participant_fee_level':
case 'participant_campaign_id':
case 'participant_registered_by_id':
$qillName = $name;
if (in_array($name, array(
'participant_status_id',
'participant_source',
'participant_id',
'participant_contact_id',
'participant_fee_amount',
'participant_fee_level',
'participant_is_pay_later',
'participant_campaign_id',
'participant_registered_by_id',
))
) {
$name = str_replace('participant_', '', $name);
if ($name == 'is_pay_later') {
$qillName = $name;
}
}
elseif ($name == 'participant_status') {
$name = 'status_id';
}
$dataType = !empty($fields[$qillName]['type']) ? CRM_Utils_Type::typeToString($fields[$qillName]['type']) : 'String';
$tableName = empty($tableName) ? 'civicrm_participant' : $tableName;
if (is_array($value) && in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
$op = key($value);
$value = $value[$op];
}
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("$tableName.$name", $op, $value, $dataType);
list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Event_DAO_Participant', $name, $value, $op);
$query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $fields[$qillName]['title'], 2 => $op, 3 => $value));
$query->_tables['civicrm_participant'] = $query->_whereTables['civicrm_participant'] = 1;
return;
case 'participant_role':
case 'participant_role_id':
$qillName = $name;
$name = 'role_id';
$dataType = !empty($fields[$qillName]['type']) ? CRM_Utils_Type::typeToString($fields[$qillName]['type']) : 'String';
$tableName = empty($tableName) ? 'civicrm_participant' : $tableName;
if (is_array($value) && in_array(key($value), CRM_Core_DAO::acceptedSQLOperators(), TRUE)) {
$op = key($value);
$value = $value[$op];
}
if (!strstr($op, 'NULL') && !strstr($op, 'EMPTY') && !strstr($op, 'LIKE')) {
$regexOp = (strstr($op, '!') || strstr($op, 'NOT')) ? 'NOT REGEXP' : 'REGEXP';
$regexp = "([[:cntrl:]]|^)" . implode('([[:cntrl:]]|$)|([[:cntrl:]]|^)', (array) $value) . "([[:cntrl:]]|$)";
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_participant.$name", $regexOp, $regexp, 'String');
}
else {
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("$tableName.$name", $op, $value, $dataType);
}
list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Event_DAO_Participant', $name, $value, $op);
$query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $fields[$qillName]['title'], 2 => $op, 3 => $value));
$query->_tables['civicrm_participant'] = $query->_whereTables['civicrm_participant'] = 1;
return;
case 'participant_register_date':
case 'participant_register_date_high':
case 'participant_register_date_low':
$query->dateQueryBuilder($values,
'civicrm_participant', 'participant_register_date', 'register_date', 'Register Date'
);
return;
case 'event_id':
case 'participant_event_id':
$name = str_replace('participant_', '', $name);
case 'event_is_public':
case 'event_type_id':
case 'event_title':
$qillName = $name;
if (in_array($name, array(
'event_id',
'event_title',
'event_is_public',
)
)
) {
$name = str_replace('event_', '', $name);
}
$dataType = !empty($fields[$qillName]['type']) ? CRM_Utils_Type::typeToString($fields[$qillName]['type']) : 'String';
$query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_event.$name", $op, $value, $dataType);
$query->_tables['civicrm_event'] = $query->_whereTables['civicrm_event'] = 1;
if (!array_key_exists($qillName, $fields)) {
break;
}
list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Event_DAO_Event', $name, $value, $op, array('check_permission' => $checkPermission));
$query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $fields[$qillName]['title'], 2 => $op, 3 => $value));
return;
}
}
/**
* @param string $name
* @param $mode
* @param $side
*
* @return null|string
*/
public static function from($name, $mode, $side) {
$from = NULL;
switch ($name) {
case 'civicrm_participant':
$from = " LEFT JOIN civicrm_participant ON civicrm_participant.contact_id = contact_a.id ";
break;
case 'civicrm_event':
//CRM-17121
$from = " LEFT JOIN civicrm_event ON civicrm_participant.event_id = civicrm_event.id ";
break;
case 'event_type':
$from = " $side JOIN civicrm_option_group option_group_event_type ON (option_group_event_type.name = 'event_type')";
$from .= " $side JOIN civicrm_option_value event_type ON (civicrm_event.event_type_id = event_type.value AND option_group_event_type.id = event_type.option_group_id ) ";
break;
case 'participant_note':
$from .= " $side JOIN civicrm_note ON ( civicrm_note.entity_table = 'civicrm_participant' AND
civicrm_participant.id = civicrm_note.entity_id )";
break;
case 'participant_status':
$from .= " $side JOIN civicrm_participant_status_type participant_status ON (civicrm_participant.status_id = participant_status.id) ";
break;
case 'participant_role':
$from = " $side JOIN civicrm_option_group option_group_participant_role ON (option_group_participant_role.name = 'participant_role')";
$from .= " $side JOIN civicrm_option_value participant_role ON ((civicrm_participant.role_id = participant_role.value OR SUBSTRING_INDEX(role_id,'', 1) = participant_role.value)
AND option_group_participant_role.id = participant_role.option_group_id ) ";
break;
case 'participant_discount_name':
$from = " $side JOIN civicrm_discount discount ON ( civicrm_participant.discount_id = discount.id )";
$from .= " $side JOIN civicrm_option_group discount_name ON ( discount_name.id = discount.price_set_id ) ";
break;
}
return $from;
}
/**
* @param $mode
* @param bool $includeCustomFields
*
* @return array|null
*/
public static function defaultReturnProperties(
$mode,
$includeCustomFields = TRUE
) {
$properties = NULL;
if ($mode & CRM_Contact_BAO_Query::MODE_EVENT) {
$properties = array(
'contact_type' => 1,
'contact_sub_type' => 1,
'sort_name' => 1,
'display_name' => 1,
'event_id' => 1,
'event_title' => 1,
'event_start_date' => 1,
'event_end_date' => 1,
'event_type' => 1,
'participant_id' => 1,
'participant_status' => 1,
'participant_status_id' => 1,
'participant_role' => 1,
'participant_role_id' => 1,
'participant_note' => 1,
'participant_register_date' => 1,
'participant_source' => 1,
'participant_fee_level' => 1,
'participant_is_test' => 1,
'participant_is_pay_later' => 1,
'participant_fee_amount' => 1,
'participant_discount_name' => 1,
'participant_fee_currency' => 1,
'participant_registered_by_id' => 1,
'participant_campaign_id' => 1,
);
if ($includeCustomFields) {
// also get all the custom participant properties
$fields = CRM_Core_BAO_CustomField::getFieldsForImport('Participant');
if (!empty($fields)) {
foreach ($fields as $name => $dontCare) {
$properties[$name] = 1;
}
}
}
}
return $properties;
}
/**
* @param CRM_Core_Form $form
*/
public static function buildSearchForm(&$form) {
$dataURLEventFee = CRM_Utils_System::url('civicrm/ajax/eventFee',
"reset=1",
FALSE, NULL, FALSE
);
$form->assign('dataURLEventFee', $dataURLEventFee);
$form->addEntityRef('event_id', ts('Event Name'), array(
'entity' => 'event',
'placeholder' => ts('- any -'),
'multiple' => 1,
'select' => array('minimumInputLength' => 0),
)
);
$form->addEntityRef('event_type_id', ts('Event Type'), array(
'entity' => 'option_value',
'placeholder' => ts('- any -'),
'select' => array('minimumInputLength' => 0),
'api' => array(
'params' => array('option_group_id' => 'event_type'),
),
)
);
$obj = new CRM_Report_Form_Event_ParticipantListing();
$form->add('select', 'participant_fee_id',
ts('Fee Level'),
$obj->getPriceLevels(),
FALSE, array('class' => 'crm-select2', 'multiple' => 'multiple', 'placeholder' => ts('- any -'))
);
CRM_Core_Form_Date::buildDateRange($form, 'event', 1, '_start_date_low', '_end_date_high', ts('From'), FALSE);
CRM_Core_Form_Date::buildDateRange($form, 'participant', 1, '_register_date_low', '_register_date_high', ts('From'), FALSE);
$form->addElement('hidden', 'event_date_range_error');
$form->addElement('hidden', 'participant_date_range_error');
$form->addFormRule(array('CRM_Event_BAO_Query', 'formRule'), $form);
$form->addElement('checkbox', "event_include_repeating_events", NULL, ts('Include participants from all events in the %1 series', array(1 => '<em>%1</em>')));
$form->addSelect('participant_status_id',
array(
'entity' => 'participant',
'label' => ts('Participant Status'),
'multiple' => 'multiple',
'option_url' => NULL,
'placeholder' => ts('- any -'),
)
);
$form->addSelect('participant_role_id',
array(
'entity' => 'participant',
'label' => ts('Participant Role'),
'multiple' => 'multiple',
'option_url' => NULL,
'placeholder' => ts('- any -'),
)
);
$form->addYesNo('participant_test', ts('Participant is a Test?'), TRUE);
$form->addYesNo('participant_is_pay_later', ts('Participant is Pay Later?'), TRUE);
$form->addElement('text', 'participant_fee_amount_low', ts('From'), array('size' => 8, 'maxlength' => 8));
$form->addElement('text', 'participant_fee_amount_high', ts('To'), array('size' => 8, 'maxlength' => 8));
$form->addRule('participant_fee_amount_low', ts('Please enter a valid money value.'), 'money');
$form->addRule('participant_fee_amount_high', ts('Please enter a valid money value.'), 'money');
self::addCustomFormFields($form, array('Participant', 'Event'));
CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($form, 'participant_campaign_id');
$form->assign('validCiviEvent', TRUE);
$form->setDefaults(array('participant_test' => 0));
}
/**
* @param $tables
*/
public static function tableNames(&$tables) {
//add participant table
if (!empty($tables['civicrm_event'])) {
$tables = array_merge(array('civicrm_participant' => 1), $tables);
}
}
/**
* Check if the values in the date range are in correct chronological order.
*
* @todo Get this to work with CRM_Utils_Rule::validDateRange
*
* @param array $fields
* @param array $files
* @param CRM_Core_Form $form
*
* @return bool|array
*/
public static function formRule($fields, $files, $form) {
$errors = array();
if ((empty($fields['event_start_date_low']) || empty($fields['event_end_date_high'])) && (empty($fields['participant_register_date_low']) || empty($fields['participant_register_date_high']))) {
return TRUE;
}
$lowDate = strtotime($fields['event_start_date_low']);
$highDate = strtotime($fields['event_end_date_high']);
if ($lowDate > $highDate) {
$errors['event_date_range_error'] = ts('Please check that your Event Date Range is in correct chronological order.');
}
$lowDate1 = strtotime($fields['participant_register_date_low']);
$highDate1 = strtotime($fields['participant_register_date_high']);
if ($lowDate1 > $highDate1) {
$errors['participant_date_range_error'] = ts('Please check that your Registration Date Range is in correct chronological order.');
}
return empty($errors) ? TRUE : $errors;
}
}

View file

@ -0,0 +1,211 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/*
* Copyright (C) 2010 Tech To The People
* Licensed to CiviCRM under the Academic Free License version 3.0.
*
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class print the name badges for the participants
* It isn't supposed to be called directly, but is the parent class of the classes in CRM/Event/Badges/XXX.php
*
*/
class CRM_Event_Badge {
/**
*/
public function __construct() {
$this->style = array(
'width' => 0.1,
'cap' => 'round',
'join' => 'round',
'dash' => '2,2',
'color' => array(0, 0, 200),
);
$this->format = '5160';
$this->imgExtension = 'png';
$this->imgRes = 300;
$this->event = NULL;
$this->setDebug(FALSE);
}
/**
* @param bool $debug
*/
public function setDebug($debug = TRUE) {
if (!$debug) {
$this->debug = FALSE;
$this->border = 0;
}
else {
$this->debug = TRUE;
$this->border = "LTRB";
}
}
/**
* Create the labels (pdf).
*
* It assumes the participants are from the same event
*
* @param array $participants
*/
public function run(&$participants) {
// fetch the 1st participant, and take her event to retrieve its attributes
$participant = reset($participants);
$eventID = $participant['event_id'];
$this->event = self::retrieveEvent($eventID);
//call function to create labels
self::createLabels($participants);
CRM_Utils_System::civiExit(1);
}
/**
* @param int $eventID
*
* @return CRM_Event_BAO_Event|null
*/
protected function retrieveEvent($eventID) {
$bao = new CRM_Event_BAO_Event();
if ($bao->get('id', $eventID)) {
return $bao;
}
return NULL;
}
/**
* @param int $eventID
* @param bool $img
*
* @return string
*/
public function getImageFileName($eventID, $img = FALSE) {
global $civicrm_root;
$path = "CRM/Event/Badge";
if ($img == FALSE) {
return FALSE;
}
if ($img == TRUE) {
$img = get_class($this) . "." . $this->imgExtension;
}
// CRM-13235 - leverage the Smarty path to get all templates directories
$template = CRM_Core_Smarty::singleton();
if (isset($template->template_dir) && $template->template_dir) {
$dirs = is_array($template->template_dir) ? $template->template_dir : array($template->template_dir);
foreach ($dirs as $dir) {
foreach (array("$dir/$path/$eventID/$img", "$dir/$path/$img") as $imgFile) {
if (file_exists($imgFile)) {
return $imgFile;
}
}
}
}
else {
$imgFile = 'No template directories defined anywhere??';
}
// not sure it exists, but at least will display a meaniful fatal error in debug mode
return $imgFile;
}
/**
* @param bool $img
*/
public function printBackground($img = FALSE) {
$x = $this->pdf->GetAbsX();
$y = $this->pdf->GetY();
if ($this->debug) {
$this->pdf->Rect($x, $y, $this->pdf->width, $this->pdf->height, 'D', array(
'all' => array(
'width' => 1,
'cap' => 'round',
'join' => 'round',
'dash' => '2,10',
'color' => array(255, 0, 0),
),
));
}
$img = $this->getImageFileName($this->event->id, $img);
if ($img) {
$imgsize = getimagesize($img);
// mm
$f = $this->imgRes / 25.4;
$w = $imgsize[0] / $f;
$h = $imgsize[1] / $f;
$this->pdf->Image($img, $this->pdf->GetAbsX(), $this->pdf->GetY(), $w, $h, strtoupper($this->imgExtension), '', '', FALSE, 72, '', FALSE, FALSE, $this->debug, FALSE, FALSE, FALSE);
}
$this->pdf->SetXY($x, $y);
}
/**
* This is supposed to be overridden.
*
* @param array $participant
*/
public function generateLabel($participant) {
$txt = "{$this->event['title']}
{$participant['display_name']}
{$participant['current_employer']}";
$this->pdf->MultiCell($this->pdf->width, $this->pdf->lineHeight, $txt);
}
public function pdfExtraFormat() {
}
/**
* Create labels (pdf).
*
* @param array $participants
*/
public function createLabels(&$participants) {
$this->pdf = new CRM_Utils_PDF_Label($this->format, 'mm');
$this->pdfExtraFormat();
$this->pdf->Open();
$this->pdf->setPrintHeader(FALSE);
$this->pdf->setPrintFooter(FALSE);
$this->pdf->AddPage();
$this->pdf->AddFont('DejaVu Sans', '', 'DejaVuSans.php');
$this->pdf->SetFont('DejaVu Sans');
$this->pdf->SetGenerator($this, "generateLabel");
foreach ($participants as $participant) {
$this->pdf->AddPdfLabel($participant);
}
$this->pdf->Output($this->event->title . '.pdf', 'D');
}
}

View file

@ -0,0 +1,63 @@
<?php
/**
* Class CRM_Event_Badge_Logo
*/
class CRM_Event_Badge_Logo extends CRM_Event_Badge {
/**
*/
public function __construct() {
parent::__construct();
// A4
$pw = 210;
$ph = 297;
$h = 50;
$w = 75;
$this->format = array(
'name' => 'Sigel 3C',
'paper-size' => 'A4',
'metric' => 'mm',
'lMargin' => ($pw - $w * 2) / 2,
'tMargin' => ($ph - $h * 5) / 2,
'NX' => 2,
'NY' => 5,
'SpaceX' => 0,
'SpaceY' => 0,
'width' => $w,
'height' => $h,
'font-size' => 12,
);
$this->lMarginLogo = 20;
$this->tMarginName = 20;
// $this->setDebug ();
}
/**
* @param $participant
*/
public function generateLabel($participant) {
$x = $this->pdf->GetAbsX();
$y = $this->pdf->GetY();
$this->printBackground(TRUE);
$this->pdf->SetLineStyle(array(
'width' => 0.1,
'cap' => 'round',
'join' => 'round',
'dash' => '2,2',
'color' => array(0, 0, 200),
));
$this->pdf->SetFontSize(8);
$this->pdf->MultiCell($this->pdf->width - $this->lMarginLogo, 0, $participant['event_title'], $this->border, "L", 0, 1, $x + $this->lMarginLogo, $y);
$this->pdf->SetXY($x, $y + $this->pdf->height - 5);
$date = CRM_Utils_Date::customFormat($participant['event_start_date'], "%e %b");
$this->pdf->Cell($this->pdf->width, 0, $date, $this->border, 2, "R");
$this->pdf->SetFontSize(15);
$this->pdf->MultiCell($this->pdf->width, 10, $participant['display_name'], $this->border, "C", 0, 1, $x, $y + $this->tMarginName);
$this->pdf->SetFontSize(10);
$this->pdf->MultiCell($this->pdf->width, 0, $participant['current_employer'], $this->border, "C", 0, 1, $x, $this->pdf->getY());
}
}

View file

@ -0,0 +1,63 @@
<?php
/**
* Class CRM_Event_Badge_Logo5395
*/
class CRM_Event_Badge_Logo5395 extends CRM_Event_Badge {
/**
*/
public function __construct() {
parent::__construct();
// A4
$pw = 210;
$ph = 297;
$h = 59.2;
$w = 85.7;
$this->format = array(
'name' => 'Avery 5395',
'paper-size' => 'A4',
'metric' => 'mm',
'lMargin' => 13.5,
'tMargin' => 3,
'NX' => 2,
'NY' => 4,
'SpaceX' => 15,
'SpaceY' => 8.5,
'width' => $w,
'height' => $h,
'font-size' => 12,
);
$this->lMarginLogo = 20;
$this->tMarginName = 20;
// $this->setDebug ();
}
/**
* @param $participant
*/
public function generateLabel($participant) {
$x = $this->pdf->GetAbsX();
$y = $this->pdf->GetY();
$this->printBackground(TRUE);
$this->pdf->SetLineStyle(array(
'width' => 0.1,
'cap' => 'round',
'join' => 'round',
'dash' => '2,2',
'color' => array(0, 0, 200),
));
$this->pdf->SetFontSize(9);
$this->pdf->MultiCell($this->pdf->width - $this->lMarginLogo, 0, $participant['event_title'], $this->border, "L", 0, 1, $x + $this->lMarginLogo, $y);
$this->pdf->SetXY($x, $y + $this->pdf->height - 5);
$date = CRM_Utils_Date::customFormat($participant['event_start_date'], "%e %b");
$this->pdf->Cell($this->pdf->width, 0, $date, $this->border, 2, "R");
$this->pdf->SetFontSize(20);
$this->pdf->MultiCell($this->pdf->width, 10, $participant['display_name'], $this->border, "C", 0, 1, $x, $y + $this->tMarginName);
$this->pdf->SetFontSize(15);
$this->pdf->MultiCell($this->pdf->width, 0, $participant['current_employer'], $this->border, "C", 0, 1, $x, $this->pdf->getY());
}
}

View file

@ -0,0 +1,99 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/*
* Copyright (C) 2010 Tech To The People
* Licensed to CiviCRM under the Academic Free License version 3.0.
*
*/
/**
*
* @package CRM
*
*/
class CRM_Event_Badge_NameTent extends CRM_Event_Badge {
/**
*/
public function __construct() {
parent::__construct();
// A4
$pw = 297;
$ph = 210;
$this->lMargin = 10;
$this->tMargin = 0;
$w = $pw - 2 * $this->lMargin;
$h = $ph - 2 * $this->tMargin;
$this->format = array(
'name' => 'A4 horiz',
'paper-size' => 'A4',
'metric' => 'mm',
'lMargin' => 0,
'tMargin' => 0,
'NX' => 1,
'NY' => 1,
'SpaceX' => 0,
'SpaceY' => 0,
'width' => $w,
'height' => $h,
'font-size' => 36,
);
// $this->setDebug ();
}
public function pdfExtraFormat() {
$this->pdf->setPageFormat('A4', 'L');
}
/**
* @param $participant
*/
protected function writeOneSide(&$participant) {
$this->pdf->SetXY(0, $this->pdf->height / 2);
$this->printBackground(TRUE);
$txt = $participant['display_name'];
$this->pdf->SetXY(0, $this->pdf->height / 2 + 20);
$this->pdf->SetFontSize(54);
$this->pdf->Write(0, $txt, NULL, NULL, 'C');
$this->pdf->SetXY(0, $this->pdf->height / 2 + 50);
$this->pdf->SetFontSize(36);
$this->pdf->Write(0, $participant['current_employer'], NULL, NULL, 'C');
}
/**
* @param $participant
*/
public function generateLabel($participant) {
$this->writeOneSide($participant);
$this->pdf->StartTransform();
$this->pdf->Rotate(180, $this->pdf->width / 2 + $this->pdf->marginLeft, $this->pdf->height / 2);
$this->writeOneSide($participant);
$this->pdf->StopTransform();
}
}

View file

@ -0,0 +1,62 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/*
* Copyright (C) 2010 Tech To The People
* Licensed to CiviCRM under the Academic Free License version 3.0.
*
*/
/**
*
* @package CRM
*
*/
class CRM_Event_Badge_Simple extends CRM_Event_Badge {
/**
* @param $participant
*/
public function generateLabel($participant) {
$date = CRM_Utils_Date::customFormat($participant['event_start_date'], "%e %b");
$this->pdf->SetFontSize(8);
$y = $this->pdf->GetY();
$x = $this->pdf->GetAbsX();
$this->pdf->Cell($this->pdf->width, $this->pdf->lineHeight, $participant['event_title'], 0, 1, "L");
$this->pdf->SetXY($x, $y + 4);
$this->pdf->Cell($this->pdf->width, $this->pdf->lineHeight, $date, 0, 2, "R");
$this->pdf->SetFontSize(12);
$this->pdf->SetXY($x, $this->pdf->GetY() + 5);
$this->pdf->Cell($this->pdf->width, $this->pdf->lineHeight, $participant['display_name'], 0, 2, "C");
$this->pdf->SetFontSize(10);
$this->pdf->SetXY($x, $this->pdf->GetY() + 2);
$this->pdf->Cell($this->pdf->width, $this->pdf->lineHeight, $participant['current_employer'], 0, 2, "C");
//$this->pdf->MultiCell ($this->pdf->width, $this->pdf->lineHeight, $txt,1,"L");
}
}

View file

@ -0,0 +1,344 @@
<?php
/**
* Class CRM_Event_Cart_BAO_Cart
*/
class CRM_Event_Cart_BAO_Cart extends CRM_Event_Cart_DAO_Cart {
public $associations_loaded = FALSE;
/* event_in_cart_id => $event_in_cart */
public $events_in_carts = array();
/**
* @param array $params
*
* @return CRM_Event_Cart_BAO_Cart
*/
public static function add(&$params) {
$cart = new CRM_Event_Cart_BAO_Cart();
$cart->copyValues($params);
$result = $cart->save();
return $result;
}
/**
* @param int $event_id
*
* @return mixed
*/
public function add_event($event_id) {
$this->load_associations();
$event_in_cart = $this->get_event_in_cart_by_event_id($event_id);
if ($event_in_cart) {
return $event_in_cart;
}
$params = array(
'event_id' => $event_id,
'event_cart_id' => $this->id,
);
$event_in_cart = CRM_Event_Cart_BAO_EventInCart::create($params);
$event_in_cart->load_associations($this);
$this->events_in_carts[$event_in_cart->event_id] = $event_in_cart;
return $this->events_in_carts[$event_in_cart->event_id];
}
/**
* @param $participant
*/
public function add_participant_to_cart($participant) {
$event_in_cart = $this->get_event_in_cart_by_event_id($participant->event_id);
if (!$event_in_cart) {
$event_in_cart = $this->add_event($participant->event_id);
}
$event_in_cart->add_participant($participant);
$event_in_cart->save();
}
/**
* @param array $params
*
* @return CRM_Event_Cart_BAO_Cart
* @throws Exception
*/
public static function create($params) {
$transaction = new CRM_Core_Transaction();
$cart = self::add($params);
if (is_a($cart, 'CRM_Core_Error')) {
$transaction->rollback();
CRM_Core_Error::fatal(ts('There was an error creating an event cart'));
}
$transaction->commit();
return $cart;
}
/**
* @param int $id
*
* @return bool|CRM_Event_Cart_BAO_Cart
*/
public static function find_by_id($id) {
return self::find_by_params(array('id' => $id));
}
/**
* @param array $params
*
* @return bool|CRM_Event_Cart_BAO_Cart
*/
public static function find_by_params($params) {
$cart = new CRM_Event_Cart_BAO_Cart();
$cart->copyValues($params);
if ($cart->find(TRUE)) {
return $cart;
}
else {
return FALSE;
}
}
/**
* @return self|bool|CRM_Event_Cart_BAO_Cart
*/
public static function find_or_create_for_current_session() {
$session = CRM_Core_Session::singleton();
$event_cart_id = $session->get('event_cart_id');
$userID = $session->get('userID');
$cart = FALSE;
if (!is_null($event_cart_id)) {
$cart = self::find_uncompleted_by_id($event_cart_id);
if ($cart && $userID) {
if (!$cart->user_id) {
$saved_cart = self::find_uncompleted_by_user_id($userID);
if ($saved_cart) {
$cart->adopt_participants($saved_cart->id);
$saved_cart->delete();
$cart->load_associations();
}
else {
$cart->user_id = $userID;
$cart->save();
}
}
}
}
if ($cart === FALSE) {
if (is_null($userID)) {
$cart = self::create(array());
}
else {
$cart = self::find_uncompleted_by_user_id($userID);
if ($cart === FALSE) {
$cart = self::create(array('user_id' => $userID));
}
}
$session->set('event_cart_id', $cart->id);
}
return $cart;
}
/**
* @param int $id
*
* @return bool|CRM_Event_Cart_BAO_Cart
*/
public static function find_uncompleted_by_id($id) {
return self::find_by_params(array('id' => $id, 'completed' => 0));
}
/**
* @param int $user_id
*
* @return bool|CRM_Event_Cart_BAO_Cart
*/
public static function find_uncompleted_by_user_id($user_id) {
return self::find_by_params(array('user_id' => $user_id, 'completed' => 0));
}
/**
* @return array
*/
public function get_main_events_in_carts() {
//return CRM_Event_Cart_BAO_EventInCart::find_all_by_params( array('main_conference_event_id'
$all = array();
foreach ($this->events_in_carts as $event_in_cart) {
if (!$event_in_cart->is_child_event()) {
$all[] = $event_in_cart;
}
}
return $all;
}
/**
* @param int $main_conference_event_id
*
* @return array
*/
public function get_events_in_carts_by_main_event_id($main_conference_event_id) {
$all = array();
if (!$main_conference_event_id) {
return $all;
}
foreach ($this->events_in_carts as $event_in_cart) {
if ($event_in_cart->event->parent_event_id == $main_conference_event_id) {
$all[] = $event_in_cart;
}
}
usort($all, "CRM_Event_Cart_BAO_Cart::compare_event_dates");
return $all;
}
/**
* @param $event_in_cart_1
* @param $event_in_cart_2
*
* @return int
*/
public static function compare_event_dates($event_in_cart_1, $event_in_cart_2) {
$date_1 = CRM_Utils_Date::unixTime($event_in_cart_1->event->start_date);
$date_2 = CRM_Utils_Date::unixTime($event_in_cart_2->event->start_date);
if ($date_1 == $date_2) {
return 0;
}
return ($date_1 < $date_2) ? -1 : 1;
}
/**
* @param $main_participant
*
* @return array
*/
public function get_subparticipants($main_participant) {
$subparticipants = array();
foreach ($this->events_in_carts as $event_in_cart) {
if ($event_in_cart->is_child_event($main_participant->event_id)) {
foreach ($event_in_cart->participants as $participant) {
if ($participant->contact_id == $main_participant->contact_id) {
$subparticipants[] = $participant;
continue;
}
}
}
}
return $subparticipants;
}
/**
* @param int $event_id
*
* @return mixed
*/
public function get_event_in_cart_by_event_id($event_id) {
return CRM_Utils_Array::value($event_id, $this->events_in_carts);
}
/**
* @param int $event_in_cart_id
*
* @return null
*/
public function &get_event_in_cart_by_id($event_in_cart_id) {
foreach ($this->events_in_carts as $event_in_cart) {
if ($event_in_cart->id == $event_in_cart_id) {
return $event_in_cart;
}
}
return NULL;
}
/**
* @return array
*/
public function get_main_event_participants() {
$participants = array();
foreach ($this->get_main_events_in_carts() as $event_in_cart) {
$participants = array_merge($participants, $event_in_cart->participants);
}
return $participants;
}
public function load_associations() {
if ($this->associations_loaded) {
return;
}
$this->associations_loaded = TRUE;
$this->events_in_carts = CRM_Event_Cart_BAO_EventInCart::find_all_by_event_cart_id($this->id);
foreach ($this->events_in_carts as $event_in_cart) {
$event_in_cart->load_associations($this);
}
$this->save();
}
/**
* @param int $event_in_cart_id
*
* @return bool|CRM_Event_Cart_BAO_EventInCart
*/
public function remove_event_in_cart($event_in_cart_id) {
$event_in_cart = CRM_Event_Cart_BAO_EventInCart::find_by_id($event_in_cart_id);
if ($event_in_cart) {
$sessions_to_remove = $this->get_events_in_carts_by_main_event_id($event_in_cart->event_id);
foreach ($sessions_to_remove as $session) {
$this->remove_event_in_cart($session->id);
}
unset($this->events_in_carts[$event_in_cart->event_id]);
$event_in_cart->delete();
}
return $event_in_cart;
}
/**
* @param int $participant_id
*
* @return int
*/
public function get_participant_index_from_id($participant_id) {
foreach ($this->events_in_carts as $event_in_cart) {
$index = 0;
foreach ($event_in_cart->participants as $participant) {
if ($participant->id == $participant_id) {
return $index;
}
$index++;
}
}
return -1;
}
/**
* @param array $params
* @param $values
*
* @return mixed
* @throws Exception
*/
public static function retrieve(&$params, &$values) {
$cart = self::find_by_params($params);
if ($cart === FALSE) {
CRM_Core_Error::fatal(ts('Could not find cart matching %1', array(1 => var_export($params, TRUE))));
}
CRM_Core_DAO::storeValues($cart, $values);
return $values;
}
/**
* @param int $from_cart_id
*/
public function adopt_participants($from_cart_id) {
$params = array(
1 => array($this->id, 'Integer'),
2 => array($from_cart_id, 'Integer'),
);
$sql = "UPDATE civicrm_participant SET cart_id='%1' WHERE cart_id='%2'";
CRM_Core_DAO::executeQuery($sql, $params);
}
}

View file

@ -0,0 +1,43 @@
<?php
/**
* Class CRM_Event_Cart_BAO_Conference
*/
class CRM_Event_Cart_BAO_Conference {
/**
* XXX assumes we don't allow a contact to register for the same conference more than once
* XXX flattens the object tree for convenient templating
* @param int $main_event_participant_id
*
* @return array|null
*/
public static function get_participant_sessions($main_event_participant_id) {
$sql = <<<EOS
SELECT sub_event.* FROM civicrm_participant main_participant
JOIN civicrm_event sub_event ON sub_event.parent_event_id = main_participant.event_id
JOIN civicrm_participant sub_participant ON sub_participant.event_id = sub_event.id
LEFT JOIN
civicrm_option_value slot ON sub_event.slot_label_id = slot.value
LEFT JOIN
civicrm_option_group og ON slot.option_group_id = og.id
WHERE
main_participant.id = %1
AND sub_participant.contact_id = main_participant.contact_id
AND og.name = 'conference_slot'
ORDER BY
slot.weight,
sub_event.start_date
EOS;
$sql_args = array(1 => array($main_event_participant_id, 'Integer'));
$dao = CRM_Core_DAO::executeQuery($sql, $sql_args);
$smarty_sessions = array();
while ($dao->fetch()) {
$smarty_sessions[] = get_object_vars($dao);
}
if (empty($smarty_sessions)) {
return NULL;
}
return $smarty_sessions;
}
}

View file

@ -0,0 +1,329 @@
<?php
/**
* Class CRM_Event_Cart_BAO_EventInCart
*/
class CRM_Event_Cart_BAO_EventInCart extends CRM_Event_Cart_DAO_EventInCart implements ArrayAccess {
public $assocations_loaded = FALSE;
public $event;
public $event_cart;
public $location = NULL;
public $participants = array();
/**
* Class constructor.
*/
public function __construct() {
parent::__construct();
}
/**
* Add participant to cart.
*
* @param $participant
*/
public function add_participant($participant) {
$this->participants[$participant->id] = $participant;
}
/**
* @param array $params
*
* @return object $this|CRM_Event_Cart_BAO_EventInCart
* @throws Exception
*/
public static function create(&$params) {
$transaction = new CRM_Core_Transaction();
$event_in_cart = new CRM_Event_Cart_BAO_EventInCart();
$event_in_cart->copyValues($params);
$event_in_cart = $event_in_cart->save();
if (is_a($event_in_cart, 'CRM_Core_Error')) {
$transaction->rollback();
CRM_Core_Error::fatal(ts('There was an error creating an event_in_cart'));
}
$transaction->commit();
return $event_in_cart;
}
/**
* @param bool $useWhere
*
* @return mixed|void
*/
public function delete($useWhere = FALSE) {
$this->load_associations();
$contacts_to_delete = array();
foreach ($this->participants as $participant) {
$defaults = array();
$params = array('id' => $participant->contact_id);
$temporary_contact = CRM_Contact_BAO_Contact::retrieve($params, $defaults);
if ($temporary_contact->is_deleted) {
$contacts_to_delete[$temporary_contact->id] = 1;
}
$participant->delete();
}
foreach (array_keys($contacts_to_delete) as $contact_id) {
CRM_Contact_BAO_Contact::deleteContact($contact_id);
}
return parent::delete();
}
/**
* @param int $event_cart_id
*
* @return array
*/
public static function find_all_by_event_cart_id($event_cart_id) {
return self::find_all_by_params(array('event_cart_id' => $event_cart_id));
}
/**
* @param array $params
*
* @return array
*/
public static function find_all_by_params($params) {
$event_in_cart = new CRM_Event_Cart_BAO_EventInCart();
$event_in_cart->copyValues($params);
$result = array();
if ($event_in_cart->find()) {
while ($event_in_cart->fetch()) {
$result[$event_in_cart->event_id] = clone($event_in_cart);
}
}
return $result;
}
/**
* @param int $id
*
* @return bool|CRM_Event_Cart_BAO_EventInCart
*/
public static function find_by_id($id) {
return self::find_by_params(array('id' => $id));
}
/**
* @param array $params
*
* @return bool|CRM_Event_Cart_BAO_EventInCart
*/
public static function find_by_params($params) {
$event_in_cart = new CRM_Event_Cart_BAO_EventInCart();
$event_in_cart->copyValues($params);
if ($event_in_cart->find(TRUE)) {
return $event_in_cart;
}
else {
return FALSE;
}
}
/**
* @param int $contact_id
*/
public function remove_participant_by_contact_id($contact_id) {
$to_remove = array();
foreach ($this->participants as $participant) {
if ($participant->contact_id == $contact_id) {
$to_remove[$participant->id] = 1;
$participant->delete();
}
}
$this->participants = array_diff_key($this->participants, $to_remove);
}
/**
* @param int $participant_id
*
* @return mixed
*/
public function get_participant_by_id($participant_id) {
return $this->participants[$participant_id];
}
/**
* @param int $participant_id
*/
public function remove_participant_by_id($participant_id) {
$this->get_participant_by_id($participant_id)->delete();
unset($this->participants[$participant_id]);
}
/**
* @param $participant
*
* @return mixed
*/
public static function part_key($participant) {
return $participant->id;
}
/**
* @param null $event_cart
*/
public function load_associations($event_cart = NULL) {
if ($this->assocations_loaded) {
return;
}
$this->assocations_loaded = TRUE;
$params = array('id' => $this->event_id);
$defaults = array();
$this->event = CRM_Event_BAO_Event::retrieve($params, $defaults);
if ($event_cart != NULL) {
$this->event_cart = $event_cart;
$this->event_cart_id = $event_cart->id;
}
else {
$this->event_cart = CRM_Event_Cart_BAO_Cart::find_by_id($this->event_cart_id);
}
$participants = CRM_Event_Cart_BAO_MerParticipant::find_all_by_event_and_cart_id($this->event_id, $this->event_cart->id);
foreach ($participants as $participant) {
$participant->load_associations();
$this->add_participant($participant);
}
}
public function load_location() {
if ($this->location == NULL) {
$location_params = array('entity_id' => $this->event_id, 'entity_table' => 'civicrm_event');
$this->location = CRM_Core_BAO_Location::getValues($location_params, TRUE);
}
}
/**
* @return array
*/
public function not_waiting_participants() {
$result = array();
foreach ($this->participants as $participant) {
if (!$participant->must_wait) {
$result[] = $participant;
}
}
return $result;
}
/**
* @return int
*/
public function num_not_waiting_participants() {
return count($this->not_waiting_participants());
}
/**
* @return int
*/
public function num_waiting_participants() {
return count($this->waiting_participants());
}
/**
* @param mixed $offset
*
* @return bool
*/
public function offsetExists($offset) {
return array_key_exists(array_merge($this->fields(), array('main_conference_event_id')), $offset);
}
/**
* @param mixed $offset
*
* @return int
*/
public function offsetGet($offset) {
if ($offset == 'event') {
return $this->event->toArray();
}
if ($offset == 'id') {
return $this->id;
}
if ($offset == 'main_conference_event_id') {
return $this->main_conference_event_id;
}
$fields = &$this->fields();
return $fields[$offset];
}
/**
* @param mixed $offset
* @param mixed $value
*/
public function offsetSet($offset, $value) {
}
/**
* @param mixed $offset
*/
public function offsetUnset($offset) {
}
/**
* @return array
*/
public function waiting_participants() {
$result = array();
foreach ($this->participants as $participant) {
if ($participant->must_wait) {
$result[] = $participant;
}
}
return $result;
}
/**
* @param int $event_id
*
* @return array
*/
public static function get_registration_link($event_id) {
$cart = CRM_Event_Cart_BAO_Cart::find_or_create_for_current_session();
$cart->load_associations();
$event_in_cart = $cart->get_event_in_cart_by_event_id($event_id);
if ($event_in_cart) {
return array(
'label' => ts("Remove from Cart"),
'path' => 'civicrm/event/remove_from_cart',
'query' => "reset=1&id={$event_id}",
);
}
else {
return array(
'label' => ts("Add to Cart"),
'path' => 'civicrm/event/add_to_cart',
'query' => "reset=1&id={$event_id}",
);
}
}
/**
* @return bool
*/
public function is_parent_event() {
return (NULL !== (CRM_Event_BAO_Event::get_sub_events($this->event_id)));
}
/**
* @param int $parent_event_id
*
* @return bool
*/
public function is_child_event($parent_event_id = NULL) {
if ($parent_event_id == NULL) {
return $this->event->parent_event_id;
}
else {
return $this->event->parent_event_id == $parent_event_id;
}
}
}

View file

@ -0,0 +1,191 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* Class CRM_Event_Cart_BAO_MerParticipant
*/
class CRM_Event_Cart_BAO_MerParticipant extends CRM_Event_BAO_Participant {
public $email = NULL;
public $contribution_id = NULL;
public $cart = NULL;
/**
* XXX.
* @param null $participant
*/
public function __construct($participant = NULL) {
parent::__construct();
$a = (array) $participant;
$this->copyValues($a);
$this->email = CRM_Utils_Array::value('email', $participant);
}
/**
* @param array $params
*
* @return CRM_Event_Cart_BAO_MerParticipant
* @throws Exception
*/
public static function create(&$params) {
$participantParams = array(
'id' => CRM_Utils_Array::value('id', $params),
'role_id' => self::get_attendee_role_id(),
'status_id' => self::get_pending_in_cart_status_id(),
'contact_id' => $params['contact_id'],
'event_id' => $params['event_id'],
'cart_id' => $params['cart_id'],
//XXX
//'registered_by_id' =>
//'discount_amount' =>
//'fee_level' => $params['fee_level'],
);
$participant = CRM_Event_BAO_Participant::create($participantParams);
if (is_a($participant, 'CRM_Core_Error')) {
CRM_Core_Error::fatal(ts('There was an error creating a cart participant'));
}
$mer_participant = new CRM_Event_Cart_BAO_MerParticipant($participant);
return $mer_participant;
}
/**
* @return mixed
*/
public static function get_attendee_role_id() {
$roles = CRM_Event_PseudoConstant::participantRole(NULL, "v.label='Attendee'");
$role_names = array_keys($roles);
return end($role_names);
}
/**
* @return mixed
*/
public static function get_pending_in_cart_status_id() {
$status_types = CRM_Event_PseudoConstant::participantStatus(NULL, "name='Pending in cart'");
$status_names = array_keys($status_types);
return end($status_names);
}
/**
* @param int $event_cart_id
*
* @return array|null
*/
public static function find_all_by_cart_id($event_cart_id) {
if ($event_cart_id == NULL) {
return NULL;
}
return self::find_all_by_params(array('cart_id' => $event_cart_id));
}
/**
* @param int $event_id
* @param int $event_cart_id
*
* @return array|null
*/
public static function find_all_by_event_and_cart_id($event_id, $event_cart_id) {
if ($event_cart_id == NULL) {
return NULL;
}
return self::find_all_by_params(array('event_id' => $event_id, 'cart_id' => $event_cart_id));
}
/**
* @param array $params
*
* @return array
*/
public static function find_all_by_params($params) {
$participant = new CRM_Event_BAO_Participant();
$participant->copyValues($params);
$result = array();
if ($participant->find()) {
while ($participant->fetch()) {
$result[] = new CRM_Event_Cart_BAO_MerParticipant(clone($participant));
}
}
return $result;
}
/**
* @param int $id
*
* @return mixed
*/
public static function get_by_id($id) {
$results = self::find_all_by_params(array('id' => $id));
return array_pop($results);
}
public function load_associations() {
$contact_details = CRM_Contact_BAO_Contact::getContactDetails($this->contact_id);
$this->email = $contact_details[1];
}
/**
* @return int
*/
public function get_participant_index() {
if (!$this->cart) {
$this->cart = CRM_Event_Cart_BAO_Cart::find_by_id($this->cart_id);
$this->cart->load_associations();
}
$index = $this->cart->get_participant_index_from_id($this->id);
return $index + 1;
}
/**
* @param $contact
*
* @return null
*/
public static function billing_address_from_contact($contact) {
foreach ($contact->address as $loc) {
if ($loc['is_billing']) {
return $loc;
}
}
foreach ($contact->address as $loc) {
if ($loc['is_primary']) {
return $loc;
}
}
return NULL;
}
/**
* @return CRM_Event_Cart_Form_MerParticipant
*/
public function get_form() {
return new CRM_Event_Cart_Form_MerParticipant($this);
}
}

View file

@ -0,0 +1,30 @@
<?php
/**
* Class CRM_Event_Cart_Controller_Checkout
*/
class CRM_Event_Cart_Controller_Checkout extends CRM_Core_Controller {
/**
* @param null $title
* @param bool|int $action
* @param bool $modal
*/
public function __construct($title = NULL, $action = CRM_Core_Action::NONE, $modal = TRUE) {
parent::__construct($title, $modal);
$this->_stateMachine = new CRM_Event_Cart_StateMachine_Checkout($this, $action);
$this->addPages($this->_stateMachine, $action);
$config = CRM_Core_Config::singleton();
//changes for custom data type File
$uploadNames = $this->get('uploadNames');
if (is_array($uploadNames) && !empty($uploadNames)) {
$this->addActions($config->customFileUploadDir, $uploadNames);
}
else {
// add all the actions
$this->addActions();
}
}
}

View file

@ -0,0 +1,192 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/Event/Cart/Cart.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:fd3bfb8e04f5a5101f38d928b1d056cb)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Event_Cart_DAO_Cart constructor.
*/
class CRM_Event_Cart_DAO_Cart extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_event_carts';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = false;
/**
* Cart Id
*
* @var int unsigned
*/
public $id;
/**
* FK to civicrm_contact who created this cart
*
* @var int unsigned
*/
public $user_id;
/**
*
* @var boolean
*/
public $completed;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_event_carts';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'user_id', 'civicrm_contact', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'cart_id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Cart ID') ,
'description' => 'Cart Id',
'required' => true,
'table_name' => 'civicrm_event_carts',
'entity' => 'Cart',
'bao' => 'CRM_Event_Cart_BAO_Cart',
'localizable' => 0,
) ,
'user_id' => array(
'name' => 'user_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Created By') ,
'description' => 'FK to civicrm_contact who created this cart',
'table_name' => 'civicrm_event_carts',
'entity' => 'Cart',
'bao' => 'CRM_Event_Cart_BAO_Cart',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
) ,
'completed' => array(
'name' => 'completed',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Complete?') ,
'table_name' => 'civicrm_event_carts',
'entity' => 'Cart',
'bao' => 'CRM_Event_Cart_BAO_Cart',
'localizable' => 0,
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return self::$_tableName;
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'event_carts', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'event_carts', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array();
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,196 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/Event/Cart/EventInCart.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:6b0b02cd86b7cc7e07b35cd72afa785f)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Event_Cart_DAO_EventInCart constructor.
*/
class CRM_Event_Cart_DAO_EventInCart extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_events_in_carts';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = false;
/**
* Event In Cart Id
*
* @var int unsigned
*/
public $id;
/**
* FK to Event ID
*
* @var int unsigned
*/
public $event_id;
/**
* FK to Event Cart ID
*
* @var int unsigned
*/
public $event_cart_id;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_events_in_carts';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'event_id', 'civicrm_event', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'event_cart_id', 'civicrm_event_carts', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'event_in_cart_id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Event In Cart') ,
'description' => 'Event In Cart Id',
'required' => true,
'table_name' => 'civicrm_events_in_carts',
'entity' => 'EventInCart',
'bao' => 'CRM_Event_Cart_BAO_EventInCart',
'localizable' => 0,
) ,
'event_id' => array(
'name' => 'event_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Event') ,
'description' => 'FK to Event ID',
'table_name' => 'civicrm_events_in_carts',
'entity' => 'EventInCart',
'bao' => 'CRM_Event_Cart_BAO_EventInCart',
'localizable' => 0,
'FKClassName' => 'CRM_Event_DAO_Event',
) ,
'event_cart_id' => array(
'name' => 'event_cart_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Event In Cart') ,
'description' => 'FK to Event Cart ID',
'table_name' => 'civicrm_events_in_carts',
'entity' => 'EventInCart',
'bao' => 'CRM_Event_Cart_BAO_EventInCart',
'localizable' => 0,
'FKClassName' => 'CRM_Event_Cart_DAO_Cart',
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return self::$_tableName;
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'events_in_carts', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'events_in_carts', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array();
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,170 @@
<?php
/**
* Class CRM_Event_Cart_Form_Cart
*/
class CRM_Event_Cart_Form_Cart extends CRM_Core_Form {
public $cart;
public $_action;
public $contact;
public $event_cart_id = NULL;
public $_mode;
public $participants;
public function preProcess() {
$this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE);
$this->_mode = 'live';
$this->loadCart();
$this->checkWaitingList();
$this->assignBillingType();
$event_titles = array();
foreach ($this->cart->get_main_events_in_carts() as $event_in_cart) {
$event_titles[] = $event_in_cart->event->title;
}
$this->description = ts("Online Registration for %1", array(1 => implode(", ", $event_titles)));
if (!isset($this->discounts)) {
$this->discounts = array();
}
}
public function loadCart() {
if ($this->event_cart_id == NULL) {
$this->cart = CRM_Event_Cart_BAO_Cart::find_or_create_for_current_session();
}
else {
$this->cart = CRM_Event_Cart_BAO_Cart::find_by_id($this->event_cart_id);
}
$this->cart->load_associations();
$this->stub_out_and_inherit();
}
public function stub_out_and_inherit() {
$transaction = new CRM_Core_Transaction();
foreach ($this->cart->get_main_events_in_carts() as $event_in_cart) {
if (empty($event_in_cart->participants)) {
$participant_params = array(
'cart_id' => $this->cart->id,
'event_id' => $event_in_cart->event_id,
'contact_id' => self::find_or_create_contact($this->getContactID()),
);
$participant = CRM_Event_Cart_BAO_MerParticipant::create($participant_params);
$participant->save();
$event_in_cart->add_participant($participant);
}
$event_in_cart->save();
}
$transaction->commit();
}
public function checkWaitingList() {
foreach ($this->cart->events_in_carts as $event_in_cart) {
$empty_seats = $this->checkEventCapacity($event_in_cart->event_id);
if ($empty_seats === NULL) {
continue;
}
foreach ($event_in_cart->participants as $participant) {
$participant->must_wait = ($empty_seats <= 0);
$empty_seats--;
}
}
}
/**
* @param int $event_id
*
* @return bool|int|null|string
*/
public function checkEventCapacity($event_id) {
$empty_seats = CRM_Event_BAO_Participant::eventFull($event_id, TRUE);
if (is_numeric($empty_seats)) {
return $empty_seats;
}
if (is_string($empty_seats)) {
return 0;
}
else {
return NULL;
}
}
/**
* @return bool
*/
public static function is_administrator() {
global $user;
return CRM_Core_Permission::check('administer CiviCRM');
}
/**
* @return mixed
*/
public function getContactID() {
//XXX when do we query 'cid' ?
$tempID = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
//check if this is a checksum authentication
$userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this);
if ($userChecksum) {
//check for anonymous user.
$validUser = CRM_Contact_BAO_Contact_Utils::validChecksum($tempID, $userChecksum);
if ($validUser) {
return $tempID;
}
}
// check if the user is registered and we have a contact ID
$session = CRM_Core_Session::singleton();
return $session->get('userID');
}
/**
* @param $fields
*
* @return mixed|null
*/
public static function find_contact($fields) {
return CRM_Contact_BAO_Contact::getFirstDuplicateContact($fields, 'Individual', 'Unsupervised', array(), FALSE);
}
/**
* @param int $registeringContactID
* @param array $fields
*
* @return int|mixed|null
*/
public static function find_or_create_contact($registeringContactID = NULL, $fields = array()) {
$contact_id = self::find_contact($fields);
if ($contact_id) {
return $contact_id;
}
$contact_params = array(
'email-Primary' => CRM_Utils_Array::value('email', $fields, NULL),
'first_name' => CRM_Utils_Array::value('first_name', $fields, NULL),
'last_name' => CRM_Utils_Array::value('last_name', $fields, NULL),
'is_deleted' => CRM_Utils_Array::value('is_deleted', $fields, TRUE),
);
$no_fields = array();
$contact_id = CRM_Contact_BAO_Contact::createProfileContact($contact_params, $no_fields, NULL);
if (!$contact_id) {
CRM_Core_Error::displaySessionError("Could not create or match a contact with that email address. Please contact the webmaster.");
}
return $contact_id;
}
/**
* @param string $page_name
*
* @return mixed
*/
public function getValuesForPage($page_name) {
$container = $this->controller->container();
return $container['values'][$page_name];
}
}

View file

@ -0,0 +1,148 @@
<?php
/**
* Class CRM_Event_Cart_Form_Checkout_ConferenceEvents
*/
class CRM_Event_Cart_Form_Checkout_ConferenceEvents extends CRM_Event_Cart_Form_Cart {
public $conference_event = NULL;
public $events_by_slot = array();
public $main_participant = NULL;
public $contact_id = NULL;
public function preProcess() {
parent::preProcess();
$matches = array();
preg_match("/.*_(\d+)_(\d+)/", $this->getAttribute('name'), $matches);
$event_id = $matches[1];
$participant_id = $matches[2];
$event_in_cart = $this->cart->get_event_in_cart_by_event_id($event_id);
$this->conference_event = $event_in_cart->event;
$this->main_participant = $event_in_cart->get_participant_by_id($participant_id);
$this->contact_id = $this->main_participant->contact_id;
$this->main_participant->display_name = CRM_Contact_BAO_Contact::displayName($this->contact_id);
$events = new CRM_Event_BAO_Event();
$query = <<<EOS
SELECT
civicrm_event.*,
slot.label AS slot_label
FROM
civicrm_event
JOIN
civicrm_option_value slot ON civicrm_event.slot_label_id = slot.value
JOIN
civicrm_option_group og ON slot.option_group_id = og.id
WHERE
parent_event_id = {$this->conference_event->id}
AND civicrm_event.is_active = 1
AND COALESCE(civicrm_event.is_template, 0) = 0
AND og.name = 'conference_slot'
ORDER BY
slot.weight, start_date
EOS;
$events->query($query);
while ($events->fetch()) {
if (!array_key_exists($events->slot_label, $this->events_by_slot)) {
$this->events_by_slot[$events->slot_label] = array();
}
$this->events_by_slot[$events->slot_label][] = clone($events);
}
}
public function buildQuickForm() {
//drupal_add_css(drupal_get_path('module', 'jquery_ui') . '/jquery.ui/themes/base/jquery-ui.css');
//variable_set('jquery_update_compression_type', 'none');
//jquery_ui_add('ui.dialog');
$slot_index = -1;
$slot_fields = array();
$session_options = array();
$defaults = array();
$previous_event_choices = $this->cart->get_subparticipants($this->main_participant);
foreach ($this->events_by_slot as $slot_name => $events) {
$slot_index++;
$slot_buttons = array();
$group_name = "slot_$slot_index";
foreach ($events as $event) {
$seats_available = $this->checkEventCapacity($event->id);
$event_is_full = ($seats_available === NULL) ? FALSE : ($seats_available < 1);
$radio = $this->createElement('radio', NULL, NULL, $event->title, $event->id);
$slot_buttons[] = $radio;
$event_description = ($event_is_full ? $event->event_full_text . "<p>" : '') . $event->description;
$session_options[$radio->getAttribute('id')] = array(
'session_title' => $event->title,
'session_description' => $event_description,
'session_full' => $event_is_full,
'event_id' => $event->id,
);
foreach ($previous_event_choices as $choice) {
if ($choice->event_id == $event->id) {
$defaults[$group_name] = $event->id;
}
}
}
$this->addGroup($slot_buttons, $group_name, $slot_name);
$slot_fields[$slot_name] = $group_name;
if (!isset($defaults[$group_name])) {
$defaults[$group_name] = $events[0]->id;
}
}
$this->setDefaults($defaults);
$this->assign('mer_participant', $this->main_participant);
$this->assign('events_by_slot', $this->events_by_slot);
$this->assign('slot_fields', $slot_fields);
$this->assign('session_options', json_encode($session_options));
$buttons = array();
$buttons[] = array(
'name' => ts('Go Back'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp',
'type' => 'back',
);
$buttons[] = array(
'isDefault' => TRUE,
'name' => ts('Continue'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
'type' => 'next',
);
$this->addButtons($buttons);
}
public function postProcess() {
$params = $this->controller->exportValues($this->_name);
$main_event_in_cart = $this->cart->get_event_in_cart_by_event_id($this->conference_event->id);
foreach ($this->cart->events_in_carts as $event_in_cart) {
if ($event_in_cart->event->parent_event_id == $this->conference_event->id) {
$event_in_cart->remove_participant_by_contact_id($this->contact_id);
if (empty($event_in_cart->participants)) {
$this->cart->remove_event_in_cart($event_in_cart->id);
}
}
}
$slot_index = -1;
foreach ($this->events_by_slot as $slot_name => $events) {
$slot_index++;
$field_name = "slot_$slot_index";
$session_event_id = CRM_Utils_Array::value($field_name, $params, NULL);
if (!$session_event_id) {
continue;
}
$event_in_cart = $this->cart->add_event($session_event_id);
$values = array();
CRM_Core_DAO::storeValues($this->main_participant, $values);
$values['id'] = NULL;
$values['event_id'] = $event_in_cart->event_id;
$participant = CRM_Event_Cart_BAO_MerParticipant::create($values);
$participant->save();
$event_in_cart->add_participant($participant);
}
$this->cart->save();
}
}

View file

@ -0,0 +1,305 @@
<?php
/**
* Class CRM_Event_Cart_Form_Checkout_ParticipantsAndPrices
*/
class CRM_Event_Cart_Form_Checkout_ParticipantsAndPrices extends CRM_Event_Cart_Form_Cart {
public $price_fields_for_event;
public $_values = NULL;
/**
* Pre process function.
*/
public function preProcess() {
parent::preProcess();
$this->cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
if (!isset($this->cid) || $this->cid > 0) {
//TODO users with permission can default to another contact
$this->cid = self::getContactID();
}
}
/**
* Build quick form.
*/
public function buildQuickForm() {
$this->price_fields_for_event = array();
foreach ($this->cart->get_main_event_participants() as $participant) {
$form = new CRM_Event_Cart_Form_MerParticipant($participant);
$form->appendQuickForm($this);
}
foreach ($this->cart->get_main_events_in_carts() as $event_in_cart) {
$this->price_fields_for_event[$event_in_cart->event_id] = $this->build_price_options($event_in_cart->event);
}
//If events in cart have discounts the textbox for discount code will be displayed at the top, as long as this
//form name is added to cividiscount
$this->assign('events_in_carts', $this->cart->get_main_events_in_carts());
$this->assign('price_fields_for_event', $this->price_fields_for_event);
$this->addButtons(
array(
array(
'type' => 'upload',
'name' => ts('Continue'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
'isDefault' => TRUE,
),
)
);
if ($this->cid) {
$params = array('id' => $this->cid);
$contact = CRM_Contact_BAO_Contact::retrieve($params, $defaults);
$contact_values = array();
CRM_Core_DAO::storeValues($contact, $contact_values);
$this->assign('contact', $contact_values);
}
}
/**
* Get the primary emil for the contact.
*
* @param CRM_Contact_BAO_Contact $contact
*
* @return string
*/
public static function primary_email_from_contact($contact) {
foreach ($contact->email as $email) {
if ($email['is_primary']) {
return $email['email'];
}
}
return NULL;
}
/**
* Build price options.
*
* @param CRM_Event_BAO_Event $event
*
* @return array
*/
public function build_price_options($event) {
$price_fields_for_event = array();
$base_field_name = "event_{$event->id}_amount";
$price_set_id = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $event->id);
//CRM-14492 display admin fields only if user is admin
$adminFieldVisible = FALSE;
if (CRM_Core_Permission::check('administer CiviCRM')) {
$adminFieldVisible = TRUE;
}
if ($price_set_id) {
$price_sets = CRM_Price_BAO_PriceSet::getSetDetail($price_set_id, TRUE, TRUE);
$price_set = $price_sets[$price_set_id];
$index = -1;
foreach ($price_set['fields'] as $field) {
$index++;
if (CRM_Utils_Array::value('visibility', $field) == 'public' ||
(CRM_Utils_Array::value('visibility', $field) == 'admin' && $adminFieldVisible == TRUE)) {
$field_name = "event_{$event->id}_price_{$field['id']}";
if (!empty($field['options'])) {
CRM_Price_BAO_PriceField::addQuickFormElement($this, $field_name, $field['id'], FALSE);
$price_fields_for_event[] = $field_name;
}
}
}
}
return $price_fields_for_event;
}
/**
* Validate values.
*
* @return bool
*/
public function validate() {
parent::validate();
if ($this->_errors) {
return FALSE;
}
$this->cart->load_associations();
$fields = $this->_submitValues;
foreach ($this->cart->get_main_events_in_carts() as $event_in_cart) {
$price_set_id = CRM_Event_BAO_Event::usesPriceSet($event_in_cart->event_id);
if ($price_set_id) {
$priceField = new CRM_Price_DAO_PriceField();
$priceField->price_set_id = $price_set_id;
$priceField->find();
$check = array();
while ($priceField->fetch()) {
if (!empty($fields["event_{$event_in_cart->event_id}_price_{$priceField->id}"])) {
$check[] = $priceField->id;
}
}
//XXX
if (empty($check)) {
$this->_errors['_qf_default'] = ts("Select at least one option from Price Levels.");
}
$lineItem = array();
if (is_array($this->_values['fee']['fields'])) {
CRM_Price_BAO_PriceSet::processAmount($this->_values['fee']['fields'], $fields, $lineItem);
//XXX total...
if ($fields['amount'] < 0) {
$this->_errors['_qf_default'] = ts("Price Levels can not be less than zero. Please select the options accordingly");
}
}
}
foreach ($event_in_cart->participants as $mer_participant) {
$participant_fields = $fields['event'][$event_in_cart->event_id]['participant'][$mer_participant->id];
//TODO what to do when profile responses differ for the same contact?
$contact_id = self::find_contact($participant_fields);
if ($contact_id) {
$participant = new CRM_Event_BAO_Participant();
$participant->event_id = $event_in_cart->event_id;
$participant->contact_id = $contact_id;
$statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1');
$participant->find();
while ($participant->fetch()) {
if (array_key_exists($participant->status_id, $statusTypes)) {
$form = $mer_participant->get_form();
$this->_errors[$form->html_field_name('email')] = ts("The participant %1 is already registered for %2 (%3).", array(
1 => $participant_fields['email'],
2 => $event_in_cart->event->title,
3 => $event_in_cart->event->start_date,
));
}
}
}
}
}
return empty($this->_errors);
}
/**
* Set default values.
*
* @return array
*/
public function setDefaultValues() {
$this->loadCart();
$defaults = array();
foreach ($this->cart->get_main_event_participants() as $participant) {
$form = $participant->get_form();
if (empty($participant->email)
&& !CRM_Event_Cart_Form_Cart::is_administrator()
&& ($participant->get_participant_index() == 1)
&& ($this->cid != 0)
) {
$defaults = array();
$params = array('id' => $this->cid);
$contact = CRM_Contact_BAO_Contact::retrieve($params, $defaults);
$participant->contact_id = $this->cid;
$participant->save();
$participant->email = self::primary_email_from_contact($contact);
}
elseif ($this->cid == 0
&& $participant->contact_id == self::getContactID()
) {
$participant->email = NULL;
$participant->contact_id = self::find_or_create_contact($this->getContactID());
}
$defaults += $form->setDefaultValues();
//Set price defaults if any
foreach ($this->cart->get_main_events_in_carts() as $event_in_cart) {
$event_id = $event_in_cart->event_id;
$price_set_id = CRM_Event_BAO_Event::usesPriceSet($event_in_cart->event_id);
if ($price_set_id) {
$price_sets = CRM_Price_BAO_PriceSet::getSetDetail($price_set_id, TRUE, TRUE);
$price_set = $price_sets[$price_set_id];
foreach ($price_set['fields'] as $field) {
$options = CRM_Utils_Array::value('options', $field);
if (!is_array($options)) {
continue;
}
$field_name = "event_{$event_id}_price_{$field['id']}";
foreach ($options as $value) {
if ($value['is_default']) {
if ($field['html_type'] == 'Checkbox') {
$defaults[$field_name] = 1;
}
else {
$defaults[$field_name] = $value['id'];
}
}
}
}
}
}
}
return $defaults;
}
/**
* Post process function.
*/
public function postProcess() {
if (!array_key_exists('event', $this->_submitValues)) {
return;
}
// XXX de facto primary key
$email_to_contact_id = array();
foreach ($this->_submitValues['event'] as $event_id => $participants) {
foreach ($participants['participant'] as $participant_id => $fields) {
if (array_key_exists($fields['email'], $email_to_contact_id)) {
$contact_id = $email_to_contact_id[$fields['email']];
}
else {
$contact_id = self::find_or_create_contact($this->getContactID(), $fields);
$email_to_contact_id[$fields['email']] = $contact_id;
}
$participant = $this->cart->get_event_in_cart_by_event_id($event_id)->get_participant_by_id($participant_id);
if ($participant->contact_id && $contact_id != $participant->contact_id) {
$defaults = array();
$params = array('id' => $participant->contact_id);
$temporary_contact = CRM_Contact_BAO_Contact::retrieve($params, $defaults);
foreach ($this->cart->get_subparticipants($participant) as $subparticipant) {
$subparticipant->contact_id = $contact_id;
$subparticipant->save();
}
$participant->contact_id = $contact_id;
$participant->save();
if ($temporary_contact->is_deleted) {
// ARGH a permissions check prevents us from using skipUndelete,
// so we potentially leave records pointing to this contact for now
// CRM_Contact_BAO_Contact::deleteContact($temporary_contact->id);
$temporary_contact->delete();
}
}
//TODO security check that participant ids are already in this cart
$participant_params = array(
'id' => $participant_id,
'cart_id' => $this->cart->id,
'event_id' => $event_id,
'contact_id' => $contact_id,
//'registered_by_id' => $this->cart->user_id,
'email' => $fields['email'],
);
$participant = new CRM_Event_Cart_BAO_MerParticipant($participant_params);
$participant->save();
$this->cart->add_participant_to_cart($participant);
if (array_key_exists('field', $this->_submitValues) && array_key_exists($participant_id, $this->_submitValues['field'])) {
$custom_fields = array_merge($participant->get_form()->get_participant_custom_data_fields());
CRM_Contact_BAO_Contact::createProfileContact($this->_submitValues['field'][$participant_id], $custom_fields, $contact_id);
}
}
}
$this->cart->save();
}
}

View file

@ -0,0 +1,836 @@
<?php
/**
* Class CRM_Event_Cart_Form_Checkout_Payment
*/
class CRM_Event_Cart_Form_Checkout_Payment extends CRM_Event_Cart_Form_Cart {
public $all_participants;
public $financial_type_id;
public $description;
public $line_items;
public $_fields = array();
public $_paymentProcessor;
public $total;
public $sub_total;
public $payment_required = TRUE;
public $payer_contact_id;
public $is_pay_later = FALSE;
public $pay_later_receipt;
/**
* Register a participant.
*
* @param array $params
* @param CRM_Event_BAO_Participant $participant
* @param CRM_Event_BAO_Event $event
*
* @return mixed
*/
public function registerParticipant($params, &$participant, $event) {
$transaction = new CRM_Core_Transaction();
// handle register date CRM-4320
$registerDate = date('YmdHis');
$participantParams = array(
'id' => $participant->id,
'event_id' => $event->id,
'register_date' => $registerDate,
'source' => CRM_Utils_Array::value('participant_source', $params, $this->description),
//'fee_level' => $participant->fee_level,
'is_pay_later' => $this->is_pay_later,
'fee_amount' => CRM_Utils_Array::value('amount', $params, 0),
//XXX why is this a ref to participant and not contact?:
//'registered_by_id' => $this->payer_contact_id,
'fee_currency' => CRM_Utils_Array::value('currencyID', $params),
);
if ($participant->must_wait) {
$participant_status = 'On waitlist';
}
elseif (CRM_Utils_Array::value('is_pay_later', $params, FALSE)) {
$participant_status = 'Pending from pay later';
}
else {
$participant_status = 'Registered';
}
$participant_statuses = CRM_Event_PseudoConstant::participantStatus();
$participantParams['status_id'] = array_search($participant_status, $participant_statuses);
$participant_status_label = CRM_Utils_Array::value($participantParams['status_id'], CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label'));
$participantParams['participant_status'] = $participant_status_label;
$this->assign('isOnWaitlist', $participant->must_wait);
if ($this->_action & CRM_Core_Action::PREVIEW || CRM_Utils_Array::value('mode', $params) == 'test') {
$participantParams['is_test'] = 1;
}
else {
$participantParams['is_test'] = 0;
}
if (self::is_administrator()) {
if (!empty($params['note'])) {
$note_params = array(
'participant_id' => $participant->id,
'contact_id' => self::getContactID(),
'note' => $params['note'],
);
CRM_Event_BAO_Participant::update_note($note_params);
}
}
$participant->copyValues($participantParams);
$participant->save();
if (!empty($params['contributionID'])) {
$payment_params = array(
'participant_id' => $participant->id,
'contribution_id' => $params['contributionID'],
);
$ids = array();
CRM_Event_BAO_ParticipantPayment::create($payment_params, $ids);
}
$transaction->commit();
$event_values = array();
CRM_Core_DAO::storeValues($event, $event_values);
$location = array();
if (CRM_Utils_Array::value('is_show_location', $event_values) == 1) {
$locationParams = array(
'entity_id' => $participant->event_id,
'entity_table' => 'civicrm_event',
);
$location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
CRM_Core_BAO_Address::fixAddress($location['address'][1]);
}
list($pre_id, $post_id) = CRM_Event_Cart_Form_MerParticipant::get_profile_groups($participant->event_id);
$payer_values = array(
'email' => '',
'name' => '',
);
if ($this->payer_contact_id) {
$payer_contact_details = CRM_Contact_BAO_Contact::getContactDetails($this->payer_contact_id);
$payer_values = array(
'email' => $payer_contact_details[1],
'name' => $payer_contact_details[0],
);
}
$values = array(
'params' => array($participant->id => $participantParams),
'event' => $event_values,
'location' => $location,
'custom_pre_id' => $pre_id,
'custom_post_id' => $post_id,
'payer' => $payer_values,
);
CRM_Event_BAO_Event::sendMail($participant->contact_id, $values, $participant->id);
return $participant;
}
/**
* Build payment fields.
*/
public function buildPaymentFields() {
$payment_processor_id = NULL;
$can_pay_later = TRUE;
$pay_later_text = "";
$this->pay_later_receipt = "";
foreach ($this->cart->get_main_events_in_carts() as $event_in_cart) {
if ($payment_processor_id == NULL && $event_in_cart->event->payment_processor != NULL) {
$payment_processor_id = $event_in_cart->event->payment_processor;
$this->financial_type_id = $event_in_cart->event->financial_type_id;
}
else {
if ($event_in_cart->event->payment_processor != NULL && $event_in_cart->event->payment_processor != $payment_processor_id) {
CRM_Core_Error::statusBounce(ts('When registering for multiple events all events must use the same payment processor. '));
}
}
if (!$event_in_cart->event->is_pay_later) {
$can_pay_later = FALSE;
}
else {
//XXX
$pay_later_text = $event_in_cart->event->pay_later_text;
$this->pay_later_receipt = $event_in_cart->event->pay_later_receipt;
}
}
if ($payment_processor_id == NULL) {
CRM_Core_Error::statusBounce(ts('A payment processor must be selected for this event registration page, or the event must be configured to give users the option to pay later (contact the site administrator for assistance).'));
}
$this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($payment_processor_id, $this->_mode);
$this->assign('paymentProcessor', $this->_paymentProcessor);
CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, FALSE, FALSE);
if ($can_pay_later || self::is_administrator()) {
$this->addElement('checkbox', 'is_pay_later',
$pay_later_text
);
$this->addElement('checkbox', 'payment_completed',
ts('Payment Completed')
);
$this->assign('pay_later_instructions', $this->pay_later_receipt);
}
}
/**
* Build QuickForm.
*/
public function buildQuickForm() {
$this->line_items = array();
$this->sub_total = 0;
$this->_price_values = $this->getValuesForPage('ParticipantsAndPrices');
// iterate over each event in cart
foreach ($this->cart->get_main_events_in_carts() as $event_in_cart) {
$this->process_event_line_item($event_in_cart);
foreach ($this->cart->get_events_in_carts_by_main_event_id($event_in_cart->event_id) as $subevent) {
$this->process_event_line_item($subevent, 'subevent');
}
}
$this->total = $this->sub_total;
$this->payment_required = ($this->total > 0);
$this->assign('payment_required', $this->payment_required);
$this->assign('line_items', $this->line_items);
$this->assign('sub_total', $this->sub_total);
$this->assign('total', $this->total);
$buttons = array();
$buttons[] = array(
'name' => ts('Go Back'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp',
'type' => 'back',
);
$buttons[] = array(
'isDefault' => TRUE,
'name' => ts('Complete Transaction'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
'type' => 'next',
);
if ($this->total) {
$this->add('text', 'billing_contact_email', 'Billing Email', '', TRUE);
$this->assign('collect_billing_email', TRUE);
}
if (self::is_administrator()) {
$this->add('textarea', 'note', 'Note');
$this->add('text', 'source', 'Source', array('size' => 80));
$instruments = array();
CRM_Core_OptionGroup::getAssoc('payment_instrument', $instruments, TRUE);
$options = array();
foreach ($instruments as $type) {
$options[] = $this->createElement('radio', NULL, '', $type['label'], $type['value']);
}
$this->addGroup($options, 'payment_type', ts("Alternative Payment Type"));
$this->add('text', 'check_number', ts('Check No.'), array('size' => 20));
$this->addElement('checkbox', 'is_pending', ts('Create a pending registration'));
$this->assign('administrator', TRUE);
}
$this->addButtons($buttons);
$this->addFormRule(array('CRM_Event_Cart_Form_Checkout_Payment', 'formRule'), $this);
if ($this->payment_required) {
$this->buildPaymentFields();
}
}
/**
* Process line item for event.
*
* @param bool $event_in_cart
* @param string $class
*/
public function process_event_line_item(&$event_in_cart, $class = NULL) {
$cost = 0;
$price_set_id = CRM_Price_BAO_PriceSet::getFor("civicrm_event", $event_in_cart->event_id);
$amount_level = NULL;
if ($price_set_id) {
$event_price_values = array();
foreach ($this->_price_values as $key => $value) {
if (preg_match("/event_{$event_in_cart->event_id}_(price.*)/", $key, $matches)) {
$event_price_values[$matches[1]] = $value;
}
}
$price_sets = CRM_Price_BAO_PriceSet::getSetDetail($price_set_id, TRUE);
$price_set = $price_sets[$price_set_id];
$price_set_amount = array();
CRM_Price_BAO_PriceSet::processAmount($price_set['fields'], $event_price_values, $price_set_amount);
$discountCode = $this->_price_values['discountcode'];
if (!empty($discountCode)) {
$ret = $this->apply_discount($discountCode, $price_set_amount, $cost, $event_in_cart->event_id);
if ($ret == FALSE) {
$cost = $event_price_values['amount'];
}
}
else {
$cost = $event_price_values['amount'];
}
// @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
// function to get correct amount level consistently. Remove setting of the amount level in
// CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
// to cover all variants.
$amount_level = $event_price_values['amount_level'];
$price_details[$price_set_id] = $price_set_amount;
}
// iterate over each participant in event
foreach ($event_in_cart->participants as & $participant) {
$participant->cost = $cost;
$participant->fee_level = $amount_level;
$participant->price_details = $price_details;
}
$this->add_line_item($event_in_cart, $class);
}
/**
* Add line item.
*
* @param CRM_Event_BAO_Event $event_in_cart
* @param string $class
*/
public function add_line_item($event_in_cart, $class = NULL) {
$amount = 0;
$cost = 0;
$not_waiting_participants = array();
foreach ($event_in_cart->not_waiting_participants() as $participant) {
$amount += $participant->cost;
$cost = max($cost, $participant->cost);
$not_waiting_participants[] = array(
'display_name' => CRM_Contact_BAO_Contact::displayName($participant->contact_id),
);
}
$waiting_participants = array();
foreach ($event_in_cart->waiting_participants() as $participant) {
$waiting_participants[] = array(
'display_name' => CRM_Contact_BAO_Contact::displayName($participant->contact_id),
);
}
$this->line_items[] = array(
'amount' => $amount,
'cost' => $cost,
'event' => $event_in_cart->event,
'participants' => $not_waiting_participants,
'num_participants' => count($not_waiting_participants),
'num_waiting_participants' => count($waiting_participants),
'waiting_participants' => $waiting_participants,
'class' => $class,
);
$this->sub_total += $amount;
}
/**
* Get default from address.
*
* @return mixed
*/
public function getDefaultFrom() {
$values = CRM_Core_OptionGroup::values('from_email_address');
return $values[1];
}
/**
* Send email receipt.
*
* @param array $events_in_cart
* @param array $params
*/
public function emailReceipt($events_in_cart, $params) {
$contact_details = CRM_Contact_BAO_Contact::getContactDetails($this->payer_contact_id);
$state_province = new CRM_Core_DAO_StateProvince();
$state_province->id = $params["billing_state_province_id-{$this->_bltID}"];
$state_province->find();
$state_province->fetch();
$country = new CRM_Core_DAO_Country();
$country->id = $params["billing_country_id-{$this->_bltID}"];
$country->find();
$country->fetch();
foreach ($this->line_items as & $line_item) {
$location_params = array('entity_id' => $line_item['event']->id, 'entity_table' => 'civicrm_event');
$line_item['location'] = CRM_Core_BAO_Location::getValues($location_params, TRUE);
CRM_Core_BAO_Address::fixAddress($line_item['location']['address'][1]);
}
$send_template_params = array(
'table' => 'civicrm_msg_template',
'contactId' => $this->payer_contact_id,
'from' => $this->getDefaultFrom(),
'groupName' => 'msg_tpl_workflow_event',
'isTest' => FALSE,
'toEmail' => $contact_details[1],
'toName' => $contact_details[0],
'tplParams' => array(
'billing_name' => "{$params['billing_first_name']} {$params['billing_last_name']}",
'billing_city' => $params["billing_city-{$this->_bltID}"],
'billing_country' => $country->name,
'billing_postal_code' => $params["billing_postal_code-{$this->_bltID}"],
'billing_state' => $state_province->abbreviation,
'billing_street_address' => $params["billing_street_address-{$this->_bltID}"],
'credit_card_exp_date' => $params['credit_card_exp_date'],
'credit_card_type' => $params['credit_card_type'],
'credit_card_number' => "************" . substr($params['credit_card_number'], -4, 4),
// XXX cart->get_discounts
'discounts' => $this->discounts,
'email' => $contact_details[1],
'events_in_cart' => $events_in_cart,
'line_items' => $this->line_items,
'name' => $contact_details[0],
'transaction_id' => $params['trxn_id'],
'transaction_date' => $params['trxn_date'],
'is_pay_later' => $this->is_pay_later,
'pay_later_receipt' => $this->pay_later_receipt,
),
'valueName' => 'event_registration_receipt',
'PDFFilename' => ts('confirmation') . '.pdf',
);
$template_params_to_copy = array(
'billing_name',
'billing_city',
'billing_country',
'billing_postal_code',
'billing_state',
'billing_street_address',
'credit_card_exp_date',
'credit_card_type',
'credit_card_number',
);
foreach ($template_params_to_copy as $template_param_to_copy) {
$this->set($template_param_to_copy, $send_template_params['tplParams'][$template_param_to_copy]);
}
CRM_Core_BAO_MessageTemplate::sendTemplate($send_template_params);
}
/**
* Apply form rules.
*
* @param array $fields
* @param array $files
* @param CRM_Core_Form $self
*
* @return array|bool
*/
public static function formRule($fields, $files, $self) {
$errors = array();
if ($self->payment_required && empty($self->_submitValues['is_pay_later'])) {
CRM_Core_Form::validateMandatoryFields($self->_fields, $fields, $errors);
// validate payment instrument values (e.g. credit card number)
CRM_Core_Payment_Form::validatePaymentInstrument($self->_paymentProcessor['id'], $fields, $errors, NULL);
}
return empty($errors) ? TRUE : $errors;
}
/**
* Validate form.
*
* @todo this should surely go! Test & remove.
* @return bool
*/
public function validate() {
if ($this->is_pay_later) {
$this->_fields['credit_card_number']['is_required'] = FALSE;
$this->_fields['cvv2']['is_required'] = FALSE;
$this->_fields['credit_card_exp_date']['is_required'] = FALSE;
$this->_fields['credit_card_type']['is_required'] = FALSE;
}
return parent::validate();
}
/**
* Pre-process form.
*/
public function preProcess() {
$params = $this->_submitValues;
$this->is_pay_later = CRM_Utils_Array::value('is_pay_later', $params, FALSE) && !CRM_Utils_Array::value('payment_completed', $params);
parent::preProcess();
}
/**
* Post process form.
*/
public function postProcess() {
$transaction = new CRM_Core_Transaction();
$trxnDetails = NULL;
$params = $this->_submitValues;
$main_participants = $this->cart->get_main_event_participants();
foreach ($main_participants as $participant) {
$defaults = array();
$ids = array('contact_id' => $participant->contact_id);
$contact = CRM_Contact_BAO_Contact::retrieve($ids, $defaults);
$contact->is_deleted = 0;
$contact->save();
}
$trxn_prefix = 'VR';
if (array_key_exists('billing_contact_email', $params)) {
$this->payer_contact_id = self::find_or_create_contact($this->getContactID(), array(
'email' => $params['billing_contact_email'],
'first_name' => $params['billing_first_name'],
'last_name' => $params['billing_last_name'],
'is_deleted' => FALSE,
));
$ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
$this->payer_contact_id,
'contact_type'
);
$billing_fields = array(
"billing_first_name" => 1,
"billing_middle_name" => 1,
"billing_last_name" => 1,
"billing_street_address-{$this->_bltID}" => 1,
"billing_city-{$this->_bltID}" => 1,
"billing_state_province_id-{$this->_bltID}" => 1,
"billing_postal_code-{$this->_bltID}" => 1,
"billing_country_id-{$this->_bltID}" => 1,
"address_name-{$this->_bltID}" => 1,
"email-{$this->_bltID}" => 1,
);
$params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
$params["email-{$this->_bltID}"] = $params['billing_contact_email'];
CRM_Contact_BAO_Contact::createProfileContact(
$params,
$billing_fields,
$this->payer_contact_id,
NULL,
NULL,
$ctype,
TRUE
);
}
$params['now'] = date('YmdHis');
$params['invoiceID'] = md5(uniqid(rand(), TRUE));
$params['amount'] = $this->total;
$params['financial_type_id'] = $this->financial_type_id;
if ($this->payment_required && empty($params['is_pay_later'])) {
$trxnDetails = $this->make_payment($params);
$params['trxn_id'] = $trxnDetails['trxn_id'];
$params['trxn_date'] = $trxnDetails['trxn_date'];
$params['currencyID'] = $trxnDetails['currency'];
}
$this->cart->completed = TRUE;
$this->cart->save();
$this->set('last_event_cart_id', $this->cart->id);
$contribution_statuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
$params['payment_instrument_id'] = NULL;
if (!empty($params['is_pay_later'])) {
$params['payment_instrument_id'] = CRM_Core_OptionGroup::getValue('payment_instrument', 'Check', 'name');
$trxn_prefix = 'CK';
}
else {
$params['payment_instrument_id'] = CRM_Core_OptionGroup::getValue('payment_instrument', 'Credit Card', 'name');
}
if ($this->is_pay_later && empty($params['payment_completed'])) {
$params['contribution_status_id'] = array_search('Pending', $contribution_statuses);
}
else {
$params['contribution_status_id'] = array_search('Completed', $contribution_statuses);
$params['participant_status'] = 'Registered';
$params['is_pay_later'] = 0;
}
if ($trxnDetails == NULL) {
$params['trxn_id'] = $trxn_prefix . strftime("%Y%m%d%H%M%S");
$params['trxn_date'] = $params['now'];
}
if ($this->payment_required) {
$this->emailReceipt($this->cart->events_in_carts, $params);
}
// n.b. we need to process the subparticipants before main event
// participants so that session attendance can be included in the email
$main_participants = $this->cart->get_main_event_participants();
$this->all_participants = array();
foreach ($main_participants as $main_participant) {
$this->all_participants = array_merge($this->all_participants, $this->cart->get_subparticipants($main_participant));
}
$this->all_participants = array_merge($this->all_participants, $main_participants);
$this->sub_trxn_index = 0;
foreach ($this->all_participants as $mer_participant) {
$event_in_cart = $this->cart->get_event_in_cart_by_event_id($mer_participant->event_id);
$this->sub_trxn_index += 1;
unset($params['contributionID']);
if ($mer_participant->must_wait) {
$this->registerParticipant($params, $mer_participant, $event_in_cart->event);
}
else {
$params['amount'] = $mer_participant->cost - $mer_participant->discount_amount;
if ($event_in_cart->event->financial_type_id && $mer_participant->cost) {
$params['financial_type_id'] = $event_in_cart->event->financial_type_id;
$params['participant_contact_id'] = $mer_participant->contact_id;
$contribution = $this->record_contribution($mer_participant, $params, $event_in_cart->event);
// Record civicrm_line_item
CRM_Price_BAO_LineItem::processPriceSet($mer_participant->id, $mer_participant->price_details, $contribution, $entity_table = 'civicrm_participant');
}
$this->registerParticipant($params, $mer_participant, $event_in_cart->event);
}
}
$this->trxn_id = $params['trxn_id'];
$this->trxn_date = $params['trxn_date'];
$this->saveDataToSession();
$transaction->commit();
}
/**
* Make payment.
*
* @param array $params
*
* @return array
* @throws Exception
*/
public function make_payment(&$params) {
$config = CRM_Core_Config::singleton();
if (isset($params["billing_state_province_id-{$this->_bltID}"]) && $params["billing_state_province_id-{$this->_bltID}"]) {
$params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($params["billing_state_province_id-{$this->_bltID}"]);
}
if (isset($params["billing_country_id-{$this->_bltID}"]) && $params["billing_country_id-{$this->_bltID}"]) {
$params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($params["billing_country_id-{$this->_bltID}"]);
}
$params['ip_address'] = CRM_Utils_System::ipAddress();
$params['currencyID'] = $config->defaultCurrency;
$payment = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
CRM_Core_Payment_Form::mapParams($this->_bltID, $params, $params, TRUE);
$params['month'] = $params['credit_card_exp_date']['M'];
$params['year'] = $params['credit_card_exp_date']['Y'];
try {
$result = $payment->doPayment($params);
}
catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
CRM_Core_Error::displaySessionError($result);
CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/event/cart_checkout', "_qf_Payment_display=1&qfKey={$this->controller->_key}", TRUE, NULL, FALSE));
}
$trxnDetails = array(
'trxn_id' => $result['trxn_id'],
'trxn_date' => $result['now'],
'currency' => CRM_Utils_Array::value('currencyID', $result),
);
return $trxnDetails;
}
/**
* Record contribution.
*
* @param CRM_Event_BAO_Participant $mer_participant
* @param array $params
* @param CRM_Event_BAO_Event $event
*
* @return object
* @throws Exception
*/
public function record_contribution(&$mer_participant, &$params, $event) {
if (self::is_administrator() && !empty($params['payment_type'])) {
$params['payment_instrument_id'] = $params['payment_type'];
}
if ($this->payer_contact_id) {
$payer = $this->payer_contact_id;
}
elseif (self::getContactID()) {
$payer = self::getContactID();
}
else {
$payer = $params['participant_contact_id'];
}
$contribParams = array(
'contact_id' => $payer,
'financial_type_id' => $params['financial_type_id'],
'receive_date' => $params['now'],
'total_amount' => $params['amount'],
'amount_level' => $mer_participant->fee_level,
'net_amount' => $params['amount'],
'invoice_id' => "{$params['invoiceID']}-{$this->sub_trxn_index}",
'trxn_id' => "{$params['trxn_id']}-{$this->sub_trxn_index}",
'currency' => CRM_Utils_Array::value('currencyID', $params),
'source' => $event->title,
'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0),
'contribution_status_id' => $params['contribution_status_id'],
'payment_instrument_id' => $params['payment_instrument_id'],
'check_number' => CRM_Utils_Array::value('check_number', $params),
'skipLineItem' => 1,
);
if (is_array($this->_paymentProcessor)) {
$contribParams['payment_processor'] = $this->_paymentProcessor['id'];
}
$contribution = &CRM_Contribute_BAO_Contribution::add($contribParams);
if (is_a($contribution, 'CRM_Core_Error')) {
CRM_Core_Error::fatal(ts("There was an error creating a contribution record for your event. Please report this error to the webmaster. Details: %1", array(1 => $contribution->getMessages($contribution))));
}
$mer_participant->contribution_id = $contribution->id;
$params['contributionID'] = $contribution->id;
return $contribution;
}
/**
* Save data to session.
*/
public function saveDataToSession() {
$session_line_items = array();
foreach ($this->line_items as $line_item) {
$session_line_item = array();
$session_line_item['amount'] = $line_item['amount'];
$session_line_item['cost'] = $line_item['cost'];
$session_line_item['event_id'] = $line_item['event']->id;
$session_line_items[] = $session_line_item;
}
$this->set('line_items', $session_line_items);
$this->set('payment_required', $this->payment_required);
$this->set('is_pay_later', $this->is_pay_later);
$this->set('pay_later_receipt', $this->pay_later_receipt);
$this->set('trxn_id', $this->trxn_id);
$this->set('trxn_date', $this->trxn_date);
$this->set('total', $this->total);
}
/**
* Set form default values.
*
* @return array
*/
public function setDefaultValues() {
$defaults = parent::setDefaultValues();
$config = CRM_Core_Config::singleton();
$default_country = new CRM_Core_DAO_Country();
$default_country->iso_code = $config->defaultContactCountry();
$default_country->find(TRUE);
$defaults["billing_country_id-{$this->_bltID}"] = $default_country->id;
if (self::getContactID() && !self::is_administrator()) {
$params = array('id' => self::getContactID());
$contact = CRM_Contact_BAO_Contact::retrieve($params, $defaults);
foreach ($contact->email as $email) {
if ($email['is_billing']) {
$defaults["billing_contact_email"] = $email['email'];
}
}
if (empty($defaults['billing_contact_email'])) {
foreach ($contact->email as $email) {
if ($email['is_primary']) {
$defaults["billing_contact_email"] = $email['email'];
}
}
}
$defaults["billing_first_name"] = $contact->first_name;
$defaults["billing_middle_name"] = $contact->middle_name;
$defaults["billing_last_name"] = $contact->last_name;
$billing_address = CRM_Event_Cart_BAO_MerParticipant::billing_address_from_contact($contact);
if ($billing_address != NULL) {
$defaults["billing_street_address-{$this->_bltID}"] = $billing_address['street_address'];
$defaults["billing_city-{$this->_bltID}"] = $billing_address['city'];
$defaults["billing_postal_code-{$this->_bltID}"] = $billing_address['postal_code'];
$defaults["billing_state_province_id-{$this->_bltID}"] = $billing_address['state_province_id'];
$defaults["billing_country_id-{$this->_bltID}"] = $billing_address['country_id'];
}
}
$defaults["source"] = $this->description;
return $defaults;
}
/**
* Apply discount.
*
* @param string $discountCode
* @param array $price_set_amount
* @param float $cost
* @param int $event_id
*
* @return bool
*/
protected function apply_discount($discountCode, &$price_set_amount, &$cost, $event_id) {
//need better way to determine if cividiscount installed
$autoDiscount = array();
$sql = "select is_active from civicrm_extension where name like 'CiviDiscount%'";
$dao = CRM_Core_DAO::executeQuery($sql, '');
while ($dao->fetch()) {
if ($dao->is_active != '1') {
return FALSE;
}
}
$discounted_priceset_ids = _cividiscount_get_discounted_priceset_ids();
$discounts = _cividiscount_get_discounts();
$stat = FALSE;
foreach ($discounts as $key => $discountValue) {
if ($key == $discountCode) {
$events = CRM_Utils_Array::value('events', $discountValue);
$evt_ids = implode(",", $events);
if ($evt_ids == "0" || strpos($evt_ids, $event_id)) {
$event_match = TRUE;
}
//check priceset is_active
if ($discountValue['active_on'] != NULL) {
$today = date('Y-m-d');
$diff1 = date_diff(date_create($today), date_create($discountValue['active_on']));
if ($diff1->days > 0) {
$active1 = TRUE;
}
}
else {
$active1 = TRUE;
}
if ($discountValue['expire_on'] != NULL) {
$diff2 = date_diff(date_create($today), date_create($discountValue['expire_on']));
if ($diff2->days > 0) {
$active2 = TRUE;
}
}
else {
$active2 = TRUE;
}
}
if ($discountValue['is_active'] == TRUE && ($discountValue['count_max'] == 0 || ($discountValue['count_max'] > $discountValue['count_use'])) && $active1 == TRUE && $active2 == TRUE && $event_match == TRUE) {
foreach ($price_set_amount as $key => $price) {
if (array_search($price['price_field_value_id'], $discounted_priceset_ids) != NULL) {
$discounted = _cividiscount_calc_discount($price['line_total'], $price['label'], $discountValue, $autoDiscount, "USD");
$price_set_amount[$key]['line_total'] = $discounted[0];
$cost += $discounted[0];
$price_set_amount[$key]['label'] = $discounted[1];
}
else {
$cost += $price['line_total'];
}
}
$stat = TRUE;
}
}
return $stat;
}
}

View file

@ -0,0 +1,83 @@
<?php
/**
* Class CRM_Event_Cart_Form_Checkout_ThankYou
*/
class CRM_Event_Cart_Form_Checkout_ThankYou extends CRM_Event_Cart_Form_Cart {
public $line_items = NULL;
public $sub_total = 0;
public function buildLineItems() {
foreach ($this->cart->events_in_carts as $event_in_cart) {
$event_in_cart->load_location();
}
$line_items = $this->get('line_items');
foreach ($line_items as $line_item) {
$event_in_cart = $this->cart->get_event_in_cart_by_event_id($line_item['event_id']);
$not_waiting_participants = array();
foreach ($event_in_cart->not_waiting_participants() as $participant) {
$not_waiting_participants[] = array(
'display_name' => CRM_Contact_BAO_Contact::displayName($participant->contact_id),
);
}
$waiting_participants = array();
foreach ($event_in_cart->waiting_participants() as $participant) {
$waiting_participants[] = array(
'display_name' => CRM_Contact_BAO_Contact::displayName($participant->contact_id),
);
}
$line_item['event'] = $event_in_cart->event;
$line_item['num_participants'] = count($not_waiting_participants);
$line_item['participants'] = $not_waiting_participants;
$line_item['num_waiting_participants'] = count($waiting_participants);
$line_item['waiting_participants'] = $waiting_participants;
$line_item['location'] = $event_in_cart->location;
$line_item['class'] = $event_in_cart->event->parent_event_id ? 'subevent' : NULL;
$this->sub_total += $line_item['amount'];
$this->line_items[] = $line_item;
}
$this->assign('line_items', $this->line_items);
}
public function buildQuickForm() {
$defaults = array();
$ids = array();
$template_params_to_copy = array(
'billing_name',
'billing_city',
'billing_country',
'billing_postal_code',
'billing_state',
'billing_street_address',
'credit_card_exp_date',
'credit_card_type',
'credit_card_number',
);
foreach ($template_params_to_copy as $template_param_to_copy) {
$this->assign($template_param_to_copy, $this->get($template_param_to_copy));
}
$this->buildLineItems();
$this->assign('discounts', $this->get('discounts'));
$this->assign('events_in_carts', $this->cart->events_in_carts);
$this->assign('transaction_id', $this->get('trxn_id'));
$this->assign('transaction_date', $this->get('trxn_date'));
$this->assign('payment_required', $this->get('payment_required'));
$this->assign('is_pay_later', $this->get('is_pay_later'));
$this->assign('pay_later_receipt', $this->get('pay_later_receipt'));
$this->assign('sub_total', $this->sub_total);
$this->assign('total', $this->get('total'));
// XXX Configure yourself
//$this->assign( 'site_name', "" );
//$this->assign( 'site_contact', "" );
}
public function preProcess() {
$this->event_cart_id = $this->get('last_event_cart_id');
$this->loadCart();
//$this->loadParticipants( );
}
}

View file

@ -0,0 +1,137 @@
<?php
/**
* Class CRM_Event_Cart_Form_MerParticipant
*/
class CRM_Event_Cart_Form_MerParticipant extends CRM_Core_Form {
public $participant = NULL;
/**
* @param null|object $participant
*/
public function __construct($participant) {
parent::__construct();
//XXX
$this->participant = $participant;
}
/**
* @param CRM_Core_Form $form
*/
public function appendQuickForm(&$form) {
$textarea_size = array('size' => 30, 'maxlength' => 60);
$form->add('text', $this->email_field_name(), ts('Email Address'), $textarea_size, TRUE);
list(
$custom_fields_pre,
$custom_fields_post
) = $this->get_participant_custom_data_fields($this->participant->event_id);
foreach ($custom_fields_pre as $key => $field) {
CRM_Core_BAO_UFGroup::buildProfile($form, $field, CRM_Profile_Form::MODE_CREATE, $this->participant->id);
}
foreach ($custom_fields_post as $key => $field) {
CRM_Core_BAO_UFGroup::buildProfile($form, $field, CRM_Profile_Form::MODE_CREATE, $this->participant->id);
}
$custom = CRM_Utils_Array::value('custom', $form->getTemplate()->_tpl_vars, array());
$form->assign('custom', array_merge($custom, array(
$this->html_field_name('customPre') => $custom_fields_pre,
$this->html_field_name('customPost') => $custom_fields_post,
$this->html_field_name('number') => $this->name(),
)));
}
/**
* @param int $event_id
*
* @return array
*/
public static function get_profile_groups($event_id) {
$ufJoinParams = array(
'entity_table' => 'civicrm_event',
'module' => 'CiviEvent',
'entity_id' => $event_id,
);
$group_ids = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
return $group_ids;
}
/**
* @return array
*/
public function get_participant_custom_data_fields() {
list($custom_pre_id, $custom_post_id) = self::get_profile_groups($this->participant->event_id);
$pre_fields = $post_fields = array();
if ($custom_pre_id && CRM_Core_BAO_UFGroup::filterUFGroups($custom_pre_id, $this->participant->contact_id)) {
$pre_fields = CRM_Core_BAO_UFGroup::getFields($custom_pre_id, FALSE, CRM_Core_Action::ADD);
}
if ($custom_post_id && CRM_Core_BAO_UFGroup::filterUFGroups($custom_post_id, $this->participant->contact_id)) {
$post_fields = CRM_Core_BAO_UFGroup::getFields($custom_post_id, FALSE, CRM_Core_Action::ADD);
}
return array($pre_fields, $post_fields);
}
/**
* @return string
*/
public function email_field_name() {
return $this->html_field_name("email");
}
/**
* @param int $event_id
* @param int $participant_id
* @param string $field_name
*
* @return string
*/
public static function full_field_name($event_id, $participant_id, $field_name) {
return "event[$event_id][participant][$participant_id][$field_name]";
}
/**
* @param string $field_name
*
* @return string
*/
public function html_field_name($field_name) {
return self::full_field_name($this->participant->event_id, $this->participant->id, $field_name);
}
/**
* @return string
*/
public function name() {
return "Participant {$this->participant->get_participant_index()}";
}
/**
* XXX poor name.
* @param $participant
*
* @return CRM_Event_Cart_Form_MerParticipant
*/
static public function get_form($participant) {
return new CRM_Event_Cart_Form_MerParticipant($participant);
}
/**
* @return array
*/
public function setDefaultValues() {
$defaults = array(
$this->html_field_name('email') => $this->participant->email,
);
list($custom_fields_pre, $custom_fields_post) = $this->get_participant_custom_data_fields($this->participant->event_id);
$all_fields = $custom_fields_pre + $custom_fields_post;
$flat = array();
CRM_Core_BAO_UFGroup::setProfileDefaults($this->participant->contact_id, $all_fields, $flat);
foreach ($flat as $name => $field) {
$defaults["field[{$this->participant->id}][{$name}]"] = $field;
}
return $defaults;
}
}

View file

@ -0,0 +1,34 @@
<?php
/**
* Class CRM_Event_Cart_Page_AddToCart
*/
class CRM_Event_Cart_Page_AddToCart extends CRM_Core_Page {
/**
* This function takes care of all the things common to all pages.
*
* This typically involves assigning the appropriate smarty variables :)
*/
public function run() {
$transaction = new CRM_Core_Transaction();
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
if (!CRM_Core_Permission::event(CRM_Core_Permission::VIEW, $this->_id, 'register for events')) {
CRM_Core_Error::fatal(ts('You do not have permission to register for this event'));
}
$cart = CRM_Event_Cart_BAO_Cart::find_or_create_for_current_session();
$event_in_cart = $cart->add_event($this->_id);
$url = CRM_Utils_System::url('civicrm/event/view_cart');
CRM_Utils_System::setUFMessage(ts("<b>%1</b> has been added to your cart. <a href='%2'>View your cart.</a>", array(
1 => $event_in_cart->event->title,
2 => $url,
)));
$transaction->commit();
return CRM_Utils_System::redirect($_SERVER['HTTP_REFERER']);
}
}

View file

@ -0,0 +1,55 @@
<?php
/**
* Class CRM_Event_Cart_Page_CheckoutAJAX
*/
class CRM_Event_Cart_Page_CheckoutAJAX {
public function add_participant_to_cart() {
$transaction = new CRM_Core_Transaction();
$cart_id = CRM_Utils_Request::retrieve('cart_id', 'Integer');
$event_id = CRM_Utils_Request::retrieve('event_id', 'Integer');
$cart = CRM_Event_Cart_BAO_Cart::find_by_id($cart_id);
$params_array = array(
'cart_id' => $cart->id,
'contact_id' => CRM_Event_Cart_Form_Cart::find_or_create_contact(),
'event_id' => $event_id,
);
//XXX security?
$participant = CRM_Event_Cart_BAO_MerParticipant::create($params_array);
$participant->save();
$form = new CRM_Core_Form();
$pform = new CRM_Event_Cart_Form_MerParticipant($participant);
$pform->appendQuickForm($form);
$renderer = $form->getRenderer();
$config = CRM_Core_Config::singleton();
$templateDir = $config->templateDir;
if (is_array($templateDir)) {
$templateDir = array_pop($templateDir);
}
$requiredTemplate = file_get_contents($templateDir . '/CRM/Form/label.tpl');
$renderer->setRequiredTemplate($requiredTemplate);
$template = CRM_Core_Smarty::singleton();
$template->assign('form', $form->toSmarty());
$template->assign('participant', $participant);
$output = $template->fetch("CRM/Event/Cart/Form/Checkout/Participant.tpl");
$transaction->commit();
echo $output;
CRM_Utils_System::civiExit();
}
public function remove_participant_from_cart() {
$id = CRM_Utils_Request::retrieve('id', 'Integer');
$participant = CRM_Event_Cart_BAO_MerParticipant::get_by_id($id);
$participant->delete();
CRM_Utils_System::civiExit();
}
}

View file

@ -0,0 +1,25 @@
<?php
/**
* Class CRM_Event_Cart_Page_RemoveFromCart
*/
class CRM_Event_Cart_Page_RemoveFromCart extends CRM_Core_Page {
/**
* This function takes care of all the things common to all pages.
*
* This typically involves assigning the appropriate smarty variables :)
*/
public function run() {
$transaction = new CRM_Core_Transaction();
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
$cart = CRM_Event_Cart_BAO_Cart::find_or_create_for_current_session();
$cart->load_associations();
$event_in_cart = $cart->get_event_in_cart_by_event_id($this->_id);
$removed_event = $cart->remove_event_in_cart($event_in_cart->id);
$removed_event_title = $removed_event->event->title;
CRM_Core_Session::setStatus(ts("<b>%1</b> has been removed from your cart.", array(1 => $removed_event_title)), '', 'success');
$transaction->commit();
return CRM_Utils_System::redirect($_SERVER['HTTP_REFERER']);
}
}

View file

@ -0,0 +1,23 @@
<?php
/**
* Class CRM_Event_Cart_Page_ViewCart
*/
class CRM_Event_Cart_Page_ViewCart extends CRM_Core_Page {
/**
* @return string
*/
public function run() {
$transaction = new CRM_Core_Transaction();
$cart = CRM_Event_Cart_BAO_Cart::find_or_create_for_current_session();
$cart->load_associations();
$this->assign('events_in_carts', $cart->get_main_events_in_carts());
$this->assign('events_count', count($cart->get_main_events_in_carts()));
$transaction->commit();
return parent::run();
}
}

View file

@ -0,0 +1,44 @@
<?php
/**
* Class CRM_Event_Cart_StateMachine_Checkout
*/
class CRM_Event_Cart_StateMachine_Checkout extends CRM_Core_StateMachine {
/**
* @param object $controller
* @param const|int $action
*/
public function __construct($controller, $action = CRM_Core_Action::NONE) {
parent::__construct($controller, $action);
$cart = CRM_Event_Cart_BAO_Cart::find_or_create_for_current_session();
$cart->load_associations();
if ($cart->is_empty()) {
CRM_Core_Error::statusBounce(ts("You don't have any events in you cart. Please add some events."), CRM_Utils_System::url('civicrm/event'));
}
$pages = array();
$is_monetary = FALSE;
$is_conference = FALSE;
foreach ($cart->events_in_carts as $event_in_cart) {
if ($event_in_cart->event->is_monetary) {
$is_monetary = TRUE;
}
}
$pages["CRM_Event_Cart_Form_Checkout_ParticipantsAndPrices"] = NULL;
foreach ($cart->events_in_carts as $event_in_cart) {
if ($event_in_cart->is_parent_event()) {
foreach ($event_in_cart->participants as $participant) {
$pages["CRM_Event_Cart_Form_Checkout_ConferenceEvents_{$event_in_cart->event_id}_{$participant->id}"] = array(
'className' => 'CRM_Event_Cart_Form_Checkout_ConferenceEvents',
'title' => "Select {$event_in_cart->event->title} Events For {$participant->email}",
);
}
}
}
$pages["CRM_Event_Cart_Form_Checkout_Payment"] = NULL;
$pages["CRM_Event_Cart_Form_Checkout_ThankYou"] = NULL;
$this->addSequentialPages($pages, $action);
}
}

View file

@ -0,0 +1,69 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
class CRM_Event_Controller_Registration extends CRM_Core_Controller {
/**
* Class constructor.
*
* @param null $title
* @param bool|int $action
* @param bool $modal
*/
public function __construct($title = NULL, $action = CRM_Core_Action::NONE, $modal = TRUE) {
parent::__construct($title, $modal);
$this->_stateMachine = new CRM_Event_StateMachine_Registration($this, $action);
// create and instantiate the pages
$this->addPages($this->_stateMachine, $action);
$config = CRM_Core_Config::singleton();
//changes for custom data type File
$uploadNames = $this->get('uploadNames');
if (is_array($uploadNames) && !empty($uploadNames)) {
$this->addActions($config->customFileUploadDir, $uploadNames);
}
else {
// add all the actions
$this->addActions();
}
}
public function invalidKey() {
$this->invalidKeyRedirect();
}
}

View file

@ -0,0 +1,83 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class is used by the Search functionality.
*
* - the search controller is used for building/processing multiform
* searches.
*
* Typically the first form will display the search criteria and its results
*
* The second form is used to process search results with the associated actions
*
*/
class CRM_Event_Controller_Search extends CRM_Core_Controller {
/**
* Class constructor.
*
* @param string $title
* @param bool|int $action
* @param bool $modal
*/
public function __construct($title = NULL, $action = CRM_Core_Action::NONE, $modal = TRUE) {
parent::__construct($title, $modal);
$this->_stateMachine = new CRM_Event_StateMachine_Search($this, $action);
// create and instantiate the pages
$this->addPages($this->_stateMachine, $action);
$session = CRM_Core_Session::singleton();
$uploadNames = $session->get('uploadNames');
if (!empty($uploadNames)) {
$uploadNames = array_merge($uploadNames,
CRM_Core_BAO_File::uploadNames()
);
}
else {
$uploadNames = CRM_Core_BAO_File::uploadNames();
}
$config = CRM_Core_Config::singleton();
$uploadDir = $config->uploadDir;
// add all the actions
$this->addActions($uploadDir, $uploadNames);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,607 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/Event/Participant.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:89138cc7e79eac37b1b499084956428f)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Event_DAO_Participant constructor.
*/
class CRM_Event_DAO_Participant extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_participant';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = true;
/**
* Participant Id
*
* @var int unsigned
*/
public $id;
/**
* FK to Contact ID
*
* @var int unsigned
*/
public $contact_id;
/**
* FK to Event ID
*
* @var int unsigned
*/
public $event_id;
/**
* Participant status ID. FK to civicrm_participant_status_type. Default of 1 should map to status = Registered.
*
* @var int unsigned
*/
public $status_id;
/**
* Participant role ID. Implicit FK to civicrm_option_value where option_group = participant_role.
*
* @var string
*/
public $role_id;
/**
* When did contact register for event?
*
* @var datetime
*/
public $register_date;
/**
* Source of this event registration.
*
* @var string
*/
public $source;
/**
* Populate with the label (text) associated with a fee level for paid events with multiple levels. Note that
we store the label value and not the key
*
* @var text
*/
public $fee_level;
/**
*
* @var boolean
*/
public $is_test;
/**
*
* @var boolean
*/
public $is_pay_later;
/**
* actual processor fee if known - may be 0.
*
* @var float
*/
public $fee_amount;
/**
* FK to Participant ID
*
* @var int unsigned
*/
public $registered_by_id;
/**
* FK to Discount ID
*
* @var int unsigned
*/
public $discount_id;
/**
* 3 character string, value derived from config setting.
*
* @var string
*/
public $fee_currency;
/**
* The campaign for which this participant has been registered.
*
* @var int unsigned
*/
public $campaign_id;
/**
* Discount Amount
*
* @var int unsigned
*/
public $discount_amount;
/**
* FK to civicrm_event_carts
*
* @var int unsigned
*/
public $cart_id;
/**
* On Waiting List
*
* @var int
*/
public $must_wait;
/**
* FK to Contact ID
*
* @var int unsigned
*/
public $transferred_to_contact_id;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_participant';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contact_id', 'civicrm_contact', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'event_id', 'civicrm_event', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'status_id', 'civicrm_participant_status_type', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'registered_by_id', 'civicrm_participant', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'discount_id', 'civicrm_discount', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'campaign_id', 'civicrm_campaign', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'cart_id', 'civicrm_event_carts', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'transferred_to_contact_id', 'civicrm_contact', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'participant_id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Participant ID') ,
'description' => 'Participant Id',
'required' => true,
'import' => true,
'where' => 'civicrm_participant.id',
'headerPattern' => '/(^(participant(.)?)?id$)/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
) ,
'participant_contact_id' => array(
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Contact ID') ,
'description' => 'FK to Contact ID',
'required' => true,
'import' => true,
'where' => 'civicrm_participant.contact_id',
'headerPattern' => '/contact(.?id)?/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
) ,
'event_id' => array(
'name' => 'event_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Event') ,
'description' => 'FK to Event ID',
'required' => true,
'import' => true,
'where' => 'civicrm_participant.event_id',
'headerPattern' => '/event id$/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
'FKClassName' => 'CRM_Event_DAO_Event',
) ,
'participant_status_id' => array(
'name' => 'status_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Participant Status') ,
'description' => 'Participant status ID. FK to civicrm_participant_status_type. Default of 1 should map to status = Registered.',
'required' => true,
'import' => true,
'where' => 'civicrm_participant.status_id',
'headerPattern' => '/(participant.)?(status)$/i',
'dataPattern' => '',
'export' => true,
'default' => '1',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
'FKClassName' => 'CRM_Event_DAO_ParticipantStatusType',
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'table' => 'civicrm_participant_status_type',
'keyColumn' => 'id',
'labelColumn' => 'label',
)
) ,
'participant_role_id' => array(
'name' => 'role_id',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Participant Role') ,
'description' => 'Participant role ID. Implicit FK to civicrm_option_value where option_group = participant_role.',
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
'import' => true,
'where' => 'civicrm_participant.role_id',
'headerPattern' => '/(participant.)?(role)$/i',
'dataPattern' => '',
'export' => true,
'default' => 'NULL',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'optionGroupName' => 'participant_role',
'optionEditPath' => 'civicrm/admin/options/participant_role',
)
) ,
'participant_register_date' => array(
'name' => 'register_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Register date') ,
'description' => 'When did contact register for event?',
'import' => true,
'where' => 'civicrm_participant.register_date',
'headerPattern' => '/^(r(egister\s)?date)$/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
'html' => array(
'type' => 'Select Date',
'formatType' => 'activityDateTime',
) ,
) ,
'participant_source' => array(
'name' => 'source',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Participant Source') ,
'description' => 'Source of this event registration.',
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
'import' => true,
'where' => 'civicrm_participant.source',
'headerPattern' => '/(participant.)?(source)$/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
) ,
'participant_fee_level' => array(
'name' => 'fee_level',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Fee level') ,
'description' => 'Populate with the label (text) associated with a fee level for paid events with multiple levels. Note that
we store the label value and not the key
',
'import' => true,
'where' => 'civicrm_participant.fee_level',
'headerPattern' => '/^(f(ee\s)?level)$/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
) ,
'participant_is_test' => array(
'name' => 'is_test',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Test') ,
'import' => true,
'where' => 'civicrm_participant.is_test',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
) ,
'participant_is_pay_later' => array(
'name' => 'is_pay_later',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Is Pay Later') ,
'import' => true,
'where' => 'civicrm_participant.is_pay_later',
'headerPattern' => '/(is.)?(pay(.)?later)$/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
) ,
'participant_fee_amount' => array(
'name' => 'fee_amount',
'type' => CRM_Utils_Type::T_MONEY,
'title' => ts('Fee Amount') ,
'description' => 'actual processor fee if known - may be 0.',
'precision' => array(
20,
2
) ,
'import' => true,
'where' => 'civicrm_participant.fee_amount',
'headerPattern' => '/fee(.?am(ou)?nt)?/i',
'dataPattern' => '/^\d+(\.\d{2})?$/',
'export' => true,
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
) ,
'participant_registered_by_id' => array(
'name' => 'registered_by_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Registered By ID') ,
'description' => 'FK to Participant ID',
'import' => true,
'where' => 'civicrm_participant.registered_by_id',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'default' => 'NULL',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
'FKClassName' => 'CRM_Event_DAO_Participant',
) ,
'participant_discount_id' => array(
'name' => 'discount_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Discount ID') ,
'description' => 'FK to Discount ID',
'default' => 'NULL',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_Discount',
) ,
'participant_fee_currency' => array(
'name' => 'fee_currency',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Fee Currency') ,
'description' => '3 character string, value derived from config setting.',
'maxlength' => 3,
'size' => CRM_Utils_Type::FOUR,
'import' => true,
'where' => 'civicrm_participant.fee_currency',
'headerPattern' => '/(fee)?.?cur(rency)?/i',
'dataPattern' => '/^[A-Z]{3}$/i',
'export' => true,
'default' => 'NULL',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
)
) ,
'participant_campaign_id' => array(
'name' => 'campaign_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Campaign') ,
'description' => 'The campaign for which this participant has been registered.',
'import' => true,
'where' => 'civicrm_participant.campaign_id',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
'FKClassName' => 'CRM_Campaign_DAO_Campaign',
'pseudoconstant' => array(
'table' => 'civicrm_campaign',
'keyColumn' => 'id',
'labelColumn' => 'title',
)
) ,
'discount_amount' => array(
'name' => 'discount_amount',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Discount Amount') ,
'description' => 'Discount Amount',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
) ,
'cart_id' => array(
'name' => 'cart_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Event Cart ID') ,
'description' => 'FK to civicrm_event_carts',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
'FKClassName' => 'CRM_Event_Cart_DAO_Cart',
) ,
'must_wait' => array(
'name' => 'must_wait',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Must Wait on List') ,
'description' => 'On Waiting List',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
) ,
'transferred_to_contact_id' => array(
'name' => 'transferred_to_contact_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Transferred to Contact ID') ,
'description' => 'FK to Contact ID',
'import' => true,
'where' => 'civicrm_participant.transferred_to_contact_id',
'headerPattern' => '/transfer(.?id)?/i',
'dataPattern' => '',
'export' => true,
'default' => 'NULL',
'table_name' => 'civicrm_participant',
'entity' => 'Participant',
'bao' => 'CRM_Event_BAO_Participant',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return self::$_tableName;
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'participant', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'participant', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array(
'index_status_id' => array(
'name' => 'index_status_id',
'field' => array(
0 => 'status_id',
) ,
'localizable' => false,
'sig' => 'civicrm_participant::0::status_id',
) ,
'index_role_id' => array(
'name' => 'index_role_id',
'field' => array(
0 => 'role_id',
) ,
'localizable' => false,
'sig' => 'civicrm_participant::0::role_id',
) ,
);
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,209 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/Event/ParticipantPayment.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:293a5e4f208de9a01639960975850cd4)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Event_DAO_ParticipantPayment constructor.
*/
class CRM_Event_DAO_ParticipantPayment extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_participant_payment';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = true;
/**
* Participant Payment Id
*
* @var int unsigned
*/
public $id;
/**
* Participant Id (FK)
*
* @var int unsigned
*/
public $participant_id;
/**
* FK to contribution table.
*
* @var int unsigned
*/
public $contribution_id;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_participant_payment';
parent::__construct();
}
/**
* Returns foreign keys and entity references.
*
* @return array
* [CRM_Core_Reference_Interface]
*/
static function getReferenceColumns() {
if (!isset(Civi::$statics[__CLASS__]['links'])) {
Civi::$statics[__CLASS__]['links'] = static ::createReferenceColumns(__CLASS__);
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'participant_id', 'civicrm_participant', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contribution_id', 'civicrm_contribution', 'id');
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'links_callback', Civi::$statics[__CLASS__]['links']);
}
return Civi::$statics[__CLASS__]['links'];
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Payment ID') ,
'description' => 'Participant Payment Id',
'required' => true,
'table_name' => 'civicrm_participant_payment',
'entity' => 'ParticipantPayment',
'bao' => 'CRM_Event_BAO_ParticipantPayment',
'localizable' => 0,
) ,
'participant_id' => array(
'name' => 'participant_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Participant ID') ,
'description' => 'Participant Id (FK)',
'required' => true,
'table_name' => 'civicrm_participant_payment',
'entity' => 'ParticipantPayment',
'bao' => 'CRM_Event_BAO_ParticipantPayment',
'localizable' => 0,
'FKClassName' => 'CRM_Event_DAO_Participant',
) ,
'contribution_id' => array(
'name' => 'contribution_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Contribution') ,
'description' => 'FK to contribution table.',
'required' => true,
'table_name' => 'civicrm_participant_payment',
'entity' => 'ParticipantPayment',
'bao' => 'CRM_Event_BAO_ParticipantPayment',
'localizable' => 0,
'FKClassName' => 'CRM_Contribute_DAO_Contribution',
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return self::$_tableName;
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'participant_payment', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'participant_payment', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array(
'UI_contribution_participant' => array(
'name' => 'UI_contribution_participant',
'field' => array(
0 => 'contribution_id',
1 => 'participant_id',
) ,
'localizable' => false,
'unique' => true,
'sig' => 'civicrm_participant_payment::1::contribution_id::participant_id',
) ,
);
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,301 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*
* Generated from xml/schema/CRM/Event/ParticipantStatusType.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:614f4f6813728d18eb5ccd003c6d3d33)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Event_DAO_ParticipantStatusType constructor.
*/
class CRM_Event_DAO_ParticipantStatusType extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_participant_status_type';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = true;
/**
* unique participant status type id
*
* @var int unsigned
*/
public $id;
/**
* non-localized name of the status type
*
* @var string
*/
public $name;
/**
* localized label for display of this status type
*
* @var string
*/
public $label;
/**
* the general group of status type this one belongs to
*
* @var string
*/
public $class;
/**
* whether this is a status type required by the system
*
* @var boolean
*/
public $is_reserved;
/**
* whether this status type is active
*
* @var boolean
*/
public $is_active;
/**
* whether this status type is counted against event size limit
*
* @var boolean
*/
public $is_counted;
/**
* controls sort order
*
* @var int unsigned
*/
public $weight;
/**
* whether the status type is visible to the public, an implicit foreign key to option_value.value related to the `visibility` option_group
*
* @var int unsigned
*/
public $visibility_id;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_participant_status_type';
parent::__construct();
}
/**
* Returns all the column names of this table
*
* @return array
*/
static function &fields() {
if (!isset(Civi::$statics[__CLASS__]['fields'])) {
Civi::$statics[__CLASS__]['fields'] = array(
'id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Participant Status Type ID') ,
'description' => 'unique participant status type id',
'required' => true,
'table_name' => 'civicrm_participant_status_type',
'entity' => 'ParticipantStatusType',
'bao' => 'CRM_Event_BAO_ParticipantStatusType',
'localizable' => 0,
) ,
'participant_status' => array(
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Participant Status') ,
'description' => 'non-localized name of the status type',
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'import' => true,
'where' => 'civicrm_participant_status_type.name',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_participant_status_type',
'entity' => 'ParticipantStatusType',
'bao' => 'CRM_Event_BAO_ParticipantStatusType',
'localizable' => 0,
) ,
'label' => array(
'name' => 'label',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Participant Status Label') ,
'description' => 'localized label for display of this status type',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_participant_status_type',
'entity' => 'ParticipantStatusType',
'bao' => 'CRM_Event_BAO_ParticipantStatusType',
'localizable' => 1,
) ,
'class' => array(
'name' => 'class',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Participant Status Class') ,
'description' => 'the general group of status type this one belongs to',
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
'table_name' => 'civicrm_participant_status_type',
'entity' => 'ParticipantStatusType',
'bao' => 'CRM_Event_BAO_ParticipantStatusType',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'callback' => 'CRM_Event_PseudoConstant::participantStatusClassOptions',
)
) ,
'is_reserved' => array(
'name' => 'is_reserved',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Participant Status Is Reserved?>') ,
'description' => 'whether this is a status type required by the system',
'table_name' => 'civicrm_participant_status_type',
'entity' => 'ParticipantStatusType',
'bao' => 'CRM_Event_BAO_ParticipantStatusType',
'localizable' => 0,
) ,
'is_active' => array(
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Participant Status is Active') ,
'description' => 'whether this status type is active',
'default' => '1',
'table_name' => 'civicrm_participant_status_type',
'entity' => 'ParticipantStatusType',
'bao' => 'CRM_Event_BAO_ParticipantStatusType',
'localizable' => 0,
) ,
'is_counted' => array(
'name' => 'is_counted',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Participant Status Counts?') ,
'description' => 'whether this status type is counted against event size limit',
'table_name' => 'civicrm_participant_status_type',
'entity' => 'ParticipantStatusType',
'bao' => 'CRM_Event_BAO_ParticipantStatusType',
'localizable' => 0,
) ,
'weight' => array(
'name' => 'weight',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Order') ,
'description' => 'controls sort order',
'required' => true,
'table_name' => 'civicrm_participant_status_type',
'entity' => 'ParticipantStatusType',
'bao' => 'CRM_Event_BAO_ParticipantStatusType',
'localizable' => 0,
) ,
'visibility_id' => array(
'name' => 'visibility_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Participant Status Visibility') ,
'description' => 'whether the status type is visible to the public, an implicit foreign key to option_value.value related to the `visibility` option_group',
'table_name' => 'civicrm_participant_status_type',
'entity' => 'ParticipantStatusType',
'bao' => 'CRM_Event_BAO_ParticipantStatusType',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'optionGroupName' => 'visibility',
'optionEditPath' => 'civicrm/admin/options/visibility',
)
) ,
);
CRM_Core_DAO_AllCoreTables::invoke(__CLASS__, 'fields_callback', Civi::$statics[__CLASS__]['fields']);
}
return Civi::$statics[__CLASS__]['fields'];
}
/**
* Return a mapping from field-name to the corresponding key (as used in fields()).
*
* @return array
* Array(string $name => string $uniqueName).
*/
static function &fieldKeys() {
if (!isset(Civi::$statics[__CLASS__]['fieldKeys'])) {
Civi::$statics[__CLASS__]['fieldKeys'] = array_flip(CRM_Utils_Array::collect('name', self::fields()));
}
return Civi::$statics[__CLASS__]['fieldKeys'];
}
/**
* Returns the names of this table
*
* @return string
*/
static function getTableName() {
return CRM_Core_DAO::getLocaleTableName(self::$_tableName);
}
/**
* Returns if this table needs to be logged
*
* @return boolean
*/
function getLog() {
return self::$_log;
}
/**
* Returns the list of fields that can be imported
*
* @param bool $prefix
*
* @return array
*/
static function &import($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getImports(__CLASS__, 'participant_status_type', $prefix, array());
return $r;
}
/**
* Returns the list of fields that can be exported
*
* @param bool $prefix
*
* @return array
*/
static function &export($prefix = false) {
$r = CRM_Core_DAO_AllCoreTables::getExports(__CLASS__, 'participant_status_type', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array();
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,515 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class generates form components for processing a participation fee block
*/
class CRM_Event_Form_EventFees {
/**
* Set variables up before form is built.
*
* @param CRM_Core_Form $form
*/
public static function preProcess(&$form) {
//as when call come from register.php
if (!$form->_eventId) {
$form->_eventId = CRM_Utils_Request::retrieve('eventId', 'Positive', $form);
}
$form->_pId = CRM_Utils_Request::retrieve('participantId', 'Positive', $form);
$form->_discountId = CRM_Utils_Request::retrieve('discountId', 'Positive', $form);
$form->_fromEmails = CRM_Event_BAO_Event::getFromEmailIds($form->_eventId);
//CRM-6907 set event specific currency.
if ($form->_eventId &&
($currency = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $form->_eventId, 'currency'))
) {
CRM_Core_Config::singleton()->defaultCurrency = $currency;
}
}
/**
* This function sets the default values for the form in edit/view mode.
*
* @param CRM_Core_Form $form
*
* @return array
*/
public static function setDefaultValues(&$form) {
$defaults = array();
if ($form->_eventId) {
//get receipt text and financial type
$returnProperities = array('confirm_email_text', 'financial_type_id', 'campaign_id', 'start_date');
$details = array();
CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $form->_eventId, $details, $returnProperities);
if (!empty($details[$form->_eventId]['financial_type_id'])) {
$defaults[$form->_pId]['financial_type_id'] = $details[$form->_eventId]['financial_type_id'];
}
}
if ($form->_pId) {
$ids = array();
$params = array('id' => $form->_pId);
CRM_Event_BAO_Participant::getValues($params, $defaults, $ids);
if ($form->_action == CRM_Core_Action::UPDATE) {
$discounts = array();
if (!empty($form->_values['discount'])) {
foreach ($form->_values['discount'] as $key => $value) {
$value = current($value);
$discounts[$key] = $value['name'];
}
}
if ($form->_discountId && !empty($discounts[$defaults[$form->_pId]['discount_id']])) {
$form->assign('discount', $discounts[$defaults[$form->_pId]['discount_id']]);
}
$form->assign('fee_amount', CRM_Utils_Array::value('fee_amount', $defaults[$form->_pId]));
$form->assign('fee_level', CRM_Utils_Array::value('fee_level', $defaults[$form->_pId]));
}
$defaults[$form->_pId]['send_receipt'] = 0;
}
else {
$defaults[$form->_pId]['send_receipt'] = (strtotime(CRM_Utils_Array::value('start_date', $details[$form->_eventId])) >= time()) ? 1 : 0;
if ($form->_eventId && !empty($details[$form->_eventId]['confirm_email_text'])) {
//set receipt text
$defaults[$form->_pId]['receipt_text'] = $details[$form->_eventId]['confirm_email_text'];
}
list($defaults[$form->_pId]['receive_date'], $defaults[$form->_pId]['receive_date_time']) = CRM_Utils_Date::setDateDefaults();
}
//CRM-11601 we should keep the record contribution
//true by default while adding participant
if ($form->_action == CRM_Core_Action::ADD && !$form->_mode && $form->_isPaidEvent) {
$defaults[$form->_pId]['record_contribution'] = 1;
}
//CRM-13420
if (empty($defaults['payment_instrument_id'])) {
$defaults[$form->_pId]['payment_instrument_id'] = key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
}
if ($form->_mode) {
$config = CRM_Core_Config::singleton();
// set default country from config if no country set
if (empty($defaults[$form->_pId]["billing_country_id-{$form->_bltID}"])) {
$defaults[$form->_pId]["billing_country_id-{$form->_bltID}"] = $config->defaultContactCountry;
}
if (empty($defaults["billing_state_province_id-{$form->_bltID}"])) {
$defaults[$form->_pId]["billing_state_province_id-{$form->_bltID}"] = $config->defaultContactStateProvince;
}
$billingDefaults = $form->getProfileDefaults('Billing', $form->_contactId);
$defaults[$form->_pId] = array_merge($defaults[$form->_pId], $billingDefaults);
// // hack to simplify credit card entry for testing
// $defaults[$form->_pId]['credit_card_type'] = 'Visa';
// $defaults[$form->_pId]['credit_card_number'] = '4807731747657838';
// $defaults[$form->_pId]['cvv2'] = '000';
// $defaults[$form->_pId]['credit_card_exp_date'] = array( 'Y' => '2012', 'M' => '05' );
}
// if user has selected discount use that to set default
if (isset($form->_discountId)) {
$defaults[$form->_pId]['discount_id'] = $form->_discountId;
//hack to set defaults for already selected discount value
if ($form->_action == CRM_Core_Action::UPDATE && !$form->_originalDiscountId) {
$form->_originalDiscountId = $defaults[$form->_pId]['discount_id'];
if ($form->_originalDiscountId) {
$defaults[$form->_pId]['discount_id'] = $form->_originalDiscountId;
}
}
$discountId = $form->_discountId;
}
else {
$discountId = CRM_Core_BAO_Discount::findSet($form->_eventId, 'civicrm_event');
}
if ($discountId) {
$priceSetId = CRM_Core_DAO::getFieldValue('CRM_Core_BAO_Discount', $discountId, 'price_set_id');
}
else {
$priceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $form->_eventId);
}
if (($form->_action == CRM_Core_Action::ADD) && $form->_eventId && $discountId) {
// this case is for add mode, where we show discount automatically
$defaults[$form->_pId]['discount_id'] = $discountId;
}
if ($priceSetId) {
// get price set default values, CRM-4090
if (in_array(get_class($form),
array(
'CRM_Event_Form_Participant',
'CRM_Event_Form_Registration_Register',
'CRM_Event_Form_Registration_AdditionalParticipant',
)
)) {
$priceSetValues = self::setDefaultPriceSet($form->_pId, $form->_eventId);
if (!empty($priceSetValues)) {
$defaults[$form->_pId] = array_merge($defaults[$form->_pId], $priceSetValues);
}
}
if ($form->_action == CRM_Core_Action::ADD && !empty($form->_priceSet['fields'])) {
foreach ($form->_priceSet['fields'] as $key => $val) {
foreach ($val['options'] as $keys => $values) {
if ($values['is_default']) {
if (get_class($form) != 'CRM_Event_Form_Participant' && !empty($values['is_full'])) {
continue;
}
if ($val['html_type'] == 'CheckBox') {
$defaults[$form->_pId]["price_{$key}"][$keys] = 1;
}
else {
$defaults[$form->_pId]["price_{$key}"] = $keys;
}
}
}
}
}
$form->assign('totalAmount', CRM_Utils_Array::value('fee_amount', $defaults[$form->_pId]));
if ($form->_action == CRM_Core_Action::UPDATE) {
$fee_level = $defaults[$form->_pId]['fee_level'];
CRM_Event_BAO_Participant::fixEventLevel($fee_level);
$form->assign('fee_level', $fee_level);
$form->assign('fee_amount', CRM_Utils_Array::value('fee_amount', $defaults[$form->_pId]));
}
}
//CRM-4453
if (!empty($defaults[$form->_pId]['participant_fee_currency'])) {
$form->assign('fee_currency', $defaults[$form->_pId]['participant_fee_currency']);
}
// CRM-4395
if ($contriId = $form->get('onlinePendingContributionId')) {
$defaults[$form->_pId]['record_contribution'] = 1;
$contribution = new CRM_Contribute_DAO_Contribution();
$contribution->id = $contriId;
$contribution->find(TRUE);
foreach (array(
'financial_type_id',
'payment_instrument_id',
'contribution_status_id',
'receive_date',
'total_amount',
) as $f) {
if ($f == 'receive_date') {
list($defaults[$form->_pId]['receive_date']) = CRM_Utils_Date::setDateDefaults($contribution->$f);
}
else {
$defaults[$form->_pId][$f] = $contribution->$f;
}
}
}
return $defaults[$form->_pId];
}
/**
* This function sets the default values for price set.
*
* @param int $participantID
* @param int $eventID
* @param bool $includeQtyZero
*
* @return array
*/
public static function setDefaultPriceSet($participantID, $eventID = NULL, $includeQtyZero = TRUE) {
$defaults = array();
if (!$eventID && $participantID) {
$eventID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantID, 'event_id');
}
if (!$participantID || !$eventID) {
return $defaults;
}
// get price set ID.
$priceSetID = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $eventID);
if (!$priceSetID) {
return $defaults;
}
// use line items for setdefault price set fields, CRM-4090
$lineItems[$participantID] = CRM_Price_BAO_LineItem::getLineItems($participantID, 'participant', FALSE, $includeQtyZero);
if (is_array($lineItems[$participantID]) &&
!CRM_Utils_System::isNull($lineItems[$participantID])
) {
$priceFields = $htmlTypes = $optionValues = array();
foreach ($lineItems[$participantID] as $lineId => $items) {
$priceFieldId = CRM_Utils_Array::value('price_field_id', $items);
$priceOptionId = CRM_Utils_Array::value('price_field_value_id', $items);
if ($priceFieldId && $priceOptionId) {
$priceFields[$priceFieldId][] = $priceOptionId;
}
}
if (empty($priceFields)) {
return $defaults;
}
// get all price set field html types.
$sql = '
SELECT id, html_type
FROM civicrm_price_field
WHERE id IN (' . implode(',', array_keys($priceFields)) . ')';
$fieldDAO = CRM_Core_DAO::executeQuery($sql);
while ($fieldDAO->fetch()) {
$htmlTypes[$fieldDAO->id] = $fieldDAO->html_type;
}
foreach ($lineItems[$participantID] as $lineId => $items) {
$fieldId = $items['price_field_id'];
$htmlType = CRM_Utils_Array::value($fieldId, $htmlTypes);
if (!$htmlType) {
continue;
}
if ($htmlType == 'Text') {
$defaults["price_{$fieldId}"] = $items['qty'];
}
else {
$fieldOptValues = CRM_Utils_Array::value($fieldId, $priceFields);
if (!is_array($fieldOptValues)) {
continue;
}
foreach ($fieldOptValues as $optionId) {
if ($htmlType == 'CheckBox') {
$defaults["price_{$fieldId}"][$optionId] = TRUE;
}
else {
$defaults["price_{$fieldId}"] = $optionId;
break;
}
}
}
}
}
return $defaults;
}
/**
* Build the form object.
*
* @param CRM_Core_Form $form
*/
public static function buildQuickForm(&$form) {
if ($form->_eventId) {
$form->_isPaidEvent = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $form->_eventId, 'is_monetary');
if ($form->_isPaidEvent) {
$form->addElement('hidden', 'hidden_feeblock', 1);
}
// make sure this is for backoffice registration.
if ($form->getName() == 'Participant') {
$eventfullMsg = CRM_Event_BAO_Participant::eventFullMessage($form->_eventId, $form->_pId);
$form->addElement('hidden', 'hidden_eventFullMsg', $eventfullMsg, array('id' => 'hidden_eventFullMsg'));
}
}
if ($form->_pId) {
if (CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
$form->_pId, 'contribution_id', 'participant_id'
)
) {
$form->_online = TRUE;
}
}
if ($form->_isPaidEvent) {
$params = array('id' => $form->_eventId);
CRM_Event_BAO_Event::retrieve($params, $event);
//retrieve custom information
$form->_values = array();
CRM_Event_Form_Registration::initEventFee($form, $event['id']);
CRM_Event_Form_Registration_Register::buildAmount($form, TRUE, $form->_discountId);
$lineItem = array();
$invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
$invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
$totalTaxAmount = 0;
if (!CRM_Utils_System::isNull(CRM_Utils_Array::value('line_items', $form->_values))) {
$lineItem[] = $form->_values['line_items'];
foreach ($form->_values['line_items'] as $key => $value) {
$totalTaxAmount = $value['tax_amount'] + $totalTaxAmount;
}
}
if ($invoicing) {
$form->assign('totalTaxAmount', $totalTaxAmount);
}
$form->assign('lineItem', empty($lineItem) ? FALSE : $lineItem);
$discounts = array();
if (!empty($form->_values['discount'])) {
foreach ($form->_values['discount'] as $key => $value) {
$value = current($value);
$discounts[$key] = $value['name'];
}
$element = $form->add('select', 'discount_id',
ts('Discount Set'),
array(
0 => ts('- select -'),
) + $discounts,
FALSE,
array('class' => "crm-select2")
);
if ($form->_online) {
$element->freeze();
}
}
if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()
&& !CRM_Utils_Array::value('fee', $form->_values)
&& CRM_Utils_Array::value('snippet', $_REQUEST) == CRM_Core_Smarty::PRINT_NOFORM
) {
CRM_Core_Session::setStatus(ts('You do not have all the permissions needed for this page.'), 'Permission Denied', 'error');
return FALSE;
}
CRM_Core_Payment_Form::buildPaymentForm($form, $form->_paymentProcessor, FALSE, TRUE, self::getDefaultPaymentInstrumentId());
if (!$form->_mode) {
$form->addElement('checkbox', 'record_contribution', ts('Record Payment?'), NULL,
array('onclick' => "return showHideByValue('record_contribution','','payment_information','table-row','radio',false);")
);
// Check permissions for financial type first
if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, $form->_action);
}
else {
$financialTypes = CRM_Contribute_PseudoConstant::financialType();
}
$form->add('select', 'financial_type_id',
ts('Financial Type'),
array('' => ts('- select -')) + $financialTypes
);
$form->addDateTime('receive_date', ts('Received'), FALSE, array('formatType' => 'activityDateTime'));
$form->add('select', 'payment_instrument_id',
ts('Payment Method'),
array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
FALSE, array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
);
// don't show transaction id in batch update mode
$path = CRM_Utils_System::currentPath();
$form->assign('showTransactionId', FALSE);
if ($path != 'civicrm/contact/search/basic') {
$form->add('text', 'trxn_id', ts('Transaction ID'));
$form->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
'objectExists', array('CRM_Contribute_DAO_Contribution', $form->_eventId, 'trxn_id')
);
$form->assign('showTransactionId', TRUE);
}
$form->add('select', 'contribution_status_id',
ts('Payment Status'), CRM_Contribute_BAO_Contribution_Utils::getContributionStatuses('participant')
);
$form->add('text', 'check_number', ts('Check Number'),
CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number')
);
$form->add('text', 'total_amount', ts('Amount'),
CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution', 'total_amount')
);
}
}
else {
$form->add('text', 'amount', ts('Event Fee(s)'));
}
$form->assign('onlinePendingContributionId', $form->get('onlinePendingContributionId'));
$form->assign('paid', $form->_isPaidEvent);
$form->addElement('checkbox',
'send_receipt',
ts('Send Confirmation?'), NULL,
array('onclick' => "showHideByValue('send_receipt','','notice','table-row','radio',false); showHideByValue('send_receipt','','from-email','table-row','radio',false);")
);
$form->add('select', 'from_email_address', ts('Receipt From'), $form->_fromEmails['from_email_id']);
$form->add('textarea', 'receipt_text', ts('Confirmation Message'));
// Retrieve the name and email of the contact - form will be the TO for receipt email ( only if context is not standalone)
if ($form->_context != 'standalone') {
if ($form->_contactId) {
list($form->_contributorDisplayName,
$form->_contributorEmail
) = CRM_Contact_BAO_Contact_Location::getEmailDetails($form->_contactId);
$form->assign('email', $form->_contributorEmail);
}
else {
//show email block for batch update for event
$form->assign('batchEmail', TRUE);
}
}
$mailingInfo = Civi::settings()->get('mailing_backend');
$form->assign('outBound_option', $mailingInfo['outBound_option']);
$form->assign('hasPayment', $form->_paymentId);
}
/**
* Get the default payment instrument id.
*
* @todo resolve relationship between this form & abstractEdit -which should be it's parent.
*
* @return int
*/
protected static function getDefaultPaymentInstrumentId() {
$paymentInstrumentID = CRM_Utils_Request::retrieve('payment_instrument_id', 'Integer');
if ($paymentInstrumentID) {
return $paymentInstrumentID;
}
return key(CRM_Core_OptionGroup::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
}
}

View file

@ -0,0 +1,429 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class generates form components for processing Event.
*/
class CRM_Event_Form_ManageEvent extends CRM_Core_Form {
/**
* The id of the event we are processing.
*
* @var int
*/
public $_id;
/**
* Is this the first page?
*
* @var boolean
*/
protected $_first = FALSE;
/**
* Are we in single form mode or wizard mode?
*
* @var boolean
*/
protected $_single;
public $_action;
/**
* Are we actually managing an event template?
* @var boolean
*/
protected $_isTemplate = FALSE;
/**
* Pre-populate fields based on this template event_id
* @var integer
*/
protected $_templateId;
protected $_cancelURL = NULL;
/**
* The campaign id of the existing event, we use this to know if we need to update
* the participant records
*/
protected $_campaignID = NULL;
/**
* Check if repeating event.
*/
public $_isRepeatingEvent;
/**
* Explicitly declare the entity api name.
*/
public function getDefaultEntity() {
return 'Event';
}
/**
* Explicitly declare the form context.
*/
public function getDefaultContext() {
return 'create';
}
/**
* Set variables up before form is built.
*/
public function preProcess() {
$config = CRM_Core_Config::singleton();
if (in_array('CiviEvent', $config->enableComponents)) {
$this->assign('CiviEvent', TRUE);
}
CRM_Core_Form_RecurringEntity::preProcess('civicrm_event');
$this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add', 'REQUEST');
$this->assign('action', $this->_action);
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE, NULL, 'GET');
if ($this->_id) {
$this->_isRepeatingEvent = CRM_Core_BAO_RecurringEntity::getParentFor($this->_id, 'civicrm_event');
$this->assign('eventId', $this->_id);
if (!empty($this->_addBlockName) && empty($this->_addProfileBottom) && empty($this->_addProfileBottomAdd)) {
$this->add('hidden', 'id', $this->_id);
}
$this->_single = TRUE;
$params = array('id' => $this->_id);
CRM_Event_BAO_Event::retrieve($params, $eventInfo);
// its an update mode, do a permission check
if (!CRM_Event_BAO_Event::checkPermission($this->_id, CRM_Core_Permission::EDIT)) {
CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
}
$participantListingID = CRM_Utils_Array::value('participant_listing_id', $eventInfo);
//CRM_Core_DAO::getFieldValue( 'CRM_Event_DAO_Event', $this->_id, 'participant_listing_id' );
if ($participantListingID) {
$participantListingURL = CRM_Utils_System::url('civicrm/event/participant',
"reset=1&id={$this->_id}",
TRUE, NULL, TRUE, TRUE
);
$this->assign('participantListingURL', $participantListingURL);
}
$this->assign('isOnlineRegistration', CRM_Utils_Array::value('is_online_registration', $eventInfo));
$this->assign('id', $this->_id);
}
// figure out whether were handling an event or an event template
if ($this->_id) {
$this->_isTemplate = CRM_Utils_Array::value('is_template', $eventInfo);
}
elseif ($this->_action & CRM_Core_Action::ADD) {
$this->_isTemplate = CRM_Utils_Request::retrieve('is_template', 'Boolean', $this);
}
$this->assign('isTemplate', $this->_isTemplate);
if ($this->_id) {
if ($this->_isTemplate) {
$title = CRM_Utils_Array::value('template_title', $eventInfo);
CRM_Utils_System::setTitle(ts('Edit Event Template') . " - $title");
}
else {
$configureText = ts('Configure Event');
$title = CRM_Utils_Array::value('title', $eventInfo);
//If it is a repeating event change title
if ($this->_isRepeatingEvent) {
$configureText = 'Configure Repeating Event';
}
CRM_Utils_System::setTitle($configureText . " - $title");
}
$this->assign('title', $title);
}
elseif ($this->_action & CRM_Core_Action::ADD) {
if ($this->_isTemplate) {
$title = ts('New Event Template');
CRM_Utils_System::setTitle($title);
}
else {
$title = ts('New Event');
CRM_Utils_System::setTitle($title);
}
$this->assign('title', $title);
}
if (CRM_Core_Permission::check('view event participants') &&
CRM_Core_Permission::check('view all contacts')
) {
$statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1', 'label');
$statusTypesPending = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 0', 'label');
$findParticipants['statusCounted'] = implode(', ', array_values($statusTypes));
$findParticipants['statusNotCounted'] = implode(', ', array_values($statusTypesPending));
$this->assign('findParticipants', $findParticipants);
}
$this->_templateId = (int) CRM_Utils_Request::retrieve('template_id', 'Integer', $this);
//Is a repeating event
if ($this->_isRepeatingEvent) {
$isRepeatingEntity = TRUE;
$this->assign('isRepeatingEntity', $isRepeatingEntity);
}
// CRM-16776 - show edit/copy/create buttons for Profiles if user has required permission.
$ufGroups = CRM_Core_PseudoConstant::get('CRM_Core_DAO_UFField', 'uf_group_id');
$ufCreate = CRM_ACL_API::group(CRM_Core_Permission::CREATE, NULL, 'civicrm_uf_group', $ufGroups);
$ufEdit = CRM_ACL_API::group(CRM_Core_Permission::EDIT, NULL, 'civicrm_uf_group', $ufGroups);
$checkPermission = array(
array(
'administer CiviCRM',
'manage event profiles',
),
);
if (CRM_Core_Permission::check($checkPermission) || !empty($ufCreate) || !empty($ufEdit)) {
$this->assign('perm', TRUE);
}
// also set up tabs
CRM_Event_Form_ManageEvent_TabHeader::build($this);
// Set Done button URL and breadcrumb. Templates go back to Manage Templates,
// otherwise go to Manage Event for new event or ManageEventEdit if event if exists.
$breadCrumb = array();
if (!$this->_isTemplate) {
if ($this->_id) {
$this->_doneUrl = CRM_Utils_System::url(CRM_Utils_System::currentPath(),
"action=update&reset=1&id={$this->_id}"
);
}
else {
$this->_doneUrl = CRM_Utils_System::url('civicrm/event/manage',
'reset=1'
);
$breadCrumb = array(
array(
'title' => ts('Manage Events'),
'url' => $this->_doneUrl,
),
);
}
}
else {
$this->_doneUrl = CRM_Utils_System::url('civicrm/admin/eventTemplate', 'reset=1');
$breadCrumb = array(
array(
'title' => ts('Manage Event Templates'),
'url' => $this->_doneUrl,
),
);
}
CRM_Utils_System::appendBreadCrumb($breadCrumb);
}
/**
* Set default values for the form.
*
* For edit/view mode the default values are retrieved from the database.
*/
public function setDefaultValues() {
$defaults = array();
if (isset($this->_id)) {
$params = array('id' => $this->_id);
CRM_Event_BAO_Event::retrieve($params, $defaults);
$this->_campaignID = CRM_Utils_Array::value('campaign_id', $defaults);
}
elseif ($this->_templateId) {
$params = array('id' => $this->_templateId);
CRM_Event_BAO_Event::retrieve($params, $defaults);
$defaults['is_template'] = $this->_isTemplate;
$defaults['template_id'] = $defaults['id'];
unset($defaults['id']);
}
else {
$defaults['is_active'] = 1;
$defaults['style'] = 'Inline';
}
return $defaults;
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$session = CRM_Core_Session::singleton();
$this->_cancelURL = CRM_Utils_Array::value('cancelURL', $_POST);
if (!$this->_cancelURL) {
if ($this->_isTemplate) {
$this->_cancelURL = CRM_Utils_System::url('civicrm/admin/eventTemplate',
'reset=1'
);
}
else {
$this->_cancelURL = CRM_Utils_System::url('civicrm/event/manage',
'reset=1'
);
}
}
if ($this->_cancelURL) {
$this->addElement('hidden', 'cancelURL', $this->_cancelURL);
}
if ($this->_single) {
$buttons = array(
array(
'type' => 'upload',
'name' => ts('Save'),
'isDefault' => TRUE,
),
array(
'type' => 'upload',
'name' => ts('Save and Done'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
'subName' => 'done',
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
);
$this->addButtons($buttons);
}
else {
$buttons = array();
if (!$this->_first) {
$buttons[] = array(
'type' => 'back',
'name' => ts('Previous'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
);
}
$buttons[] = array(
'type' => 'upload',
'name' => ts('Continue'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
'isDefault' => TRUE,
);
$buttons[] = array(
'type' => 'cancel',
'name' => ts('Cancel'),
);
$this->addButtons($buttons);
}
$session->replaceUserContext($this->_cancelURL);
$this->add('hidden', 'is_template', $this->_isTemplate);
}
public function endPostProcess() {
// make submit buttons keep the current working tab opened.
if ($this->_action & CRM_Core_Action::UPDATE) {
$className = CRM_Utils_String::getClassName($this->_name);
// hack for special cases.
switch ($className) {
case 'Event':
$attributes = $this->getVar('_attributes');
$subPage = strtolower(basename(CRM_Utils_Array::value('action', $attributes)));
break;
case 'EventInfo':
$subPage = 'settings';
break;
case 'ScheduleReminders':
$subPage = 'reminder';
break;
default:
$subPage = strtolower($className);
break;
}
CRM_Core_Session::setStatus(ts("'%1' information has been saved.",
array(1 => CRM_Utils_Array::value('title', CRM_Utils_Array::value($subPage, $this->get('tabHeader')), $className))
), ts('Saved'), 'success');
$config = CRM_Core_Config::singleton();
if (in_array('CiviCampaign', $config->enableComponents)) {
$values = $this->controller->exportValues($this->_name);
$newCampaignID = CRM_Utils_Array::value('campaign_id', $values);
$eventID = CRM_Utils_Array::value('id', $values);
if ($eventID && $this->_campaignID != $newCampaignID) {
CRM_Event_BAO_Event::updateParticipantCampaignID($eventID, $newCampaignID);
}
}
$this->postProcessHook();
if ($this->controller->getButtonName('submit') == "_qf_{$className}_upload_done") {
if ($this->_isTemplate) {
CRM_Core_Session::singleton()
->pushUserContext(CRM_Utils_System::url('civicrm/admin/eventTemplate', 'reset=1'));
}
else {
CRM_Core_Session::singleton()->pushUserContext(CRM_Utils_System::url('civicrm/event/manage', 'reset=1'));
}
}
else {
CRM_Core_Session::singleton()->pushUserContext(CRM_Utils_System::url("civicrm/event/manage/{$subPage}",
"action=update&reset=1&id={$this->_id}"
));
}
}
}
/**
* @return string
*/
public function getTemplateFileName() {
if ($this->controller->getPrint() || $this->getVar('_id') <= 0 || $this->_action & CRM_Core_Action::DELETE) {
return parent::getTemplateFileName();
}
else {
// hack lets suppress the form rendering for now
self::$_template->assign('isForm', FALSE);
return 'CRM/Event/Form/ManageEvent/Tab.tpl';
}
}
/**
* Pre-load libraries required by Online Registration Profile fields
*/
public static function addProfileEditScripts() {
CRM_UF_Page_ProfileEditor::registerProfileScripts();
CRM_UF_Page_ProfileEditor::registerSchemas(array('IndividualModel', 'ParticipantModel'));
}
}

View file

@ -0,0 +1,90 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class generates form components for Conference Slots.
*/
class CRM_Event_Form_ManageEvent_Conference extends CRM_Event_Form_ManageEvent {
/**
* Page action.
*/
public $_action;
/**
* Build quick form.
*/
public function buildQuickForm() {
$slots = CRM_Core_OptionGroup::values('conference_slot');
$this->add('select',
'slot_label_id',
ts('Conference Slot'),
array(
'' => ts('- select -'),
) + $slots,
FALSE
);
$this->addEntityRef('parent_event_id', ts('Parent Event'), array(
'entity' => 'event',
'placeholder' => ts('- any -'),
'select' => array('minimumInputLength' => 0),
)
);
parent::buildQuickForm();
}
/**
* Post process form.
*/
public function postProcess() {
$params = $this->exportValues();
$params['id'] = $this->_id;
CRM_Event_BAO_Event::add($params);
parent::endPostProcess();
}
/**
* Return a descriptive name for the page, used in wizard header.
*
* @return string
*/
public function getTitle() {
return ts('Conference Slots');
}
}

View file

@ -0,0 +1,108 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class is to build the form for Deleting Group.
*/
class CRM_Event_Form_ManageEvent_Delete extends CRM_Event_Form_ManageEvent {
/**
* Page title.
*
* @var string
*/
protected $_title;
/**
* Set variables up before form is built.
*/
public function preProcess() {
parent::preProcess();
if ($this->_isTemplate) {
$this->_title = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_id, 'template_title');
}
else {
$this->_title = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_id, 'title');
}
if (!CRM_Event_BAO_Event::checkPermission($this->_id, CRM_Core_Permission::DELETE)) {
CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
}
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->assign('title', $this->_title);
$buttons = array(
array(
'type' => 'next',
'name' => $this->_isTemplate ? ts('Delete Event Template') : ts('Delete Event'),
'isDefault' => TRUE,
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
);
$this->addButtons($buttons);
}
/**
* Process the form when submitted.
*/
public function postProcess() {
$participant = new CRM_Event_DAO_Participant();
$participant->event_id = $this->_id;
if ($participant->find()) {
$searchURL = CRM_Utils_System::url('civicrm/event/search', 'reset=1');
CRM_Core_Session::setStatus(ts('This event cannot be deleted because there are participant records linked to it. If you want to delete this event, you must first find the participants linked to this event and delete them. You can use use <a href=\'%1\'> CiviEvent >> Find Participants page </a>.',
array(1 => $searchURL)
), ts('Deletion Error'), 'error');
return;
}
CRM_Event_BAO_Event::del($this->_id);
if ($this->_isTemplate) {
CRM_Core_Session::setStatus(ts("'%1' has been deleted.", array(1 => $this->_title)), ts('Template Deleted'), 'success');
CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/admin/eventTemplate', 'reset=1'));
}
else {
CRM_Core_Session::setStatus(ts("'%1' has been deleted.", array(1 => $this->_title)), ts('Event Deleted'), 'success');
}
}
}

View file

@ -0,0 +1,309 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class generates form components for processing Event.
*/
class CRM_Event_Form_ManageEvent_EventInfo extends CRM_Event_Form_ManageEvent {
/**
* Event type.
*/
protected $_eventType = NULL;
/**
* Set variables up before form is built.
*/
public function preProcess() {
parent::preProcess();
if ($this->_id) {
$this->assign('entityID', $this->_id);
$eventType = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event',
$this->_id,
'event_type_id'
);
}
else {
$eventType = 'null';
}
$showLocation = FALSE;
// when custom data is included in this page
if (!empty($_POST['hidden_custom'])) {
$this->set('type', 'Event');
$this->set('subType', CRM_Utils_Array::value('event_type_id', $_POST));
$this->assign('customDataSubType', CRM_Utils_Array::value('event_type_id', $_POST));
$this->set('entityId', $this->_id);
CRM_Custom_Form_CustomData::preProcess($this, NULL, $this->_eventType, 1, 'Event', $this->_id);
CRM_Custom_Form_CustomData::buildQuickForm($this);
CRM_Custom_Form_CustomData::setDefaultValues($this);
}
}
/**
* Set default values for the form.
*
* For edit/view mode he default values are retrieved from the database.
*/
public function setDefaultValues() {
$defaults = parent::setDefaultValues();
// in update mode, we need to set custom data subtype to tpl
if (!empty($defaults['event_type_id'])) {
$this->assign('customDataSubType', $defaults['event_type_id']);
}
$this->_showHide = new CRM_Core_ShowHideBlocks();
// Show waitlist features or event_full_text if max participants set
if (!empty($defaults['max_participants'])) {
$this->_showHide->addShow('id-waitlist');
if (!empty($defaults['has_waitlist'])) {
$this->_showHide->addShow('id-waitlist-text');
$this->_showHide->addHide('id-event_full');
}
else {
$this->_showHide->addHide('id-waitlist-text');
$this->_showHide->addShow('id-event_full');
}
}
else {
$this->_showHide->addHide('id-event_full');
$this->_showHide->addHide('id-waitlist');
$this->_showHide->addHide('id-waitlist-text');
}
$this->_showHide->addToTemplate();
$this->assign('elemType', 'table-row');
$this->assign('description', CRM_Utils_Array::value('description', $defaults));
// Provide suggested text for event full and waitlist messages if they're empty
$defaults['event_full_text'] = CRM_Utils_Array::value('event_full_text', $defaults, ts('This event is currently full.'));
$defaults['waitlist_text'] = CRM_Utils_Array::value('waitlist_text', $defaults, ts('This event is currently full. However you can register now and get added to a waiting list. You will be notified if spaces become available.'));
list($defaults['start_date'], $defaults['start_date_time']) = CRM_Utils_Date::setDateDefaults(CRM_Utils_Array::value('start_date', $defaults), 'activityDateTime');
if (!empty($defaults['end_date'])) {
list($defaults['end_date'], $defaults['end_date_time']) = CRM_Utils_Date::setDateDefaults($defaults['end_date'], 'activityDateTime');
}
return $defaults;
}
/**
* Build the form object.
*/
public function buildQuickForm() {
//need to assign custom data type and subtype to the template
$this->assign('customDataType', 'Event');
if ($this->_eventType) {
$this->assign('customDataSubType', $this->_eventType);
}
$this->assign('entityId', $this->_id);
$this->_first = TRUE;
$this->applyFilter('__ALL__', 'trim');
$attributes = CRM_Core_DAO::getAttribute('CRM_Event_DAO_Event');
if ($this->_isTemplate) {
$this->add('text', 'template_title', ts('Template Title'), $attributes['template_title'], TRUE);
}
if ($this->_action & CRM_Core_Action::ADD) {
$eventTemplates = CRM_Event_PseudoConstant::eventTemplates();
if (CRM_Utils_System::isNull($eventTemplates) && !$this->_isTemplate) {
$url = CRM_Utils_System::url('civicrm/admin/eventTemplate', array('reset' => 1));
CRM_Core_Session::setStatus(ts('If you find that you are creating multiple events with similar settings, you may want to use the <a href="%1">Event Templates</a> feature to streamline your workflow.', array(1 => $url)), ts('Tip'), 'info');
}
if (!CRM_Utils_System::isNull($eventTemplates)) {
$this->add('select', 'template_id', ts('From Template'), array('' => ts('- select -')) + $eventTemplates, FALSE, array('class' => 'crm-select2 huge'));
}
// Make sure this form redirects properly
$this->preventAjaxSubmit();
}
// add event title, make required if this is not a template
$this->add('text', 'title', ts('Event Title'), $attributes['event_title'], !$this->_isTemplate);
$this->addSelect('event_type_id',
array('onChange' => "CRM.buildCustomData( 'Event', this.value );"),
TRUE
);
//CRM-7362 --add campaigns.
$campaignId = NULL;
if ($this->_id) {
$campaignId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_id, 'campaign_id');
}
CRM_Campaign_BAO_Campaign::addCampaign($this, $campaignId);
$this->addSelect('default_role_id', array(), TRUE);
$this->addSelect('participant_listing_id', array('placeholder' => ts('Disabled'), 'option_url' => NULL));
$this->add('textarea', 'summary', ts('Event Summary'), $attributes['summary']);
$this->add('wysiwyg', 'description', ts('Complete Description'), $attributes['event_description'] + array('preset' => 'civievent'));
$this->addElement('checkbox', 'is_public', ts('Public Event'));
$this->addElement('checkbox', 'is_share', ts('Allow sharing through social media?'));
$this->addElement('checkbox', 'is_map', ts('Include Map to Event Location'));
$this->addDateTime('start_date', ts('Start Date'), FALSE, array('formatType' => 'activityDateTime'));
$this->addDateTime('end_date', ts('End Date / Time'), FALSE, array('formatType' => 'activityDateTime'));
$this->add('text', 'max_participants', ts('Max Number of Participants'),
array('onchange' => "if (this.value != '') {cj('#id-waitlist').show(); showHideByValue('has_waitlist','0','id-waitlist-text','table-row','radio',false); showHideByValue('has_waitlist','0','id-event_full','table-row','radio',true); return;} else {cj('#id-event_full, #id-waitlist, #id-waitlist-text').hide(); return;}")
);
$this->addRule('max_participants', ts('Max participants should be a positive number'), 'positiveInteger');
$participantStatuses = CRM_Event_PseudoConstant::participantStatus();
$waitlist = 0;
if (in_array('On waitlist', $participantStatuses) and in_array('Pending from waitlist', $participantStatuses)) {
$this->addElement('checkbox', 'has_waitlist', ts('Offer a Waitlist?'), NULL, array('onclick' => "showHideByValue('has_waitlist','0','id-event_full','table-row','radio',true); showHideByValue('has_waitlist','0','id-waitlist-text','table-row','radio',false);"));
$this->add('textarea', 'waitlist_text', ts('Waitlist Message'), $attributes['waitlist_text']);
$waitlist = 1;
}
$this->assign('waitlist', $waitlist);
$this->add('textarea', 'event_full_text', ts('Message if Event Is Full'), $attributes['event_full_text']);
$this->addElement('checkbox', 'is_active', ts('Is this Event Active?'));
$this->addFormRule(array('CRM_Event_Form_ManageEvent_EventInfo', 'formRule'));
parent::buildQuickForm();
}
/**
* Global validation rules for the form.
*
* @param array $values
*
* @return array
* list of errors to be posted back to the form
*/
public static function formRule($values) {
$errors = array();
if (!$values['is_template']) {
if (CRM_Utils_System::isNull($values['start_date'])) {
$errors['start_date'] = ts('Start Date and Time are required fields');
}
else {
$start = CRM_Utils_Date::processDate($values['start_date']);
$end = CRM_Utils_Date::processDate($values['end_date']);
if (($end < $start) && ($end != 0)) {
$errors['end_date'] = ts('End date should be after Start date.');
}
}
}
//CRM-4286
if (strstr($values['title'], '/')) {
$errors['title'] = ts("Please do not use '/' in Event Title.");
}
return $errors;
}
/**
* Process the form submission.
*/
public function postProcess() {
$params = $this->controller->exportValues($this->_name);
//format params
$params['start_date'] = CRM_Utils_Date::processDate($params['start_date'], $params['start_date_time']);
$params['end_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('end_date', $params),
CRM_Utils_Array::value('end_date_time', $params),
TRUE
);
$params['has_waitlist'] = CRM_Utils_Array::value('has_waitlist', $params, FALSE);
$params['is_map'] = CRM_Utils_Array::value('is_map', $params, FALSE);
$params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
$params['is_public'] = CRM_Utils_Array::value('is_public', $params, FALSE);
$params['is_share'] = CRM_Utils_Array::value('is_share', $params, FALSE);
$params['default_role_id'] = CRM_Utils_Array::value('default_role_id', $params, FALSE);
$params['id'] = $this->_id;
$customFields = CRM_Core_BAO_CustomField::getFields('Event', FALSE, FALSE,
CRM_Utils_Array::value('event_type_id', $params)
);
$params['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
$this->_id,
'Event'
);
//merge params with defaults from templates
if (!empty($params['template_id'])) {
$params = array_merge(CRM_Event_BAO_Event::getTemplateDefaultValues($params['template_id']), $params);
}
$event = CRM_Event_BAO_Event::create($params);
// now that we have the events id, do some more template-based stuff
if (!empty($params['template_id'])) {
CRM_Event_BAO_Event::copy($params['template_id'], $event, TRUE);
}
$this->set('id', $event->id);
$this->postProcessHook();
if ($this->_action & CRM_Core_Action::ADD) {
$url = 'civicrm/event/manage/location';
$urlParams = "action=update&reset=1&id={$event->id}";
// special case for 'Save and Done' consistency.
if ($this->controller->getButtonName('submit') == '_qf_EventInfo_upload_done') {
$url = 'civicrm/event/manage';
$urlParams = 'reset=1';
CRM_Core_Session::setStatus(ts("'%1' information has been saved.",
array(1 => $this->getTitle())
), ts('Saved'), 'success');
}
CRM_Utils_System::redirect(CRM_Utils_System::url($url, $urlParams));
}
parent::endPostProcess();
}
/**
* Return a descriptive name for the page, used in wizard header.
*
* @return string
*/
public function getTitle() {
return ts('Event Information and Settings');
}
}

View file

@ -0,0 +1,816 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class generates form components for Event Fees.
*/
class CRM_Event_Form_ManageEvent_Fee extends CRM_Event_Form_ManageEvent {
/**
* Constants for number of options for data types of multiple option.
*/
const NUM_OPTION = 11;
/**
* Constants for number of discounts for the event.
*/
const NUM_DISCOUNT = 6;
/**
* Page action.
*/
public $_action;
/**
* In Date.
*/
private $_inDate;
/**
* Set variables up before form is built.
*/
public function preProcess() {
parent::preProcess();
}
/**
* Set default values for the form.
*
* For edit/view mode the default values are retrieved from the database.
*/
public function setDefaultValues() {
$parentDefaults = parent::setDefaultValues();
$eventId = $this->_id;
$params = array();
$defaults = array();
if (isset($eventId)) {
$params = array('id' => $eventId);
}
CRM_Event_BAO_Event::retrieve($params, $defaults);
if (isset($eventId)) {
$price_set_id = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $eventId, NULL, 1);
if ($price_set_id) {
$defaults['price_set_id'] = $price_set_id;
}
else {
$priceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $eventId, NULL);
if ($priceSetId) {
if ($isQuick = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $priceSetId, 'is_quick_config')) {
$this->assign('isQuick', $isQuick);
$priceField = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $priceSetId, 'id', 'price_set_id');
$options = array();
$priceFieldOptions = CRM_Price_BAO_PriceFieldValue::getValues($priceField, $options, 'weight', TRUE);
$defaults['price_field_id'] = $priceField;
$countRow = 0;
foreach ($options as $optionId => $optionValue) {
$countRow++;
$defaults['value'][$countRow] = CRM_Utils_Money::format($optionValue['amount'], NULL, '%a');
$defaults['label'][$countRow] = $optionValue['label'];
$defaults['name'][$countRow] = $optionValue['name'];
$defaults['weight'][$countRow] = $optionValue['weight'];
$defaults['price_field_value'][$countRow] = $optionValue['id'];
if ($optionValue['is_default']) {
$defaults['default'] = $countRow;
}
}
}
}
}
}
//check if discounted
$discountedEvent = CRM_Core_BAO_Discount::getOptionGroup($this->_id, 'civicrm_event');
if (!empty($discountedEvent)) {
$defaults['is_discount'] = $i = 1;
$totalLables = $maxSize = $defaultDiscounts = array();
foreach ($discountedEvent as $optionGroupId) {
$defaults['discount_price_set'][] = $optionGroupId;
$name = $defaults["discount_name[$i]"] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $optionGroupId, 'title');
list($defaults["discount_start_date[$i]"]) = CRM_Utils_Date::setDateDefaults(CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Discount', $optionGroupId,
'start_date', 'price_set_id'
));
list($defaults["discount_end_date[$i]"]) = CRM_Utils_Date::setDateDefaults(CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Discount', $optionGroupId,
'end_date', 'price_set_id'
));
$defaultDiscounts[] = CRM_Price_BAO_PriceSet::getSetDetail($optionGroupId);
$i++;
}
//avoid moving up value of lable when some labels don't
//have a value ,fixed for CRM-3088
$rowCount = 1;
foreach ($defaultDiscounts as $val) {
$discountFields = current($val);
$discountFields = current($discountFields['fields']);
foreach ($discountFields['options'] as $discountFieldsval) {
$defaults['discounted_label'][$discountFieldsval['weight']] = $discountFieldsval['label'];
$defaults['discounted_value'][$discountFieldsval['weight']][$rowCount] = CRM_Utils_Money::format($discountFieldsval['amount'], NULL, '%a');
$defaults['discount_option_id'][$rowCount][$discountFieldsval['weight']] = $discountFieldsval['id'];
if (!empty($discountFieldsval['is_default'])) {
$defaults['discounted_default'] = $discountFieldsval['weight'];
}
}
$rowCount++;
}
//CRM-12970
ksort($defaults['discounted_value']);
ksort($defaults['discounted_label']);
$rowCount = 1;
foreach ($defaults['discounted_label'] as $key => $value) {
if ($key != $rowCount) {
$defaults['discounted_label'][$rowCount] = $value;
$defaults['discounted_value'][$rowCount] = $defaults['discounted_value'][$key];
unset($defaults['discounted_value'][$key]);
unset($defaults['discounted_label'][$key]);
foreach ($defaults['discount_option_id'] as &$optionIds) {
if (array_key_exists($key, $optionIds)) {
$optionIds[$rowCount] = $optionIds[$key];
unset($optionIds[$key]);
}
}
}
$rowCount++;
}
$this->set('discountSection', 1);
$this->buildQuickForm();
}
elseif (!empty($defaults['label'])) {
//if Regular Fees are present in DB and event fee page is in update mode
$defaults['discounted_label'] = $defaults['label'];
}
elseif (!empty($this->_submitValues['label'])) {
//if event is newly created, use submitted values for
//discount labels
if (is_array($this->_submitValues['label'])) {
$k = 1;
foreach ($this->_submitValues['label'] as $value) {
if ($value) {
$defaults['discounted_label'][$k] = $value;
$k++;
}
}
}
}
$defaults['id'] = $eventId;
if (!empty($totalLables)) {
$maxKey = count($totalLables) - 1;
if (isset($maxKey) && !empty($totalLables[$maxKey]['value'])) {
foreach ($totalLables[$maxKey]['value'] as $i => $v) {
if ($totalLables[$maxKey]['amount_id'][$i] == CRM_Utils_Array::value('default_discount_fee_id', $defaults)) {
$defaults['discounted_default'] = $i;
break;
}
}
}
}
if (!isset($defaults['discounted_default'])) {
$defaults['discounted_default'] = 1;
}
if (!isset($defaults['is_monetary'])) {
$defaults['is_monetary'] = 1;
}
if (!isset($defaults['fee_label'])) {
$defaults['fee_label'] = ts('Event Fee(s)');
}
if (!isset($defaults['pay_later_text']) ||
empty($defaults['pay_later_text'])
) {
$defaults['pay_later_text'] = ts('I will send payment by check');
}
$this->_showHide = new CRM_Core_ShowHideBlocks();
if (!$defaults['is_monetary']) {
$this->_showHide->addHide('event-fees');
}
if (isset($defaults['price_set_id'])) {
$this->_showHide->addHide('map-field');
}
$this->_showHide->addToTemplate();
$this->assign('inDate', $this->_inDate);
if (!empty($defaults['payment_processor'])) {
$defaults['payment_processor'] = array_fill_keys(explode(CRM_Core_DAO::VALUE_SEPARATOR,
$defaults['payment_processor']
), '1');
}
return $defaults;
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->addYesNo('is_monetary',
ts('Paid Event'),
NULL,
NULL,
array('onclick' => "return showHideByValue('is_monetary','0','event-fees','block','radio',false);")
);
//add currency element.
$this->addCurrency('currency', ts('Currency'), FALSE);
$paymentProcessor = CRM_Core_PseudoConstant::paymentProcessor();
$this->assign('paymentProcessor', $paymentProcessor);
$this->addCheckBox('payment_processor', ts('Payment Processor'),
array_flip($paymentProcessor),
NULL, NULL, NULL, NULL,
array('&nbsp;&nbsp;', '&nbsp;&nbsp;', '&nbsp;&nbsp;', '<br/>')
);
// financial type
if (!CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus() ||
(CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus() && CRM_Core_Permission::check('administer CiviCRM Financial Types'))) {
$this->addSelect('financial_type_id');
}
else {
CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, CRM_Core_Action::ADD);
$this->addSelect('financial_type_id', array('context' => 'search', 'options' => $financialTypes));
}
// add pay later options
$this->addElement('checkbox', 'is_pay_later', ts('Enable Pay Later option?'), NULL,
array('onclick' => "return showHideByValue('is_pay_later','','payLaterOptions','block','radio',false);")
);
$this->addElement('textarea', 'pay_later_text', ts('Pay Later Label'),
CRM_Core_DAO::getAttribute('CRM_Event_DAO_Event', 'pay_later_text'),
FALSE
);
$this->add('wysiwyg', 'pay_later_receipt', ts('Pay Later Instructions'), CRM_Core_DAO::getAttribute('CRM_Event_DAO_Event', 'pay_later_receipt'));
$this->addElement('checkbox', 'is_billing_required', ts('Billing address required'));
$this->add('text', 'fee_label', ts('Fee Label'));
$price = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviEvent');
if (CRM_Utils_System::isNull($price)) {
$this->assign('price', FALSE);
}
else {
$this->assign('price', TRUE);
}
$this->add('select', 'price_set_id', ts('Price Set'),
array(
'' => ts('- none -'),
) + $price,
NULL, array('onchange' => "return showHideByValue('price_set_id', '', 'map-field', 'block', 'select', false);")
);
$default = array($this->createElement('radio', NULL, NULL, NULL, 0));
$this->add('hidden', 'price_field_id', '', array('id' => 'price_field_id'));
for ($i = 1; $i <= self::NUM_OPTION; $i++) {
// label
$this->add('text', "label[$i]", ts('Label'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'label'));
$this->add('hidden', "price_field_value[$i]", '', array('id' => "price_field_value[$i]"));
// value
$this->add('text', "value[$i]", ts('Value'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'value'));
$this->addRule("value[$i]", ts('Please enter a valid money value for this field (e.g. %1).', array(1 => CRM_Utils_Money::format('99.99', ' '))), 'money');
// default
$default[] = $this->createElement('radio', NULL, NULL, NULL, $i);
}
$this->addGroup($default, 'default');
$this->addElement('checkbox', 'is_discount', ts('Discounts by Signup Date?'), NULL,
array('onclick' => "warnDiscountDel(); return showHideByValue('is_discount','','discount','block','radio',false);")
);
$discountSection = $this->get('discountSection');
$this->assign('discountSection', $discountSection);
// form fields of Discount sets
$defaultOption = array();
$_showHide = new CRM_Core_ShowHideBlocks('', '');
for ($i = 1; $i <= self::NUM_DISCOUNT; $i++) {
//the show hide blocks
$showBlocks = 'discount_' . $i;
if ($i > 2) {
$_showHide->addHide($showBlocks);
}
else {
$_showHide->addShow($showBlocks);
}
//Increment by 1 of start date of previous end date.
if (is_array($this->_submitValues) &&
!empty($this->_submitValues['discount_name'][$i]) &&
!empty($this->_submitValues['discount_name'][$i + 1]) &&
isset($this->_submitValues['discount_end_date']) &&
isset($this->_submitValues['discount_end_date'][$i]) &&
$i < self::NUM_DISCOUNT - 1
) {
$end_date = CRM_Utils_Date::processDate($this->_submitValues['discount_end_date'][$i]);
if (!empty($this->_submitValues['discount_end_date'][$i + 1])
&& empty($this->_submitValues['discount_start_date'][$i + 1])
) {
list($this->_submitValues['discount_start_date'][$i + 1]) = CRM_Utils_Date::setDateDefaults(date('Y-m-d', strtotime("+1 days $end_date")));
}
}
//Decrement by 1 of end date from next start date.
if ($i > 1 &&
is_array($this->_submitValues) &&
!empty($this->_submitValues['discount_name'][$i]) &&
!empty($this->_submitValues['discount_name'][$i - 1]) &&
isset($this->_submitValues['discount_start_date']) &&
isset($this->_submitValues['discount_start_date'][$i])
) {
$start_date = CRM_Utils_Date::processDate($this->_submitValues['discount_start_date'][$i]);
if (!empty($this->_submitValues['discount_start_date'][$i])
&& empty($this->_submitValues['discount_end_date'][$i - 1])
) {
list($this->_submitValues['discount_end_date'][$i - 1]) = CRM_Utils_Date::setDateDefaults(date('Y-m-d', strtotime("-1 days $start_date")));
}
}
//discount name
$this->add('text', 'discount_name[' . $i . ']', ts('Discount Name'),
CRM_Core_DAO::getAttribute('CRM_Price_DAO_PriceSet', 'title')
);
$this->add('hidden', "discount_price_set[$i]", '', array('id' => "discount_price_set[$i]"));
//discount start date
$this->addDate('discount_start_date[' . $i . ']', ts('Discount Start Date'), FALSE, array('formatType' => 'activityDate'));
//discount end date
$this->addDate('discount_end_date[' . $i . ']', ts('Discount End Date'), FALSE, array('formatType' => 'activityDate'));
}
$_showHide->addToTemplate();
$this->addElement('submit', $this->getButtonName('submit'), ts('Add Discount Set to Fee Table'),
array('class' => 'crm-form-submit cancel')
);
if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
$deferredFinancialType = CRM_Financial_BAO_FinancialAccount::getDeferredFinancialType();
$this->assign('deferredFinancialType', array_keys($deferredFinancialType));
}
$this->buildAmountLabel();
parent::buildQuickForm();
}
/**
* Add local and global form rules.
*/
public function addRules() {
$this->addFormRule(array('CRM_Event_Form_ManageEvent_Fee', 'formRule'));
}
/**
* Global validation rules for the form.
*
* @param array $values
* Posted values of the form.
*
* @return array
* list of errors to be posted back to the form
*/
public static function formRule($values) {
$errors = array();
if (!empty($values['is_discount'])) {
$occurDiscount = array_count_values($values['discount_name']);
$countemptyrows = 0;
$countemptyvalue = 0;
for ($i = 1; $i <= self::NUM_DISCOUNT; $i++) {
$start_date = $end_date = NULL;
if (!empty($values['discount_name'][$i])) {
if (!empty($values['discount_start_date'][$i])) {
$start_date = ($values['discount_start_date'][$i]) ? CRM_Utils_Date::processDate($values['discount_start_date'][$i]) : 0;
}
if (!empty($values['discount_end_date'][$i])) {
$end_date = ($values['discount_end_date'][$i]) ? CRM_Utils_Date::processDate($values['discount_end_date'][$i]) : 0;
}
if ($start_date && $end_date && strcmp($end_date, $start_date) < 0) {
$errors["discount_end_date[$i]"] = ts('The discount end date cannot be prior to the start date.');
}
if (!$start_date && !$end_date) {
$errors["discount_start_date[$i]"] = $errors["discount_end_date[$i]"] = ts('Please specify either start date or end date.');
}
if ($i > 1) {
$end_date_1 = ($values['discount_end_date'][$i - 1]) ? CRM_Utils_Date::processDate($values['discount_end_date'][$i - 1]) : 0;
if ($start_date && $end_date_1 && strcmp($end_date_1, $start_date) >= 0) {
$errors["discount_start_date[$i]"] = ts('Select non-overlapping discount start date.');
}
elseif (!$start_date && !$end_date_1) {
$j = $i - 1;
$errors["discount_start_date[$i]"] = $errors["discount_end_date[$j]"] = ts('Select either of the dates.');
}
}
foreach ($occurDiscount as $key => $value) {
if ($value > 1 && $key <> '') {
if ($key == $values['discount_name'][$i]) {
$errors['discount_name[' . $i . ']'] = ts('%1 is already used for Discount Name.', array(1 => $key));
}
}
}
//validation for discount labels and values
for ($index = (self::NUM_OPTION); $index > 0; $index--) {
$label = TRUE;
if (empty($values['discounted_label'][$index]) && !empty($values['discounted_value'][$index][$i])) {
$label = FALSE;
if (!$label) {
$errors["discounted_label[{$index}]"] = ts('Label cannot be empty.');
}
}
if (!empty($values['discounted_label'][$index])) {
$duplicateIndex = CRM_Utils_Array::key($values['discounted_label'][$index], $values['discounted_label']);
if ((!($duplicateIndex === FALSE)) && (!($duplicateIndex == $index))) {
$errors["discounted_label[{$index}]"] = ts('Duplicate label value');
}
}
if (empty($values['discounted_label'][$index]) && empty($values['discounted_value'][$index][$i])) {
$countemptyrows++;
}
if (empty($values['discounted_value'][$index][$i])) {
$countemptyvalue++;
}
}
if (!empty($values['_qf_Fee_next']) && ($countemptyrows == 11 || $countemptyvalue == 11)) {
$errors["discounted_label[1]"] = $errors["discounted_value[1][$i]"] = ts('At least one fee should be entered for your Discount Set. If you do not see the table to enter discount fees, click the "Add Discount Set to Fee Table" button.');
}
}
}
}
if ($values['is_monetary']) {
//check if financial type is selected
if (!$values['financial_type_id']) {
$errors['financial_type_id'] = ts("Please select financial type.");
}
//check for the event fee label (mandatory)
if (!$values['fee_label']) {
$errors['fee_label'] = ts('Please enter the fee label for the paid event.');
}
if (empty($values['price_set_id'])) {
//check fee label and amount
$check = 0;
$optionKeys = array();
foreach ($values['label'] as $key => $val) {
if (trim($val) && trim($values['value'][$key])) {
$optionKeys[$key] = $key;
$check++;
}
}
$default = CRM_Utils_Array::value('default', $values);
if ($default && !in_array($default, $optionKeys)) {
$errors['default'] = ts('Please select an appropriate option as default.');
}
if (!$check) {
if (!$values['label'][1]) {
$errors['label[1]'] = ts('Please enter a label for at least one fee level.');
}
if (!$values['value'][1]) {
$errors['value[1]'] = ts('Please enter an amount for at least one fee level.');
}
}
}
if (isset($values['is_pay_later'])) {
if (empty($values['pay_later_text'])) {
$errors['pay_later_text'] = ts('Please enter the Pay Later prompt to be displayed on the Registration form.');
}
if (empty($values['pay_later_receipt'])) {
$errors['pay_later_receipt'] = ts('Please enter the Pay Later instructions to be displayed to your users.');
}
}
}
return empty($errors) ? TRUE : $errors;
}
public function buildAmountLabel() {
$default = array();
for ($i = 1; $i <= self::NUM_OPTION; $i++) {
// label
$this->add('text', "discounted_label[$i]", ts('Label'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'label'));
// value
for ($j = 1; $j <= self::NUM_DISCOUNT; $j++) {
$this->add('text', "discounted_value[$i][$j]", ts('Value'), array('size' => 10));
$this->addRule("discounted_value[$i][$j]", ts('Please enter a valid money value for this field (e.g. %1).', array(1 => CRM_Utils_Money::format('99.99', ' '))), 'money');
}
// default
$default[] = $this->createElement('radio', NULL, NULL, NULL, $i);
}
$this->addGroup($default, 'discounted_default');
}
/**
* Process the form.
*/
public function postProcess() {
$eventTitle = '';
$params = $this->exportValues();
$this->set('discountSection', 0);
if (!empty($_POST['_qf_Fee_submit'])) {
$this->buildAmountLabel();
$this->set('discountSection', 2);
return;
}
if (!empty($params['payment_processor'])) {
$params['payment_processor'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($params['payment_processor']));
}
else {
$params['payment_processor'] = 'null';
}
$params['is_pay_later'] = CRM_Utils_Array::value('is_pay_later', $params, 0);
$params['is_billing_required'] = CRM_Utils_Array::value('is_billing_required', $params, 0);
if ($this->_id) {
// delete all the prior label values or discounts in the custom options table
// and delete a price set if one exists
//@todo note that this removes the reference from existing participants -
// even where there is not change - redress?
// note that a more tentative form of this is invoked by passing price_set_id as an array
// to event.create see CRM-14069
// @todo get all of this logic out of form layer (currently partially in BAO/api layer)
if (CRM_Price_BAO_PriceSet::removeFrom('civicrm_event', $this->_id)) {
CRM_Core_BAO_Discount::del($this->_id, 'civicrm_event');
}
}
if ($params['is_monetary']) {
if (!empty($params['price_set_id'])) {
//@todo this is now being done in the event BAO if passed price_set_id as an array
// per notes on that fn - looking at the api converting to an array
// so calling via the api may cause this to be done in the api
CRM_Price_BAO_PriceSet::addTo('civicrm_event', $this->_id, $params['price_set_id']);
if (!empty($params['price_field_id'])) {
$priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
}
}
else {
// if there are label / values, create custom options for them
$labels = CRM_Utils_Array::value('label', $params);
$values = CRM_Utils_Array::value('value', $params);
$default = CRM_Utils_Array::value('default', $params);
$options = array();
if (!CRM_Utils_System::isNull($labels) && !CRM_Utils_System::isNull($values)) {
for ($i = 1; $i < self::NUM_OPTION; $i++) {
if (!empty($labels[$i]) && !CRM_Utils_System::isNull($values[$i])) {
$options[] = array(
'label' => trim($labels[$i]),
'value' => CRM_Utils_Rule::cleanMoney(trim($values[$i])),
'weight' => $i,
'is_active' => 1,
'is_default' => $default == $i,
);
}
}
if (!empty($options)) {
$params['default_fee_id'] = NULL;
if (empty($params['price_set_id'])) {
if (empty($params['price_field_id'])) {
$setParams['title'] = $eventTitle = ($this->_isTemplate) ? $this->_defaultValues['template_title'] : $this->_defaultValues['title'];
$eventTitle = strtolower(CRM_Utils_String::munge($eventTitle, '_', 245));
if (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceSet', $eventTitle, 'id', 'name')) {
$setParams['name'] = $eventTitle;
}
elseif (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceSet', $eventTitle . '_' . $this->_id, 'id', 'name')) {
$setParams['name'] = $eventTitle . '_' . $this->_id;
}
else {
$timeSec = explode('.', microtime(TRUE));
$setParams['name'] = $eventTitle . '_' . date('is', $timeSec[0]) . $timeSec[1];
}
$setParams['is_quick_config'] = 1;
$setParams['financial_type_id'] = $params['financial_type_id'];
$setParams['extends'] = CRM_Core_Component::getComponentID('CiviEvent');
$priceSet = CRM_Price_BAO_PriceSet::create($setParams);
$fieldParams['name'] = strtolower(CRM_Utils_String::munge($params['fee_label'], '_', 245));
$fieldParams['price_set_id'] = $priceSet->id;
}
else {
foreach ($params['price_field_value'] as $arrayID => $fieldValueID) {
if (empty($params['label'][$arrayID]) && empty($params['value'][$arrayID]) && !empty($fieldValueID)) {
CRM_Price_BAO_PriceFieldValue::setIsActive($fieldValueID, '0');
unset($params['price_field_value'][$arrayID]);
}
}
$fieldParams['id'] = CRM_Utils_Array::value('price_field_id', $params);
$fieldParams['option_id'] = $params['price_field_value'];
$priceSet = new CRM_Price_BAO_PriceSet();
$priceSet->id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('price_field_id', $params), 'price_set_id');
if ($this->_defaultValues['financial_type_id'] != $params['financial_type_id']) {
CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceSet', $priceSet->id, 'financial_type_id', $params['financial_type_id']);
}
}
$fieldParams['label'] = $params['fee_label'];
$fieldParams['html_type'] = 'Radio';
CRM_Price_BAO_PriceSet::addTo('civicrm_event', $this->_id, $priceSet->id);
$fieldParams['option_label'] = $params['label'];
$fieldParams['option_amount'] = $params['value'];
$fieldParams['financial_type_id'] = $params['financial_type_id'];
foreach ($options as $value) {
$fieldParams['option_weight'][$value['weight']] = $value['weight'];
}
$fieldParams['default_option'] = $params['default'];
$priceField = CRM_Price_BAO_PriceField::create($fieldParams);
}
}
}
$discountPriceSets = !empty($this->_defaultValues['discount_price_set']) ? $this->_defaultValues['discount_price_set'] : array();
$discountFieldIDs = !empty($this->_defaultValues['discount_option_id']) ? $this->_defaultValues['discount_option_id'] : array();
if (CRM_Utils_Array::value('is_discount', $params) == 1) {
// if there are discounted set of label / values,
// create custom options for them
$labels = CRM_Utils_Array::value('discounted_label', $params);
$values = CRM_Utils_Array::value('discounted_value', $params);
$default = CRM_Utils_Array::value('discounted_default', $params);
if (!CRM_Utils_System::isNull($labels) && !CRM_Utils_System::isNull($values)) {
for ($j = 1; $j <= self::NUM_DISCOUNT; $j++) {
$discountOptions = array();
for ($i = 1; $i < self::NUM_OPTION; $i++) {
if (!empty($labels[$i]) &&
!CRM_Utils_System::isNull(CRM_Utils_Array::value($j, $values[$i]))
) {
$discountOptions[] = array(
'label' => trim($labels[$i]),
'value' => CRM_Utils_Rule::cleanMoney(trim($values[$i][$j])),
'weight' => $i,
'is_active' => 1,
'is_default' => $default == $i,
);
}
}
if (!empty($discountOptions)) {
$fieldParams = array();
$params['default_discount_fee_id'] = NULL;
$keyCheck = $j - 1;
$setParams = array();
if (empty($discountPriceSets[$keyCheck])) {
if (!$eventTitle) {
$eventTitle = strtolower(CRM_Utils_String::munge($this->_defaultValues['title'], '_', 200));
}
$setParams['title'] = $params['discount_name'][$j];
if (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceSet', $eventTitle . '_' . $params['discount_name'][$j], 'id', 'name')) {
$setParams['name'] = $eventTitle . '_' . $params['discount_name'][$j];
}
elseif (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceSet', $eventTitle . '_' . $params['discount_name'][$j] . '_' . $this->_id, 'id', 'name')) {
$setParams['name'] = $eventTitle . '_' . $params['discount_name'][$j] . '_' . $this->_id;
}
else {
$timeSec = explode('.', microtime(TRUE));
$setParams['name'] = $eventTitle . '_' . $params['discount_name'][$j] . '_' . date('is', $timeSec[0]) . $timeSec[1];
}
$setParams['is_quick_config'] = 1;
$setParams['financial_type_id'] = $params['financial_type_id'];
$setParams['extends'] = CRM_Core_Component::getComponentID('CiviEvent');
$priceSet = CRM_Price_BAO_PriceSet::create($setParams);
$priceSetID = $priceSet->id;
}
else {
$priceSetID = $discountPriceSets[$j - 1];
$setParams = array(
'title' => $params['discount_name'][$j],
'id' => $priceSetID,
);
if ($this->_defaultValues['financial_type_id'] != $params['financial_type_id']) {
$setParams['financial_type_id'] = $params['financial_type_id'];
}
CRM_Price_BAO_PriceSet::create($setParams);
unset($discountPriceSets[$j - 1]);
$fieldParams['id'] = CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceField', $priceSetID, 'id', 'price_set_id');
}
$fieldParams['name'] = $fieldParams['label'] = $params['fee_label'];
$fieldParams['is_required'] = 1;
$fieldParams['price_set_id'] = $priceSetID;
$fieldParams['html_type'] = 'Radio';
$fieldParams['financial_type_id'] = $params['financial_type_id'];
foreach ($discountOptions as $value) {
$fieldParams['option_label'][$value['weight']] = $value['label'];
$fieldParams['option_amount'][$value['weight']] = $value['value'];
$fieldParams['option_weight'][$value['weight']] = $value['weight'];
if (!empty($value['is_default'])) {
$fieldParams['default_option'] = $value['weight'];
}
if (!empty($discountFieldIDs[$j]) && !empty($discountFieldIDs[$j][$value['weight']])) {
$fieldParams['option_id'][$value['weight']] = $discountFieldIDs[$j][$value['weight']];
unset($discountFieldIDs[$j][$value['weight']]);
}
}
//create discount priceset
$priceField = CRM_Price_BAO_PriceField::create($fieldParams);
if (!empty($discountFieldIDs[$j])) {
foreach ($discountFieldIDs[$j] as $fID) {
CRM_Price_BAO_PriceFieldValue::setIsActive($fID, '0');
}
}
$discountParams = array(
'entity_table' => 'civicrm_event',
'entity_id' => $this->_id,
'price_set_id' => $priceSetID,
'start_date' => CRM_Utils_Date::processDate($params['discount_start_date'][$j]),
'end_date' => CRM_Utils_Date::processDate($params['discount_end_date'][$j]),
);
CRM_Core_BAO_Discount::add($discountParams);
}
}
}
}
if (!empty($discountPriceSets)) {
foreach ($discountPriceSets as $setId) {
CRM_Price_BAO_PriceSet::setIsQuickConfig($setId, 0);
}
}
}
}
else {
if (!empty($params['price_field_id'])) {
$priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
}
$params['financial_type_id'] = '';
$params['is_pay_later'] = 0;
$params['is_billing_required'] = 0;
}
//update 'is_billing_required'
if (empty($params['is_pay_later'])) {
$params['is_billing_required'] = FALSE;
}
//update events table
$params['id'] = $this->_id;
// skip update of financial type in price set
$params['skipFinancialType'] = TRUE;
CRM_Event_BAO_Event::add($params);
// Update tab "disabled" css class
$this->ajaxResponse['tabValid'] = !empty($params['is_monetary']);
parent::endPostProcess();
}
/**
* Return a descriptive name for the page, used in wizard header
*
* @return string
*/
public function getTitle() {
return ts('Event Fees');
}
}

View file

@ -0,0 +1,284 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class generates form components for processing Event Location
* civicrm_event_page.
*/
class CRM_Event_Form_ManageEvent_Location extends CRM_Event_Form_ManageEvent {
/**
* How many locationBlocks should we display?
*
* @var int
* @const
*/
const LOCATION_BLOCKS = 1;
/**
* The variable, for storing the location array
*
* @var array
*/
protected $_locationIds = array();
/**
* The variable, for storing location block id with event
*
* @var int
*/
protected $_oldLocBlockId = 0;
/**
* Get the db values for this form.
*/
public $_values = array();
/**
* Set variables up before form is built.
*/
public function preProcess() {
parent::preProcess();
$this->_values = $this->get('values');
if ($this->_id && empty($this->_values)) {
//get location values.
$params = array(
'entity_id' => $this->_id,
'entity_table' => 'civicrm_event',
);
$this->_values = CRM_Core_BAO_Location::getValues($params);
//get event values.
$params = array('id' => $this->_id);
CRM_Event_BAO_Event::retrieve($params, $this->_values);
$this->set('values', $this->_values);
}
//location blocks.
CRM_Contact_Form_Location::preProcess($this);
}
/**
* Set default values for the form.
*
* Note that in edit/view mode the default values are retrieved from the database.
*/
public function setDefaultValues() {
$defaults = $this->_values;
if (!empty($defaults['loc_block_id'])) {
$defaults['loc_event_id'] = $defaults['loc_block_id'];
$countLocUsed = CRM_Event_BAO_Event::countEventsUsingLocBlockId($defaults['loc_block_id']);
$this->assign('locUsed', $countLocUsed);
}
$config = CRM_Core_Config::singleton();
if (!isset($defaults['address'][1]['country_id'])) {
$defaults['address'][1]['country_id'] = $config->defaultContactCountry;
}
if (!isset($defaults['address'][1]['state_province_id'])) {
$defaults['address'][1]['state_province_id'] = $config->defaultContactStateProvince;
}
$defaults['location_option'] = $this->_oldLocBlockId ? 2 : 1;
return $defaults;
}
/**
* Add local and global form rules.
*/
public function addRules() {
$this->addFormRule(array('CRM_Event_Form_ManageEvent_Location', 'formRule'));
}
/**
* Global validation rules for the form.
*
* @param array $fields
* Posted values of the form.
*
* @return array
* list of errors to be posted back to the form
*/
public static function formRule($fields) {
// check for state/country mapping
$errors = CRM_Contact_Form_Edit_Address::formRule($fields);
return empty($errors) ? TRUE : $errors;
}
/**
* Function to build location block.
*/
public function buildQuickForm() {
//load form for child blocks
if ($this->_addBlockName) {
$className = "CRM_Contact_Form_Edit_{$this->_addBlockName}";
return $className::buildQuickForm($this);
}
$this->applyFilter('__ALL__', 'trim');
//build location blocks.
CRM_Contact_Form_Location::buildQuickForm($this);
//fix for CRM-1971
$this->assign('action', $this->_action);
if ($this->_id) {
$this->_oldLocBlockId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event',
$this->_id, 'loc_block_id'
);
}
// get the list of location blocks being used by other events
$locationEvents = CRM_Event_BAO_Event::getLocationEvents();
// remove duplicates and make sure that the duplicate entry with key as
// loc_block_id of this event (this->_id) is preserved
if (!empty($locationEvents[$this->_oldLocBlockId])) {
$possibleDuplicate = $locationEvents[$this->_oldLocBlockId];
$locationEvents = array_flip(array_unique($locationEvents));
if (!empty($locationEvents[$possibleDuplicate])) {
$locationEvents[$possibleDuplicate] = $this->_oldLocBlockId;
}
$locationEvents = array_flip($locationEvents);
}
else {
$locationEvents = array_unique($locationEvents);
}
$events = array();
if (!empty($locationEvents)) {
$this->assign('locEvents', TRUE);
$optionTypes = array(
'1' => ts('Create new location'),
'2' => ts('Use existing location'),
);
$this->addRadio('location_option', ts("Choose Location"), $optionTypes);
if (!isset($locationEvents[$this->_oldLocBlockId]) || (!$this->_oldLocBlockId)) {
$locationEvents = array('' => ts('- select -')) + $locationEvents;
}
$this->add('select', 'loc_event_id', ts('Use Location'), $locationEvents, FALSE, array('class' => 'crm-select2'));
}
$this->addElement('advcheckbox', 'is_show_location', ts('Show Location?'));
parent::buildQuickForm();
}
/**
* Process the form submission.
*/
public function postProcess() {
$params = $this->exportValues();
$deleteOldBlock = FALSE;
// if 'use existing location' option is selected -
if (CRM_Utils_Array::value('location_option', $params) == 2 && !empty($params['loc_event_id']) &&
($params['loc_event_id'] != $this->_oldLocBlockId)
) {
// if new selected loc is different from old loc, update the loc_block_id
// so that loc update would affect the selected loc and not the old one.
$deleteOldBlock = TRUE;
CRM_Core_DAO::setFieldValue('CRM_Event_DAO_Event', $this->_id,
'loc_block_id', $params['loc_event_id']
);
}
// if 'create new loc' option is selected, set the loc_block_id for this event to null
// so that an update would result in creating a new loc.
if ($this->_oldLocBlockId && (CRM_Utils_Array::value('location_option', $params) == 1)) {
$deleteOldBlock = TRUE;
CRM_Core_DAO::setFieldValue('CRM_Event_DAO_Event', $this->_id,
'loc_block_id', 'null'
);
}
// if 'create new loc' optioin is selected OR selected new loc is different
// from old one, go ahead and delete the old loc provided thats not being
// used by any other event
if ($this->_oldLocBlockId && $deleteOldBlock) {
CRM_Event_BAO_Event::deleteEventLocBlock($this->_oldLocBlockId, $this->_id);
}
// get ready with location block params
$params['entity_table'] = 'civicrm_event';
$params['entity_id'] = $this->_id;
$defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
foreach (array(
'address',
'phone',
'email',
) as $block) {
if (empty($params[$block]) || !is_array($params[$block])) {
continue;
}
foreach ($params[$block] as $count => & $values) {
if ($count == 1) {
$values['is_primary'] = 1;
}
$values['location_type_id'] = ($defaultLocationType->id) ? $defaultLocationType->id : 1;
}
}
// create/update event location
$location = CRM_Core_BAO_Location::create($params, TRUE, 'event');
$params['loc_block_id'] = $location['id'];
// finally update event params
$params['id'] = $this->_id;
CRM_Event_BAO_Event::add($params);
// Update tab "disabled" css class
$this->ajaxResponse['tabValid'] = TRUE;
parent::endPostProcess();
}
/**
* Return a descriptive name for the page, used in wizard header
*
* @return string
*/
public function getTitle() {
return ts('Event Location');
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,219 @@
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of Repeat
*
* @author Priyanka
*/
class CRM_Event_Form_ManageEvent_Repeat extends CRM_Event_Form_ManageEvent {
/**
* Parent Event Start Date.
*/
protected $_parentEventStartDate = NULL;
/**
* Parent Event End Date.
*/
protected $_parentEventEndDate = NULL;
public function preProcess() {
parent::preProcess();
$this->assign('currentEventId', $this->_id);
$checkParentExistsForThisId = CRM_Core_BAO_RecurringEntity::getParentFor($this->_id, 'civicrm_event');
//If this ID has parent, send parent id
if ($checkParentExistsForThisId) {
/**
* Get connected event information list
*/
//Get all connected event ids
$allEventIdsArray = CRM_Core_BAO_RecurringEntity::getEntitiesForParent($checkParentExistsForThisId, 'civicrm_event');
$allEventIds = array();
if (!empty($allEventIdsArray)) {
foreach ($allEventIdsArray as $key => $val) {
$allEventIds[] = $val['id'];
}
if (!empty($allEventIds)) {
$params = array();
$query = "
SELECT *
FROM civicrm_event
WHERE id IN (" . implode(",", $allEventIds) . ")
ORDER BY start_date asc
";
$dao = CRM_Core_DAO::executeQuery($query, $params, TRUE, 'CRM_Event_DAO_Event');
$permissions = CRM_Event_BAO_Event::checkPermission();
while ($dao->fetch()) {
if (in_array($dao->id, $permissions[CRM_Core_Permission::VIEW])) {
$manageEvent[$dao->id] = array();
CRM_Core_DAO::storeValues($dao, $manageEvent[$dao->id]);
}
}
}
$this->assign('rows', $manageEvent);
}
}
$parentEventParams = array('id' => $this->_id);
$parentEventValues = array();
$parentEventReturnProperties = array('start_date', 'end_date');
$parentEventAttributes = CRM_Core_DAO::commonRetrieve('CRM_Event_DAO_Event', $parentEventParams, $parentEventValues, $parentEventReturnProperties);
$this->_parentEventStartDate = $parentEventAttributes->start_date;
$this->_parentEventEndDate = $parentEventAttributes->end_date;
}
/**
* Set default values for the form. For edit/view mode
* the default values are retrieved from the database
*
*
* @return array
*/
public function setDefaultValues() {
$defaults = array();
//Always pass current event's start date by default
$currentEventStartDate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_id, 'start_date', 'id');
list($defaults['repetition_start_date'], $defaults['repetition_start_date_time']) = CRM_Utils_Date::setDateDefaults($currentEventStartDate, 'activityDateTime');
$recurringEntityDefaults = CRM_Core_Form_RecurringEntity::setDefaultValues();
return array_merge($defaults, $recurringEntityDefaults);
}
public function buildQuickForm() {
CRM_Core_Form_RecurringEntity::buildQuickForm($this);
}
public function postProcess() {
if ($this->_id) {
$params = $this->controller->exportValues($this->_name);
if ($this->_parentEventStartDate && $this->_parentEventEndDate) {
$interval = CRM_Core_BAO_RecurringEntity::getInterval($this->_parentEventStartDate, $this->_parentEventEndDate);
$params['intervalDateColumns'] = array('end_date' => $interval);
}
$params['dateColumns'] = array('start_date');
$params['excludeDateRangeColumns'] = array('start_date', 'end_date');
$params['entity_table'] = 'civicrm_event';
$params['entity_id'] = $this->_id;
// CRM-16568 - check if parent exist for the event.
$parentId = CRM_Core_BAO_RecurringEntity::getParentFor($this->_id, 'civicrm_event');
$params['parent_entity_id'] = !empty($parentId) ? $parentId : $params['entity_id'];
//Unset event id
unset($params['id']);
$url = 'civicrm/event/manage/repeat';
$urlParams = "action=update&reset=1&id={$this->_id}";
$linkedEntities = array(
array(
'table' => 'civicrm_price_set_entity',
'findCriteria' => array(
'entity_id' => $this->_id,
'entity_table' => 'civicrm_event',
),
'linkedColumns' => array('entity_id'),
'isRecurringEntityRecord' => FALSE,
),
array(
'table' => 'civicrm_uf_join',
'findCriteria' => array(
'entity_id' => $this->_id,
'entity_table' => 'civicrm_event',
),
'linkedColumns' => array('entity_id'),
'isRecurringEntityRecord' => FALSE,
),
array(
'table' => 'civicrm_tell_friend',
'findCriteria' => array(
'entity_id' => $this->_id,
'entity_table' => 'civicrm_event',
),
'linkedColumns' => array('entity_id'),
'isRecurringEntityRecord' => TRUE,
),
array(
'table' => 'civicrm_pcp_block',
'findCriteria' => array(
'entity_id' => $this->_id,
'entity_table' => 'civicrm_event',
),
'linkedColumns' => array('entity_id'),
'isRecurringEntityRecord' => TRUE,
),
);
CRM_Core_Form_RecurringEntity::postProcess($params, 'civicrm_event', $linkedEntities);
CRM_Utils_System::redirect(CRM_Utils_System::url($url, $urlParams));
}
else {
CRM_Core_Error::fatal("Could not find Event ID");
}
parent::endPostProcess();
}
/**
* This function gets the number of participant count for the list of related event ids.
*
* @param array $listOfRelatedEntities
* List of related event ids .
*
*
* @return array
*/
static public function getParticipantCountforEvent($listOfRelatedEntities = array()) {
$participantDetails = array();
if (!empty($listOfRelatedEntities)) {
$implodeRelatedEntities = implode(',', array_map(function ($entity) {
return $entity['id'];
}, $listOfRelatedEntities));
if ($implodeRelatedEntities) {
$query = "SELECT p.event_id as event_id,
concat_ws(' ', e.title, concat_ws(' - ', DATE_FORMAT(e.start_date, '%b %d %Y %h:%i %p'), DATE_FORMAT(e.end_date, '%b %d %Y %h:%i %p'))) as event_data,
count(p.id) as participant_count
FROM civicrm_participant p, civicrm_event e
WHERE p.event_id = e.id AND p.event_id IN ({$implodeRelatedEntities})
GROUP BY p.event_id";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$participantDetails['countByID'][$dao->event_id] = $dao->participant_count;
$participantDetails['countByName'][$dao->event_id][$dao->event_data] = $dao->participant_count;
}
}
}
return $participantDetails;
}
/**
* This function checks if there was any registraion for related event ids,
* and returns array of ids with no regsitrations
*
* @param string or int or object... $eventID
*
* @return array
*/
public static function checkRegistrationForEvents($eventID) {
$eventIdsWithNoRegistration = array();
if ($eventID) {
$getRelatedEntities = CRM_Core_BAO_RecurringEntity::getEntitiesFor($eventID, 'civicrm_event', TRUE);
$participantDetails = CRM_Event_Form_ManageEvent_Repeat::getParticipantCountforEvent($getRelatedEntities);
//Check if participants exists for events
foreach ($getRelatedEntities as $key => $value) {
if (!CRM_Utils_Array::value($value['id'], $participantDetails['countByID']) && $value['id'] != $eventID) {
//CRM_Event_BAO_Event::del($value['id']);
$eventIdsWithNoRegistration[] = $value['id'];
}
}
}
CRM_Core_BAO_RecurringEntity::$_entitiesToBeDeleted = $eventIdsWithNoRegistration;
return CRM_Core_BAO_RecurringEntity::$_entitiesToBeDeleted;
}
}

View file

@ -0,0 +1,99 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class generates form components for scheduling reminders for Event
*
*/
class CRM_Event_Form_ManageEvent_ScheduleReminders extends CRM_Event_Form_ManageEvent {
/**
* Set variables up before form is built.
*
* @return void
*/
public function preProcess() {
parent::preProcess();
$setTab = CRM_Utils_Request::retrieve('setTab', 'Int', $this, FALSE, 0);
$mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array(
'id' => ($this->_isTemplate ? CRM_Event_ActionMapping::EVENT_TPL_MAPPING_ID : CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID),
)));
$reminderList = CRM_Core_BAO_ActionSchedule::getList(FALSE, $mapping, $this->_id);
if ($reminderList && is_array($reminderList)) {
// Add action links to each of the reminders
foreach ($reminderList as & $format) {
$action = CRM_Core_Action::UPDATE + CRM_Core_Action::DELETE;
if ($format['is_active']) {
$action += CRM_Core_Action::DISABLE;
}
else {
$action += CRM_Core_Action::ENABLE;
}
$scheduleReminder = new CRM_Admin_Page_ScheduleReminders();
$links = $scheduleReminder->links();
$links[CRM_Core_Action::DELETE]['qs'] .= "&context=event&compId={$this->_id}";
$links[CRM_Core_Action::UPDATE]['qs'] .= "&context=event&compId={$this->_id}";
$format['action'] = CRM_Core_Action::formLink(
$links,
$action,
array('id' => $format['id']),
ts('more'),
FALSE,
'actionSchedule.manage.action',
'ActionSchedule',
$this->_id
);
}
}
$this->assign('rows', $reminderList);
$this->assign('setTab', $setTab);
$this->assign('component', 'event');
// Update tab "disabled" css class
$this->ajaxResponse['tabValid'] = is_array($reminderList) && (count($reminderList) > 0);
$this->setPageTitle(ts('Scheduled Reminder'));
}
/**
* @return string
*/
public function getTemplateFileName() {
return 'CRM/Admin/Page/ScheduleReminders.tpl';
}
}

View file

@ -0,0 +1,249 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* Helper class to build navigation links
*/
class CRM_Event_Form_ManageEvent_TabHeader {
/**
* @param CRM_Event_Form_ManageEvent $form
*
* @return array
*/
public static function build(&$form) {
$tabs = $form->get('tabHeader');
if (!$tabs || empty($_GET['reset'])) {
$tabs = self::process($form);
$form->set('tabHeader', $tabs);
}
$form->assign_by_ref('tabHeader', $tabs);
CRM_Core_Resources::singleton()
->addScriptFile('civicrm', 'templates/CRM/common/TabHeader.js', 1, 'html-header')
->addSetting(array(
'tabSettings' => array(
'active' => self::getCurrentTab($tabs),
),
));
CRM_Event_Form_ManageEvent::addProfileEditScripts();
return $tabs;
}
/**
* @param CRM_Event_Form_ManageEvent $form
*
* @return array
* @throws Exception
*/
public static function process(&$form) {
if ($form->getVar('_id') <= 0) {
return NULL;
}
$default = array(
'link' => NULL,
'valid' => TRUE,
'active' => TRUE,
'current' => FALSE,
'class' => 'ajaxForm',
);
$tabs = array();
$tabs['settings'] = array('title' => ts('Info and Settings'), 'class' => 'ajaxForm livePage') + $default;
$tabs['location'] = array('title' => ts('Event Location')) + $default;
$tabs['fee'] = array('title' => ts('Fees')) + $default;
$tabs['registration'] = array('title' => ts('Online Registration')) + $default;
if (CRM_Core_Permission::check('administer CiviCRM') || CRM_Event_BAO_Event::checkPermission(NULL, CRM_Core_Permission::EDIT)) {
$tabs['reminder'] = array('title' => ts('Schedule Reminders'), 'class' => 'livePage') + $default;
}
$tabs['conference'] = array('title' => ts('Conference Slots')) + $default;
$tabs['friend'] = array('title' => ts('Tell a Friend')) + $default;
$tabs['pcp'] = array('title' => ts('Personal Campaigns')) + $default;
$tabs['repeat'] = array('title' => ts('Repeat')) + $default;
// Repeat tab must refresh page when switching repeat mode so js & vars will get set-up
if (!$form->_isRepeatingEvent) {
unset($tabs['repeat']['class']);
}
// check if we're in shopping cart mode for events
$enableCart = Civi::settings()->get('enable_cart');
if (!$enableCart) {
unset($tabs['conference']);
}
$eventID = $form->getVar('_id');
if ($eventID) {
// disable tabs based on their configuration status
$eventNameMapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array(
'id' => CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID,
)));
$sql = "
SELECT e.loc_block_id as is_location, e.is_online_registration, e.is_monetary, taf.is_active, pcp.is_active as is_pcp, sch.id as is_reminder, re.id as is_repeating_event
FROM civicrm_event e
LEFT JOIN civicrm_tell_friend taf ON ( taf.entity_table = 'civicrm_event' AND taf.entity_id = e.id )
LEFT JOIN civicrm_pcp_block pcp ON ( pcp.entity_table = 'civicrm_event' AND pcp.entity_id = e.id )
LEFT JOIN civicrm_action_schedule sch ON ( sch.mapping_id = %2 AND sch.entity_value = %1 )
LEFT JOIN civicrm_recurring_entity re ON ( e.id = re.entity_id AND re.entity_table = 'civicrm_event' )
WHERE e.id = %1
";
//Check if repeat is configured
$eventHasParent = CRM_Core_BAO_RecurringEntity::getParentFor($eventID, 'civicrm_event');
$params = array(
1 => array($eventID, 'Integer'),
2 => array($eventNameMapping->getId(), 'Integer'),
);
$dao = CRM_Core_DAO::executeQuery($sql, $params);
if (!$dao->fetch()) {
CRM_Core_Error::fatal();
}
if (!$dao->is_location) {
$tabs['location']['valid'] = FALSE;
}
if (!$dao->is_online_registration) {
$tabs['registration']['valid'] = FALSE;
}
if (!$dao->is_monetary) {
$tabs['fee']['valid'] = FALSE;
}
if (!$dao->is_active) {
$tabs['friend']['valid'] = FALSE;
}
if (!$dao->is_pcp) {
$tabs['pcp']['valid'] = FALSE;
}
if (!$dao->is_reminder) {
$tabs['reminder']['valid'] = FALSE;
}
if (!$dao->is_repeating_event) {
$tabs['repeat']['valid'] = FALSE;
}
}
// see if any other modules want to add any tabs
// note: status of 'valid' flag of any injected tab, needs to be taken care in the hook implementation.
CRM_Utils_Hook::tabset('civicrm/event/manage', $tabs,
array('event_id' => $eventID));
$fullName = $form->getVar('_name');
$className = CRM_Utils_String::getClassName($fullName);
$new = '';
// hack for special cases.
switch ($className) {
case 'Event':
$attributes = $form->getVar('_attributes');
$class = strtolower(basename(CRM_Utils_Array::value('action', $attributes)));
break;
case 'EventInfo':
$class = 'settings';
break;
case 'ScheduleReminders':
$class = 'reminder';
break;
default:
$class = strtolower($className);
break;
}
if (array_key_exists($class, $tabs)) {
$tabs[$class]['current'] = TRUE;
$qfKey = $form->get('qfKey');
if ($qfKey) {
$tabs[$class]['qfKey'] = "&qfKey={$qfKey}";
}
}
if ($eventID) {
$reset = !empty($_GET['reset']) ? 'reset=1&' : '';
foreach ($tabs as $key => $value) {
if (!isset($tabs[$key]['qfKey'])) {
$tabs[$key]['qfKey'] = NULL;
}
$action = 'update';
if ($key == 'reminder') {
$action = 'browse';
}
$link = "civicrm/event/manage/{$key}";
$query = "{$reset}action={$action}&id={$eventID}&component=event{$tabs[$key]['qfKey']}";
$tabs[$key]['link'] = (isset($value['link']) ? $value['link'] :
CRM_Utils_System::url($link, $query));
}
}
return $tabs;
}
/**
* @param CRM_Event_Form_ManageEvent $form
*/
public static function reset(&$form) {
$tabs = self::process($form);
$form->set('tabHeader', $tabs);
}
/**
* @param $tabs
*
* @return int|string
*/
public static function getCurrentTab($tabs) {
static $current = FALSE;
if ($current) {
return $current;
}
if (is_array($tabs)) {
foreach ($tabs as $subPage => $pageVal) {
if ($pageVal['current'] === TRUE) {
$current = $subPage;
break;
}
}
}
$current = $current ? $current : 'settings';
return $current;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,391 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be usefusul, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This form used for changing / updating fee selections for the events
* event/contribution is partially paid
*
*/
class CRM_Event_Form_ParticipantFeeSelection extends CRM_Core_Form {
public $useLivePageJS = TRUE;
protected $_contactId = NULL;
protected $_contributorDisplayName = NULL;
protected $_contributorEmail = NULL;
protected $_toDoNotEmail = NULL;
protected $_contributionId = NULL;
protected $fromEmailId = NULL;
public $_eventId = NULL;
public $_action = NULL;
public $_values = NULL;
public $_participantId = NULL;
protected $_participantStatus = NULL;
protected $_paidAmount = NULL;
public $_isPaidEvent = NULL;
protected $contributionAmt = NULL;
public function preProcess() {
$this->_participantId = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
$this->_contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
$this->_eventId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_participantId, 'event_id');
$this->_fromEmails = CRM_Event_BAO_Event::getFromEmailIds($this->_eventId);
$this->_contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_participantId, 'contribution_id', 'participant_id');
if (!$this->_contributionId) {
if ($primaryParticipantId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $this->_participantId, 'registered_by_id')) {
$this->_contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
}
}
if ($this->_contributionId) {
$this->_isPaidEvent = TRUE;
}
$this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, TRUE);
list($this->_contributorDisplayName, $this->_contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactId);
$this->assign('displayName', $this->_contributorDisplayName);
$this->assign('email', $this->_contributorEmail);
$this->_participantStatus = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $this->_participantId, 'status_id');
//set the payment mode - _mode property is defined in parent class
$this->_mode = CRM_Utils_Request::retrieve('mode', 'String', $this);
$this->assign('contactId', $this->_contactId);
$this->assign('id', $this->_participantId);
$paymentInfo = CRM_Contribute_BAO_Contribution::getPaymentInfo($this->_participantId, 'event');
$this->_paidAmount = $paymentInfo['paid'];
$this->assign('paymentInfo', $paymentInfo);
$this->assign('feePaid', $this->_paidAmount);
$ids = CRM_Event_BAO_Participant::getParticipantIds($this->_contributionId);
if (count($ids) > 1) {
$total = CRM_Price_BAO_LineItem::getLineTotal($this->_contributionId);
$this->assign('totalLineTotal', $total);
$this->assign('lineItemTotal', $total);
}
$title = ts("Change selections for %1", array(1 => $this->_contributorDisplayName));
if ($title) {
CRM_Utils_System::setTitle($title);
}
}
/**
* Set default values for the form.
*
* @return array
*/
public function setDefaultValues() {
$params = array('id' => $this->_participantId);
CRM_Event_BAO_Participant::getValues($params, $defaults, $ids);
$priceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $this->_eventId);
$priceSetValues = CRM_Event_Form_EventFees::setDefaultPriceSet($this->_participantId, $this->_eventId, FALSE);
$priceFieldId = (array_keys($this->_values['fee']));
if (!empty($priceSetValues)) {
$defaults[$this->_participantId] = array_merge($defaults[$this->_participantId], $priceSetValues);
}
else {
foreach ($priceFieldId as $key => $value) {
if (!empty($value) && ($this->_values['fee'][$value]['html_type'] == 'Radio' || $this->_values['fee'][$value]['html_type'] == 'Select') && !$this->_values['fee'][$value]['is_required']) {
$fee_keys = array_keys($this->_values['fee']);
$defaults[$this->_participantId]['price_' . $fee_keys[$key]] = 0;
}
}
}
$this->assign('totalAmount', CRM_Utils_Array::value('fee_amount', $defaults[$this->_participantId]));
if ($this->_action == CRM_Core_Action::UPDATE) {
$fee_level = $defaults[$this->_participantId]['fee_level'];
CRM_Event_BAO_Participant::fixEventLevel($fee_level);
$this->assign('fee_level', $fee_level);
$this->assign('fee_amount', CRM_Utils_Array::value('fee_amount', $defaults[$this->_participantId]));
}
$defaults = $defaults[$this->_participantId];
return $defaults;
}
public function buildQuickForm() {
$statuses = CRM_Event_PseudoConstant::participantStatus();
$this->assign('partiallyPaid', array_search('Partially paid', $statuses));
$this->assign('pendingRefund', array_search('Pending refund', $statuses));
$this->assign('participantStatus', $this->_participantStatus);
$config = CRM_Core_Config::singleton();
$this->assign('currencySymbol', $config->defaultCurrencySymbol);
// line items block
$lineItem = $event = array();
$params = array('id' => $this->_eventId);
CRM_Event_BAO_Event::retrieve($params, $event);
//retrieve custom information
$this->_values = array();
CRM_Event_Form_Registration::initEventFee($this, $event['id']);
CRM_Event_Form_Registration_Register::buildAmount($this, TRUE);
if (!CRM_Utils_System::isNull(CRM_Utils_Array::value('line_items', $this->_values))) {
$lineItem[] = $this->_values['line_items'];
}
$this->assign('lineItem', empty($lineItem) ? FALSE : $lineItem);
$event = CRM_Event_BAO_Event::getEvents(0, $this->_eventId);
$this->assign('eventName', $event[$this->_eventId]);
$statusOptions = CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label');
$this->add('select', 'status_id', ts('Participant Status'),
array(
'' => ts('- select -'),
) + $statusOptions,
TRUE
);
$this->addElement('checkbox',
'send_receipt',
ts('Send Confirmation?'), NULL,
array('onclick' => "showHideByValue('send_receipt','','notice','table-row','radio',false); showHideByValue('send_receipt','','from-email','table-row','radio',false);")
);
$this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails['from_email_id']);
$this->add('textarea', 'receipt_text', ts('Confirmation Message'));
$noteAttributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_Note');
$this->add('textarea', 'note', ts('Notes'), $noteAttributes['note']);
$buttons[] = array(
'type' => 'upload',
'name' => ts('Save'),
'isDefault' => TRUE,
);
if (CRM_Event_BAO_Participant::isPrimaryParticipant($this->_participantId)) {
$buttons[] = array(
'type' => 'upload',
'name' => ts('Save and Record Payment'),
'subName' => 'new',
);
}
$buttons[] = array(
'type' => 'cancel',
'name' => ts('Cancel'),
);
$this->addButtons($buttons);
$this->addFormRule(array('CRM_Event_Form_ParticipantFeeSelection', 'formRule'), $this);
}
/**
* @param $fields
* @param $files
* @param $self
*
* @return array
*/
public static function formRule($fields, $files, $self) {
$errors = array();
return $errors;
}
public function postProcess() {
$params = $this->controller->exportValues($this->_name);
$feeBlock = $this->_values['fee'];
$lineItems = $this->_values['line_items'];
CRM_Price_BAO_LineItem::changeFeeSelections($params, $this->_participantId, 'participant', $this->_contributionId, $feeBlock, $lineItems, $this->_paidAmount);
$this->contributionAmt = CRM_Core_DAO::getFieldValue('CRM_Contribute_BAO_Contribution', $this->_contributionId, 'total_amount');
// email sending
if (!empty($params['send_receipt'])) {
$fetchParticipantVals = array('id' => $this->_participantId);
CRM_Event_BAO_Participant::getValues($fetchParticipantVals, $participantDetails, CRM_Core_DAO::$_nullArray);
$participantParams = array_merge($params, $participantDetails[$this->_participantId]);
$mailSent = $this->emailReceipt($participantParams);
}
// update participant
CRM_Core_DAO::setFieldValue('CRM_Event_DAO_Participant', $this->_participantId, 'status_id', $params['status_id']);
if (!empty($params['note'])) {
$noteParams = array(
'entity_table' => 'civicrm_participant',
'note' => $params['note'],
'entity_id' => $this->_participantId,
'contact_id' => $this->_contactId,
'modified_date' => date('Ymd'),
);
CRM_Core_BAO_Note::add($noteParams);
}
CRM_Core_Session::setStatus(ts("The fee selection has been changed for this participant"), ts('Saved'), 'success');
$buttonName = $this->controller->getButtonName();
if ($buttonName == $this->getButtonName('upload', 'new')) {
$session = CRM_Core_Session::singleton();
$session->pushUserContext(CRM_Utils_System::url('civicrm/payment/add',
"reset=1&action=add&component=event&id={$this->_participantId}&cid={$this->_contactId}"
));
}
}
/**
* @param array $params
*
* @return mixed
*/
public function emailReceipt(&$params) {
$updatedLineItem = CRM_Price_BAO_LineItem::getLineItems($this->_participantId, 'participant', FALSE, FALSE);
$lineItem = array();
if ($updatedLineItem) {
$lineItem[] = $updatedLineItem;
}
$this->assign('lineItem', empty($lineItem) ? FALSE : $lineItem);
// offline receipt sending
if (array_key_exists($params['from_email_address'], $this->_fromEmails['from_email_id'])) {
$receiptFrom = $params['from_email_address'];
}
$this->assign('module', 'Event Registration');
//use of the message template below requires variables in different format
$event = $events = array();
$returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
//get all event details.
CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
$event = $events[$params['event_id']];
unset($event['start_date']);
unset($event['end_date']);
$role = CRM_Event_PseudoConstant::participantRole();
$participantRoles = CRM_Utils_Array::value('role_id', $params);
if (is_array($participantRoles)) {
$selectedRoles = array();
foreach (array_keys($participantRoles) as $roleId) {
$selectedRoles[] = $role[$roleId];
}
$event['participant_role'] = implode(', ', $selectedRoles);
}
else {
$event['participant_role'] = CRM_Utils_Array::value($participantRoles, $role);
}
$event['is_monetary'] = $this->_isPaidEvent;
if ($params['receipt_text']) {
$event['confirm_email_text'] = $params['receipt_text'];
}
$this->assign('isAmountzero', 1);
$this->assign('event', $event);
$this->assign('isShowLocation', $event['is_show_location']);
if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
$locationParams = array(
'entity_id' => $params['event_id'],
'entity_table' => 'civicrm_event',
);
$location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
$this->assign('location', $location);
}
$status = CRM_Event_PseudoConstant::participantStatus();
if ($this->_isPaidEvent) {
$paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
if (!$this->_mode) {
if (isset($params['payment_instrument_id'])) {
$this->assign('paidBy',
CRM_Utils_Array::value($params['payment_instrument_id'],
$paymentInstrument
)
);
}
}
$this->assign('totalAmount', $this->contributionAmt);
$this->assign('isPrimary', 1);
$this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
}
$this->assign('register_date', $params['register_date']);
$template = CRM_Core_Smarty::singleton();
// Retrieve the name and email of the contact - this will be the TO for receipt email
list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_contactId);
$this->_contributorDisplayName = ($this->_contributorDisplayName == ' ') ? $this->_contributorEmail : $this->_contributorDisplayName;
$waitStatus = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
if ($waitingStatus = CRM_Utils_Array::value($params['status_id'], $waitStatus)) {
$this->assign('isOnWaitlist', TRUE);
}
$this->assign('contactID', $this->_contactId);
$this->assign('participantID', $this->_participantId);
$sendTemplateParams = array(
'groupName' => 'msg_tpl_workflow_event',
'valueName' => 'event_offline_receipt',
'contactId' => $this->_contactId,
'isTest' => FALSE,
'PDFFilename' => ts('confirmation') . '.pdf',
);
// try to send emails only if email id is present
// and the do-not-email option is not checked for that contact
if ($this->_contributorEmail && !$this->_toDoNotEmail) {
$sendTemplateParams['from'] = $receiptFrom;
$sendTemplateParams['toName'] = $this->_contributorDisplayName;
$sendTemplateParams['toEmail'] = $this->_contributorEmail;
$sendTemplateParams['cc'] = CRM_Utils_Array::value('cc', $this->_fromEmails);
$sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc', $this->_fromEmails);
}
list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
return $mailSent;
}
}

View file

@ -0,0 +1,251 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class generates form components for Participant
*
*/
class CRM_Event_Form_ParticipantView extends CRM_Core_Form {
public $useLivePageJS = TRUE;
/**
* Set variables up before form is built.
*
* @return void
*/
public function preProcess() {
$values = $ids = array();
$participantID = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
$contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
$params = array('id' => $participantID);
CRM_Event_BAO_Participant::getValues($params,
$values,
$ids
);
if (empty($values)) {
CRM_Core_Error::statusBounce(ts('The requested participant record does not exist (possibly the record was deleted).'));
}
CRM_Event_BAO_Participant::resolveDefaults($values[$participantID]);
if (!empty($values[$participantID]['fee_level'])) {
CRM_Event_BAO_Participant::fixEventLevel($values[$participantID]['fee_level']);
}
$this->assign('contactId', $contactID);
$this->assign('participantId', $participantID);
$paymentId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
$participantID, 'id', 'participant_id'
);
$this->assign('hasPayment', $paymentId);
$this->assign('componentId', $participantID);
$this->assign('component', 'event');
if ($parentParticipantId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
$participantID, 'registered_by_id'
)
) {
$parentHasPayment = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment',
$parentParticipantId, 'id', 'participant_id'
);
$this->assign('parentHasPayment', $parentHasPayment);
}
$statusId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $participantID, 'status_id', 'id');
$status = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantStatusType', $statusId, 'name', 'id');
$status = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantStatusType', $statusId, 'name', 'id');
if ($status == 'Transferred') {
$transferId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $participantID, 'transferred_to_contact_id', 'id');
$pid = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $transferId, 'id', 'contact_id');
$transferName = current(CRM_Contact_BAO_Contact::getContactDetails($transferId));
$this->assign('pid', $pid);
$this->assign('transferId', $transferId);
$this->assign('transferName', $transferName);
}
$participantStatuses = CRM_Event_PseudoConstant::participantStatus();
if ($values[$participantID]['is_test']) {
$values[$participantID]['status'] .= ' (test) ';
}
// Get Note
$noteValue = CRM_Core_BAO_Note::getNote($participantID, 'civicrm_participant');
$values[$participantID]['note'] = array_values($noteValue);
// Get Line Items
$lineItem = CRM_Price_BAO_LineItem::getLineItems($participantID);
if (!CRM_Utils_System::isNull($lineItem)) {
$values[$participantID]['lineItem'][] = $lineItem;
}
$values[$participantID]['totalAmount'] = CRM_Utils_Array::value('fee_amount', $values[$participantID]);
// Get registered_by contact ID and display_name if participant was registered by someone else (CRM-4859)
if (!empty($values[$participantID]['participant_registered_by_id'])) {
$values[$participantID]['registered_by_contact_id'] = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Participant",
$values[$participantID]['participant_registered_by_id'],
'contact_id', 'id'
);
$values[$participantID]['registered_by_display_name'] = CRM_Contact_BAO_Contact::displayName($values[$participantID]['registered_by_contact_id']);
}
// Check if this is a primaryParticipant (registered for others) and retrieve additional participants if true (CRM-4859)
if (CRM_Event_BAO_Participant::isPrimaryParticipant($participantID)) {
$values[$participantID]['additionalParticipants'] = CRM_Event_BAO_Participant::getAdditionalParticipants($participantID);
}
// get the option value for custom data type
$customDataType = CRM_Core_OptionGroup::values('custom_data_type', FALSE, FALSE, FALSE, NULL, 'name');
$roleCustomDataTypeID = array_search('ParticipantRole', $customDataType);
$eventNameCustomDataTypeID = array_search('ParticipantEventName', $customDataType);
$eventTypeCustomDataTypeID = array_search('ParticipantEventType', $customDataType);
$allRoleIDs = explode(CRM_Core_DAO::VALUE_SEPARATOR, $values[$participantID]['role_id']);
$groupTree = array();
$finalTree = array();
foreach ($allRoleIDs as $k => $v) {
$roleGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', NULL, $participantID, NULL, $v, $roleCustomDataTypeID);
$eventGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', NULL, $participantID, NULL,
$values[$participantID]['event_id'], $eventNameCustomDataTypeID
);
$eventTypeID = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Event", $values[$participantID]['event_id'], 'event_type_id', 'id');
$eventTypeGroupTree = CRM_Core_BAO_CustomGroup::getTree('Participant', NULL, $participantID, NULL, $eventTypeID, $eventTypeCustomDataTypeID);
$groupTree = CRM_Utils_Array::crmArrayMerge($roleGroupTree, $eventGroupTree);
$groupTree = CRM_Utils_Array::crmArrayMerge($groupTree, $eventTypeGroupTree);
$groupTree = CRM_Utils_Array::crmArrayMerge($groupTree, CRM_Core_BAO_CustomGroup::getTree('Participant', NULL, $participantID));
foreach ($groupTree as $treeId => $trees) {
$finalTree[$treeId] = $trees;
}
}
CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $finalTree, FALSE, NULL, NULL, NULL, $participantID);
$eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $values[$participantID]['event_id'], 'title');
//CRM-7150, show event name on participant view even if the event is disabled
if (empty($values[$participantID]['event'])) {
$values[$participantID]['event'] = $eventTitle;
}
//do check for campaigns
if ($campaignId = CRM_Utils_Array::value('campaign_id', $values[$participantID])) {
$campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId);
$values[$participantID]['campaign'] = $campaigns[$campaignId];
}
$this->assign($values[$participantID]);
// add viewed participant to recent items list
$url = CRM_Utils_System::url('civicrm/contact/view/participant',
"action=view&reset=1&id={$values[$participantID]['id']}&cid={$values[$participantID]['contact_id']}&context=home"
);
$recentOther = array();
if (CRM_Core_Permission::check('edit event participants')) {
$recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/participant',
"action=update&reset=1&id={$values[$participantID]['id']}&cid={$values[$participantID]['contact_id']}&context=home"
);
}
if (CRM_Core_Permission::check('delete in CiviEvent')) {
$recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/participant',
"action=delete&reset=1&id={$values[$participantID]['id']}&cid={$values[$participantID]['contact_id']}&context=home"
);
}
$participantRoles = CRM_Event_PseudoConstant::participantRole();
$displayName = CRM_Contact_BAO_Contact::displayName($values[$participantID]['contact_id']);
$participantCount = array();
$invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
$invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
$totalTaxAmount = 0;
foreach ($lineItem as $k => $v) {
if (CRM_Utils_Array::value('participant_count', $lineItem[$k]) > 0) {
$participantCount[] = $lineItem[$k]['participant_count'];
}
$totalTaxAmount = $v['tax_amount'] + $totalTaxAmount;
}
if ($invoicing) {
$this->assign('totalTaxAmount', $totalTaxAmount);
}
if ($participantCount) {
$this->assign('pricesetFieldsCount', $participantCount);
}
$this->assign('displayName', $displayName);
// omitting contactImage from title for now since the summary overlay css doesn't work outside of our crm-container
CRM_Utils_System::setTitle(ts('View Event Registration for') . ' ' . $displayName);
$roleId = CRM_Utils_Array::value('role_id', $values[$participantID]);
$title = $displayName . ' (' . CRM_Utils_Array::value($roleId, $participantRoles) . ' - ' . $eventTitle . ')';
$sep = CRM_Core_DAO::VALUE_SEPARATOR;
$viewRoles = array();
foreach (explode($sep, $values[$participantID]['role_id']) as $k => $v) {
$viewRoles[] = $participantRoles[$v];
}
$values[$participantID]['role_id'] = implode(', ', $viewRoles);
$this->assign('role', $values[$participantID]['role_id']);
// add Participant to Recent Items
CRM_Utils_Recent::add($title,
$url,
$values[$participantID]['id'],
'Participant',
$values[$participantID]['contact_id'],
NULL,
$recentOther
);
}
/**
* Build the form object.
*
* @return void
*/
public function buildQuickForm() {
$this->addButtons(array(
array(
'type' => 'cancel',
'name' => ts('Done'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
'isDefault' => TRUE,
),
)
);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,783 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class generates form components for processing Event.
*/
class CRM_Event_Form_Registration_AdditionalParticipant extends CRM_Event_Form_Registration {
/**
* Pre-registered additional participant id.
*/
public $additionalParticipantId = NULL;
/**
* Set variables up before form is built.
*
* @return void
*/
public function preProcess() {
parent::preProcess();
$participantNo = substr($this->_name, 12);
//lets process in-queue participants.
if ($this->_participantId && $this->_additionalParticipantIds) {
$this->_additionalParticipantId = CRM_Utils_Array::value($participantNo, $this->_additionalParticipantIds);
}
$participantCnt = $participantNo + 1;
$this->assign('formId', $participantNo);
$this->_params = array();
$this->_params = $this->get('params');
$participantTot = $this->_params[0]['additional_participants'] + 1;
$skipCount = count(array_keys($this->_params, "skip"));
if ($skipCount) {
$this->assign('skipCount', $skipCount);
}
CRM_Utils_System::setTitle(ts('Register Participant %1 of %2', array(1 => $participantCnt, 2 => $participantTot)));
//CRM-4320, hack to check last participant.
$this->_lastParticipant = FALSE;
if ($participantTot == $participantCnt) {
$this->_lastParticipant = TRUE;
}
$this->assign('lastParticipant', $this->_lastParticipant);
}
/**
* Set default values for the form. For edit/view mode
* the default values are retrieved from the database
*
*
* @return void
*/
public function setDefaultValues() {
$defaults = $unsetSubmittedOptions = array();
$discountId = NULL;
//fix for CRM-3088, default value for discount set.
if (!empty($this->_values['discount'])) {
$discountId = CRM_Core_BAO_Discount::findSet($this->_eventId, 'civicrm_event');
if ($discountId && !empty($this->_values['event']['default_discount_fee_id'])) {
$discountKey = CRM_Core_DAO::getFieldValue("CRM_Core_DAO_OptionValue", $this->_values['event']['default_discount_fee_id'], 'weight', 'id'
);
$defaults['amount'] = key(array_slice($this->_values['discount'][$discountId], $discountKey - 1, $discountKey, TRUE));
}
}
if ($this->_priceSetId) {
foreach ($this->_feeBlock as $key => $val) {
if (empty($val['options'])) {
continue;
}
$optionsFull = CRM_Utils_Array::value('option_full_ids', $val, array());
foreach ($val['options'] as $keys => $values) {
if ($values['is_default'] && !in_array($keys, $optionsFull)) {
if ($val['html_type'] == 'CheckBox') {
$defaults["price_{$key}"][$keys] = 1;
}
else {
$defaults["price_{$key}"] = $keys;
}
}
}
if (!empty($optionsFull)) {
$unsetSubmittedOptions[$val['id']] = $optionsFull;
}
}
}
//CRM-4320, setdefault additional participant values.
if ($this->_allowConfirmation && $this->_additionalParticipantId) {
//hack to get set default from eventFees.php
$this->_discountId = $discountId;
$this->_pId = $this->_additionalParticipantId;
$this->_contactId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_additionalParticipantId, 'contact_id');
CRM_Event_BAO_Participant::formatFieldsAndSetProfileDefaults($this->_contactId, $this);
$participantDefaults = CRM_Event_Form_EventFees::setDefaultValues($this);
$participantDefaults = array_merge($this->_defaults, $participantDefaults);
// use primary email address if billing email address is empty
if (empty($this->_defaults["email-{$this->_bltID}"]) &&
!empty($this->_defaults["email-Primary"])
) {
$participantDefaults["email-{$this->_bltID}"] = $this->_defaults["email-Primary"];
}
$defaults = array_merge($defaults, $participantDefaults);
}
$defaults = array_merge($this->_defaults, $defaults);
//reset values for all options those are full.
CRM_Event_Form_Registration::resetElementValue($unsetSubmittedOptions, $this);
//load default campaign from page.
if (array_key_exists('participant_campaign_id', $this->_fields)) {
$defaults['participant_campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->_values['event']);
}
//CRM-17865 set custom field defaults
if (!empty($this->_fields)) {
foreach ($this->_fields as $name => $field) {
if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
if (!isset($defaults[$name])) {
CRM_Core_BAO_CustomField::setProfileDefaults($customFieldID, $name, $defaults,
NULL, CRM_Profile_Form::MODE_REGISTER
);
}
}
}
}
return $defaults;
}
/**
* Build the form object.
*
* @return void
*/
public function buildQuickForm() {
$button = substr($this->controller->getButtonName(), -4);
$this->add('hidden', 'scriptFee', NULL);
$this->add('hidden', 'scriptArray', NULL);
if ($this->_values['event']['is_monetary']) {
CRM_Event_Form_Registration_Register::buildAmount($this);
}
$first_name = $last_name = NULL;
$pre = $post = array();
foreach (array(
'pre',
'post',
) as $keys) {
if (isset($this->_values['additional_custom_' . $keys . '_id'])) {
$this->buildCustom($this->_values['additional_custom_' . $keys . '_id'], 'additionalCustom' . ucfirst($keys));
$$keys = CRM_Core_BAO_UFGroup::getFields($this->_values['additional_custom_' . $keys . '_id']);
}
foreach (array(
'first_name',
'last_name',
) as $name) {
if (array_key_exists($name, $$keys) &&
CRM_Utils_Array::value('is_required', CRM_Utils_Array::value($name, $$keys))
) {
$$name = 1;
}
}
}
$required = ($button == 'skip' ||
$this->_values['event']['allow_same_participant_emails'] == 1 &&
($first_name && $last_name)
) ? FALSE : TRUE;
//add buttons
$js = NULL;
if ($this->isLastParticipant(TRUE) && empty($this->_values['event']['is_monetary'])) {
$js = array('onclick' => "return submitOnce(this,'" . $this->_name . "','" . ts('Processing') . "');");
}
//handle case where user might sart with waiting by group
//registration and skip some people and now group fit to
//become registered so need to take payment from user.
//this case only occurs at dynamic waiting status, CRM-4320
$statusMessage = NULL;
$allowToProceed = TRUE;
$includeSkipButton = TRUE;
$this->_resetAllowWaitlist = FALSE;
$pricesetFieldsCount = CRM_Price_BAO_PriceSet::getPricesetCount($this->_priceSetId);
if ($this->_lastParticipant || $pricesetFieldsCount) {
//get the participant total.
$processedCnt = self::getParticipantCount($this, $this->_params, TRUE);
}
if (!$this->_allowConfirmation && !empty($this->_params[0]['bypass_payment']) &&
$this->_lastParticipant
) {
//get the event spaces.
$spaces = $this->_availableRegistrations;
$currentPageMaxCount = 1;
if ($pricesetFieldsCount) {
$currentPageMaxCount = $pricesetFieldsCount;
}
//we might did reset allow waiting in case of dynamic calculation
// @TODO - does this bypass_payment still exist?
if (!empty($this->_params[0]['bypass_payment']) &&
is_numeric($spaces) &&
$processedCnt > $spaces
) {
$this->_allowWaitlist = TRUE;
$this->set('allowWaitlist', TRUE);
}
//lets allow to become a part of runtime waiting list, if primary selected pay later.
$realPayLater = FALSE;
if (!empty($this->_values['event']['is_monetary']) && !empty($this->_values['event']['is_pay_later'])) {
$realPayLater = CRM_Utils_Array::value('is_pay_later', $this->_params[0]);
}
//truly spaces are greater than required.
if (is_numeric($spaces) && $spaces >= ($processedCnt + $currentPageMaxCount)) {
if (CRM_Utils_Array::value('amount', $this->_params[0], 0) == 0 || $this->_requireApproval) {
$this->_allowWaitlist = FALSE;
$this->set('allowWaitlist', $this->_allowWaitlist);
if ($this->_requireApproval) {
$statusMessage = ts("It looks like you are now registering a group of %1 participants. The event has %2 available spaces (you will not be wait listed). Registration for this event requires approval. You will receive an email once your registration has been reviewed.", array(
1 => ++$processedCnt,
2 => $spaces,
));
}
else {
$statusMessage = ts("It looks like you are now registering a group of %1 participants. The event has %2 available spaces (you will not be wait listed).", array(
1 => ++$processedCnt,
2 => $spaces,
));
}
}
else {
$statusMessage = ts("It looks like you are now registering a group of %1 participants. The event has %2 available spaces (you will not be wait listed). Please go back to the main registration page and reduce the number of additional people. You will also need to complete payment information.", array(
1 => ++$processedCnt,
2 => $spaces,
));
$allowToProceed = FALSE;
}
CRM_Core_Session::setStatus($statusMessage, ts('Registration Error'), 'error');
}
elseif ($processedCnt == $spaces) {
if (CRM_Utils_Array::value('amount', $this->_params[0], 0) == 0
|| $realPayLater || $this->_requireApproval
) {
$this->_resetAllowWaitlist = TRUE;
if ($this->_requireApproval) {
$statusMessage = ts("If you skip this participant there will be enough spaces in the event for your group (you will not be wait listed). Registration for this event requires approval. You will receive an email once your registration has been reviewed.");
}
else {
$statusMessage = ts("If you skip this participant there will be enough spaces in the event for your group (you will not be wait listed).");
}
}
else {
//hey there is enough space and we require payment.
$statusMessage = ts("If you skip this participant there will be enough spaces in the event for your group (you will not be wait listed). Please go back to the main registration page and reduce the number of additional people. You will also need to complete payment information.");
$includeSkipButton = FALSE;
}
}
}
// for priceset with count
if ($pricesetFieldsCount && !empty($this->_values['event']['has_waitlist']) &&
!$this->_allowConfirmation
) {
if ($this->_isEventFull) {
$statusMessage = ts('This event is currently full. You are registering for the waiting list. You will be notified if spaces become available.');
}
elseif ($this->_allowWaitlist ||
(!$this->_allowWaitlist && ($processedCnt + $pricesetFieldsCount) > $this->_availableRegistrations)
) {
$waitingMsg = ts('It looks like you are registering more participants then there are spaces available. All participants will be added to the waiting list. You will be notified if spaces become available.');
$confirmedMsg = ts('It looks like there are enough spaces in this event for your group (you will not be wait listed).');
if ($this->_requireApproval) {
$waitingMsg = ts('It looks like you are now registering a group of %1 participants. The event has %2 available spaces (you will not be wait listed). Registration for this event requires approval. You will receive an email once your registration has been reviewed.');
$confirmedMsg = ts('It looks there are enough spaces in this event for your group (you will not be wait listed). Registration for this event requires approval. You will receive an email once your registration has been reviewed.');
}
$this->assign('waitingMsg', $waitingMsg);
$this->assign('confirmedMsg', $confirmedMsg);
$this->assign('availableRegistrations', $this->_availableRegistrations);
$this->assign('currentParticipantCount', $processedCnt);
$this->assign('allowGroupOnWaitlist', TRUE);
$paymentBypassed = NULL;
if (!empty($this->_params[0]['bypass_payment']) &&
!$this->_allowWaitlist &&
!$realPayLater &&
!$this->_requireApproval &&
!(CRM_Utils_Array::value('amount', $this->_params[0], 0) == 0)
) {
$paymentBypassed = ts('Please go back to the main registration page, to complete payment information.');
}
$this->assign('paymentBypassed', $paymentBypassed);
}
}
$this->assign('statusMessage', $statusMessage);
$buttons = array(
array(
'type' => 'back',
'name' => ts('Go Back'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp',
),
);
//CRM-4320
if ($allowToProceed) {
$buttons = array_merge($buttons, array(
array(
'type' => 'upload',
'name' => ts('Continue'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
'isDefault' => TRUE,
'js' => $js,
),
)
);
if ($includeSkipButton) {
$buttons = array_merge($buttons, array(
array(
'type' => 'next',
'name' => ts('Skip Participant'),
'subName' => 'skip',
'icon' => 'fa-fast-forward',
),
)
);
}
}
$this->addButtons($buttons);
$this->addFormRule(array('CRM_Event_Form_Registration_AdditionalParticipant', 'formRule'), $this);
$this->unsavedChangesWarn = TRUE;
}
/**
* Global form rule.
*
* @param array $fields
* The input form values.
* @param array $files
* The uploaded files if any.
* @param $self
*
*
* @return bool|array
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $self) {
$errors = array();
//get the button name.
$button = substr($self->controller->getButtonName(), -4);
$realPayLater = FALSE;
if (!empty($self->_values['event']['is_monetary']) && !empty($self->_values['event']['is_pay_later'])) {
$realPayLater = CRM_Utils_Array::value('is_pay_later', $self->_params[0]);
}
if ($button != 'skip') {
//Check that either an email or firstname+lastname is included in the form(CRM-9587)
CRM_Event_Form_Registration_Register::checkProfileComplete($fields, $errors, $self->_eventId);
//Additional Participant can also register for an event only once
$isRegistered = CRM_Event_Form_Registration_Register::checkRegistration($fields, $self, TRUE);
if ($isRegistered) {
if ($self->_values['event']['allow_same_participant_emails']) {
$errors['_qf_default'] = ts('A person is already registered for this event.');
}
else {
$errors["email-{$self->_bltID}"] = ts('A person with this email address is already registered for this event.');
}
}
//get the complete params.
$params = $self->get('params');
//take the participant instance.
$addParticipantNum = substr($self->_name, 12);
if (is_array($params)) {
foreach ($params as $key => $value) {
if ($key != $addParticipantNum) {
if (!$self->_values['event']['allow_same_participant_emails']) {
//collect all email fields
$existingEmails = array();
$additionalParticipantEmails = array();
if (is_array($value)) {
foreach ($value as $key => $val) {
if (substr($key, 0, 6) == 'email-' && $val) {
$existingEmails[] = $val;
}
}
}
foreach ($fields as $key => $val) {
if (substr($key, 0, 6) == 'email-' && $val) {
$additionalParticipantEmails[] = $val;
$mailKey = $key;
}
}
//check if any emails are common to both arrays
if (count(array_intersect($existingEmails, $additionalParticipantEmails))) {
$errors[$mailKey] = ts('The email address must be unique for each participant.');
break;
}
}
else {
// check with first_name and last_name for additional participants
if (!empty($value['first_name']) && ($value['first_name'] == CRM_Utils_Array::value('first_name', $fields)) &&
(CRM_Utils_Array::value('last_name', $value) == CRM_Utils_Array::value('last_name', $fields))
) {
$errors['first_name'] = ts('The first name and last name must be unique for each participant.');
break;
}
}
}
}
}
//check for atleast one pricefields should be selected
if (!empty($fields['priceSetId'])) {
$allParticipantParams = $params;
//format current participant params.
$allParticipantParams[$addParticipantNum] = self::formatPriceSetParams($self, $fields);
$totalParticipants = self::getParticipantCount($self, $allParticipantParams);
//validate price field params.
$priceSetErrors = self::validatePriceSet($self, $allParticipantParams);
$errors = array_merge($errors, CRM_Utils_Array::value($addParticipantNum, $priceSetErrors, array()));
if (!$self->_allowConfirmation &&
is_numeric($self->_availableRegistrations)
) {
if (!empty($self->_params[0]['bypass_payment']) &&
!$self->_allowWaitlist &&
!$realPayLater &&
!$self->_requireApproval &&
!(CRM_Utils_Array::value('amount', $self->_params[0], 0) == 0) &&
$totalParticipants < $self->_availableRegistrations
) {
$errors['_qf_default'] = ts("Your event registration will be confirmed. Please go back to the main registration page, to complete payment information.");
}
//check for availability of registrations.
if (!$self->_allowConfirmation && empty($self->_values['event']['has_waitlist']) &&
$totalParticipants > $self->_availableRegistrations
) {
$errors['_qf_default'] = ts('Sorry, it looks like this event only has %2 spaces available, and you are trying to register %1 participants. Please change your selections accordingly.', array(
1 => $totalParticipants,
2 => $self->_availableRegistrations,
));
}
}
}
}
if ($button == 'skip' && $self->_lastParticipant && !empty($fields['priceSetId'])) {
$pricesetFieldsCount = CRM_Price_BAO_PriceSet::getPricesetCount($fields['priceSetId']);
if (($pricesetFieldsCount < 1) || $self->_allowConfirmation) {
return $errors;
}
if (!empty($self->_values['event']['has_waitlist']) && !empty($self->_params[0]['bypass_payment']) &&
!$self->_allowWaitlist &&
!$realPayLater &&
!$self->_requireApproval &&
!(CRM_Utils_Array::value('amount', $self->_params[0], 0) == 0)
) {
$errors['_qf_default'] = ts("You are going to skip the last participant, your event registration will be confirmed. Please go back to the main registration page, to complete payment information.");
}
}
if ($button != 'skip' &&
$self->_values['event']['is_monetary'] &&
!isset($errors['_qf_default']) &&
!$self->validatePaymentValues($self, $fields)
) {
$errors['_qf_default'] = ts("Your payment information looks incomplete. Please go back to the main registration page, to complete payment information.");
$self->set('forcePayement', TRUE);
}
elseif ($button == 'skip') {
$self->set('forcePayement', TRUE);
}
return $errors;
}
/**
* @param $self
* @param $fields
*
* @return bool
*/
public function validatePaymentValues($self, $fields) {
if (!empty($self->_params[0]['bypass_payment']) ||
$self->_allowWaitlist ||
empty($self->_fields) ||
CRM_Utils_Array::value('amount', $self->_params[0]) > 0
) {
return TRUE;
}
$validatePayement = FALSE;
if (!empty($fields['priceSetId'])) {
$lineItem = array();
CRM_Price_BAO_PriceSet::processAmount($self->_values['fee'], $fields, $lineItem);
if ($fields['amount'] > 0) {
$validatePayement = TRUE;
// $self->_forcePayement = true;
// return false;
}
}
elseif (!empty($fields['amount']) &&
(CRM_Utils_Array::value('value', $self->_values['fee'][$fields['amount']]) > 0)
) {
$validatePayement = TRUE;
}
if (!$validatePayement) {
return TRUE;
}
$errors = array();
CRM_Core_Form::validateMandatoryFields($self->_fields, $fields, $errors);
if (isset($self->_params[0]['payment_processor'])) {
// validate supplied payment instrument values (e.g. credit card number and cvv)
$payment_processor_id = $self->_params[0]['payment_processor'];
CRM_Core_Payment_Form::validatePaymentInstrument($payment_processor_id, $self->_params[0], $errors, (!$self->_isBillingAddressRequiredForPayLater ? NULL : 'billing'));
}
if (!empty($errors)) {
return FALSE;
}
foreach (CRM_Contact_BAO_Contact::$_greetingTypes as $greeting) {
if ($greetingType = CRM_Utils_Array::value($greeting, $self->_params[0])) {
$customizedValue = CRM_Core_OptionGroup::getValue($greeting, 'Customized', 'name');
if ($customizedValue == $greetingType && empty($self->_params[0][$greeting . '_custom'])) {
return FALSE;
}
}
}
return TRUE;
}
/**
* Process the form submission.
*
*
* @return void
*/
public function postProcess() {
//get the button name.
$button = substr($this->controller->getButtonName(), -4);
//take the participant instance.
$addParticipantNum = substr($this->_name, 12);
//user submitted params.
$params = $this->controller->exportValues($this->_name);
if (!$this->_allowConfirmation) {
// check if the participant is already registered
$params['contact_id'] = CRM_Event_Form_Registration_Register::getRegistrationContactID($params, $this, TRUE);
}
if (!empty($params['image_URL'])) {
CRM_Contact_BAO_Contact::processImageParams($params);
}
//carry campaign to partcipants.
if (array_key_exists('participant_campaign_id', $params)) {
$params['campaign_id'] = $params['participant_campaign_id'];
}
else {
$params['campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->_values['event']);
}
// if waiting is enabled
if (!$this->_allowConfirmation &&
is_numeric($this->_availableRegistrations)
) {
$this->_allowWaitlist = FALSE;
//get the current page count.
$currentCount = self::getParticipantCount($this, $params);
if ($button == 'skip') {
$currentCount = 'skip';
}
//get the total count.
$previousCount = self::getParticipantCount($this, $this->_params, TRUE);
$totalParticipants = $previousCount;
if (is_numeric($currentCount)) {
$totalParticipants += $currentCount;
}
if (!empty($this->_values['event']['has_waitlist']) &&
$totalParticipants > $this->_availableRegistrations
) {
$this->_allowWaitlist = TRUE;
}
$this->set('allowWaitlist', $this->_allowWaitlist);
$this->_lineItemParticipantsCount[$addParticipantNum] = $currentCount;
}
if ($button == 'skip') {
//hack for free/zero amount event.
if ($this->_resetAllowWaitlist) {
$this->_allowWaitlist = FALSE;
$this->set('allowWaitlist', FALSE);
if ($this->_requireApproval) {
$status = ts("You have skipped last participant and which result into event having enough spaces, but your registration require approval, Once your registration has been reviewed, you will receive an email with a link to a web page where you can complete the registration process.");
}
else {
$status = ts("You have skipped last participant and which result into event having enough spaces, hence your group become as register participants though you selected on wait list.");
}
CRM_Core_Session::setStatus($status);
}
$this->_params[$addParticipantNum] = 'skip';
if (isset($this->_lineItem)) {
$this->_lineItem[$addParticipantNum] = 'skip';
$this->_lineItemParticipantsCount[$addParticipantNum] = 'skip';
}
}
else {
$config = CRM_Core_Config::singleton();
$params['currencyID'] = $config->defaultCurrency;
if ($this->_values['event']['is_monetary']) {
//added for discount
$discountId = CRM_Core_BAO_Discount::findSet($this->_eventId, 'civicrm_event');
$params['amount_level'] = $this->getAmountLevel($params, $discountId);
if (!empty($this->_values['discount'][$discountId])) {
$params['discount_id'] = $discountId;
$params['amount'] = $this->_values['discount'][$discountId][$params['amount']]['value'];
}
elseif (empty($params['priceSetId'])) {
$params['amount'] = $this->_values['fee'][$params['amount']]['value'];
}
else {
$lineItem = array();
CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem);
//build line item array..
//if requireApproval/waitlist is enabled we hide fees for primary participant
// (and not for additional participant which might be is a bug)
//lineItem are not correctly build for primary participant
//this results in redundancy since now lineItems for additional participant will be build against primary participantNum
//therefore lineItems must always be build against current participant No
$this->_lineItem[$addParticipantNum] = $lineItem;
}
}
if (array_key_exists('participant_role', $params)) {
$params['participant_role_id'] = $params['participant_role'];
}
if (empty($params['participant_role_id']) && $this->_values['event']['default_role_id']) {
$params['participant_role_id'] = $this->_values['event']['default_role_id'];
}
if (!empty($this->_params[0]['is_pay_later'])) {
$params['is_pay_later'] = 1;
}
//carry additional participant id, contact id if pre-registered.
if ($this->_allowConfirmation && $this->_additionalParticipantId) {
$params['contact_id'] = $this->_contactId;
$params['participant_id'] = $this->_additionalParticipantId;
}
//build the params array.
$this->_params[$addParticipantNum] = $params;
}
//finally set the params.
$this->set('params', $this->_params);
//set the line item.
if ($this->_lineItem) {
$this->set('lineItem', $this->_lineItem);
$this->set('lineItemParticipantsCount', $this->_lineItemParticipantsCount);
}
$participantNo = count($this->_params);
if ($button != 'skip') {
$statusMsg = ts('Registration information for participant %1 has been saved.', array(1 => $participantNo));
CRM_Core_Session::setStatus($statusMsg, ts('Registration Saved'), 'success');
}
// Check whether to process the registration now, calling processRegistration()
if (
!$this->_values['event']['is_confirm_enabled'] // CRM-11182 - Optional confirmation screen
&& !$this->_values['event']['is_monetary']
&& CRM_Utils_Array::value('additional_participants', $this->_params[0])
&& $this->isLastParticipant()
) {
$this->processRegistration($this->_params);
}
}
/**
* @param $additionalParticipant
*
* @return array
*/
public static function &getPages($additionalParticipant) {
$details = array();
for ($i = 1; $i <= $additionalParticipant; $i++) {
$details["Participant_{$i}"] = array(
'className' => 'CRM_Event_Form_Registration_AdditionalParticipant',
'title' => "Register Additional Participant {$i}",
);
}
return $details;
}
/**
* Check whether call current participant is last one.
*
* @param bool $isButtonJs
*
* @return bool
* ture on success.
*/
public function isLastParticipant($isButtonJs = FALSE) {
$participant = $isButtonJs ? $this->_params[0]['additional_participants'] : $this->_params[0]['additional_participants'] + 1;
if (count($this->_params) == $participant) {
return TRUE;
}
return FALSE;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,225 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class generates form components for processing Event
*
*/
class CRM_Event_Form_Registration_ParticipantConfirm extends CRM_Event_Form_Registration {
// optional credit card return status code
// CRM-6060
protected $_cc = NULL;
/**
* Set variables up before form is built.
*
* @return void
*/
public function preProcess() {
$this->_participantId = CRM_Utils_Request::retrieve('participantId', 'Positive', $this);
$this->_cc = CRM_Utils_Request::retrieve('cc', 'String', $this);
//get the contact and event id and assing to session.
$values = array();
$csContactID = NULL;
if ($this->_participantId) {
$params = array('id' => $this->_participantId);
CRM_Core_DAO::commonRetrieve('CRM_Event_DAO_Participant', $params, $values,
array('contact_id', 'event_id', 'status_id')
);
}
$this->_participantStatusId = CRM_Utils_Array::value('status_id', $values);
$this->_eventId = CRM_Utils_Array::value('event_id', $values);
$csContactId = CRM_Utils_Array::value('contact_id', $values);
// make sure we have right permission to edit this user
$this->_csContactID = NULL;
if ($csContactId && $this->_eventId) {
$session = CRM_Core_Session::singleton();
if ($csContactId == $session->get('userID')) {
$this->_csContactID = $csContactId;
}
else {
if (CRM_Contact_BAO_Contact_Permission::validateChecksumContact($csContactId, $this)) {
//since we have landing page so get this contact
//id in session if user really want to walk wizard.
$this->_csContactID = $csContactId;
}
}
}
if (!$this->_csContactID) {
$config = CRM_Core_Config::singleton();
CRM_Core_Error::statusBounce(ts('You do not have permission to access this event registration. Contact the site administrator if you need assistance.'), $config->userFrameworkBaseURL);
}
}
/**
* Build the form object.
*
* @return void
*/
public function buildQuickForm() {
$params = array('id' => $this->_eventId);
$values = array();
CRM_Core_DAO::commonRetrieve('CRM_Event_DAO_Event', $params, $values,
array('title')
);
$buttons = array();
// only pending status class family able to confirm.
$statusMsg = NULL;
if (array_key_exists($this->_participantStatusId,
CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Pending'")
)) {
//need to confirm that though participant confirming
//registration - but is there enough space to confirm.
$emptySeats = CRM_Event_BAO_Participant::pendingToConfirmSpaces($this->_eventId);
$additonalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_participantId);
$requireSpace = 1 + count($additonalIds);
if ($emptySeats !== NULL && ($requireSpace > $emptySeats)) {
$statusMsg = ts("Oops, it looks like there are currently no available spaces for the %1 event.", array(1 => $values['title']));
}
else {
if ($this->_cc == 'fail') {
$statusMsg = '<div class="bold">' . ts('Your Credit Card transaction was not successful. No money has yet been charged to your card.') . '</div><div><br />' . ts('Click the "Confirm Registration" button to complete your registration in %1, or click "Cancel Registration" if you are no longer interested in attending this event.', array(
1 => $values['title'],
)) . '</div>';
}
else {
$statusMsg = '<div class="bold">' . ts('Confirm your registration for %1.', array(
1 => $values['title'],
)) . '</div><div><br />' . ts('Click the "Confirm Registration" button to begin, or click "Cancel Registration" if you are no longer interested in attending this event.') . '</div>';
}
$buttons = array_merge($buttons, array(
array(
'type' => 'next',
'name' => ts('Confirm Registration'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
'isDefault' => TRUE,
),
));
}
}
// status class other than Negative should be able to cancel registration.
if (array_key_exists($this->_participantStatusId,
CRM_Event_PseudoConstant::participantStatus(NULL, "class != 'Negative'")
)) {
$cancelConfirm = ts('Are you sure you want to cancel your registration for this event?');
$buttons = array_merge($buttons, array(
array(
'type' => 'submit',
'name' => ts('Cancel Registration'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
'js' => array('onclick' => 'return confirm(\'' . $cancelConfirm . '\');'),
),
));
if (!$statusMsg) {
$statusMsg = ts('You can cancel your registration for %1 by clicking "Cancel Registration".', array(1 => $values['title']));
}
}
if (!$statusMsg) {
$statusMsg = ts("Oops, it looks like your registration for %1 has already been cancelled.",
array(1 => $values['title'])
);
}
$this->assign('statusMsg', $statusMsg);
$this->addButtons($buttons);
}
/**
* Process the form submission.
*
*
* @return void
*/
public function postProcess() {
//get the button.
$buttonName = $this->controller->getButtonName();
$participantId = $this->_participantId;
if ($buttonName == '_qf_ParticipantConfirm_next') {
//lets get contact id in session.
$session = CRM_Core_Session::singleton();
$session->set('userID', $this->_csContactID);
$this->postProcessHook();
//check user registration status is from pending class
$url = CRM_Utils_System::url('civicrm/event/register',
"reset=1&id={$this->_eventId}&participantId={$participantId}"
);
CRM_Utils_System::redirect($url);
}
elseif ($buttonName == '_qf_ParticipantConfirm_submit') {
//need to registration status to 'cancelled'.
$cancelledId = array_search('Cancelled', CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'"));
$additionalParticipantIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($participantId);
$participantIds = array_merge(array($participantId), $additionalParticipantIds);
$results = CRM_Event_BAO_Participant::transitionParticipants($participantIds, $cancelledId, NULL, TRUE);
if (count($participantIds) > 1) {
$statusMessage = ts("%1 Event registration(s) have been cancelled.", array(1 => count($participantIds)));
}
else {
$statusMessage = ts("Your Event Registration has been cancelled.");
}
if (!empty($results['mailedParticipants'])) {
foreach ($results['mailedParticipants'] as $key => $displayName) {
$statusMessage .= "<br />" . ts("Email has been sent to : %1", array(1 => $displayName));
}
}
$this->postProcessHook();
CRM_Core_Session::setStatus($statusMessage);
CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/event/info',
"reset=1&id={$this->_eventId}&noFullMsg=1",
FALSE, NULL, FALSE, TRUE
)
);
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,250 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class generates form components for processing Event
*
*/
class CRM_Event_Form_Registration_ThankYou extends CRM_Event_Form_Registration {
/**
* Set variables up before form is built.
*
* @return void
*/
public function preProcess() {
parent::preProcess();
$this->_params = $this->get('params');
$this->_lineItem = $this->get('lineItem');
$this->_part = $this->get('part');
$this->_totalAmount = $this->get('totalAmount');
$this->_receiveDate = $this->get('receiveDate');
$this->_trxnId = $this->get('trxnId');
$finalAmount = $this->get('finalAmount');
$this->assign('finalAmount', $finalAmount);
$participantInfo = $this->get('participantInfo');
$this->assign('part', $this->_part);
$this->assign('participantInfo', $participantInfo);
$customGroup = $this->get('customProfile');
$this->assign('customProfile', $customGroup);
$this->assign('individual', $this->get('individual'));
CRM_Event_Form_Registration_Confirm::assignProfiles($this);
CRM_Utils_System::setTitle(CRM_Utils_Array::value('thankyou_title', $this->_values['event']));
}
/**
* Overwrite action, since we are only showing elements in frozen mode
* no help display needed
*
* @return int
*/
public function getAction() {
if ($this->_action & CRM_Core_Action::PREVIEW) {
return CRM_Core_Action::VIEW | CRM_Core_Action::PREVIEW;
}
else {
return CRM_Core_Action::VIEW;
}
}
/**
* Build the form object.
*
* @return void
*/
public function buildQuickForm() {
// Assign the email address from a contact id lookup as in CRM_Event_BAO_Event->sendMail()
$primaryContactId = $this->get('primaryContactId');
if ($primaryContactId) {
list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($primaryContactId);
$this->assign('email', $email);
}
$this->assignToTemplate();
$invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
$taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
$invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
$getTaxDetails = FALSE;
$taxAmount = 0;
$lineItemForTemplate = array();
if (!empty($this->_lineItem) && is_array($this->_lineItem)) {
foreach ($this->_lineItem as $key => $value) {
if (!empty($value) && $value != 'skip') {
$lineItemForTemplate[$key] = $value;
if ($invoicing) {
foreach ($value as $v) {
if (isset($v['tax_amount']) || isset($v['tax_rate'])) {
$taxAmount += $v['tax_amount'];
$getTaxDetails = TRUE;
}
}
}
}
}
}
if ($this->_priceSetId &&
!CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config') &&
!empty($lineItemForTemplate)
) {
$this->assign('lineItem', $lineItemForTemplate);
}
if ($invoicing) {
$this->assign('getTaxDetails', $getTaxDetails);
$this->assign('totalTaxAmount', $taxAmount);
$this->assign('taxTerm', $taxTerm);
}
$this->assign('totalAmount', $this->_totalAmount);
$hookDiscount = $this->get('hookDiscount');
if ($hookDiscount) {
$this->assign('hookDiscount', $hookDiscount);
}
$this->assign('receive_date', $this->_receiveDate);
$this->assign('trxn_id', $this->_trxnId);
//cosider total amount.
$this->assign('isAmountzero', ($this->_totalAmount <= 0) ? TRUE : FALSE);
$this->assign('defaultRole', FALSE);
if (CRM_Utils_Array::value('defaultRole', $this->_params[0]) == 1) {
$this->assign('defaultRole', TRUE);
}
$defaults = array();
$fields = array();
if (!empty($this->_fields)) {
foreach ($this->_fields as $name => $dontCare) {
$fields[$name] = 1;
}
}
$fields['state_province'] = $fields['country'] = $fields['email'] = 1;
foreach ($fields as $name => $dontCare) {
if (isset($this->_params[0][$name])) {
$defaults[$name] = $this->_params[0][$name];
if (substr($name, 0, 7) == 'custom_') {
$timeField = "{$name}_time";
if (isset($this->_params[0][$timeField])) {
$defaults[$timeField] = $this->_params[0][$timeField];
}
}
elseif (in_array($name, CRM_Contact_BAO_Contact::$_greetingTypes)
&& !empty($this->_params[0][$name . '_custom'])
) {
$defaults[$name . '_custom'] = $this->_params[0][$name . '_custom'];
}
}
}
$this->_submitValues = array_merge($this->_submitValues, $defaults);
$this->setDefaults($defaults);
$params['entity_id'] = $this->_eventId;
$params['entity_table'] = 'civicrm_event';
$data = array();
CRM_Friend_BAO_Friend::retrieve($params, $data);
if (!empty($data['is_active'])) {
$friendText = $data['title'];
$this->assign('friendText', $friendText);
if ($this->_action & CRM_Core_Action::PREVIEW) {
$url = CRM_Utils_System::url('civicrm/friend',
"eid={$this->_eventId}&reset=1&action=preview&pcomponent=event"
);
}
else {
$url = CRM_Utils_System::url('civicrm/friend',
"eid={$this->_eventId}&reset=1&pcomponent=event"
);
}
$this->assign('friendURL', $url);
}
$this->freeze();
//lets give meaningful status message, CRM-4320.
$isOnWaitlist = $isRequireApproval = FALSE;
if ($this->_allowWaitlist && !$this->_allowConfirmation) {
$isOnWaitlist = TRUE;
}
if ($this->_requireApproval && !$this->_allowConfirmation) {
$isRequireApproval = TRUE;
}
$this->assign('isOnWaitlist', $isOnWaitlist);
$this->assign('isRequireApproval', $isRequireApproval);
// find pcp info
$dao = new CRM_PCP_DAO_PCPBlock();
$dao->entity_table = 'civicrm_event';
$dao->entity_id = $this->_eventId;
$dao->is_active = 1;
$dao->find(TRUE);
if ($dao->id) {
$this->assign('pcpLink', CRM_Utils_System::url('civicrm/contribute/campaign', 'action=add&reset=1&pageId=' . $this->_eventId . '&component=event'));
$this->assign('pcpLinkText', $dao->link_text);
}
// Assign Participant Count to Lineitem Table
$this->assign('pricesetFieldsCount', CRM_Price_BAO_PriceSet::getPricesetCount($this->_priceSetId));
// can we blow away the session now to prevent hackery
$this->controller->reset();
}
/**
* Process the form submission.
*
*
* @return void
*/
public function postProcess() {
}
/**
* Return a descriptive name for the page, used in wizard header
*
* @return string
*/
public function getTitle() {
return ts('Thank You Page');
}
}

View file

@ -0,0 +1,481 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* Files required
*/
/**
* This file is for civievent search
*/
class CRM_Event_Form_Search extends CRM_Core_Form_Search {
/**
* The params that are sent to the query.
*
* @var array
*/
protected $_queryParams;
/**
* Are we restricting ourselves to a single contact.
*
* @var boolean
*/
protected $_single = FALSE;
/**
* Are we restricting ourselves to a single contact.
*
* @var boolean
*/
protected $_limit = NULL;
/**
* Prefix for the controller.
*/
protected $_prefix = "event_";
/**
* The saved search ID retrieved from the GET vars.
*
* @var int
*/
protected $_ssID;
/**
* Processing needed for buildForm and later.
*
* @return void
*/
public function preProcess() {
$this->set('searchFormName', 'Search');
/**
* set the button names
*/
$this->_searchButtonName = $this->getButtonName('refresh');
$this->_actionButtonName = $this->getButtonName('next', 'action');
$this->_done = FALSE;
$this->defaults = array();
/*
* we allow the controller to set force/reset externally, useful when we are being
* driven by the wizard framework
*/
$this->_reset = CRM_Utils_Request::retrieve('reset', 'Boolean');
$this->_force = CRM_Utils_Request::retrieve('force', 'Boolean', $this, FALSE);
$this->_limit = CRM_Utils_Request::retrieve('limit', 'Positive', $this);
$this->_context = CRM_Utils_Request::retrieve('context', 'String', $this, FALSE, 'search');
$this->_ssID = CRM_Utils_Request::retrieve('ssID', 'Positive', $this);
$this->assign("context", $this->_context);
// get user submitted values
// get it from controller only if form has been submitted, else preProcess has set this
if (!empty($_POST) && !$this->controller->isModal()) {
$this->_formValues = $this->controller->exportValues($this->_name);
}
else {
$this->_formValues = $this->get('formValues');
}
if (empty($this->_formValues)) {
if (isset($this->_ssID)) {
$this->_formValues = CRM_Contact_BAO_SavedSearch::getFormValues($this->_ssID);
}
}
if ($this->_force) {
$this->postProcess();
$this->set('force', 0);
}
$sortID = NULL;
if ($this->get(CRM_Utils_Sort::SORT_ID)) {
$sortID = CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID),
$this->get(CRM_Utils_Sort::SORT_DIRECTION)
);
}
$this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues, 0, FALSE, NULL, array('event_id'));
$selector = new CRM_Event_Selector_Search($this->_queryParams,
$this->_action,
NULL,
$this->_single,
$this->_limit,
$this->_context
);
$prefix = NULL;
if ($this->_context == 'user') {
$prefix = $this->_prefix;
}
$this->assign("{$prefix}limit", $this->_limit);
$this->assign("{$prefix}single", $this->_single);
$controller = new CRM_Core_Selector_Controller($selector,
$this->get(CRM_Utils_Pager::PAGE_ID),
$sortID,
CRM_Core_Action::VIEW,
$this,
CRM_Core_Selector_Controller::TRANSFER,
$prefix
);
$controller->setEmbedded(TRUE);
$controller->moveFromSessionToTemplate();
$this->assign('summary', $this->get('summary'));
}
/**
* Build the form object.
*
*
* @return void
*/
public function buildQuickForm() {
parent::buildQuickForm();
$this->addSortNameField();
if (CRM_Core_Permission::check('access deleted contacts') and Civi::settings()->get('contact_undelete')) {
$this->addElement('checkbox', 'deleted_contacts', ts('Search in Trash') . '<br />' . ts('(deleted contacts)'));
}
CRM_Event_BAO_Query::buildSearchForm($this);
$rows = $this->get('rows');
if (is_array($rows)) {
$lineItems = $eventIds = array();
if (!$this->_single) {
$this->addRowSelectors($rows);
}
foreach ($rows as $row) {
$eventIds[$row['event_id']] = $row['event_id'];
if (CRM_Event_BAO_Event::usesPriceSet($row['event_id'])) {
// add line item details if applicable
$lineItems[$row['participant_id']] = CRM_Price_BAO_LineItem::getLineItems($row['participant_id']);
}
}
//get actual count only when we are dealing w/ single event.
$participantCount = 0;
if (count($eventIds) == 1) {
//convert form values to clause.
$seatClause = array();
if (CRM_Utils_Array::value('participant_test', $this->_formValues) == '1' || CRM_Utils_Array::value('participant_test', $this->_formValues) == '0') {
$seatClause[] = "( participant.is_test = {$this->_formValues['participant_test']} )";
}
if (!empty($this->_formValues['participant_status_id'])) {
$seatClause[] = CRM_Contact_BAO_Query::buildClause("participant.status_id", '=', $this->_formValues['participant_status_id'], 'Int');
if ($status = CRM_Utils_Array::value('IN', $this->_formValues['participant_status_id'])) {
$this->_formValues['participant_status_id'] = $status;
}
}
if (!empty($this->_formValues['participant_role_id'])) {
$escapedRoles = array();
foreach ((array) $this->_formValues['participant_role_id'] as $participantRole) {
$escapedRoles[] = CRM_Utils_Type::escape($participantRole, 'String');
}
$seatClause[] = "( participant.role_id IN ( '" . implode("' , '", $escapedRoles) . "' ) )";
}
// CRM-15379
if (!empty($this->_formValues['participant_fee_id'])) {
$participant_fee_id = $this->_formValues['participant_fee_id'];
foreach ($participant_fee_id as $k => &$val) {
$val = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $val, 'label');
$val = CRM_Core_DAO::escapeString(trim($val));
}
$feeLabel = implode('|', $participant_fee_id);
$seatClause[] = "( participant.fee_level REGEXP '{$feeLabel}' )";
}
$seatClause = implode(' AND ', $seatClause);
$participantCount = CRM_Event_BAO_Event::eventTotalSeats(array_pop($eventIds), $seatClause);
}
$this->assign('participantCount', $participantCount);
$this->assign('lineItems', $lineItems);
$permission = CRM_Core_Permission::getPermission();
$tasks = CRM_Event_Task::permissionedTaskTitles($permission);
if (isset($this->_ssID)) {
if ($permission == CRM_Core_Permission::EDIT) {
$tasks = $tasks + CRM_Event_Task::optionalTaskTitle();
}
$savedSearchValues = array(
'id' => $this->_ssID,
'name' => CRM_Contact_BAO_SavedSearch::getName($this->_ssID, 'title'),
);
$this->assign_by_ref('savedSearch', $savedSearchValues);
$this->assign('ssID', $this->_ssID);
}
$this->addTaskMenu($tasks);
}
}
/**
* Get the label for the sortName field if email searching is on.
*
* (email searching is a setting under search preferences).
*
* @return string
*/
protected function getSortNameLabelWithEmail() {
return ts('Participant Name or Email');
}
/**
* Get the label for the sortName field if email searching is off.
*
* (email searching is a setting under search preferences).
*
* @return string
*/
protected function getSortNameLabelWithOutEmail() {
return ts('Participant Name');
}
/**
* The post processing of the form gets done here.
*
* Key things done during post processing are
* - check for reset or next request. if present, skip post procesing.
* - now check if user requested running a saved search, if so, then
* the form values associated with the saved search are used for searching.
* - if user has done a submit with new values the regular post submissing is
* done.
* The processing consists of using a Selector / Controller framework for getting the
* search results.
*
* @param
*
* @return void
*/
public function postProcess() {
if ($this->_done) {
return;
}
$this->_done = TRUE;
if (!empty($_POST)) {
$this->_formValues = $this->controller->exportValues($this->_name);
CRM_Contact_BAO_Query::processSpecialFormValue($this->_formValues, array('participant_status_id'));
}
if (empty($this->_formValues)) {
$this->_formValues = $this->controller->exportValues($this->_name);
}
$this->fixFormValues();
if (isset($this->_ssID) && empty($_POST)) {
// if we are editing / running a saved search and the form has not been posted
$this->_formValues = CRM_Contact_BAO_SavedSearch::getFormValues($this->_ssID);
}
// We don't show test records in summaries or dashboards
if (empty($this->_formValues['participant_test']) && $this->_force) {
$this->_formValues["participant_test"] = 0;
}
CRM_Core_BAO_CustomValue::fixCustomFieldValue($this->_formValues);
$this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues, 0, FALSE, NULL, array('event_id'));
$this->set('formValues', $this->_formValues);
$this->set('queryParams', $this->_queryParams);
$buttonName = $this->controller->getButtonName();
if ($buttonName == $this->_actionButtonName) {
// check actionName and if next, then do not repeat a search, since we are going to the next page
// hack, make sure we reset the task values
$stateMachine = $this->controller->getStateMachine();
$formName = $stateMachine->getTaskFormName();
$this->controller->resetPage($formName);
return;
}
$sortID = NULL;
if ($this->get(CRM_Utils_Sort::SORT_ID)) {
$sortID = CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID),
$this->get(CRM_Utils_Sort::SORT_DIRECTION)
);
}
$this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues, 0, FALSE, NULL, array('event_id'));
$selector = new CRM_Event_Selector_Search($this->_queryParams,
$this->_action,
NULL,
$this->_single,
$this->_limit,
$this->_context
);
$selector->setKey($this->controller->_key);
$prefix = NULL;
if ($this->_context == 'user') {
$prefix = $this->_prefix;
}
$this->assign("{$prefix}limit", $this->_limit);
$this->assign("{$prefix}single", $this->_single);
$controller = new CRM_Core_Selector_Controller($selector,
$this->get(CRM_Utils_Pager::PAGE_ID),
$sortID,
CRM_Core_Action::VIEW,
$this,
CRM_Core_Selector_Controller::SESSION,
$prefix
);
$controller->setEmbedded(TRUE);
$query = $selector->getQuery();
if ($this->_context == 'user') {
$query->setSkipPermission(TRUE);
}
$controller->run();
}
/**
* add the rules (mainly global rules) for form.
* All local rules are added near the element
*
* @return void
* @see valid_date
*/
public function addRules() {
}
/**
* Set the default form values.
*
*
* @return array
* the default array reference
*/
public function setDefaultValues() {
$defaults = array();
$defaults = $this->_formValues;
return $defaults;
}
public function fixFormValues() {
// if this search has been forced
// then see if there are any get values, and if so over-ride the post values
// note that this means that GET over-rides POST :)
$event = CRM_Utils_Request::retrieve('event', 'Positive');
if ($event) {
$this->_formValues['event_id'] = $event;
$this->_formValues['event_name'] = CRM_Event_PseudoConstant::event($event, TRUE);
}
$status = CRM_Utils_Request::retrieve('status', 'String');
if (isset($status)) {
if ($status === 'true') {
$statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, "is_counted = 1");
}
elseif ($status === 'false') {
$statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, "is_counted = 0");
}
elseif (is_numeric($status)) {
$statusTypes = (int) $status;
}
elseif (is_array($status) && !array_key_exists('IN', $status)) {
$statusTypes = array_keys($status);
}
$this->_formValues['participant_status_id'] = is_array($statusTypes) ? array('IN' => array_keys($statusTypes)) : $statusTypes;
}
$role = CRM_Utils_Request::retrieve('role', 'String');
if (isset($role)) {
if ($role === 'true') {
$roleTypes = CRM_Event_PseudoConstant::participantRole(NULL, "filter = 1");
}
elseif ($role === 'false') {
$roleTypes = CRM_Event_PseudoConstant::participantRole(NULL, "filter = 0");
}
elseif (is_numeric($role)) {
$roleTypes = (int) $role;
}
$this->_formValues['participant_role_id'] = is_array($roleTypes) ? array_keys($roleTypes) : $roleTypes;
}
$type = CRM_Utils_Request::retrieve('type', 'Positive');
if ($type) {
$this->_formValues['event_type'] = $type;
}
$cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
if ($cid) {
$cid = CRM_Utils_Type::escape($cid, 'Integer');
if ($cid > 0) {
$this->_formValues['contact_id'] = $cid;
// also assign individual mode to the template
$this->_single = TRUE;
}
}
}
/**
* @return null
*/
public function getFormValues() {
return NULL;
}
/**
* Return a descriptive name for the page, used in wizard header
*
* @return string
*/
public function getTitle() {
return ts('Find Participants');
}
}

View file

@ -0,0 +1,116 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
class CRM_Event_Form_SearchEvent extends CRM_Core_Form {
/**
* Explicitly declare the entity api name.
*/
public function getDefaultEntity() {
return 'Event';
}
/**
* @return array
*/
public function setDefaultValues() {
$defaults = array();
$defaults['eventsByDates'] = 0;
$this->_showHide = new CRM_Core_ShowHideBlocks();
if (empty($defaults['eventsByDates'])) {
$this->_showHide->addHide('id_fromToDates');
}
$this->_showHide->addToTemplate();
return $defaults;
}
/**
* Build the form object.
*
*
* @return void
*/
public function buildQuickForm() {
$this->add('text', 'title', ts('Find'),
array(CRM_Core_DAO::getAttribute('CRM_Event_DAO_Event', 'title'))
);
$this->addSelect('event_type_id', array('multiple' => TRUE, 'context' => 'search'));
$eventsByDates = array();
$searchOption = array(ts('Show Current and Upcoming Events'), ts('Search All or by Date Range'));
$this->addRadio('eventsByDates', ts('Events by Dates'), $searchOption, array('onclick' => "return showHideByValue('eventsByDates','1','id_fromToDates','block','radio',true);"), "<br />");
$this->addDate('start_date', ts('From'), FALSE, array('formatType' => 'searchDate'));
$this->addDate('end_date', ts('To'), FALSE, array('formatType' => 'searchDate'));
CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($this);
$this->addButtons(array(
array(
'type' => 'refresh',
'name' => ts('Search'),
'isDefault' => TRUE,
),
));
}
public function postProcess() {
$params = $this->controller->exportValues($this->_name);
$parent = $this->controller->getParent();
$parent->set('searchResult', 1);
if (!empty($params)) {
$fields = array('title', 'event_type_id', 'start_date', 'end_date', 'eventsByDates', 'campaign_id');
foreach ($fields as $field) {
if (isset($params[$field]) &&
!CRM_Utils_System::isNull($params[$field])
) {
if (substr($field, -4) == 'date') {
$time = ($field == 'end_date') ? '235959' : NULL;
$parent->set($field, CRM_Utils_Date::processDate($params[$field], $time));
}
else {
$parent->set($field, $params[$field]);
}
}
else {
$parent->set($field, NULL);
}
}
}
}
}

View file

@ -0,0 +1,529 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class generates form components to transfer an Event to another participant
*
*/
class CRM_Event_Form_SelfSvcTransfer extends CRM_Core_Form {
/**
* from particpant id
*
* @var string
*
*/
protected $_from_participant_id;
/**
* from contact id
*
* @var string
*
*/
protected $_from_contact_id;
/**
* last name of the particpant to transfer to
*
* @var string
*
*/
protected $_to_contact_last_name;
/**
* first name of the particpant to transfer to
*
* @var string
*
*/
protected $_to_contact_first_name;
/**
* email of participant
*
*
* @var string
*/
protected $_to_contact_email;
/**
* _to_contact_id
*
* @var string
*/
protected $_to_contact_id;
/**
* event to be cancelled/transferred
*
* @var string
*/
protected $_event_id;
/**
* event title
*
* @var string
*/
protected $_event_title;
/**
* event title
*
* @var string
*/
protected $_event_start_date;
/**
* action
*
* @var string
*/
public $_action;
/**
* participant object
*
* @var string
*/
protected $_participant = array();
/**
* particpant values
*
* @array string
*/
protected $_part_values;
/**
* details
*
* @array string
*/
protected $_details = array();
/**
* line items
*
* @array string
*/
protected $_line_items = array();
/**
* contact_id
*
* @array string
*/
protected $contact_id;
/**
* Get source values for transfer based on participant id in URL. Line items will
* be transferred to this participant - at this point no transaction changes processed
*
* return @void
*/
public function preProcess() {
$config = CRM_Core_Config::singleton();
$session = CRM_Core_Session::singleton();
$this->_userContext = $session->readUserContext();
$this->_from_participant_id = CRM_Utils_Request::retrieve('pid', 'Positive', $this, FALSE, NULL, 'REQUEST');
$this->_userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this, FALSE, NULL, 'REQUEST');
$params = array('id' => $this->_from_participant_id);
$participant = $values = array();
$this->_participant = CRM_Event_BAO_Participant::getValues($params, $values, $participant);
$this->_part_values = $values[$this->_from_participant_id];
$this->set('values', $this->_part_values);
$this->_event_id = $this->_part_values['event_id'];
$url = CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$this->_event_id}");
$this->_from_contact_id = $this->_part_values['participant_contact_id'];
$validUser = CRM_Contact_BAO_Contact_Utils::validChecksum($this->_from_contact_id, $this->_userChecksum);
if (!$validUser && !CRM_Core_Permission::check('edit all events')) {
CRM_Core_Error::statusBounce(ts('You do not have sufficient permission to transfer/cancel this participant.'), $url);
}
$this->assign('action', $this->_action);
if ($this->_from_participant_id) {
$this->assign('participantId', $this->_from_participant_id);
}
$event = array();
$daoName = 'title';
$this->_event_title = CRM_Event_BAO_Event::getFieldValue('CRM_Event_DAO_Event', $this->_event_id, $daoName);
$daoName = 'start_date';
$this->_event_start_date = CRM_Event_BAO_Event::getFieldValue('CRM_Event_DAO_Event', $this->_event_id, $daoName);
list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_from_contact_id);
$this->_contact_name = $displayName;
$this->_contact_email = $email;
$details = array();
$details = CRM_Event_BAO_Participant::participantDetails($this->_from_participant_id);
$optionGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'participant_role', 'id', 'name');
$query = "
SELECT cpst.name as status, cov.name as role, cp.fee_level, cp.fee_amount, cp.register_date, civicrm_event.start_date
FROM civicrm_participant cp
LEFT JOIN civicrm_participant_status_type cpst ON cpst.id = cp.status_id
LEFT JOIN civicrm_option_value cov ON cov.value = cp.role_id and cov.option_group_id = {$optionGroupId}
LEFT JOIN civicrm_event ON civicrm_event.id = cp.event_id
WHERE cp.id = {$this->_from_participant_id}";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$details['status'] = $dao->status;
$details['role'] = $dao->role;
$details['fee_level'] = $dao->fee_level;
$details['fee_amount'] = $dao->fee_amount;
$details['register_date'] = $dao->register_date;
$details['event_start_date'] = $dao->start_date;
}
$this->assign('details', $details);
//This participant row will be cancelled. Get line item(s) to cancel
$this->selfsvctransferUrl = CRM_Utils_System::url('civicrm/event/selfsvcupdate',
"reset=1&id={$this->_from_participant_id}&id=0");
$this->selfsvctransferText = ts('Update');
$this->selfsvctransferButtonText = ts('Update');
}
/**
* Build form for input of transferree email, name
*
* return @void
*/
public function buildQuickForm() {
$this->add('text', 'email', ts('To Email'), ts($this->_contact_email), TRUE);
$this->add('text', 'last_name', ts('To Last Name'), ts($this->_to_contact_last_name), TRUE);
$this->add('text', 'first_name', ts('To First Name'), ts($this->_to_contact_first_name), TRUE);
$this->addButtons(array(
array(
'type' => 'submit',
'name' => ts('Transfer Registration'),),
)
);
$this->addFormRule(array('CRM_Event_Form_SelfSvcTransfer', 'formRule'), $this);
parent::buildQuickForm();
}
/**
* Set defaults
*
* return @array _defaults
*/
public function setDefaultValues() {
$this->_defaults = array();
return $this->_defaults;
}
/**
* Validate email and name input
*
* return array $errors
*/
public static function formRule($fields, $files, $self) {
$errors = array();
//check that either an email or firstname+lastname is included in the form(CRM-9587)
$to_contact_id = self::checkProfileComplete($fields, $errors, $self);
//To check if the user is already registered for the event(CRM-2426)
if ($to_contact_id) {
self::checkRegistration($fields, $self, $to_contact_id, $errors);
}
//return parent::formrule($fields, $files, $self);
return empty($errors) ? TRUE : $errors;
}
/**
* Check whether profile (name, email) is complete
*
* return $contact_id
*/
public static function checkProfileComplete($fields, &$errors, $self) {
$email = '';
foreach ($fields as $fieldname => $fieldvalue) {
if (substr($fieldname, 0, 5) == 'email' && $fieldvalue) {
$email = $fieldvalue;
}
}
if (!$email && !(CRM_Utils_Array::value('first_name', $fields) &&
CRM_Utils_Array::value('last_name', $fields))) {
$defaults = $params = array('id' => $eventId);
CRM_Event_BAO_Event::retrieve($params, $defaults);
$message = ts("Mandatory fields (first name and last name, OR email address) are missing from this form.");
$errors['_qf_default'] = $message;
}
$contact = CRM_Contact_BAO_Contact::matchContactOnEmail($email, "");
$contact_id = empty($contact->contact_id) ? NULL : $contact->contact_id;
if (!CRM_Utils_Rule::email($fields['email'])) {
$errors['email'] = ts('Enter valid email address.');
}
if (empty($errors) && empty($contact_id)) {
$params = array(
'email-Primary' => CRM_Utils_Array::value('email', $fields, NULL),
'first_name' => CRM_Utils_Array::value('first_name', $fields, NULL),
'last_name' => CRM_Utils_Array::value('last_name', $fields, NULL),
'is_deleted' => CRM_Utils_Array::value('is_deleted', $fields, FALSE),);
//create new contact for this name/email pair
//if new contact, no need to check for contact already registered
$contact_id = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $contact_id);
}
return $contact_id;
}
/**
* Check contact details
*
* return @void
*/
public static function checkRegistration($fields, $self, $contact_id, &$errors) {
// verify whether this contact already registered for this event
$contact_details = CRM_Contact_BAO_Contact::getContactDetails($contact_id);
$display_name = $contact_details[0];
$query = "select event_id from civicrm_participant where contact_id = " . $contact_id;
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$to_event_id[] = $dao->event_id;
}
if (!empty($to_event_id)) {
foreach ($to_event_id as $id) {
if ($id == $self->_event_id) {
$errors['email'] = $display_name . ts(" is already registered for this event");
}
}
}
}
/**
* Process transfer - first add the new participant to the event, then cancel
* source participant - send confirmation email to transferee
*/
public function postProcess() {
//For transfer, process form to allow selection of transferree
$params = $this->controller->exportValues($this->_name);
//cancel 'from' participant row
$query = "select contact_id from civicrm_email where email = '" . $params['email'] . "'";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$contact_id = $dao->contact_id;
}
$from_participant = $params = array();
$query = "select role_id, source, fee_level, is_test, is_pay_later, fee_amount, discount_id, fee_currency,campaign_id, discount_amount from civicrm_participant where id = " . $this->_from_participant_id;
$dao = CRM_Core_DAO::executeQuery($query);
$value_to = array();
while ($dao->fetch()) {
$value_to['role_id'] = $dao->role_id;
$value_to['source'] = $dao->source;
$value_to['fee_level'] = $dao->fee_level;
$value_to['is_test'] = $dao->is_test;
$value_to['is_pay_later'] = $dao->is_pay_later;
$value_to['fee_amount'] = $dao->fee_amount;
}
$value_to['contact_id'] = $contact_id;
$value_to['event_id'] = $this->_event_id;
$value_to['status_id'] = 1;
$value_to['register_date'] = date("Y-m-d");
//first create the new participant row -don't set registered_by yet or email won't be sent
$participant = CRM_Event_BAO_Participant::create($value_to);
//send a confirmation email to the new participant
$this->participantTransfer($participant);
//now update registered_by_id
$query = "UPDATE civicrm_participant cp SET cp.registered_by_id = %1 WHERE cp.id = ({$participant->id})";
$params = array(1 => array($this->_from_participant_id, 'Integer'));
$dao = CRM_Core_DAO::executeQuery($query, $params);
//copy line items to new participant
$line_items = CRM_Price_BAO_LineItem::getLineItems($this->_from_participant_id);
foreach ($line_items as $item) {
$item['entity_id'] = $participant->id;
$item['id'] = NULL;
$item['entity_table'] = "civicrm_participant";
$new_item = CRM_Price_BAO_LineItem::create($item);
}
//now cancel the from participant record, leaving the original line-item(s)
$value_from = array();
$value_from['id'] = $this->_from_participant_id;
$tansferId = array_search('Transferred', CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'"));
$value_from['status_id'] = $tansferId;
$value_from['transferred_to_contact_id'] = $contact_id;
$contact_details = CRM_Contact_BAO_Contact::getContactDetails($contact_id);
$display_name = current($contact_details);
$this->assign('to_participant', $display_name);
CRM_Event_BAO_Participant::create($value_from);
$this->sendCancellation();
list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contact_id);
$statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $displayName));
$statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $email));
CRM_Core_Session::setStatus($statusMsg, ts('Registration Transferred'), 'success');
$url = CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$this->_event_id}");
CRM_Utils_System::redirect($url);
}
/**
* Based on input, create participant row for transferee and send email
*
* return @ void
*/
public function participantTransfer($participant) {
$contactDetails = array();
$contactIds[] = $participant->contact_id;
list($currentContactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL,
FALSE, FALSE, NULL, array(), 'CRM_Event_BAO_Participant');
foreach ($currentContactDetails as $contactId => $contactValues) {
$contactDetails[$contactId] = $contactValues;
}
$participantRoles = CRM_Event_PseudoConstant::participantRole();
$participantDetails = array();
$query = "SELECT * FROM civicrm_participant WHERE id = " . $participant->id;
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$participantDetails[$dao->id] = array(
'id' => $dao->id,
'role' => $participantRoles[$dao->role_id],
'is_test' => $dao->is_test,
'event_id' => $dao->event_id,
'status_id' => $dao->status_id,
'fee_amount' => $dao->fee_amount,
'contact_id' => $dao->contact_id,
'register_date' => $dao->register_date,
'registered_by_id' => $dao->registered_by_id,
);
}
$domainValues = array();
if (empty($domainValues)) {
$domain = CRM_Core_BAO_Domain::getDomain();
$tokens = array(
'domain' =>
array(
'name',
'phone',
'address',
'email',
),
'contact' => CRM_Core_SelectValues::contactTokens(),
);
foreach ($tokens['domain'] as $token) {
$domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
}
}
$eventDetails = array();
$eventParams = array('id' => $participant->event_id);
CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails);
//get default participant role.
$eventDetails['participant_role'] = CRM_Utils_Array::value($eventDetails['default_role_id'], $participantRoles);
//get the location info
$locParams = array(
'entity_id' => $participant->event_id,
'entity_table' => 'civicrm_event',
);
$eventDetails['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE);
$toEmail = CRM_Utils_Array::value('email', $contactDetails[$participant->contact_id]);
if ($toEmail) {
//take a receipt from as event else domain.
$receiptFrom = $domainValues['name'] . ' <' . $domainValues['email'] . '>';
if (!empty($eventDetails['confirm_from_name']) && !empty($eventDetails['confirm_from_email'])) {
$receiptFrom = $eventDetails['confirm_from_name'] . ' <' . $eventDetails['confirm_from_email'] . '>';
}
$participantName = $contactDetails[$participant->contact_id]['display_name'];
$tplParams = array(
'event' => $eventDetails,
'participant' => $participantDetails[$participant->id],
'participantID' => $participant->id,
'participant_status' => 'Registered',
);
$sendTemplateParams = array(
'groupName' => 'msg_tpl_workflow_event',
'valueName' => 'event_online_receipt',
'contactId' => $participantDetails[$participant->id]['contact_id'],
'tplParams' => $tplParams,
'from' => $receiptFrom,
'toName' => $participantName,
'toEmail' => $toEmail,
'cc' => CRM_Utils_Array::value('cc_confirm', $eventDetails),
'bcc' => CRM_Utils_Array::value('bcc_confirm', $eventDetails),
);
CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
}
}
/**
* Send confirmation of cancellation to source participant
*
* return @ void
*/
public function sendCancellation() {
$domainValues = array();
$domain = CRM_Core_BAO_Domain::getDomain();
$tokens = array(
'domain' =>
array(
'name',
'phone',
'address',
'email',
),
'contact' => CRM_Core_SelectValues::contactTokens(),
);
foreach ($tokens['domain'] as $token) {
$domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
}
$participantRoles = array();
$participantRoles = CRM_Event_PseudoConstant::participantRole();
$participantDetails = array();
$query = "SELECT * FROM civicrm_participant WHERE id = {$this->_from_participant_id}";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$participantDetails[$dao->id] = array(
'id' => $dao->id,
'role' => $participantRoles[$dao->role_id],
'is_test' => $dao->is_test,
'event_id' => $dao->event_id,
'status_id' => $dao->status_id,
'fee_amount' => $dao->fee_amount,
'contact_id' => $dao->contact_id,
'register_date' => $dao->register_date,
'registered_by_id' => $dao->registered_by_id,
);
}
$eventDetails = array();
$eventParams = array('id' => $this->_event_id);
CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails[$this->_event_id]);
//get default participant role.
$eventDetails[$this->_event_id]['participant_role'] = CRM_Utils_Array::value($eventDetails[$this->_event_id]['default_role_id'], $participantRoles);
//get the location info
$locParams = array('entity_id' => $this->_event_id, 'entity_table' => 'civicrm_event');
$eventDetails[$this->_event_id]['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE);
//get contact details
$contactIds[$this->_from_contact_id] = $this->_from_contact_id;
list($currentContactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL,
FALSE, FALSE, NULL, array(),
'CRM_Event_BAO_Participant'
);
foreach ($currentContactDetails as $contactId => $contactValues) {
$contactDetails[$this->_from_contact_id] = $contactValues;
}
//send a 'cancelled' email to user, and cc the event's cc_confirm email
$mail = CRM_Event_BAO_Participant::sendTransitionParticipantMail($this->_from_participant_id,
$participantDetails[$this->_from_participant_id],
$eventDetails[$this->_event_id],
$contactDetails[$this->_from_contact_id],
$domainValues,
"Transferred",
""
);
$statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contact_name));
$statusMsg .= ' ' . ts('A cancellation email has been sent to %1.', array(1 => $this->_contact_email));
CRM_Core_Session::setStatus($statusMsg, ts('Thanks'), 'success');
}
}

View file

@ -0,0 +1,365 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class generates form components to allow an Event to be cancelled or transferred from an email link
*
*/
class CRM_Event_Form_SelfSvcUpdate extends CRM_Core_Form {
/**
* particpant id
*
* @var string
*
*/
protected $_participant_id;
/**
* contact id
*
* @var string
*
*/
protected $_contact_id;
/**
* name of the particpant
*
* @var string
*
*/
protected $_contact_name;
/**
* email of participant
*
* @var string
*/
protected $_contact_email;
/**
* event to be cancelled/transferred
*
* @var string
*/
protected $_event_id;
/**
* event title
*
* @var string
*/
protected $_event_title;
/**
* event title
*
* @var string
*/
protected $_event_start_date;
/**
* action
*
* @var string
*/
public $_action;
/**
* participant object
*
* @var string
*/
protected $_participant = array();
/**
* particpant values
*
* @var string
*/
protected $_part_values;
/**
* details of event registration values
*
* @var array
*/
protected $_details = array();
/**
* Set variables up before form is built based on participant ID from URL
*
* @return void
*/
public function preProcess() {
$config = CRM_Core_Config::singleton();
$session = CRM_Core_Session::singleton();
$this->_userContext = $session->readUserContext();
$participant = $values = array();
$this->_participant_id = CRM_Utils_Request::retrieve('pid', 'Positive', $this, FALSE, NULL, 'REQUEST');
$this->_userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this, FALSE, NULL, 'REQUEST');
$params = array('id' => $this->_participant_id);
$this->_participant = CRM_Event_BAO_Participant::getValues($params, $values, $participant);
$this->_part_values = $values[$this->_participant_id];
$this->set('values', $this->_part_values);
//fetch Event by event_id, verify that this event can still be xferred/cancelled
$this->_event_id = $this->_part_values['event_id'];
$url = CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$this->_event_id}");
$this->_contact_id = $this->_part_values['participant_contact_id'];
$validUser = CRM_Contact_BAO_Contact_Utils::validChecksum($this->_contact_id, $this->_userChecksum);
if (!$validUser && !CRM_Core_Permission::check('edit all events')) {
CRM_Core_Error::statusBounce(ts('You do not have sufficient permission to transfer/cancel this participant.'), $url);
}
$this->assign('action', $this->_action);
if ($this->_participant_id) {
$this->assign('participantId', $this->_participant_id);
}
$event = array();
$daoName = 'title';
$this->_event_title = CRM_Event_BAO_Event::getFieldValue('CRM_Event_DAO_Event', $this->_event_id, $daoName);
$daoName = 'start_date';
$this->_event_start_date = CRM_Event_BAO_Event::getFieldValue('CRM_Event_DAO_Event', $this->_event_id, $daoName);
list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contact_id);
$this->_contact_name = $displayName;
$this->_contact_email = $email;
$details = array();
$details = CRM_Event_BAO_Participant::participantDetails($this->_participant_id);
$optionGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'participant_role', 'id', 'name');
$contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_participant_id, 'contribution_id', 'participant_id');
$this->assign('contributionId', $contributionId);
$query = "
SELECT cpst.name as status, cov.name as role, cp.fee_level, cp.fee_amount, cp.register_date, cp.status_id, civicrm_event.start_date
FROM civicrm_participant cp
LEFT JOIN civicrm_participant_status_type cpst ON cpst.id = cp.status_id
LEFT JOIN civicrm_option_value cov ON cov.value = cp.role_id and cov.option_group_id = {$optionGroupId}
LEFT JOIN civicrm_event ON civicrm_event.id = cp.event_id
WHERE cp.id = {$this->_participant_id}";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$details['status'] = $dao->status;
$details['role'] = $dao->role;
$details['fee_level'] = $dao->fee_level;
$details['fee_amount'] = $dao->fee_amount;
$details['register_date'] = $dao->register_date;
$details['event_start_date'] = $dao->start_date;
}
//verify participant status is still Registered
if ($details['status'] != "Registered") {
$status = "You cannot transfer or cancel your registration for " . $this->_event_title . ' as you are not currently registered for this event.';
CRM_Core_Session::setStatus($status, ts('Sorry'), 'alert');
CRM_Utils_System::redirect($url);
}
$query = "select start_date as start, selfcancelxfer_time as time from civicrm_event where id = " . $this->_event_id;
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$time_limit = $dao->time;
$start_date = $dao->start;
}
$start_time = new Datetime($start_date);
$timenow = new Datetime();
if (!empty($start_time) && $start_time < $timenow) {
$status = ts("Registration for this event cannot be cancelled or transferred once the event has begun. Contact the event organizer if you have questions.");
CRM_Core_Error::statusBounce($status, $url, ts('Sorry'));
}
if (!empty($time_limit) && $time_limit > 0) {
$interval = $timenow->diff($start_time);
$days = $interval->format('%d');
$hours = $interval->format('%h');
if ($hours <= $time_limit && $days < 1) {
$status = ts("Registration for this event cannot be cancelled or transferred less than %1 hours prior to the event's start time. Contact the event organizer if you have questions.", array(1 => $time_limit));
CRM_Core_Error::statusBounce($status, $url, ts('Sorry'));
}
}
$this->assign('details', $details);
$this->selfsvcupdateUrl = CRM_Utils_System::url('civicrm/event/selfsvcupdate', "reset=1&id={$this->_participant_id}&id=0");
$this->selfsvcupdateText = ts('Update');
$this->selfsvcupdateButtonText = ts('Update');
// Based on those ids retrieve event and verify it is eligible
// for self update (event.start_date > today, event can be 'self_updated'
// retrieve contact name and email, and let user verify his/her identity
}
/**
* buildQuickForm -populate input variables for source Event
* to cancel or transfer to another person
*
* return @void
*/
public function buildQuickForm() {
$this->add('select', 'action', ts('Transfer or Cancel Registration'), array(ts('-select-'), ts('Transfer'), ts('Cancel')), TRUE);
$this->addButtons(array(
array(
'type' => 'submit',
'name' => ts('Submit'),
),
));
$this->addFormRule(array('CRM_Event_Form_SelfSvcUpdate', 'formRule'), $this);
parent::buildQuickForm();
}
/**
* Set default values for contact
*
* return @void
*/
public function setDefaultValues() {
$this->_defaults = array();
$this->_defaults['details'] = $this->_details;
return $this->_defaults;
}
/**
* Validate action input
* @param array $fields
* Posted fields of the form.
* @param $files
* @param $self
*
* @return array
* list of errors to be posted back to the form
*/
public static function formRule($fields, $files, $self) {
$errors = array();
if (empty($fields['action'])) {
$errors['action'] = ts("Please select Transfer OR Cancel action.");
}
return empty($errors) ? TRUE : $errors;
}
/**
* Process submit form - based on user selection of action
* transfer or cancel the event
*
* return @void
*/
public function postProcess() {
//if selection is cancel, cancel this participant' registration, process refund
//if transfer, process form to allow selection of transferree
$params = $this->controller->exportValues($this->_name);
$action = $params['action'];
if ($action == "1") {
$action = "Transfer Event";
$this->transferParticipant($params);
}
elseif ($action == "2") {
$action = "Cancel Event";
$this->cancelParticipant($params);
}
}
/**
* Transfer to a new form, allowing selection of a new contact
* based on email and name. The Event will be transferred to this new participant
*
* return @void
*/
public function transferParticipant($params) {
$transferUrl = 'civicrm/event/form/selfsvctransfer';
$url = CRM_Utils_System::url('civicrm/event/selfsvctransfer', 'reset=1&action=add&pid=' . $this->_participant_id . '&cs=' . $this->_userChecksum);
$this->controller->setDestination($url);
$session = CRM_Core_Session::singleton();
$session->replaceUserContext($url);
}
/**
* Cancel this participant and finish, send cancellation email. At this point no
* auto-cancellation of payment is handled, so payment needs to be manually cancelled
*
* return @void
*/
public function cancelParticipant($params) {
//set participant record status to Cancelled, refund payment if possible
// send email to participant and admin, and log Activity
$value = array();
$value['id'] = $this->_participant_id;
$cancelledId = array_search('Cancelled',
CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'"));
$value['status_id'] = $cancelledId;
CRM_Event_BAO_Participant::create($value);
$domainValues = array();
$domain = CRM_Core_BAO_Domain::getDomain();
$tokens = array(
'domain' =>
array(
'name',
'phone',
'address',
'email',
),
'contact' => CRM_Core_SelectValues::contactTokens(),
);
foreach ($tokens['domain'] as $token) {
$domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
}
$participantRoles = array();
$participantRoles = CRM_Event_PseudoConstant::participantRole();
$participantDetails = array();
$query = "SELECT * FROM civicrm_participant WHERE id = {$this->_participant_id}";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$participantDetails[$dao->id] = array(
'id' => $dao->id,
'role' => $participantRoles[$dao->role_id],
'is_test' => $dao->is_test,
'event_id' => $dao->event_id,
'status_id' => $dao->status_id,
'fee_amount' => $dao->fee_amount,
'contact_id' => $dao->contact_id,
'register_date' => $dao->register_date,
'registered_by_id' => $dao->registered_by_id,
);
}
$eventDetails = array();
$eventParams = array('id' => $this->_event_id);
CRM_Event_BAO_Event::retrieve($eventParams, $eventDetails[$this->_event_id]);
//get default participant role.
$eventDetails[$this->_event_id]['participant_role'] = CRM_Utils_Array::value($eventDetails[$this->_event_id]['default_role_id'], $participantRoles);
//get the location info
$locParams = array('entity_id' => $this->_event_id, 'entity_table' => 'civicrm_event');
$eventDetails[$this->_event_id]['location'] = CRM_Core_BAO_Location::getValues($locParams, TRUE);
//get contact details
$contactIds[$this->_contact_id] = $this->_contact_id;
list($currentContactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL,
FALSE, FALSE, NULL, array(),
'CRM_Event_BAO_Participant'
);
foreach ($currentContactDetails as $contactId => $contactValues) {
$contactDetails[$this->_contact_id] = $contactValues;
}
//send a 'cancelled' email to user, and cc the event's cc_confirm email
$mail = CRM_Event_BAO_Participant::sendTransitionParticipantMail($this->_participant_id,
$participantDetails[$this->_participant_id],
$eventDetails[$this->_event_id],
$contactDetails[$this->_contact_id],
$domainValues,
"Cancelled",
""
);
$statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contact_name));
$statusMsg .= ' ' . ts('A cancellation email has been sent to %1.', array(1 => $this->_contact_email));
CRM_Core_Session::setStatus($statusMsg, ts('Thanks'), 'success');
$url = CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$this->_event_id}&noFullMsg=true");
CRM_Utils_System::redirect($url);
}
}

View file

@ -0,0 +1,184 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class generates task actions for CiviEvent
*
*/
class CRM_Event_Form_Task extends CRM_Core_Form {
/**
* The task being performed.
*
* @var int
*/
protected $_task;
/**
* The additional clause that we restrict the search with.
*
* @var string
*/
protected $_componentClause = NULL;
/**
* The array that holds all the component ids.
*
* @var array
*/
protected $_componentIds;
/**
* The array that holds all the participant ids.
*
* @var array
*/
protected $_participantIds;
/**
* Build all the data structures needed to build the form.
*
* @param
*
* @return void
*/
public function preProcess() {
self::preProcessCommon($this);
}
/**
* @param CRM_Core_Form $form
* @param bool $useTable
*/
public static function preProcessCommon(&$form, $useTable = FALSE) {
$form->_participantIds = array();
$values = $form->controller->exportValues($form->get('searchFormName'));
$form->_task = $values['task'];
$eventTasks = CRM_Event_Task::tasks();
$form->assign('taskName', $eventTasks[$form->_task]);
$ids = array();
if ($values['radio_ts'] == 'ts_sel') {
foreach ($values as $name => $value) {
if (substr($name, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
$ids[] = substr($name, CRM_Core_Form::CB_PREFIX_LEN);
}
}
}
else {
$queryParams = $form->get('queryParams');
$sortOrder = NULL;
if ($form->get(CRM_Utils_Sort::SORT_ORDER)) {
$sortOrder = $form->get(CRM_Utils_Sort::SORT_ORDER);
}
$query = new CRM_Contact_BAO_Query($queryParams, NULL, NULL, FALSE, FALSE,
CRM_Contact_BAO_Query::MODE_EVENT
);
$query->_distinctComponentClause = "civicrm_participant.id";
$query->_groupByComponentClause = " GROUP BY civicrm_participant.id ";
$result = $query->searchQuery(0, 0, $sortOrder);
while ($result->fetch()) {
$ids[] = $result->participant_id;
}
}
if (!empty($ids)) {
$form->_componentClause = ' civicrm_participant.id IN ( ' . implode(',', $ids) . ' ) ';
$form->assign('totalSelectedParticipants', count($ids));
}
$form->_participantIds = $form->_componentIds = $ids;
//set the context for redirection for any task actions
$session = CRM_Core_Session::singleton();
$qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this);
$urlParams = 'force=1';
if (CRM_Utils_Rule::qfKey($qfKey)) {
$urlParams .= "&qfKey=$qfKey";
}
$searchFormName = strtolower($form->get('searchFormName'));
if ($searchFormName == 'search') {
$session->replaceUserContext(CRM_Utils_System::url('civicrm/event/search', $urlParams));
}
else {
$session->replaceUserContext(CRM_Utils_System::url("civicrm/contact/search/$searchFormName",
$urlParams
));
}
}
/**
* Given the participant id, compute the contact id
* since its used for things like send email
*/
public function setContactIDs() {
$this->_contactIds = &CRM_Core_DAO::getContactIDsFromComponent($this->_participantIds,
'civicrm_participant'
);
}
/**
* Simple shell that derived classes can call to add buttons to.
* the form with a customized title for the main Submit
*
* @param string $title
* Title of the main button.
* @param string $nextType
* @param string $backType
* @param bool $submitOnce
*
* @return void
*/
public function addDefaultButtons($title, $nextType = 'next', $backType = 'back', $submitOnce = FALSE) {
$this->addButtons(array(
array(
'type' => $nextType,
'name' => $title,
'isDefault' => TRUE,
),
array(
'type' => $backType,
'name' => ts('Cancel'),
),
)
);
}
}

View file

@ -0,0 +1,256 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class provides the functionality to group
* contacts. This class provides functionality for the actual
* addition of contacts to groups.
*/
class CRM_Event_Form_Task_AddToGroup extends CRM_Event_Form_Task {
/**
* The context that we are working on.
*
* @var string
*/
protected $_context;
/**
* The groupId retrieved from the GET vars.
*
* @var int
*/
protected $_id;
/**
* The title of the group.
*
* @var string
*/
protected $_title;
/**
* Build all the data structures needed to build the form.
*
* @return void
*/
public function preProcess() {
// initialize the task and row fields
parent::preProcess();
parent::setContactIDs();
$this->_context = $this->get('context');
$this->_id = $this->get('amtgID');
}
/**
* Build the form object.
*
*
* @return void
*/
public function buildQuickForm() {
//create radio buttons to select existing group or add a new group
$options = array(ts('Add Contact To Existing Group'), ts('Create New Group'));
if (!$this->_id) {
$this->addRadio('group_option', ts('Group Options'), $options, array('onclick' => "return showElements();"));
$this->add('text', 'title', ts('Group Name:') . ' ',
CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Group', 'title')
);
$this->addRule('title', ts('Name already exists in Database.'),
'objectExists', array('CRM_Contact_DAO_Group', $this->_id, 'title')
);
$this->add('textarea', 'description', ts('Description:') . ' ',
CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Group', 'description')
);
$groupTypes = CRM_Core_OptionGroup::values('group_type', TRUE);
if (!CRM_Core_Permission::access('CiviMail')) {
$isWorkFlowEnabled = CRM_Mailing_Info::workflowEnabled();
if ($isWorkFlowEnabled &&
!CRM_Core_Permission::check('create mailings') &&
!CRM_Core_Permission::check('schedule mailings') &&
!CRM_Core_Permission::check('approve mailings')
) {
unset($groupTypes['Mailing List']);
}
}
if (!empty($groupTypes)) {
$this->addCheckBox('group_type',
ts('Group Type'),
$groupTypes,
NULL, NULL, NULL, NULL, '&nbsp;&nbsp;&nbsp;'
);
}
}
// add select for groups
$group = array('' => ts('- select group -')) + CRM_Core_PseudoConstant::group();
$groupElement = $this->add('select', 'group_id', ts('Select Group'), $group);
$this->_title = $group[$this->_id];
if ($this->_context === 'amtg') {
$groupElement->freeze();
// also set the group title
$groupValues = array('id' => $this->_id, 'title' => $this->_title);
$this->assign_by_ref('group', $groupValues);
}
// Set dynamic page title for 'Add Members Group (confirm)'
if ($this->_id) {
CRM_Utils_System::setTitle(ts('Add Contacts: %1', array(1 => $this->_title)));
}
else {
CRM_Utils_System::setTitle(ts('Add Contacts to A Group'));
}
$this->addDefaultButtons(ts('Add to Group'));
}
/**
* Set the default form values.
*
*
* @return array
* the default array reference
*/
public function setDefaultValues() {
$defaults = array();
if ($this->_context === 'amtg') {
$defaults['group_id'] = $this->_id;
}
$defaults['group_option'] = 0;
return $defaults;
}
/**
* Add local and global form rules.
*
*
* @return void
*/
public function addRules() {
$this->addFormRule(array('CRM_Event_Form_Task_AddToGroup', 'formRule'));
}
/**
* Global validation rules for the form.
*
* @param array $params
* Posted values of the form.
*
* @return array
* list of errors to be posted back to the form
*/
public static function formRule($params) {
$errors = array();
if (!empty($params['group_option']) && empty($params['title'])) {
$errors['title'] = "Group Name is a required field";
}
elseif (empty($params['group_option']) && empty($params['group_id'])) {
$errors['group_id'] = "Select Group is a required field.";
}
return empty($errors) ? TRUE : $errors;
}
/**
* Process the form after the input has been submitted and validated.
*
*
* @return void
*/
public function postProcess() {
$params = $this->controller->exportValues();
$groupOption = CRM_Utils_Array::value('group_option', $params, NULL);
if ($groupOption) {
$groupParams = array();
$groupParams['title'] = $params['title'];
$groupParams['description'] = $params['description'];
$groupParams['visibility'] = "User and User Admin Only";
if (array_key_exists('group_type', $params) && is_array($params['group_type'])) {
$groupParams['group_type'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
array_keys($params['group_type'])
) . CRM_Core_DAO::VALUE_SEPARATOR;
}
else {
$groupParams['group_type'] = '';
}
$groupParams['is_active'] = 1;
$createdGroup = CRM_Contact_BAO_Group::create($groupParams);
$groupID = $createdGroup->id;
$groupName = $groupParams['title'];
}
else {
$groupID = $params['group_id'];
$group = CRM_Core_PseudoConstant::group();
$groupName = $group[$groupID];
}
list($total, $added, $notAdded) = CRM_Contact_BAO_GroupContact::addContactsToGroup($this->_contactIds, $groupID);
$status = array(
ts('%count contact added to group', array(
'count' => $added,
'plural' => '%count contacts added to group',
)),
);
if ($notAdded) {
$status[] = ts('%count contact was already in group', array(
'count' => $notAdded,
'plural' => '%count contacts were already in group',
));
}
$status = '<ul><li>' . implode('</li><li>', $status) . '</li></ul>';
CRM_Core_Session::setStatus($status, ts('Added Contact to %1', array(
1 => $groupName,
'count' => $added,
'plural' => 'Added Contacts to %1',
)), 'success', array('expires' => 0));
}
}

View file

@ -0,0 +1,114 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class helps to print the labels for contacts.
*/
class CRM_Event_Form_Task_Badge extends CRM_Event_Form_Task {
/**
* Are we operating in "single mode", i.e. sending email to one
* specific contact?
*
* @var boolean
*/
public $_single = FALSE;
/**
* Component clause.
*/
public $_componentClause;
/**
* Build all the data structures needed to build the form.
*
* @param
*
* @return void
*/
public function preProcess() {
$this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
if ($this->_context == 'view') {
$this->_single = TRUE;
$participantID = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
$contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
$this->_participantIds = array($participantID);
$this->_componentClause = " civicrm_participant.id = $participantID ";
$this->assign('totalSelectedParticipants', 1);
// also set the user context to send back to view page
$session = CRM_Core_Session::singleton();
$session->pushUserContext(CRM_Utils_System::url('civicrm/contact/view/participant',
"reset=1&action=view&id={$participantID}&cid={$contactID}"
));
}
else {
parent::preProcess();
}
}
/**
* Build the form object.
*/
public function buildQuickForm() {
CRM_Utils_System::setTitle(ts('Make Name Badges'));
// Ajax submit would interfere with file download
$this->preventAjaxSubmit();
//add select for label
$label = CRM_Badge_BAO_Layout::getList();
$this->add('select',
'badge_id',
ts('Name Badge Format'),
array(
'' => ts('- select -'),
) + $label, TRUE
);
$next = 'next';
$back = $this->_single ? 'cancel' : 'back';
$this->addDefaultButtons(ts('Make Name Badges'), $next, $back);
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
$params = $this->controller->exportValues($this->_name);
CRM_Badge_BAO_Badge::buildBadges($params, $this);
}
}

View file

@ -0,0 +1,522 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class provides the functionality for batch profile update for events
*/
class CRM_Event_Form_Task_Batch extends CRM_Event_Form_Task {
/**
* The title of the group.
*
* @var string
*/
protected $_title;
/**
* Maximum profile fields that will be displayed.
*/
protected $_maxFields = 9;
/**
* Variable to store redirect path.
*/
protected $_userContext;
/**
* Variable to store previous status id.
*/
protected $_fromStatusIds;
/**
* Build all the data structures needed to build the form.
*
* @return void
*/
public function preProcess() {
/*
* initialize the task and row fields
*/
parent::preProcess();
//get the contact read only fields to display.
$readOnlyFields = array_merge(array('sort_name' => ts('Name')),
CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
'contact_autocomplete_options',
TRUE, NULL, FALSE, 'name', TRUE
)
);
//get the read only field data.
$returnProperties = array_fill_keys(array_keys($readOnlyFields), 1);
$contactDetails = CRM_Contact_BAO_Contact_Utils::contactDetails($this->_participantIds,
'CiviEvent', $returnProperties
);
$this->assign('contactDetails', $contactDetails);
$this->assign('readOnlyFields', $readOnlyFields);
}
/**
* Build the form object.
*
*
* @return void
*/
public function buildQuickForm() {
$ufGroupId = $this->get('ufGroupId');
if (!$ufGroupId) {
CRM_Core_Error::fatal('ufGroupId is missing');
}
$this->_title = ts('Update multiple participants') . ' - ' . CRM_Core_BAO_UFGroup::getTitle($ufGroupId);
CRM_Utils_System::setTitle($this->_title);
$this->addDefaultButtons(ts('Save'));
$this->_fields = array();
$this->_fields = CRM_Core_BAO_UFGroup::getFields($ufGroupId, FALSE, CRM_Core_Action::VIEW);
if (array_key_exists('participant_status', $this->_fields)) {
$this->assign('statusProfile', 1);
$this->assignToTemplate();
}
// remove file type field and then limit fields
$suppressFields = FALSE;
$removehtmlTypes = array('File', 'Autocomplete-Select');
foreach ($this->_fields as $name => $field) {
if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name) &&
in_array($this->_fields[$name]['html_type'], $removehtmlTypes)
) {
$suppressFields = TRUE;
unset($this->_fields[$name]);
}
//fix to reduce size as we are using this field in grid
if (is_array($field['attributes']) && $this->_fields[$name]['attributes']['size'] > 19) {
//shrink class to "form-text-medium"
$this->_fields[$name]['attributes']['size'] = 19;
}
}
$this->_fields = array_slice($this->_fields, 0, $this->_maxFields);
$this->addButtons(array(
array(
'type' => 'submit',
'name' => ts('Update Participant(s)'),
'isDefault' => TRUE,
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
)
);
$this->assign('profileTitle', $this->_title);
$this->assign('componentIds', $this->_participantIds);
$fileFieldExists = FALSE;
//load all campaigns.
if (array_key_exists('participant_campaign_id', $this->_fields)) {
$this->_componentCampaigns = array();
CRM_Core_PseudoConstant::populate($this->_componentCampaigns,
'CRM_Event_DAO_Participant',
TRUE, 'campaign_id', 'id',
' id IN (' . implode(' , ', array_values($this->_participantIds)) . ' ) '
);
}
//fix for CRM-2752
// get the option value for custom data type
$customDataType = CRM_Core_OptionGroup::values('custom_data_type', FALSE, FALSE, FALSE, NULL, 'name');
$this->_roleCustomDataTypeID = array_search('ParticipantRole', $customDataType);
$this->_eventNameCustomDataTypeID = array_search('ParticipantEventName', $customDataType);
$this->_eventTypeCustomDataTypeID = array_search('ParticipantEventType', $customDataType);
// build custom data getFields array
$customFieldsRole = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, $this->_roleCustomDataTypeID);
$customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, $this->_eventNameCustomDataTypeID);
$customFieldsEventType = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, $this->_eventTypeCustomDataTypeID);
$customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole,
CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, NULL, TRUE)
);
$customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEventType, $customFields);
$this->_customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
foreach ($this->_participantIds as $participantId) {
$roleId = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Participant", $participantId, 'role_id');
$eventId = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Participant", $participantId, 'event_id');
$eventTypeId = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Event", $eventId, 'event_type_id');
foreach ($this->_fields as $name => $field) {
if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
$customValue = CRM_Utils_Array::value($customFieldID, $this->_customFields);
$entityColumnValue = array();
if (!empty($customValue['extends_entity_column_value'])) {
$entityColumnValue = explode(CRM_Core_DAO::VALUE_SEPARATOR,
$customValue['extends_entity_column_value']
);
}
$entityColumnValueRole = CRM_Utils_Array::value($roleId, $entityColumnValue);
$entityColumnValueEventType = in_array($eventTypeId, $entityColumnValue) ? $eventTypeId : NULL;
if (($this->_roleCustomDataTypeID == $customValue['extends_entity_column_id']) &&
($entityColumnValueRole)
) {
CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $participantId);
}
elseif (($this->_eventNameCustomDataTypeID == $customValue['extends_entity_column_id']) &&
($eventId == $entityColumnValueRole)
) {
CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $participantId);
}
elseif ($this->_eventTypeCustomDataTypeID == $customValue['extends_entity_column_id'] &&
($entityColumnValueEventType == $eventTypeId)
) {
CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $participantId);
}
elseif (CRM_Utils_System::isNull($entityColumnValueRole)) {
CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $participantId);
}
}
else {
if ($field['name'] == 'participant_role') {
$field['is_multiple'] = TRUE;
}
// handle non custom fields
CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $participantId);
}
}
}
$this->assign('fields', $this->_fields);
// don't set the status message when form is submitted.
$buttonName = $this->controller->getButtonName('submit');
if ($suppressFields && $buttonName != '_qf_Batch_next') {
CRM_Core_Session::setStatus(ts("File or Autocomplete-Select type field(s) in the selected profile are not supported for Update multiple participants."), ts('Unsupported Field Type'), 'info');
}
$this->addDefaultButtons(ts('Update Participant(s)'));
}
/**
* Set default values for the form.
*
*
* @return void
*/
public function setDefaultValues() {
if (empty($this->_fields)) {
return;
}
$defaults = array();
foreach ($this->_participantIds as $participantId) {
$details[$participantId] = array();
$details[$participantId] = CRM_Event_BAO_Participant::participantDetails($participantId);
CRM_Core_BAO_UFGroup::setProfileDefaults(NULL, $this->_fields, $defaults, FALSE, $participantId, 'Event');
//get the from status ids, CRM-4323
if (array_key_exists('participant_status', $this->_fields)) {
$this->_fromStatusIds[$participantId] = CRM_Utils_Array::value("field[$participantId][participant_status]", $defaults);
}
if (array_key_exists('participant_role', $this->_fields)) {
if ($defaults["field[{$participantId}][participant_role]"]) {
$roles = $defaults["field[{$participantId}][participant_role]"];
foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $roles) as $k => $v) {
$defaults["field[$participantId][participant_role][{$v}]"] = 1;
}
unset($defaults["field[{$participantId}][participant_role]"]);
}
}
}
$this->assign('details', $details);
return $defaults;
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
$params = $this->exportValues();
$statusClasses = CRM_Event_PseudoConstant::participantStatusClass();
if (isset($params['field'])) {
foreach ($params['field'] as $key => $value) {
//check for custom data
$value['custom'] = CRM_Core_BAO_CustomField::postProcess($value,
$key,
'Participant'
);
$value['id'] = $key;
if (!empty($value['participant_role'])) {
if (is_array($value['participant_role'])) {
$value['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($value['participant_role']));
}
else {
$value['role_id'] = $value['participant_role'];
}
}
//need to send mail when status change
$statusChange = FALSE;
$relatedStatusChange = FALSE;
if (!empty($value['participant_status'])) {
$value['status_id'] = $value['participant_status'];
$fromStatusId = CRM_Utils_Array::value($key, $this->_fromStatusIds);
if (!$fromStatusId) {
$fromStatusId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $key, 'status_id');
}
if ($fromStatusId != $value['status_id']) {
$relatedStatusChange = TRUE;
}
if ($statusClasses[$fromStatusId] != $statusClasses[$value['status_id']]) {
$statusChange = TRUE;
}
}
unset($value['participant_status']);
civicrm_api3('Participant', 'create', $value);
//need to trigger mails when we change status
if ($statusChange) {
CRM_Event_BAO_Participant::transitionParticipants(array($key), $value['status_id'], $fromStatusId);
}
if ($relatedStatusChange) {
//update related contribution status, CRM-4395
self::updatePendingOnlineContribution($key, $value['status_id']);
}
}
CRM_Core_Session::setStatus(ts('The updates have been saved.'), ts('Saved'), 'success');
}
else {
CRM_Core_Session::setStatus(ts('No updates have been saved.'), ts('Not Saved'), 'alert');
}
}
/**
* @param int $participantId
* @param int $statusId
*
* @return Ambigous|void
*/
public static function updatePendingOnlineContribution($participantId, $statusId) {
if (!$participantId || !$statusId) {
return NULL;
}
$contributionId = CRM_Contribute_BAO_Contribution::checkOnlinePendingContribution($participantId,
'Event'
);
if (!$contributionId) {
return;
}
//status rules.
//1. participant - positive => contribution - completed.
//2. participant - negative => contribution - cancelled.
$positiveStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Positive'");
$negativeStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'");
$contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
$contributionStatusId = NULL;
if (array_key_exists($statusId, $positiveStatuses)) {
$contributionStatusId = array_search('Completed', $contributionStatuses);
}
if (array_key_exists($statusId, $negativeStatuses)) {
$contributionStatusId = array_search('Cancelled', $contributionStatuses);
}
if (!$contributionStatusId) {
return;
}
$params = array(
'component_id' => $participantId,
'componentName' => 'Event',
'contribution_id' => $contributionId,
'contribution_status_id' => $contributionStatusId,
'IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved' => 1,
);
//change related contribution status.
$updatedStatusId = self::updateContributionStatus($params);
return $updatedStatusId;
}
/**
* Update contribution status.
*
* @deprecated
* This is only called from one place in the code &
* it is unclear whether it is a function on the way in or on the way out
*
* @param array $params
*
* @return NULL|int
*/
public static function updateContributionStatus($params) {
// get minimum required values.
$statusId = CRM_Utils_Array::value('contribution_status_id', $params);
$componentId = CRM_Utils_Array::value('component_id', $params);
$componentName = CRM_Utils_Array::value('componentName', $params);
$contributionId = CRM_Utils_Array::value('contribution_id', $params);
if (!$contributionId || !$componentId || !$componentName || !$statusId) {
return NULL;
}
$input = $ids = $objects = array();
//get the required ids.
$ids['contribution'] = $contributionId;
if (!$ids['contact'] = CRM_Utils_Array::value('contact_id', $params)) {
$ids['contact'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution',
$contributionId,
'contact_id'
);
}
if ($componentName == 'Event') {
$name = 'event';
$ids['participant'] = $componentId;
if (!$ids['event'] = CRM_Utils_Array::value('event_id', $params)) {
$ids['event'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant',
$componentId,
'event_id'
);
}
}
if ($componentName == 'Membership') {
$name = 'contribute';
$ids['membership'] = $componentId;
}
$ids['contributionPage'] = NULL;
$ids['contributionRecur'] = NULL;
$input['component'] = $name;
$baseIPN = new CRM_Core_Payment_BaseIPN();
$transaction = new CRM_Core_Transaction();
// reset template values.
$template = CRM_Core_Smarty::singleton();
$template->clearTemplateVars();
if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
CRM_Core_Error::fatal();
}
$contribution = &$objects['contribution'];
$contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array(
'labelColumn' => 'name',
'flip' => 1,
));
$input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'] = CRM_Utils_Array::value('IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved', $params);
if ($statusId == $contributionStatuses['Cancelled']) {
$baseIPN->cancelled($objects, $transaction, $input);
$transaction->commit();
return $statusId;
}
elseif ($statusId == $contributionStatuses['Failed']) {
$baseIPN->failed($objects, $transaction, $input);
$transaction->commit();
return $statusId;
}
// status is not pending
if ($contribution->contribution_status_id != $contributionStatuses['Pending']) {
$transaction->commit();
return;
}
//set values for ipn code.
foreach (array(
'fee_amount',
'check_number',
'payment_instrument_id',
) as $field) {
if (!$input[$field] = CRM_Utils_Array::value($field, $params)) {
$input[$field] = $contribution->$field;
}
}
if (!$input['trxn_id'] = CRM_Utils_Array::value('trxn_id', $params)) {
$input['trxn_id'] = $contribution->invoice_id;
}
if (!$input['amount'] = CRM_Utils_Array::value('total_amount', $params)) {
$input['amount'] = $contribution->total_amount;
}
$input['is_test'] = $contribution->is_test;
$input['net_amount'] = $contribution->net_amount;
if (!empty($input['fee_amount']) && !empty($input['amount'])) {
$input['net_amount'] = $input['amount'] - $input['fee_amount'];
}
//complete the contribution.
// @todo use the api - ie civicrm_api3('Contribution', 'completetransaction', $input);
// as this method is not preferred / supported.
$baseIPN->completeTransaction($input, $ids, $objects, $transaction, FALSE);
// reset template values before processing next transactions
$template->clearTemplateVars();
return $statusId;
}
/**
* Assign the minimal set of variables to the template.
*/
public function assignToTemplate() {
$notifyingStatuses = array('Pending from waitlist', 'Pending from approval', 'Expired', 'Cancelled');
$notifyingStatuses = array_intersect($notifyingStatuses, CRM_Event_PseudoConstant::participantStatus());
$this->assign('status', TRUE);
if (!empty($notifyingStatuses)) {
$s = '<em>' . implode('</em>, <em>', $notifyingStatuses) . '</em>';
$this->assign('notifyingStatuses', $s);
}
}
}

View file

@ -0,0 +1,90 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class provides the functionality for cancel registration for event participations
*/
class CRM_Event_Form_Task_Cancel extends CRM_Event_Form_Task {
/**
* Variable to store redirect path.
*/
protected $_userContext;
/**
* Build all the data structures needed to build the form.
*
* @return void
*/
public function preProcess() {
// initialize the task and row fields
parent::preProcess();
$session = CRM_Core_Session::singleton();
$this->_userContext = $session->readUserContext();
}
/**
* Build the form object.
*
*
* @return void
*/
public function buildQuickForm() {
CRM_Utils_System::setTitle(ts('Cancel Registration for Event Participation'));
$session = CRM_Core_Session::singleton();
$this->addDefaultButtons(ts('Continue'), 'done');
}
/**
* Process the form after the input has been submitted and validated.
*
*
* @return void
*/
public function postProcess() {
$params = $this->exportValues();
$value = array();
foreach ($this->_participantIds as $participantId) {
$value['id'] = $participantId;
// Cancelled status id = 4
$value['status_id'] = 4;
CRM_Event_BAO_Participant::create($value);
}
}
}

View file

@ -0,0 +1,143 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class provides the functionality to delete a group of
* participations. This class provides functionality for the actual
* deletion.
*/
class CRM_Event_Form_Task_Delete extends CRM_Event_Form_Task {
/**
* Are we operating in "single mode", i.e. deleting one
* specific participation?
*
* @var boolean
*/
protected $_single = FALSE;
/**
* Build all the data structures needed to build the form.
*
* @return void
*/
public function preProcess() {
//check for delete
if (!CRM_Core_Permission::checkActionPermission('CiviEvent', CRM_Core_Action::DELETE)) {
CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
}
parent::preProcess();
foreach ($this->_participantIds as $participantId) {
if (CRM_Event_BAO_Participant::isPrimaryParticipant($participantId)) {
$this->assign('additionalParticipants', TRUE);
}
}
}
/**
* Build the form object.
*
*
* @return void
*/
public function buildQuickForm() {
$deleteParticipants = array(
1 => ts('Delete this participant record along with associated participant record(s).'),
2 => ts('Delete only this participant record.'),
);
$this->addRadio('delete_participant', NULL, $deleteParticipants, NULL, '<br />');
$this->setDefaults(array('delete_participant' => 1));
$this->addDefaultButtons(ts('Delete Participations'), 'done');
}
/**
* Process the form after the input has been submitted and validated.
*
*
* @return void
*/
public function postProcess() {
$params = $this->controller->exportValues($this->_name);
$participantLinks = NULL;
if (CRM_Utils_Array::value('delete_participant', $params) == 2) {
$links = array();
foreach ($this->_participantIds as $participantId) {
$additionalId = (CRM_Event_BAO_Participant::getAdditionalParticipantIds($participantId));
$participantLinks = (CRM_Event_BAO_Participant::getAdditionalParticipantUrl($additionalId));
}
}
$deletedParticipants = $additionalCount = 0;
foreach ($this->_participantIds as $participantId) {
if (CRM_Utils_Array::value('delete_participant', $params) == 1) {
$primaryParticipantId = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Participant", $participantId, 'registered_by_id', 'id');
if (CRM_Event_BAO_Participant::isPrimaryParticipant($participantId)) {
$additionalIds = (CRM_Event_BAO_Participant::getAdditionalParticipantIds($participantId));
$additionalCount += count($additionalIds);
foreach ($additionalIds as $value) {
CRM_Event_BAO_Participant::deleteParticipant($value);
}
CRM_Event_BAO_Participant::deleteParticipant($participantId);
$deletedParticipants++;
}
// delete participant only if it is not an additional participant
// or if it is additional and its primary participant is not selected in $this->_participantIds.
elseif (empty($primaryParticipantId) || (!in_array($primaryParticipantId, $this->_participantIds))) {
CRM_Event_BAO_Participant::deleteParticipant($participantId);
$deletedParticipants++;
}
}
else {
CRM_Event_BAO_Participant::deleteParticipant($participantId);
$deletedParticipants++;
}
}
if ($additionalCount) {
$deletedParticipants += $additionalCount;
}
$status = ts('%count participant deleted.', array('plural' => '%count participants deleted.', 'count' => $deletedParticipants));
if ($participantLinks) {
$status .= '<p>' . 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:')
. '</p>' . $participantLinks;
}
CRM_Core_Session::setStatus($status, ts('Removed'), 'info');
}
}

View file

@ -0,0 +1,104 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id: Email.php 45499 2013-02-08 12:31:05Z kurund $
*/
/**
* This class provides the functionality to email a group of
* contacts.
*/
class CRM_Event_Form_Task_Email extends CRM_Event_Form_Task {
/**
* Are we operating in "single mode", i.e. sending email to one
* specific contact?
*
* @var boolean
*/
public $_single = FALSE;
/**
* Are we operating in "single mode", i.e. sending email to one
* specific contact?
*
* @var boolean
*/
public $_noEmails = FALSE;
/**
* All the existing templates in the system.
*
* @var array
*/
public $_templates = NULL;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
CRM_Contact_Form_Task_EmailCommon::preProcessFromAddress($this);
parent::preProcess();
// we have all the participant ids, so now we get the contact ids
parent::setContactIDs();
$this->assign('single', $this->_single);
}
/**
* Build the form object.
*/
public function buildQuickForm() {
//enable form element
$this->assign('emailTask', TRUE);
CRM_Contact_Form_Task_EmailCommon::buildQuickForm($this);
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
CRM_Contact_Form_Task_EmailCommon::postProcess($this);
}
/**
* List available tokens for this form.
*
* @return array
*/
public function listTokens() {
$tokens = CRM_Core_SelectValues::contactTokens();
return $tokens;
}
}

View file

@ -0,0 +1,105 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id: PDF.php 45499 2013-02-08 12:31:05Z kurund $
*/
/**
* This class provides the functionality to create PDF letter for a group of
* participants or a single participant.
*/
class CRM_Event_Form_Task_PDF extends CRM_Event_Form_Task {
/**
* Are we operating in "single mode", i.e. printing letter to one
* specific participant?
*
* @var boolean
*/
public $_single = FALSE;
/**
* All the existing templates in the system.
*
* @var array
*/
public $_templates = NULL;
public $_cid = NULL;
public $_activityId = NULL;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
CRM_Contact_Form_Task_PDFLetterCommon::preProcess($this);
parent::preProcess();
// we have all the participant ids, so now we get the contact ids
parent::setContactIDs();
$this->assign('single', $this->_single);
}
/**
* Build the form object.
*/
public function buildQuickForm() {
CRM_Contact_Form_Task_PDFLetterCommon::buildQuickForm($this);
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
CRM_Contact_Form_Task_PDFLetterCommon::postProcess($this);
}
/**
* Set default values for the form.
*
* @return void
*/
public function setDefaultValues() {
return CRM_Contact_Form_Task_PDFLetterCommon::setDefaultValues();
}
/**
* List available tokens for this form.
*
* @return array
*/
public function listTokens() {
$tokens = CRM_Core_SelectValues::contactTokens();
return $tokens;
}
}

View file

@ -0,0 +1,58 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
class CRM_Event_Form_Task_ParticipantStatus extends CRM_Event_Form_Task_Batch {
public function buildQuickForm() {
// CRM_Event_Form_Task_Batch::buildQuickForm() gets ufGroupId
// from the form, so set it here to the id of the reserved profile
$dao = new CRM_Core_DAO_UFGroup();
$dao->name = 'participant_status';
$dao->find(TRUE);
$this->set('ufGroupId', $dao->id);
$statuses = CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label');
asort($statuses, SORT_STRING);
$this->add('select', 'status_change', ts('Change All Statuses'),
array(
'' => ts('- select status -'),
) + $statuses
);
$this->assign('context', 'statusChange');
# CRM-4321: display info on users being notified if any of the below statuses is enabled
parent::assignToTemplate();
parent::buildQuickForm();
}
}

View file

@ -0,0 +1,146 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class provides the functionality for batch profile update for event participations
*/
class CRM_Event_Form_Task_PickProfile extends CRM_Event_Form_Task {
/**
* The title of the group.
*
* @var string
*/
protected $_title;
/**
* Maximum event participations that should be allowed to update.
*/
protected $_maxParticipations = 100;
/**
* Variable to store redirect path.
*/
protected $_userContext;
/**
* Build all the data structures needed to build the form.
*
* @return void
*/
public function preProcess() {
// initialize the task and row fields
parent::preProcess();
$session = CRM_Core_Session::singleton();
$this->_userContext = $session->readUserContext();
CRM_Utils_System::setTitle(ts('Update multiple participants'));
$validate = FALSE;
//validations
if (count($this->_participantIds) > $this->_maxParticipations) {
CRM_Core_Session::setStatus("The maximum number of records you can select for Update multiple participants is {$this->_maxParticipations}. You have selected " . count($this->_participantIds) . ". Please select fewer participantions from your search results and try again.");
$validate = TRUE;
}
// then redirect
if ($validate) {
CRM_Utils_System::redirect($this->_userContext);
}
}
/**
* Build the form object.
*
*
* @return void
*/
public function buildQuickForm() {
$types = array('Participant');
$profiles = CRM_Core_BAO_UFGroup::getProfiles($types, TRUE);
if (empty($profiles)) {
CRM_Core_Session::setStatus("To use Update multiple participants, you need to configure a profile containing only Participant fields (e.g. Participant Status, Participant Role, etc.). Configure a profile at 'Administer CiviCRM >> Customize >> CiviCRM Profile'.");
CRM_Utils_System::redirect($this->_userContext);
}
$ufGroupElement = $this->add('select', 'uf_group_id', ts('Select Profile'),
array(
'' => ts('- select profile -'),
) + $profiles, TRUE
);
$this->addDefaultButtons(ts('Continue'));
}
/**
* Add local and global form rules.
*
*
* @return void
*/
public function addRules() {
$this->addFormRule(array('CRM_Event_Form_Task_PickProfile', 'formRule'));
}
/**
* Global validation rules for the form.
*
* @param array $fields
* Posted values of the form.
*
* @return array
* list of errors to be posted back to the form
*/
public static function formRule($fields) {
return TRUE;
}
/**
* Process the form after the input has been submitted and validated.
*
*
* @return void
*/
public function postProcess() {
$params = $this->exportValues();
$this->set('ufGroupId', $params['uf_group_id']);
// also reset the batch page so it gets new values from the db
$this->controller->resetPage('Batch');
}
}

View file

@ -0,0 +1,105 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class provides the functionality to participant records
*/
class CRM_Event_Form_Task_Print extends CRM_Event_Form_Task {
/**
* Build all the data structures needed to build the form.
*
* @return void
*/
public function preProcess() {
parent::preprocess();
// set print view, so that print templates are called
$this->controller->setPrint(1);
// get the formatted params
$queryParams = $this->get('queryParams');
$sortID = NULL;
if ($this->get(CRM_Utils_Sort::SORT_ID)) {
$sortID = CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID),
$this->get(CRM_Utils_Sort::SORT_DIRECTION)
);
}
$selector = new CRM_Event_Selector_Search($queryParams, $this->_action, $this->_componentClause);
$controller = new CRM_Core_Selector_Controller($selector, NULL, $sortID, CRM_Core_Action::VIEW, $this, CRM_Core_Selector_Controller::SCREEN);
$controller->setEmbedded(TRUE);
$controller->run();
}
/**
* Build the form object - it consists of
* - displaying the QILL (query in local language)
* - displaying elements for saving the search
*
*
* @return void
*/
public function buildQuickForm() {
//
// just need to add a javacript to popup the window for printing
//
$this->addButtons(array(
array(
'type' => 'next',
'name' => ts('Print Participant List'),
'js' => array('onclick' => 'window.print()'),
'isDefault' => TRUE,
),
array(
'type' => 'back',
'name' => ts('Done'),
),
)
);
}
/**
* Process the form after the input has been submitted and validated.
*
*
* @return void
*/
public function postProcess() {
// redirect to the main search page after printing is over
}
}

View file

@ -0,0 +1,70 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* Used for displaying results
*
*
*/
class CRM_Event_Form_Task_Result extends CRM_Event_Form_Task {
/**
* Build all the data structures needed to build the form.
*
* @return void
*/
public function preProcess() {
$session = CRM_Core_Session::singleton();
//this is done to unset searchRows variable assign during AddToHousehold and AddToOrganization
$this->set('searchRows', '');
$ssID = $this->get('ssID');
$path = 'force=1';
if (isset($ssID)) {
$path .= "&reset=1&ssID={$ssID}";
}
$qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this);
if (CRM_Utils_Rule::qfKey($qfKey)) {
$path .= "&qfKey=$qfKey";
}
$url = CRM_Utils_System::url('civicrm/event/search', $path);
$session->replaceUserContext($url);
CRM_Utils_System::redirect($url);
}
}

View file

@ -0,0 +1,142 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class provides the functionality to save a search
* Saved Searches are used for saving frequently used queries
* regarding the event participations
*/
class CRM_Event_Form_Task_SaveSearch extends CRM_Event_Form_Task {
/**
* Saved search id if any.
*
* @var int
*/
protected $_id;
/**
* Build all the data structures needed to build the form.
*
* @return void
*/
public function preProcess() {
parent::preProcess();
$this->_id = NULL;
}
/**
* Build the form object - it consists of
* - displaying the QILL (query in local language)
* - displaying elements for saving the search
*
*
* @return void
*/
public function buildQuickForm() {
CRM_Utils_System::setTitle(ts('Smart Group'));
// get the qill
$query = new CRM_Event_BAO_Query($this->get('formValues'));
$qill = $query->qill();
// Values from the search form
$formValues = $this->controller->exportValues();
// need to save qill for the smarty template
$this->assign('qill', $qill);
// the name and description are actually stored with the group and not the saved search
$this->add('text', 'title', ts('Name'),
CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Group', 'title'), TRUE
);
$this->addElement('text', 'description', ts('Description'),
CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Group', 'description')
);
// get the group id for the saved search
$groupId = NULL;
if (isset($this->_id)) {
$params = array('saved_search_id' => $this->_id);
CRM_Contact_BAO_Group::retrieve($params, $values);
$groupId = $values['id'];
$this->addDefaultButtons(ts('Update Smart Group'));
}
else {
$this->addDefaultButtons(ts('Save Smart Group'));
$this->assign('partiallySelected', $formValues['radio_ts'] != 'ts_all');
}
$this->addRule('title', ts('Name already exists in Database.'),
'objectExists', array('CRM_Contact_DAO_Group', $groupId, 'title')
);
}
/**
* Process the form after the input has been submitted and validated.
*
*
* @return void
*/
public function postProcess() {
// saved search form values
$formValues = $this->controller->exportValues();
$session = CRM_Core_Session::singleton();
//save the search
$savedSearch = new CRM_Contact_BAO_SavedSearch();
$savedSearch->id = $this->_id;
$savedSearch->form_values = serialize($this->get('formValues'));
$savedSearch->save();
$this->set('ssID', $savedSearch->id);
CRM_Core_Session::setStatus(ts("Your smart group has been saved as '%1'.", array(1 => $formValues['title'])), ts('Saved'), 'success');
// also create a group that is associated with this saved search only if new saved search
$params = array();
$params['title'] = $formValues['title'];
$params['description'] = $formValues['description'];
$params['visibility'] = 'User and User Admin Only';
$params['saved_search_id'] = $savedSearch->id;
$params['is_active'] = 1;
if ($this->_id) {
$params['id'] = CRM_Contact_BAO_SavedSearch::getName($this->_id, 'id');
}
$group = CRM_Contact_BAO_Group::create($params);
}
}

View file

@ -0,0 +1,76 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class provides the functionality to update a saved search
*
*/
class CRM_Event_Form_Task_SaveSearch_Update extends CRM_Event_Form_Task_SaveSearch {
/**
* Build all the data structures needed to build the form.
*
* @return void
*/
public function preProcess() {
parent::preProcess();
$this->_id = $this->get('ssID');
if (!$this->_id) {
// fetch the value from the group id gid
$gid = $this->get('gid');
$this->_id = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $gid, 'saved_search_id');
}
}
/**
* Set default values for the form.
* the default values are retrieved from the database
*
*
* @return void
*/
public function setDefaultValues() {
$defaults = array();
$params = array();
$params = array('saved_search_id' => $this->_id);
CRM_Contact_BAO_Group::retrieve($params, $defaults);
return $defaults;
}
}

View file

@ -0,0 +1,90 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class provides the functionality to save a search
* Saved Searches are used for saving frequently used queries
*/
class CRM_Event_Form_Task_SearchTaskHookSample extends CRM_Event_Form_Task {
/**
* Build all the data structures needed to build the form.
*
* @return void
*/
public function preProcess() {
parent::preProcess();
$rows = array();
// display name and participation details of participants
$participantIDs = implode(',', $this->_participantIds);
$query = "
SELECT p.fee_amount as amount,
p.register_date as register_date,
p.source as source,
ct.display_name as display_name
FROM civicrm_participant p
INNER JOIN civicrm_contact ct ON ( p.contact_id = ct.id )
WHERE p.id IN ( $participantIDs )";
$dao = CRM_Core_DAO::executeQuery($query);
while ($dao->fetch()) {
$rows[] = array(
'display_name' => $dao->display_name,
'amount' => $dao->amount,
'register_date' => CRM_Utils_Date::customFormat($dao->register_date),
'source' => $dao->source,
);
}
$this->assign('rows', $rows);
}
/**
* Build the form object.
*
* @return void
*/
public function buildQuickForm() {
$this->addButtons(array(
array(
'type' => 'done',
'name' => ts('Done'),
'isDefault' => TRUE,
),
)
);
}
}

View file

@ -0,0 +1,62 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
class CRM_Event_Import_Controller extends CRM_Core_Controller {
/**
* Class constructor.
*
* @param null $title
* @param bool|int $action
* @param bool $modal
*/
public function __construct($title = NULL, $action = CRM_Core_Action::NONE, $modal = TRUE) {
parent::__construct($title, $modal);
// lets get around the time limit issue if possible, CRM-2113
if (!ini_get('safe_mode')) {
set_time_limit(0);
}
$this->_stateMachine = new CRM_Import_StateMachine($this, $action);
// create and instantiate the pages
$this->addPages($this->_stateMachine, $action);
// add all the actions
$config = CRM_Core_Config::singleton();
$this->addActions($config->uploadDir, array('uploadFile'));
}
}

View file

@ -0,0 +1,152 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* Class CRM_Event_Import_Field
*/
class CRM_Event_Import_Field {
/**#@+
* @var string
*/
/**
* Name of the field
*/
public $_name;
/**
* Title of the field to be used in display
*/
public $_title;
/**
* Type of field
* @var enum
*/
public $_type;
/**
* Regexp to match the CSV header of this column/field
* @var string
*/
public $_headerPattern;
/**
* Regexp to match the pattern of data from various column/fields
* @var string
*/
public $_dataPattern;
/**
* Value of this field
* @var object
*/
public $_value;
/**
* @param string $name
* @param $title
* @param int $type
* @param string $headerPattern
* @param string $dataPattern
*/
public function __construct($name, $title, $type = CRM_Utils_Type::T_INT, $headerPattern = '//', $dataPattern = '//') {
$this->_name = $name;
$this->_title = $title;
$this->_type = $type;
$this->_headerPattern = $headerPattern;
$this->_dataPattern = $dataPattern;
$this->_value = NULL;
}
public function resetValue() {
$this->_value = NULL;
}
/**
* Convert the value to the type of this field and set the field value with the appropriate type.
*
* @param string $value
*/
public function setValue($value) {
$this->_value = $value;
}
/**
* @return bool
*/
public function validate() {
if (CRM_Utils_System::isNull($this->_value)) {
return TRUE;
}
switch ($this->_name) {
case 'contact_id':
// note: we validate extistence of the contact in API, upon
// insert (it would be too costlty to do a db call here)
return CRM_Utils_Rule::integer($this->_value);
case 'register_date':
return CRM_Utils_Rule::date($this->_value);
/* @codingStandardsIgnoreStart
case 'event_id':
static $events = null;
if (!$events) {
$events = CRM_Event_PseudoConstant::event();
}
if (in_array($this->_value, $events)) {
return true;
}
else {
return false;
}
break;
@codingStandardsIgnoreEnd */
default:
break;
}
// check whether that's a valid custom field id
// and if so, check the contents' validity
if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($this->_name)) {
static $customFields = NULL;
if (!$customFields) {
$customFields = CRM_Core_BAO_CustomField::getFields('Participant');
}
if (!array_key_exists($customFieldID, $customFields)) {
return FALSE;
}
return CRM_Core_BAO_CustomValue::typecheck($customFields[$customFieldID]['data_type'], $this->_value);
}
return TRUE;
}
}

View file

@ -0,0 +1,88 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class gets the name of the file to upload
*/
class CRM_Event_Import_Form_DataSource extends CRM_Import_Form_DataSource {
const PATH = 'civicrm/event/import';
const IMPORT_ENTITY = 'Participant';
/**
* Build the form object.
*
* @return void
*/
public function buildQuickForm() {
parent::buildQuickForm();
$duplicateOptions = array();
$duplicateOptions[] = $this->createElement('radio',
NULL, NULL, ts('Skip'), CRM_Import_Parser::DUPLICATE_SKIP
);
$duplicateOptions[] = $this->createElement('radio',
NULL, NULL, ts('Update'), CRM_Import_Parser::DUPLICATE_UPDATE
);
$duplicateOptions[] = $this->createElement('radio',
NULL, NULL, ts('No Duplicate Checking'), CRM_Import_Parser::DUPLICATE_NOCHECK
);
$this->addGroup($duplicateOptions, 'onDuplicate',
ts('On Duplicate Entries')
);
$this->setDefaults(array('onDuplicate' => CRM_Import_Parser::DUPLICATE_SKIP));
$this->addContactTypeSelector();
}
/**
* Process the uploaded file.
*
* @return void
*/
public function postProcess() {
$this->storeFormValues(array(
'onDuplicate',
'contactType',
'dateFormats',
'savedMapping',
));
$this->submitFileForMapping('CRM_Event_Import_Parser_Participant');
}
}

View file

@ -0,0 +1,495 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class gets the name of the file to upload
*/
class CRM_Event_Import_Form_MapField extends CRM_Import_Form_MapField {
/**
* Set variables up before form is built.
*
* @return void
*/
public function preProcess() {
$this->_mapperFields = $this->get('fields');
asort($this->_mapperFields);
unset($this->_mapperFields['participant_is_test']);
$this->_columnCount = $this->get('columnCount');
$this->assign('columnCount', $this->_columnCount);
$this->_dataValues = $this->get('dataValues');
$this->assign('dataValues', $this->_dataValues);
$skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
$this->_onDuplicate = $this->get('onDuplicate');
$highlightedFields = array();
if ($skipColumnHeader) {
$this->assign('skipColumnHeader', $skipColumnHeader);
$this->assign('rowDisplayCount', 3);
/* if we had a column header to skip, stash it for later */
$this->_columnHeaders = $this->_dataValues[0];
}
else {
$this->assign('rowDisplayCount', 2);
}
if ($this->_onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE) {
$remove = array('participant_contact_id', 'email', 'first_name', 'last_name', 'external_identifier');
foreach ($remove as $value) {
unset($this->_mapperFields[$value]);
}
$highlightedFieldsArray = array('participant_id', 'event_id', 'event_title', 'participant_status_id');
foreach ($highlightedFieldsArray as $name) {
$highlightedFields[] = $name;
}
}
elseif ($this->_onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP ||
$this->_onDuplicate == CRM_Import_Parser::DUPLICATE_NOCHECK
) {
unset($this->_mapperFields['participant_id']);
$highlightedFieldsArray = array(
'participant_contact_id',
'event_id',
'email',
'first_name',
'last_name',
'external_identifier',
'participant_status_id',
);
foreach ($highlightedFieldsArray as $name) {
$highlightedFields[] = $name;
}
}
$this->assign('highlightedFields', $highlightedFields);
}
/**
* Build the form object.
*
* @return void
*/
public function buildQuickForm() {
//to save the current mappings
if (!$this->get('savedMapping')) {
$saveDetailsName = ts('Save this field mapping');
$this->applyFilter('saveMappingName', 'trim');
$this->add('text', 'saveMappingName', ts('Name'));
$this->add('text', 'saveMappingDesc', ts('Description'));
}
else {
$savedMapping = $this->get('savedMapping');
list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingRelation) = CRM_Core_BAO_Mapping::getMappingFields($savedMapping);
$mappingName = $mappingName[1];
$mappingContactType = $mappingContactType[1];
$mappingLocation = CRM_Utils_Array::value('1', $mappingLocation);
$mappingPhoneType = CRM_Utils_Array::value('1', $mappingPhoneType);
$mappingRelation = CRM_Utils_Array::value('1', $mappingRelation);
//mapping is to be loaded from database
$params = array('id' => $savedMapping);
$temp = array();
$mappingDetails = CRM_Core_BAO_Mapping::retrieve($params, $temp);
$this->assign('loadedMapping', $mappingDetails->name);
$this->set('loadedMapping', $savedMapping);
$getMappingName = new CRM_Core_DAO_Mapping();
$getMappingName->id = $savedMapping;
$getMappingName->mapping_type = 'Import Participants';
$getMappingName->find();
while ($getMappingName->fetch()) {
$mapperName = $getMappingName->name;
}
$this->assign('savedName', $mapperName);
$this->add('hidden', 'mappingId', $savedMapping);
$this->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL);
$saveDetailsName = ts('Save as a new field mapping');
$this->add('text', 'saveMappingName', ts('Name'));
$this->add('text', 'saveMappingDesc', ts('Description'));
}
$this->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, array('onclick' => "showSaveDetails(this)"));
$this->addFormRule(array('CRM_Event_Import_Form_MapField', 'formRule'), $this);
$defaults = array();
$mapperKeys = array_keys($this->_mapperFields);
$hasHeaders = !empty($this->_columnHeaders);
$headerPatterns = $this->get('headerPatterns');
$dataPatterns = $this->get('dataPatterns');
$hasLocationTypes = $this->get('fieldTypes');
/* Initialize all field usages to false */
foreach ($mapperKeys as $key) {
$this->_fieldUsed[$key] = FALSE;
}
$this->_location_types = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
$sel1 = $this->_mapperFields;
$sel2[''] = NULL;
$js = "<script type='text/javascript'>\n";
$formName = 'document.forms.' . $this->_name;
//used to warn for mismatch column count or mismatch mapping
$warning = 0;
for ($i = 0; $i < $this->_columnCount; $i++) {
$sel = &$this->addElement('hierselect', "mapper[$i]", ts('Mapper for Field %1', array(1 => $i)), NULL);
$jsSet = FALSE;
if ($this->get('savedMapping')) {
if (isset($mappingName[$i])) {
if ($mappingName[$i] != ts('- do not import -')) {
$mappingHeader = array_keys($this->_mapperFields, $mappingName[$i]);
if (!isset($locationId) || !$locationId) {
$js .= "{$formName}['mapper[$i][1]'].style.display = 'none';\n";
}
if (!isset($phoneType) || !$phoneType) {
$js .= "{$formName}['mapper[$i][2]'].style.display = 'none';\n";
}
$js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
$defaults["mapper[$i]"] = array(
$mappingHeader[0],
(isset($locationId)) ? $locationId : "",
(isset($phoneType)) ? $phoneType : "",
);
$jsSet = TRUE;
}
else {
$defaults["mapper[$i]"] = array();
}
if (!$jsSet) {
for ($k = 1; $k < 4; $k++) {
$js .= "{$formName}['mapper[$i][$k]'].style.display = 'none';\n";
}
}
}
else {
// this load section to help mapping if we ran out of saved columns when doing Load Mapping
$js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
if ($hasHeaders) {
$defaults["mapper[$i]"] = array($this->defaultFromHeader($this->_columnHeaders[$i], $headerPatterns));
}
else {
$defaults["mapper[$i]"] = array($this->defaultFromData($dataPatterns, $i));
}
}
//end of load mapping
}
else {
$js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
if ($hasHeaders) {
// Infer the default from the skipped headers if we have them
$defaults["mapper[$i]"] = array(
$this->defaultFromHeader($this->_columnHeaders[$i],
$headerPatterns
),
// $defaultLocationType->id
0,
);
}
else {
// Otherwise guess the default from the form of the data
$defaults["mapper[$i]"] = array(
$this->defaultFromData($dataPatterns, $i),
// $defaultLocationType->id
0,
);
}
}
$sel->setOptions(array($sel1, $sel2, (isset($sel3)) ? $sel3 : "", (isset($sel4)) ? $sel4 : ""));
}
$js .= "</script>\n";
$this->assign('initHideBoxes', $js);
//set warning if mismatch in more than
if (isset($mappingName)) {
if (($this->_columnCount != count($mappingName))) {
$warning++;
}
}
if ($warning != 0 && $this->get('savedMapping')) {
$session = CRM_Core_Session::singleton();
$session->setStatus(ts('The data columns in this import file appear to be different from the saved mapping. Please verify that you have selected the correct saved mapping before continuing.'));
}
else {
$session = CRM_Core_Session::singleton();
$session->setStatus(NULL);
}
$this->setDefaults($defaults);
$this->addButtons(array(
array(
'type' => 'back',
'name' => ts('Previous'),
),
array(
'type' => 'next',
'name' => ts('Continue'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
'isDefault' => TRUE,
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
)
);
}
/**
* Global validation rules for the form.
*
* @param array $fields
* Posted values of the form.
*
* @param $files
* @param $self
*
* @return array
* list of errors to be posted back to the form
*/
public static function formRule($fields, $files, $self) {
$errors = array();
// define so we avoid notices below
$errors['_qf_default'] = '';
$fieldMessage = NULL;
if (!array_key_exists('savedMapping', $fields)) {
$importKeys = array();
foreach ($fields['mapper'] as $mapperPart) {
$importKeys[] = $mapperPart[0];
}
// FIXME: should use the schema titles, not redeclare them
$requiredFields = array(
'participant_contact_id' => ts('Contact ID'),
'event_id' => ts('Event ID'),
);
$contactTypeId = $self->get('contactType');
$contactTypes = array(
CRM_Import_Parser::CONTACT_INDIVIDUAL => 'Individual',
CRM_Import_Parser::CONTACT_HOUSEHOLD => 'Household',
CRM_Import_Parser::CONTACT_ORGANIZATION => 'Organization',
);
$params = array(
'used' => 'Unsupervised',
'contact_type' => $contactTypes[$contactTypeId],
);
list($ruleFields, $threshold) = CRM_Dedupe_BAO_RuleGroup::dedupeRuleFieldsWeight($params);
$weightSum = 0;
foreach ($importKeys as $key => $val) {
if (array_key_exists($val, $ruleFields)) {
$weightSum += $ruleFields[$val];
}
}
foreach ($ruleFields as $field => $weight) {
$fieldMessage .= ' ' . $field . '(weight ' . $weight . ')';
}
foreach ($requiredFields as $field => $title) {
if (!in_array($field, $importKeys)) {
if ($field == 'participant_contact_id') {
if ($weightSum >= $threshold || in_array('external_identifier', $importKeys) ||
in_array('participant_id', $importKeys)
) {
continue;
}
if ($self->_onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE) {
$errors['_qf_default'] .= ts('Missing required field: Provide Participant ID') . '<br />';
}
else {
$errors['_qf_default'] .= ts('Missing required contact matching fields.') . " $fieldMessage " . ts('(Sum of all weights should be greater than or equal to threshold: %1).', array(
1 => $threshold,
)) . ' ' . ts('Or Provide Contact ID or External ID.') . '<br />';
}
}
elseif (!in_array('event_title', $importKeys)) {
$errors['_qf_default'] .= ts('Missing required field: Provide %1 or %2',
array(1 => $title, 2 => 'Event Title')
) . '<br />';
}
}
}
}
if (!empty($fields['saveMapping'])) {
$nameField = CRM_Utils_Array::value('saveMappingName', $fields);
if (empty($nameField)) {
$errors['saveMappingName'] = ts('Name is required to save Import Mapping');
}
else {
$mappingTypeId = CRM_Core_OptionGroup::getValue('mapping_type', 'Import Participant', 'name');
if (CRM_Core_BAO_Mapping::checkMapping($nameField, $mappingTypeId)) {
$errors['saveMappingName'] = ts('Duplicate Import Participant Mapping Name');
}
}
}
//display Error if loaded mapping is not selected
if (array_key_exists('loadMapping', $fields)) {
$getMapName = CRM_Utils_Array::value('savedMapping', $fields);
if (empty($getMapName)) {
$errors['savedMapping'] = ts('Select saved mapping');
}
}
if (empty($errors['_qf_default'])) {
unset($errors['_qf_default']);
}
if (!empty($errors)) {
if (!empty($errors['saveMappingName'])) {
$_flag = 1;
$assignError = new CRM_Core_Page();
$assignError->assign('mappingDetailsError', $_flag);
}
return $errors;
}
return TRUE;
}
/**
* Process the mapped fields and map it into the uploaded file
* preview the file and extract some summary statistics
*
* @return void
*/
public function postProcess() {
$params = $this->controller->exportValues('MapField');
//reload the mapfield if load mapping is pressed
if (!empty($params['savedMapping'])) {
$this->set('savedMapping', $params['savedMapping']);
$this->controller->resetPage($this->_name);
return;
}
$fileName = $this->controller->exportValue('DataSource', 'uploadFile');
$seperator = $this->controller->exportValue('DataSource', 'fieldSeparator');
$skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
$mapperKeys = array();
$mapper = array();
$mapperKeys = $this->controller->exportValue($this->_name, 'mapper');
$mapperKeysMain = array();
for ($i = 0; $i < $this->_columnCount; $i++) {
$mapper[$i] = $this->_mapperFields[$mapperKeys[$i][0]];
$mapperKeysMain[$i] = $mapperKeys[$i][0];
}
$this->set('mapper', $mapper);
// store mapping Id to display it in the preview page
$this->set('loadMappingId', CRM_Utils_Array::value('mappingId', $params));
//Updating Mapping Records
if (!empty($params['updateMapping'])) {
$mappingFields = new CRM_Core_DAO_MappingField();
$mappingFields->mapping_id = $params['mappingId'];
$mappingFields->find();
$mappingFieldsId = array();
while ($mappingFields->fetch()) {
if ($mappingFields->id) {
$mappingFieldsId[$mappingFields->column_number] = $mappingFields->id;
}
}
for ($i = 0; $i < $this->_columnCount; $i++) {
$updateMappingFields = new CRM_Core_DAO_MappingField();
$updateMappingFields->id = $mappingFieldsId[$i];
$updateMappingFields->mapping_id = $params['mappingId'];
$updateMappingFields->column_number = $i;
$explodedValues = explode('_', $mapperKeys[$i][0]);
$id = CRM_Utils_Array::value(0, $explodedValues);
$first = CRM_Utils_Array::value(1, $explodedValues);
$second = CRM_Utils_Array::value(2, $explodedValues);
$updateMappingFields->name = $mapper[$i];
$updateMappingFields->save();
}
}
//Saving Mapping Details and Records
if (!empty($params['saveMapping'])) {
$mappingParams = array(
'name' => $params['saveMappingName'],
'description' => $params['saveMappingDesc'],
'mapping_type_id' => CRM_Core_OptionGroup::getValue('mapping_type',
'Import Participant',
'name'
),
);
$saveMapping = CRM_Core_BAO_Mapping::add($mappingParams);
for ($i = 0; $i < $this->_columnCount; $i++) {
$saveMappingFields = new CRM_Core_DAO_MappingField();
$saveMappingFields->mapping_id = $saveMapping->id;
$saveMappingFields->column_number = $i;
$explodedValues = explode('_', $mapperKeys[$i][0]);
$id = CRM_Utils_Array::value(0, $explodedValues);
$first = CRM_Utils_Array::value(1, $explodedValues);
$second = CRM_Utils_Array::value(2, $explodedValues);
$saveMappingFields->name = $mapper[$i];
$saveMappingFields->save();
}
$this->set('savedMapping', $saveMappingFields->mapping_id);
}
$parser = new CRM_Event_Import_Parser_Participant($mapperKeysMain);
$parser->run($fileName, $seperator, $mapper, $skipColumnHeader,
CRM_Import_Parser::MODE_PREVIEW, $this->get('contactType')
);
// add all the necessary variables to the form
$parser->set($this);
}
}

View file

@ -0,0 +1,179 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class previews the uploaded file and returns summary
* statistics
*/
class CRM_Event_Import_Form_Preview extends CRM_Import_Form_Preview {
/**
* Set variables up before form is built.
*
* @return void
*/
public function preProcess() {
$skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
//get the data from the session
$dataValues = $this->get('dataValues');
$mapper = $this->get('mapper');
$invalidRowCount = $this->get('invalidRowCount');
$conflictRowCount = $this->get('conflictRowCount');
$mismatchCount = $this->get('unMatchCount');
//get the mapping name displayed if the mappingId is set
$mappingId = $this->get('loadMappingId');
if ($mappingId) {
$mapDAO = new CRM_Core_DAO_Mapping();
$mapDAO->id = $mappingId;
$mapDAO->find(TRUE);
$this->assign('loadedMapping', $mappingId);
$this->assign('savedName', $mapDAO->name);
}
if ($skipColumnHeader) {
$this->assign('skipColumnHeader', $skipColumnHeader);
$this->assign('rowDisplayCount', 3);
}
else {
$this->assign('rowDisplayCount', 2);
}
if ($invalidRowCount) {
$urlParams = 'type=' . CRM_Import_Parser::ERROR . '&parser=CRM_Event_Import_Parser';
$this->set('downloadErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
if ($conflictRowCount) {
$urlParams = 'type=' . CRM_Import_Parser::CONFLICT . '&parser=CRM_Event_Import_Parser';
$this->set('downloadConflictRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
if ($mismatchCount) {
$urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . '&parser=CRM_Event_Import_Parser';
$this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
$properties = array(
'mapper',
'dataValues',
'columnCount',
'totalRowCount',
'validRowCount',
'invalidRowCount',
'conflictRowCount',
'downloadErrorRecordsUrl',
'downloadConflictRecordsUrl',
'downloadMismatchRecordsUrl',
);
foreach ($properties as $property) {
$this->assign($property, $this->get($property));
}
}
/**
* Process the mapped fields and map it into the uploaded file
* preview the file and extract some summary statistics
*
* @return void
*/
public function postProcess() {
$fileName = $this->controller->exportValue('DataSource', 'uploadFile');
$seperator = $this->controller->exportValue('DataSource', 'fieldSeparator');
$skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
$invalidRowCount = $this->get('invalidRowCount');
$conflictRowCount = $this->get('conflictRowCount');
$onDuplicate = $this->get('onDuplicate');
$mapper = $this->controller->exportValue('MapField', 'mapper');
$mapperKeys = array();
foreach ($mapper as $key => $value) {
$mapperKeys[$key] = $mapper[$key][0];
}
$parser = new CRM_Event_Import_Parser_Participant($mapperKeys);
$mapFields = $this->get('fields');
foreach ($mapper as $key => $value) {
$header = array();
if (isset($mapFields[$mapper[$key][0]])) {
$header[] = $mapFields[$mapper[$key][0]];
}
$mapperFields[] = implode(' - ', $header);
}
$parser->run($fileName, $seperator,
$mapperFields,
$skipColumnHeader,
CRM_Import_Parser::MODE_IMPORT,
$this->get('contactType'),
$onDuplicate
);
// add all the necessary variables to the form
$parser->set($this, CRM_Import_Parser::MODE_IMPORT);
// check if there is any error occurred
$errorStack = CRM_Core_Error::singleton();
$errors = $errorStack->getErrors();
$errorMessage = array();
if (is_array($errors)) {
foreach ($errors as $key => $value) {
$errorMessage[] = $value['message'];
}
$errorFile = $fileName['name'] . '.error.log';
if ($fd = fopen($errorFile, 'w')) {
fwrite($fd, implode('\n', $errorMessage));
}
fclose($fd);
$this->set('errorFile', $errorFile);
$urlParams = 'type=' . CRM_Import_Parser::ERROR . '&parser=CRM_Event_Import_Parser';
$this->set('downloadErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
$urlParams = 'type=' . CRM_Import_Parser::CONFLICT . '&parser=CRM_Event_Import_Parser';
$this->set('downloadConflictRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
$urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . '&parser=CRM_Event_Import_Parser';
$this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
}
}

View file

@ -0,0 +1,114 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class summarizes the import results
*/
class CRM_Event_Import_Form_Summary extends CRM_Import_Form_Summary {
/**
* Set variables up before form is built.
*
* @return void
*/
public function preProcess() {
// set the error message path to display
$this->assign('errorFile', $this->get('errorFile'));
$totalRowCount = $this->get('totalRowCount');
$relatedCount = $this->get('relatedCount');
$totalRowCount += $relatedCount;
$this->set('totalRowCount', $totalRowCount);
$invalidRowCount = $this->get('invalidRowCount');
$conflictRowCount = $this->get('conflictRowCount');
$duplicateRowCount = $this->get('duplicateRowCount');
$onDuplicate = $this->get('onDuplicate');
$mismatchCount = $this->get('unMatchCount');
if ($duplicateRowCount > 0) {
$urlParams = 'type=' . CRM_Import_Parser::DUPLICATE . '&parser=CRM_Event_Import_Parser';
$this->set('downloadDuplicateRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
elseif ($mismatchCount) {
$urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . '&parser=CRM_Event_Import_Parser';
$this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
else {
$duplicateRowCount = 0;
$this->set('duplicateRowCount', $duplicateRowCount);
}
$this->assign('dupeError', FALSE);
if ($onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE) {
$dupeActionString = ts('These records have been updated with the imported data.');
}
elseif ($onDuplicate == CRM_Import_Parser::DUPLICATE_FILL) {
$dupeActionString = ts('These records have been filled in with the imported data.');
}
else {
/* Skip by default */
$dupeActionString = ts('These records have not been imported.');
$this->assign('dupeError', TRUE);
/* only subtract dupes from successful import if we're skipping */
$this->set('validRowCount', $totalRowCount - $invalidRowCount -
$conflictRowCount - $duplicateRowCount - $mismatchCount
);
}
$this->assign('dupeActionString', $dupeActionString);
$properties = array(
'totalRowCount',
'validRowCount',
'invalidRowCount',
'conflictRowCount',
'downloadConflictRecordsUrl',
'downloadErrorRecordsUrl',
'duplicateRowCount',
'downloadDuplicateRecordsUrl',
'downloadMismatchRecordsUrl',
'groupAdditions',
'unMatchCount',
);
foreach ($properties as $property) {
$this->assign($property, $this->get($property));
}
}
}

View file

@ -0,0 +1,453 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
abstract class CRM_Event_Import_Parser extends CRM_Import_Parser {
protected $_fileName;
/**#@+
* @var integer
*/
/**
* Imported file size
*/
protected $_fileSize;
/**
* Seperator being used
*/
protected $_seperator;
/**
* Total number of lines in file
*/
protected $_lineCount;
/**
* Whether the file has a column header or not
*
* @var boolean
*/
protected $_haveColumnHeader;
/**
* @param string $fileName
* @param string $seperator
* @param $mapper
* @param bool $skipColumnHeader
* @param int $mode
* @param int $contactType
* @param int $onDuplicate
*
* @return mixed
* @throws Exception
*/
public function run(
$fileName,
$seperator = ',',
&$mapper,
$skipColumnHeader = FALSE,
$mode = self::MODE_PREVIEW,
$contactType = self::CONTACT_INDIVIDUAL,
$onDuplicate = self::DUPLICATE_SKIP
) {
if (!is_array($fileName)) {
CRM_Core_Error::fatal();
}
$fileName = $fileName['name'];
switch ($contactType) {
case self::CONTACT_INDIVIDUAL:
$this->_contactType = 'Individual';
break;
case self::CONTACT_HOUSEHOLD:
$this->_contactType = 'Household';
break;
case self::CONTACT_ORGANIZATION:
$this->_contactType = 'Organization';
}
$this->init();
$this->_haveColumnHeader = $skipColumnHeader;
$this->_seperator = $seperator;
$fd = fopen($fileName, "r");
if (!$fd) {
return FALSE;
}
$this->_lineCount = $this->_warningCount = 0;
$this->_invalidRowCount = $this->_validCount = 0;
$this->_totalCount = $this->_conflictCount = 0;
$this->_errors = array();
$this->_warnings = array();
$this->_conflicts = array();
$this->_fileSize = number_format(filesize($fileName) / 1024.0, 2);
if ($mode == self::MODE_MAPFIELD) {
$this->_rows = array();
}
else {
$this->_activeFieldCount = count($this->_activeFields);
}
while (!feof($fd)) {
$this->_lineCount++;
$values = fgetcsv($fd, 8192, $seperator);
if (!$values) {
continue;
}
self::encloseScrub($values);
// skip column header if we're not in mapfield mode
if ($mode != self::MODE_MAPFIELD && $skipColumnHeader) {
$skipColumnHeader = FALSE;
continue;
}
/* trim whitespace around the values */
$empty = TRUE;
foreach ($values as $k => $v) {
$values[$k] = trim($v, " \t\r\n");
}
if (CRM_Utils_System::isNull($values)) {
continue;
}
$this->_totalCount++;
if ($mode == self::MODE_MAPFIELD) {
$returnCode = $this->mapField($values);
}
elseif ($mode == self::MODE_PREVIEW) {
$returnCode = $this->preview($values);
}
elseif ($mode == self::MODE_SUMMARY) {
$returnCode = $this->summary($values);
}
elseif ($mode == self::MODE_IMPORT) {
$returnCode = $this->import($onDuplicate, $values);
}
else {
$returnCode = self::ERROR;
}
// note that a line could be valid but still produce a warning
if ($returnCode & self::VALID) {
$this->_validCount++;
if ($mode == self::MODE_MAPFIELD) {
$this->_rows[] = $values;
$this->_activeFieldCount = max($this->_activeFieldCount, count($values));
}
}
if ($returnCode & self::WARNING) {
$this->_warningCount++;
if ($this->_warningCount < $this->_maxWarningCount) {
$this->_warningCount[] = $line;
}
}
if ($returnCode & self::ERROR) {
$this->_invalidRowCount++;
if ($this->_invalidRowCount < $this->_maxErrorCount) {
$recordNumber = $this->_lineCount;
if ($this->_haveColumnHeader) {
$recordNumber--;
}
array_unshift($values, $recordNumber);
$this->_errors[] = $values;
}
}
if ($returnCode & self::CONFLICT) {
$this->_conflictCount++;
$recordNumber = $this->_lineCount;
if ($this->_haveColumnHeader) {
$recordNumber--;
}
array_unshift($values, $recordNumber);
$this->_conflicts[] = $values;
}
if ($returnCode & self::DUPLICATE) {
if ($returnCode & self::MULTIPLE_DUPE) {
/* TODO: multi-dupes should be counted apart from singles
* on non-skip action */
}
$this->_duplicateCount++;
$recordNumber = $this->_lineCount;
if ($this->_haveColumnHeader) {
$recordNumber--;
}
array_unshift($values, $recordNumber);
$this->_duplicates[] = $values;
if ($onDuplicate != self::DUPLICATE_SKIP) {
$this->_validCount++;
}
}
// we give the derived class a way of aborting the process
// note that the return code could be multiple code or'ed together
if ($returnCode & self::STOP) {
break;
}
// if we are done processing the maxNumber of lines, break
if ($this->_maxLinesToProcess > 0 && $this->_validCount >= $this->_maxLinesToProcess) {
break;
}
}
fclose($fd);
if ($mode == self::MODE_PREVIEW || $mode == self::MODE_IMPORT) {
$customHeaders = $mapper;
$customfields = CRM_Core_BAO_CustomField::getFields('Participant');
foreach ($customHeaders as $key => $value) {
if ($id = CRM_Core_BAO_CustomField::getKeyID($value)) {
$customHeaders[$key] = $customfields[$id][0];
}
}
if ($this->_invalidRowCount) {
// removed view url for invlaid contacts
$headers = array_merge(array(
ts('Line Number'),
ts('Reason'),
),
$customHeaders
);
$this->_errorFileName = self::errorFileName(self::ERROR);
self::exportCSV($this->_errorFileName, $headers, $this->_errors);
}
if ($this->_conflictCount) {
$headers = array_merge(array(
ts('Line Number'),
ts('Reason'),
),
$customHeaders
);
$this->_conflictFileName = self::errorFileName(self::CONFLICT);
self::exportCSV($this->_conflictFileName, $headers, $this->_conflicts);
}
if ($this->_duplicateCount) {
$headers = array_merge(array(
ts('Line Number'),
ts('View Participant URL'),
),
$customHeaders
);
$this->_duplicateFileName = self::errorFileName(self::DUPLICATE);
self::exportCSV($this->_duplicateFileName, $headers, $this->_duplicates);
}
}
return $this->fini();
}
/**
* Given a list of the importable field keys that the user has selected
* set the active fields array to this list
*
* @param $fieldKeys array mapped array of values
*
* @return void
*/
public function setActiveFields($fieldKeys) {
$this->_activeFieldCount = count($fieldKeys);
foreach ($fieldKeys as $key) {
if (empty($this->_fields[$key])) {
$this->_activeFields[] = new CRM_Event_Import_Field('', ts('- do not import -'));
}
else {
$this->_activeFields[] = clone($this->_fields[$key]);
}
}
}
/**
* Format the field values for input to the api.
*
* @return array
* (reference ) associative array of name/value pairs
*/
public function &getActiveFieldParams() {
$params = array();
for ($i = 0; $i < $this->_activeFieldCount; $i++) {
if (isset($this->_activeFields[$i]->_value)
&& !isset($params[$this->_activeFields[$i]->_name])
&& !isset($this->_activeFields[$i]->_related)
) {
$params[$this->_activeFields[$i]->_name] = $this->_activeFields[$i]->_value;
}
}
return $params;
}
/**
* @param string $name
* @param $title
* @param int $type
* @param string $headerPattern
* @param string $dataPattern
*/
public function addField($name, $title, $type = CRM_Utils_Type::T_INT, $headerPattern = '//', $dataPattern = '//') {
if (empty($name)) {
$this->_fields['doNotImport'] = new CRM_Event_Import_Field($name, $title, $type, $headerPattern, $dataPattern);
}
else {
//$tempField = CRM_Contact_BAO_Contact::importableFields('Individual', null );
$tempField = CRM_Contact_BAO_Contact::importableFields('All', NULL);
if (!array_key_exists($name, $tempField)) {
$this->_fields[$name] = new CRM_Event_Import_Field($name, $title, $type, $headerPattern, $dataPattern);
}
else {
$this->_fields[$name] = new CRM_Contact_Import_Field($name, $title, $type, $headerPattern, $dataPattern,
CRM_Utils_Array::value('hasLocationType', $tempField[$name])
);
}
}
}
/**
* Store parser values.
*
* @param CRM_Core_Session $store
*
* @param int $mode
*
* @return void
*/
public function set($store, $mode = self::MODE_SUMMARY) {
$store->set('fileSize', $this->_fileSize);
$store->set('lineCount', $this->_lineCount);
$store->set('seperator', $this->_seperator);
$store->set('fields', $this->getSelectValues());
$store->set('fieldTypes', $this->getSelectTypes());
$store->set('headerPatterns', $this->getHeaderPatterns());
$store->set('dataPatterns', $this->getDataPatterns());
$store->set('columnCount', $this->_activeFieldCount);
$store->set('totalRowCount', $this->_totalCount);
$store->set('validRowCount', $this->_validCount);
$store->set('invalidRowCount', $this->_invalidRowCount);
$store->set('conflictRowCount', $this->_conflictCount);
switch ($this->_contactType) {
case 'Individual':
$store->set('contactType', CRM_Import_Parser::CONTACT_INDIVIDUAL);
break;
case 'Household':
$store->set('contactType', CRM_Import_Parser::CONTACT_HOUSEHOLD);
break;
case 'Organization':
$store->set('contactType', CRM_Import_Parser::CONTACT_ORGANIZATION);
}
if ($this->_invalidRowCount) {
$store->set('errorsFileName', $this->_errorFileName);
}
if ($this->_conflictCount) {
$store->set('conflictsFileName', $this->_conflictFileName);
}
if (isset($this->_rows) && !empty($this->_rows)) {
$store->set('dataValues', $this->_rows);
}
if ($mode == self::MODE_IMPORT) {
$store->set('duplicateRowCount', $this->_duplicateCount);
if ($this->_duplicateCount) {
$store->set('duplicatesFileName', $this->_duplicateFileName);
}
}
}
/**
* Export data to a CSV file.
*
* @param string $fileName
* @param array $header
* @param array $data
*
* @return void
*/
public static function exportCSV($fileName, $header, $data) {
$output = array();
$fd = fopen($fileName, 'w');
foreach ($header as $key => $value) {
$header[$key] = "\"$value\"";
}
$config = CRM_Core_Config::singleton();
$output[] = implode($config->fieldSeparator, $header);
foreach ($data as $datum) {
foreach ($datum as $key => $value) {
if (is_array($value)) {
foreach ($value[0] as $k1 => $v1) {
if ($k1 == 'location_type_id') {
continue;
}
$datum[$k1] = $v1;
}
}
else {
$datum[$key] = "\"$value\"";
}
}
$output[] = implode($config->fieldSeparator, $datum);
}
fwrite($fd, implode("\n", $output));
fclose($fd);
}
}

View file

@ -0,0 +1,663 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
require_once 'CRM/Utils/DeprecatedUtils.php';
/**
* class to parse membership csv files
*/
class CRM_Event_Import_Parser_Participant extends CRM_Event_Import_Parser {
protected $_mapperKeys;
private $_contactIdIndex;
private $_eventIndex;
private $_participantStatusIndex;
private $_participantRoleIndex;
private $_eventTitleIndex;
/**
* Array of successfully imported participants id's
*
* @array
*/
protected $_newParticipants;
/**
* Class constructor.
*
* @param array $mapperKeys
* @param null $mapperLocType
* @param null $mapperPhoneType
*/
public function __construct(&$mapperKeys, $mapperLocType = NULL, $mapperPhoneType = NULL) {
parent::__construct();
$this->_mapperKeys = &$mapperKeys;
}
/**
* The initializer code, called before the processing.
*/
public function init() {
$fields = CRM_Event_BAO_Participant::importableFields($this->_contactType, FALSE);
$fields['event_id']['title'] = 'Event ID';
$eventfields = &CRM_Event_BAO_Event::fields();
$fields['event_title'] = $eventfields['event_title'];
foreach ($fields as $name => $field) {
$field['type'] = CRM_Utils_Array::value('type', $field, CRM_Utils_Type::T_INT);
$field['dataPattern'] = CRM_Utils_Array::value('dataPattern', $field, '//');
$field['headerPattern'] = CRM_Utils_Array::value('headerPattern', $field, '//');
$this->addField($name, $field['title'], $field['type'], $field['headerPattern'], $field['dataPattern']);
}
$this->_newParticipants = array();
$this->setActiveFields($this->_mapperKeys);
// FIXME: we should do this in one place together with Form/MapField.php
$this->_contactIdIndex = -1;
$this->_eventIndex = -1;
$this->_participantStatusIndex = -1;
$this->_participantRoleIndex = -1;
$this->_eventTitleIndex = -1;
$index = 0;
foreach ($this->_mapperKeys as $key) {
switch ($key) {
case 'participant_contact_id':
$this->_contactIdIndex = $index;
break;
case 'event_id':
$this->_eventIndex = $index;
break;
case 'participant_status':
case 'participant_status_id':
$this->_participantStatusIndex = $index;
break;
case 'participant_role_id':
$this->_participantRoleIndex = $index;
break;
case 'event_title':
$this->_eventTitleIndex = $index;
break;
}
$index++;
}
}
/**
* Handle the values in mapField mode.
*
* @param array $values
* The array of values belonging to this line.
*
* @return bool
*/
public function mapField(&$values) {
return CRM_Import_Parser::VALID;
}
/**
* Handle the values in preview mode.
*
* @param array $values
* The array of values belonging to this line.
*
* @return bool
* the result of this processing
*/
public function preview(&$values) {
return $this->summary($values);
}
/**
* Handle the values in summary mode.
*
* @param array $values
* The array of values belonging to this line.
*
* @return bool
* the result of this processing
*/
public function summary(&$values) {
$erroneousField = NULL;
$response = $this->setActiveFieldValues($values, $erroneousField);
$errorRequired = FALSE;
$index = -1;
if ($this->_eventIndex > -1 && $this->_eventTitleIndex > -1) {
array_unshift($values, ts('Select either EventID OR Event Title'));
return CRM_Import_Parser::ERROR;
}
elseif ($this->_eventTitleIndex > -1) {
$index = $this->_eventTitleIndex;
}
elseif ($this->_eventIndex > -1) {
$index = $this->_eventIndex;
}
$params = &$this->getActiveFieldParams();
if (!(($index < 0) || ($this->_participantStatusIndex < 0))) {
$errorRequired = !CRM_Utils_Array::value($this->_participantStatusIndex, $values);
if (empty($params['event_id']) && empty($params['event_title'])) {
CRM_Contact_Import_Parser_Contact::addToErrorMsg('Event', $missingField);
}
if (empty($params['participant_status_id'])) {
CRM_Contact_Import_Parser_Contact::addToErrorMsg('Participant Status', $missingField);
}
}
else {
$errorRequired = TRUE;
$missingField = NULL;
if ($index < 0) {
CRM_Contact_Import_Parser_Contact::addToErrorMsg('Event', $missingField);
}
if ($this->_participantStatusIndex < 0) {
CRM_Contact_Import_Parser_Contact::addToErrorMsg('Participant Status', $missingField);
}
}
if ($errorRequired) {
array_unshift($values, ts('Missing required field(s) :') . $missingField);
return CRM_Import_Parser::ERROR;
}
$errorMessage = NULL;
//for date-Formats
$session = CRM_Core_Session::singleton();
$dateType = $session->get('dateTypes');
foreach ($params as $key => $val) {
if ($val && ($key == 'participant_register_date')) {
if ($dateValue = CRM_Utils_Date::formatDate($params[$key], $dateType)) {
$params[$key] = $dateValue;
}
else {
CRM_Contact_Import_Parser_Contact::addToErrorMsg('Register Date', $errorMessage);
}
}
elseif ($val && ($key == 'participant_role_id' || $key == 'participant_role')) {
$roleIDs = CRM_Event_PseudoConstant::participantRole();
$val = explode(',', $val);
if ($key == 'participant_role_id') {
foreach ($val as $role) {
if (!in_array(trim($role), array_keys($roleIDs))) {
CRM_Contact_Import_Parser_Contact::addToErrorMsg('Participant Role Id', $errorMessage);
break;
}
}
}
else {
foreach ($val as $role) {
if (!CRM_Contact_Import_Parser_Contact::in_value(trim($role), $roleIDs)) {
CRM_Contact_Import_Parser_Contact::addToErrorMsg('Participant Role', $errorMessage);
break;
}
}
}
}
elseif ($val && (($key == 'participant_status_id') || ($key == 'participant_status'))) {
$statusIDs = CRM_Event_PseudoConstant::participantStatus();
if ($key == 'participant_status_id') {
if (!in_array(trim($val), array_keys($statusIDs))) {
CRM_Contact_Import_Parser_Contact::addToErrorMsg('Participant Status Id', $errorMessage);
break;
}
}
elseif (!CRM_Contact_Import_Parser_Contact::in_value($val, $statusIDs)) {
CRM_Contact_Import_Parser_Contact::addToErrorMsg('Participant Status', $errorMessage);
break;
}
}
}
//date-Format part ends
$params['contact_type'] = 'Participant';
//checking error in custom data
CRM_Contact_Import_Parser_Contact::isErrorInCustomData($params, $errorMessage);
if ($errorMessage) {
$tempMsg = "Invalid value for field(s) : $errorMessage";
array_unshift($values, $tempMsg);
$errorMessage = NULL;
return CRM_Import_Parser::ERROR;
}
return CRM_Import_Parser::VALID;
}
/**
* Handle the values in import mode.
*
* @param int $onDuplicate
* The code for what action to take on duplicates.
* @param array $values
* The array of values belonging to this line.
*
* @return bool
* the result of this processing
*/
public function import($onDuplicate, &$values) {
// first make sure this is a valid line
$response = $this->summary($values);
if ($response != CRM_Import_Parser::VALID) {
return $response;
}
$params = &$this->getActiveFieldParams();
$session = CRM_Core_Session::singleton();
$dateType = $session->get('dateTypes');
$formatted = array('version' => 3);
$customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $params));
// don't add to recent items, CRM-4399
$formatted['skipRecentView'] = TRUE;
foreach ($params as $key => $val) {
if ($val) {
if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
if ($customFields[$customFieldID]['data_type'] == 'Date') {
CRM_Contact_Import_Parser_Contact::formatCustomDate($params, $formatted, $dateType, $key);
unset($params[$key]);
}
elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
$params[$key] = CRM_Utils_String::strtoboolstr($val);
}
}
if ($key == 'participant_register_date') {
CRM_Utils_Date::convertToDefaultDate($params, $dateType, 'participant_register_date');
$formatted['participant_register_date'] = CRM_Utils_Date::processDate($params['participant_register_date']);
}
}
}
if (!(!empty($params['participant_role_id']) || !empty($params['participant_role']))) {
if (!empty($params['event_id'])) {
$params['participant_role_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'default_role_id');
}
else {
$eventTitle = $params['event_title'];
$qParams = array();
$dao = new CRM_Core_DAO();
$params['participant_role_id'] = $dao->singleValueQuery("SELECT default_role_id FROM civicrm_event WHERE title = '$eventTitle' ",
$qParams
);
}
}
//date-Format part ends
static $indieFields = NULL;
if ($indieFields == NULL) {
$indieFields = CRM_Event_BAO_Participant::import();
}
$formatValues = array();
foreach ($params as $key => $field) {
if ($field == NULL || $field === '') {
continue;
}
$formatValues[$key] = $field;
}
$formatError = $this->formatValues($formatted, $formatValues);
if ($formatError) {
array_unshift($values, $formatError['error_message']);
return CRM_Import_Parser::ERROR;
}
if (!CRM_Utils_Rule::integer($formatted['event_id'])) {
array_unshift($values, ts('Invalid value for Event ID'));
return CRM_Import_Parser::ERROR;
}
if ($onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE) {
$formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted,
NULL,
'Participant'
);
}
else {
if ($formatValues['participant_id']) {
$dao = new CRM_Event_BAO_Participant();
$dao->id = $formatValues['participant_id'];
$formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted,
$formatValues['participant_id'],
'Participant'
);
if ($dao->find(TRUE)) {
$ids = array(
'participant' => $formatValues['participant_id'],
'userId' => $session->get('userID'),
);
$participantValues = array();
//@todo calling api functions directly is not supported
$newParticipant = _civicrm_api3_deprecated_participant_check_params($formatted, $participantValues, FALSE);
if ($newParticipant['error_message']) {
array_unshift($values, $newParticipant['error_message']);
return CRM_Import_Parser::ERROR;
}
$newParticipant = CRM_Event_BAO_Participant::create($formatted, $ids);
if (!empty($formatted['fee_level'])) {
$otherParams = array(
'fee_label' => $formatted['fee_level'],
'event_id' => $newParticipant->event_id,
);
CRM_Price_BAO_LineItem::syncLineItems($newParticipant->id, 'civicrm_participant', $newParticipant->fee_amount, $otherParams);
}
$this->_newParticipant[] = $newParticipant->id;
return CRM_Import_Parser::VALID;
}
else {
array_unshift($values, 'Matching Participant record not found for Participant ID ' . $formatValues['participant_id'] . '. Row was skipped.');
return CRM_Import_Parser::ERROR;
}
}
}
if ($this->_contactIdIndex < 0) {
$error = $this->checkContactDuplicate($formatValues);
if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
$matchedIDs = explode(',', $error['error_message']['params'][0]);
if (count($matchedIDs) >= 1) {
foreach ($matchedIDs as $contactId) {
$formatted['contact_id'] = $contactId;
$formatted['version'] = 3;
$newParticipant = _civicrm_api3_deprecated_create_participant_formatted($formatted, $onDuplicate);
}
}
}
else {
// Using new Dedupe rule.
$ruleParams = array(
'contact_type' => $this->_contactType,
'used' => 'Unsupervised',
);
$fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
$disp = '';
foreach ($fieldsArray as $value) {
if (array_key_exists(trim($value), $params)) {
$paramValue = $params[trim($value)];
if (is_array($paramValue)) {
$disp .= $params[trim($value)][0][trim($value)] . " ";
}
else {
$disp .= $params[trim($value)] . " ";
}
}
}
if (!empty($params['external_identifier'])) {
if ($disp) {
$disp .= "AND {$params['external_identifier']}";
}
else {
$disp = $params['external_identifier'];
}
}
array_unshift($values, 'No matching Contact found for (' . $disp . ')');
return CRM_Import_Parser::ERROR;
}
}
else {
if (!empty($formatValues['external_identifier'])) {
$checkCid = new CRM_Contact_DAO_Contact();
$checkCid->external_identifier = $formatValues['external_identifier'];
$checkCid->find(TRUE);
if ($checkCid->id != $formatted['contact_id']) {
array_unshift($values, 'Mismatch of External ID:' . $formatValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']);
return CRM_Import_Parser::ERROR;
}
}
$newParticipant = _civicrm_api3_deprecated_create_participant_formatted($formatted, $onDuplicate);
}
if (is_array($newParticipant) && civicrm_error($newParticipant)) {
if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) {
$contactID = CRM_Utils_Array::value('contactID', $newParticipant);
$participantID = CRM_Utils_Array::value('participantID', $newParticipant);
$url = CRM_Utils_System::url('civicrm/contact/view/participant',
"reset=1&id={$participantID}&cid={$contactID}&action=view", TRUE
);
if (is_array($newParticipant['error_message']) &&
($participantID == $newParticipant['error_message']['params'][0])
) {
array_unshift($values, $url);
return CRM_Import_Parser::DUPLICATE;
}
elseif ($newParticipant['error_message']) {
array_unshift($values, $newParticipant['error_message']);
return CRM_Import_Parser::ERROR;
}
return CRM_Import_Parser::ERROR;
}
}
if (!(is_array($newParticipant) && civicrm_error($newParticipant))) {
$this->_newParticipants[] = CRM_Utils_Array::value('id', $newParticipant);
}
return CRM_Import_Parser::VALID;
}
/**
* Get the array of successfully imported Participation ids.
*
* @return array
*/
public function &getImportedParticipations() {
return $this->_newParticipants;
}
/**
* The initializer code, called before the processing
*
* @return void
*/
public function fini() {
}
/**
* Format values
*
* @todo lots of tidy up needed here - very old function relocated.
*
* @param array $values
* @param array $params
*
* @return array|null
*/
protected function formatValues(&$values, $params) {
$fields = CRM_Event_DAO_Participant::fields();
_civicrm_api3_store_values($fields, $params, $values);
$customFields = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, NULL, FALSE, FALSE, FALSE);
foreach ($params as $key => $value) {
// ignore empty values or empty arrays etc
if (CRM_Utils_System::isNull($value)) {
continue;
}
// Handling Custom Data
if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
$values[$key] = $value;
$type = $customFields[$customFieldID]['html_type'];
if ($type == 'CheckBox' || $type == 'Multi-Select') {
$mulValues = explode(',', $value);
$customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
$values[$key] = array();
foreach ($mulValues as $v1) {
foreach ($customOption as $customValueID => $customLabel) {
$customValue = $customLabel['value'];
if ((strtolower(trim($customLabel['label'])) == strtolower(trim($v1))) ||
(strtolower(trim($customValue)) == strtolower(trim($v1)))
) {
if ($type == 'CheckBox') {
$values[$key][$customValue] = 1;
}
else {
$values[$key][] = $customValue;
}
}
}
}
}
elseif ($type == 'Select' || $type == 'Radio') {
$customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
foreach ($customOption as $customFldID => $customValue) {
$val = CRM_Utils_Array::value('value', $customValue);
$label = CRM_Utils_Array::value('label', $customValue);
$label = strtolower($label);
$value = strtolower(trim($value));
if (($value == $label) || ($value == strtolower($val))) {
$values[$key] = $val;
}
}
}
}
switch ($key) {
case 'participant_contact_id':
if (!CRM_Utils_Rule::integer($value)) {
return civicrm_api3_create_error("contact_id not valid: $value");
}
if (!CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_contact WHERE id = $value")) {
return civicrm_api3_create_error("Invalid Contact ID: There is no contact record with contact_id = $value.");
}
$values['contact_id'] = $values['participant_contact_id'];
unset($values['participant_contact_id']);
break;
case 'participant_register_date':
if (!CRM_Utils_Rule::dateTime($value)) {
return civicrm_api3_create_error("$key not a valid date: $value");
}
break;
case 'event_title':
$id = CRM_Core_DAO::getFieldValue("CRM_Event_DAO_Event", $value, 'id', 'title');
$values['event_id'] = $id;
break;
case 'event_id':
if (!CRM_Utils_Rule::integer($value)) {
return civicrm_api3_create_error("Event ID is not valid: $value");
}
$dao = new CRM_Core_DAO();
$qParams = array();
$svq = $dao->singleValueQuery("SELECT id FROM civicrm_event WHERE id = $value",
$qParams
);
if (!$svq) {
return civicrm_api3_create_error("Invalid Event ID: There is no event record with event_id = $value.");
}
break;
case 'participant_status_id':
if (!CRM_Utils_Rule::integer($value)) {
return civicrm_api3_create_error("Event Status ID is not valid: $value");
}
break;
case 'participant_status':
$status = CRM_Event_PseudoConstant::participantStatus();
$values['participant_status_id'] = CRM_Utils_Array::key($value, $status);;
break;
case 'participant_role_id':
case 'participant_role':
$role = CRM_Event_PseudoConstant::participantRole();
$participantRoles = explode(",", $value);
foreach ($participantRoles as $k => $v) {
$v = trim($v);
if ($key == 'participant_role') {
$participantRoles[$k] = CRM_Utils_Array::key($v, $role);
}
else {
$participantRoles[$k] = $v;
}
}
$values['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $participantRoles);
unset($values[$key]);
break;
default:
break;
}
}
if (array_key_exists('participant_note', $params)) {
$values['participant_note'] = $params['participant_note'];
}
// CRM_Event_BAO_Participant::create() handles register_date,
// status_id and source. So, if $values contains
// participant_register_date, participant_status_id or participant_source,
// convert it to register_date, status_id or source
$changes = array(
'participant_register_date' => 'register_date',
'participant_source' => 'source',
'participant_status_id' => 'status_id',
'participant_role_id' => 'role_id',
'participant_fee_level' => 'fee_level',
'participant_fee_amount' => 'fee_amount',
'participant_id' => 'id',
);
foreach ($changes as $orgVal => $changeVal) {
if (isset($values[$orgVal])) {
$values[$changeVal] = $values[$orgVal];
unset($values[$orgVal]);
}
}
return NULL;
}
}

View file

@ -0,0 +1,198 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* This class introduces component to the system and provides all the
* information about it. It needs to extend CRM_Core_Component_Info
* abstract class.
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
class CRM_Event_Info extends CRM_Core_Component_Info {
/**
* @inheritDoc
*/
protected $keyword = 'event';
/**
* @inheritDoc
* @return array
*/
public function getInfo() {
return array(
'name' => 'CiviEvent',
'translatedName' => ts('CiviEvent'),
'title' => ts('CiviCRM Event Engine'),
'search' => 1,
'showActivitiesInCore' => 1,
);
}
/**
* @inheritDoc
* @param bool $getAllUnconditionally
* @param bool $descriptions
* Whether to return permission descriptions
*
* @return array
*/
public function getPermissions($getAllUnconditionally = FALSE, $descriptions = FALSE) {
$permissions = array(
'access CiviEvent' => array(
ts('access CiviEvent'),
ts('Create events, view all events, and view participant records (for visible contacts)'),
),
'edit event participants' => array(
ts('edit event participants'),
ts('Record and update backend event registrations'),
),
'edit all events' => array(
ts('edit all events'),
ts('Edit events even without specific ACL granted'),
),
'register for events' => array(
ts('register for events'),
ts('Register for events online'),
),
'view event info' => array(
ts('view event info'),
ts('View online event information pages'),
),
'view event participants' => array(
ts('view event participants'),
),
'delete in CiviEvent' => array(
ts('delete in CiviEvent'),
ts('Delete participants and events that you can edit'),
),
'manage event profiles' => array(
ts('manage event profiles'),
ts('Allow users to create, edit and copy event-related profile forms used for online event registration.'),
),
);
if (!$descriptions) {
foreach ($permissions as $name => $attr) {
$permissions[$name] = array_shift($attr);
}
}
return $permissions;
}
/**
* @return array
*/
public function getAnonymousPermissionWarnings() {
return array(
'access CiviEvent',
);
}
/**
* @inheritDoc
* @return array
*/
public function getUserDashboardElement() {
return array(
'name' => ts('Events'),
'title' => ts('Your Event(s)'),
'perm' => array('register for events'),
'weight' => 20,
);
}
/**
* @inheritDoc
* @return array
*/
public function registerTab() {
return array(
'title' => ts('Events'),
'id' => 'participant',
'url' => 'participant',
'weight' => 40,
);
}
/**
* @inheritDoc
* @return array
*/
public function registerAdvancedSearchPane() {
return array(
'title' => ts('Events'),
'weight' => 40,
);
}
/**
* @inheritDoc
* @return array
*/
public function getActivityTypes() {
$types = array();
$types['Event'] = array(
'title' => ts('Event'),
'callback' => 'CRM_Event_Page_EventInfo::run()',
);
return $types;
}
/**
* add shortcut to Create New.
* @param $shortCuts
* @param $newCredit
*/
public function creatNewShortcut(&$shortCuts, $newCredit) {
if (CRM_Core_Permission::check('access CiviEvent') &&
CRM_Core_Permission::check('edit event participants')
) {
$shortCut[] = array(
'path' => 'civicrm/participant/add',
'query' => "reset=1&action=add&context=standalone",
'ref' => 'new-participant',
'title' => ts('Event Registration'),
);
if ($newCredit) {
$title = ts('Event Registration') . '<br />&nbsp;&nbsp;(' . ts('credit card') . ')';
$shortCut[0]['shortCuts'][] = array(
'path' => 'civicrm/participant/add',
'query' => "reset=1&action=add&context=standalone&mode=live",
'ref' => 'new-participant-cc',
'title' => $title,
);
}
$shortCuts = array_merge($shortCuts, $shortCut);
}
}
}

View file

@ -0,0 +1,70 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class contains all the function that are called using AJAX
*/
class CRM_Event_Page_AJAX {
/**
* Building EventFee combo box.
* FIXME: This ajax callback could be eliminated in favor of an entityRef field but the priceFieldValue api doesn't currently support filtering on entity_table
*/
public function eventFee() {
$name = trim(CRM_Utils_Type::escape($_GET['term'], 'String'));
if (!$name) {
$name = '%';
}
$whereClause = "cv.label LIKE '$name%' ";
$query = "SELECT DISTINCT (
cv.label
), cv.id
FROM civicrm_price_field_value cv
LEFT JOIN civicrm_price_field cf ON cv.price_field_id = cf.id
LEFT JOIN civicrm_price_set_entity ce ON ce.price_set_id = cf.price_set_id
WHERE ce.entity_table = 'civicrm_event' AND {$whereClause}";
$dao = CRM_Core_DAO::executeQuery($query);
$results = array();
while ($dao->fetch()) {
$results[] = array('id' => $dao->id, 'text' => $dao->label);
}
CRM_Utils_JSON::output($results);
}
}

View file

@ -0,0 +1,92 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This is page is for Event Dashboard
*/
class CRM_Event_Page_DashBoard extends CRM_Core_Page {
/**
* Heart of the viewing process. The runner gets all the meta data for
* the contact and calls the appropriate type of page to view.
*
* @return void
*/
public function preProcess() {
CRM_Utils_System::setTitle(ts('CiviEvent'));
$eventSummary = CRM_Event_BAO_Event::getEventSummary();
$enableCart = Civi::settings()->get('enable_cart');
$eventSummary['tab'] = CRM_Event_Page_ManageEvent::tabs($enableCart);
$actionColumn = FALSE;
if (!empty($eventSummary) &&
isset($eventSummary['events']) &&
is_array($eventSummary['events'])
) {
foreach ($eventSummary['events'] as $e) {
if (isset($e['isMap']) || isset($e['configure'])) {
$actionColumn = TRUE;
break;
}
}
}
$this->assign('actionColumn', $actionColumn);
$this->assign('eventSummary', $eventSummary);
}
/**
* the main function that is called when the page loads,
* it decides the which action has to be taken for the page.
*
* @return null
*/
public function run() {
$this->preProcess();
$controller = new CRM_Core_Controller_Simple('CRM_Event_Form_Search', ts('events'), NULL);
$controller->setEmbedded(TRUE);
$controller->reset();
$controller->set('limit', 10);
$controller->set('force', 1);
$controller->set('context', 'dashboard');
$controller->process();
$controller->run();
return parent::run();
}
}

View file

@ -0,0 +1,374 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Event Info Page - Summmary about the event
*/
class CRM_Event_Page_EventInfo extends CRM_Core_Page {
/**
* Run the page.
*
* This method is called after the page is created. It checks for the
* type of action and executes that action.
* Finally it calls the parent's run method.
*
* @return void
*/
public function run() {
//get the event id.
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
$config = CRM_Core_Config::singleton();
// ensure that the user has permission to see this page
if (!CRM_Core_Permission::event(CRM_Core_Permission::VIEW,
$this->_id, 'view event info'
)
) {
CRM_Utils_System::setUFMessage(ts('You do not have permission to view this event'));
return CRM_Utils_System::permissionDenied();
}
$action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE);
$context = CRM_Utils_Request::retrieve('context', 'String', $this, FALSE, 'register');
$this->assign('context', $context);
// Sometimes we want to suppress the Event Full msg
$noFullMsg = CRM_Utils_Request::retrieve('noFullMsg', 'String', $this, FALSE, 'false');
// set breadcrumb to append to 2nd layer pages
$breadCrumbPath = CRM_Utils_System::url('civicrm/event/info',
"id={$this->_id}&reset=1"
);
//retrieve event information
$params = array('id' => $this->_id);
CRM_Event_BAO_Event::retrieve($params, $values['event']);
if (!$values['event']['is_active']) {
// form is inactive, die a fatal death
CRM_Utils_System::setUFMessage(ts('The event you requested is currently unavailable (contact the site administrator for assistance).'));
return CRM_Utils_System::permissionDenied();
}
if (!empty($values['event']['is_template'])) {
// form is an Event Template
CRM_Core_Error::fatal(ts('The page you requested is currently unavailable.'));
}
// Add Event Type to $values in case folks want to display it
$values['event']['event_type'] = CRM_Utils_Array::value($values['event']['event_type_id'], CRM_Event_PseudoConstant::eventType());
$this->assign('isShowLocation', CRM_Utils_Array::value('is_show_location', $values['event']));
// show event fees.
if ($this->_id && !empty($values['event']['is_monetary'])) {
//CRM-6907
$config = CRM_Core_Config::singleton();
$config->defaultCurrency = CRM_Utils_Array::value('currency',
$values['event'],
$config->defaultCurrency
);
//CRM-10434
$discountId = CRM_Core_BAO_Discount::findSet($this->_id, 'civicrm_event');
if ($discountId) {
$priceSetId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Discount', $discountId, 'price_set_id');
}
else {
$priceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_event', $this->_id);
}
// get price set options, - CRM-5209
if ($priceSetId) {
$setDetails = CRM_Price_BAO_PriceSet::getSetDetail($priceSetId, TRUE, TRUE);
$priceSetFields = $setDetails[$priceSetId]['fields'];
if (is_array($priceSetFields)) {
$fieldCnt = 1;
$visibility = CRM_Core_PseudoConstant::visibility('name');
// CRM-14492 Admin price fields should show up on event registration if user has 'administer CiviCRM' permissions
$adminFieldVisible = FALSE;
if (CRM_Core_Permission::check('administer CiviCRM')) {
$adminFieldVisible = TRUE;
}
foreach ($priceSetFields as $fid => $fieldValues) {
if (!is_array($fieldValues['options']) ||
empty($fieldValues['options']) ||
(CRM_Utils_Array::value('visibility_id', $fieldValues) != array_search('public', $visibility) && $adminFieldVisible == FALSE)
) {
continue;
}
if (count($fieldValues['options']) > 1) {
$values['feeBlock']['value'][$fieldCnt] = '';
$values['feeBlock']['label'][$fieldCnt] = $fieldValues['label'];
$values['feeBlock']['lClass'][$fieldCnt] = 'price_set_option_group-label';
$values['feeBlock']['isDisplayAmount'][$fieldCnt] = CRM_Utils_Array::value('is_display_amounts', $fieldValues);
$fieldCnt++;
$labelClass = 'price_set_option-label';
}
else {
$labelClass = 'price_set_field-label';
}
// show tax rate with amount
$invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
$taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
$displayOpt = CRM_Utils_Array::value('tax_display_settings', $invoiceSettings);
$invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
foreach ($fieldValues['options'] as $optionId => $optionVal) {
$values['feeBlock']['isDisplayAmount'][$fieldCnt] = CRM_Utils_Array::value('is_display_amounts', $fieldValues);
if ($invoicing && isset($optionVal['tax_amount'])) {
$values['feeBlock']['value'][$fieldCnt] = CRM_Price_BAO_PriceField::getTaxLabel($optionVal, 'amount', $displayOpt, $taxTerm);
$values['feeBlock']['tax_amount'][$fieldCnt] = $optionVal['tax_amount'];
}
else {
$values['feeBlock']['value'][$fieldCnt] = $optionVal['amount'];
}
$values['feeBlock']['label'][$fieldCnt] = $optionVal['label'];
$values['feeBlock']['lClass'][$fieldCnt] = $labelClass;
$fieldCnt++;
}
}
}
// Tell tpl we have price set fee data and whether it's a quick_config price set
$this->assign('isPriceSet', 1);
$this->assign('isQuickConfig', $setDetails[$priceSetId]['is_quick_config']);
}
}
$params = array('entity_id' => $this->_id, 'entity_table' => 'civicrm_event');
$values['location'] = CRM_Core_BAO_Location::getValues($params, TRUE);
// fix phone type labels
if (!empty($values['location']['phone'])) {
$phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
foreach ($values['location']['phone'] as &$val) {
if (!empty($val['phone_type_id'])) {
$val['phone_type_display'] = $phoneTypes[$val['phone_type_id']];
}
}
}
//retrieve custom field information
$groupTree = CRM_Core_BAO_CustomGroup::getTree('Event', NULL, $this->_id, 0, $values['event']['event_type_id'], NULL, TRUE, NULL, FALSE, TRUE, NULL, TRUE);
CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree, FALSE, NULL, NULL, NULL, $this->_id);
$this->assign('action', CRM_Core_Action::VIEW);
//To show the event location on maps directly on event info page
$locations = CRM_Event_BAO_Event::getMapInfo($this->_id);
if (!empty($locations) && !empty($values['event']['is_map'])) {
$this->assign('locations', $locations);
$this->assign('mapProvider', $config->mapProvider);
$this->assign('mapKey', $config->mapAPIKey);
$sumLat = $sumLng = 0;
$maxLat = $maxLng = -400;
$minLat = $minLng = 400;
foreach ($locations as $location) {
$sumLat += $location['lat'];
$sumLng += $location['lng'];
if ($location['lat'] > $maxLat) {
$maxLat = $location['lat'];
}
if ($location['lat'] < $minLat) {
$minLat = $location['lat'];
}
if ($location['lng'] > $maxLng) {
$maxLng = $location['lng'];
}
if ($location['lng'] < $minLng) {
$minLng = $location['lng'];
}
}
$center = array(
'lat' => (float ) $sumLat / count($locations),
'lng' => (float ) $sumLng / count($locations),
);
$span = array(
'lat' => (float ) ($maxLat - $minLat),
'lng' => (float ) ($maxLng - $minLng),
);
$this->assign_by_ref('center', $center);
$this->assign_by_ref('span', $span);
if ($action == CRM_Core_Action::PREVIEW) {
$mapURL = CRM_Utils_System::url('civicrm/contact/map/event',
"eid={$this->_id}&reset=1&action=preview",
FALSE, NULL, TRUE,
TRUE
);
}
else {
$mapURL = CRM_Utils_System::url('civicrm/contact/map/event',
"eid={$this->_id}&reset=1",
FALSE, NULL, TRUE,
TRUE
);
}
$this->assign('skipLocationType', TRUE);
$this->assign('mapURL', $mapURL);
}
if (CRM_Core_Permission::check('view event participants')) {
$statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1', 'label');
$statusTypesPending = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 0', 'label');
$findParticipants['statusCounted'] = implode(', ', array_values($statusTypes));
$findParticipants['statusNotCounted'] = implode(', ', array_values($statusTypesPending));
$this->assign('findParticipants', $findParticipants);
}
$participantListingID = CRM_Utils_Array::value('participant_listing_id', $values['event']);
if ($participantListingID) {
$participantListingURL = CRM_Utils_System::url('civicrm/event/participant',
"reset=1&id={$this->_id}",
FALSE, NULL, TRUE, TRUE
);
$this->assign('participantListingURL', $participantListingURL);
}
$hasWaitingList = CRM_Utils_Array::value('has_waitlist', $values['event']);
$eventFullMessage = CRM_Event_BAO_Participant::eventFull($this->_id,
FALSE,
$hasWaitingList
);
$allowRegistration = FALSE;
if (!empty($values['event']['is_online_registration'])) {
if (CRM_Event_BAO_Event::validRegistrationRequest($values['event'], $this->_id)) {
// we always generate urls for the front end in joomla
$action_query = $action === CRM_Core_Action::PREVIEW ? "&action=$action" : '';
$url = CRM_Utils_System::url('civicrm/event/register',
"id={$this->_id}&reset=1{$action_query}",
FALSE, NULL, TRUE,
TRUE
);
if (!$eventFullMessage || $hasWaitingList) {
$registerText = ts('Register Now');
if (!empty($values['event']['registration_link_text'])) {
$registerText = $values['event']['registration_link_text'];
}
// check if we're in shopping cart mode for events
$enable_cart = Civi::settings()->get('enable_cart');
if ($enable_cart) {
$link = CRM_Event_Cart_BAO_EventInCart::get_registration_link($this->_id);
$registerText = $link['label'];
$url = CRM_Utils_System::url($link['path'], $link['query'] . $action_query, FALSE, NULL, TRUE, TRUE);
}
//Fixed for CRM-4855
$allowRegistration = CRM_Event_BAO_Event::showHideRegistrationLink($values);
$this->assign('registerText', $registerText);
$this->assign('registerURL', $url);
$this->assign('eventCartEnabled', $enable_cart);
}
}
elseif (CRM_Core_Permission::check('register for events')) {
$this->assign('registerClosed', TRUE);
}
}
$this->assign('allowRegistration', $allowRegistration);
$session = CRM_Core_Session::singleton();
$params = array(
'contact_id' => $session->get('userID'),
'event_id' => CRM_Utils_Array::value('id', $values['event']),
'role_id' => CRM_Utils_Array::value('default_role_id', $values['event']),
);
if ($eventFullMessage && ($noFullMsg == 'false') || CRM_Event_BAO_Event::checkRegistration($params)) {
$statusMessage = $eventFullMessage;
if (CRM_Event_BAO_Event::checkRegistration($params)) {
if ($noFullMsg == 'false') {
if ($values['event']['allow_same_participant_emails']) {
$statusMessage = ts('It looks like you are already registered for this event. You may proceed if you want to create an additional registration.');
}
else {
$registerUrl = CRM_Utils_System::url('civicrm/event/register',
"reset=1&id={$values['event']['id']}&cid=0"
);
$statusMessage = ts("It looks like you are already registered for this event. If you want to change your registration, or you feel that you've gotten this message in error, please contact the site administrator.") . ' ' . ts('You can also <a href="%1">register another participant</a>.', array(1 => $registerUrl));
}
}
}
elseif ($hasWaitingList) {
$statusMessage = CRM_Utils_Array::value('waitlist_text', $values['event']);
if (!$statusMessage) {
$statusMessage = ts('Event is currently full, but you can register and be a part of waiting list.');
}
}
CRM_Core_Session::setStatus($statusMessage);
}
// we do not want to display recently viewed items, so turn off
$this->assign('displayRecent', FALSE);
// set page title = event title
CRM_Utils_System::setTitle($values['event']['title']);
$this->assign('event', $values['event']);
if (isset($values['feeBlock'])) {
$this->assign('feeBlock', $values['feeBlock']);
}
$this->assign('location', $values['location']);
if (CRM_Core_Permission::check('access CiviEvent')) {
$enableCart = Civi::settings()->get('enable_cart');
$this->assign('manageEventLinks', CRM_Event_Page_ManageEvent::tabs($enableCart));
}
return parent::run();
}
/**
* @return string
*/
public function getTemplateFileName() {
if ($this->_id) {
$templateFile = "CRM/Event/Page/{$this->_id}/EventInfo.tpl";
$template = CRM_Core_Page::getTemplate();
if ($template->template_exists($templateFile)) {
return $templateFile;
}
}
return parent::getTemplateFileName();
}
}

View file

@ -0,0 +1,104 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* ICalendar class
*
*/
class CRM_Event_Page_ICalendar extends CRM_Core_Page {
/**
* Heart of the iCalendar data assignment process. The runner gets all the meta
* data for the event and calls the method to output the iCalendar
* to the user. If gData param is passed on the URL, outputs gData XML format.
* Else outputs iCalendar format per IETF RFC2445. Page param true means send
* to browser as inline content. Else, we send .ics file as attachment.
*
* @return void
*/
public function run() {
$id = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE, NULL, 'GET');
$type = CRM_Utils_Request::retrieve('type', 'Positive', $this, FALSE, 0);
$start = CRM_Utils_Request::retrieve('start', 'Positive', $this, FALSE, 0);
$end = CRM_Utils_Request::retrieve('end', 'Positive', $this, FALSE, 0);
$iCalPage = CRM_Utils_Request::retrieve('list', 'Positive', $this, FALSE, 0);
$gData = CRM_Utils_Request::retrieve('gData', 'Positive', $this, FALSE, 0);
$html = CRM_Utils_Request::retrieve('html', 'Positive', $this, FALSE, 0);
$rss = CRM_Utils_Request::retrieve('rss', 'Positive', $this, FALSE, 0);
$info = CRM_Event_BAO_Event::getCompleteInfo($start, $type, $id, $end);
$this->assign('events', $info);
$this->assign('timezone', @date_default_timezone_get());
// Send data to the correct template for formatting (iCal vs. gData)
$template = CRM_Core_Smarty::singleton();
$config = CRM_Core_Config::singleton();
if ($rss) {
// rss 2.0 requires lower case dash delimited locale
$this->assign('rssLang', str_replace('_', '-', strtolower($config->lcMessages)));
$calendar = $template->fetch('CRM/Core/Calendar/Rss.tpl');
}
elseif ($gData) {
$calendar = $template->fetch('CRM/Core/Calendar/GData.tpl');
}
elseif ($html) {
// check if we're in shopping cart mode for events
$enable_cart = Civi::settings()->get('enable_cart');
if ($enable_cart) {
$this->assign('registration_links', TRUE);
}
return parent::run();
}
else {
$calendar = $template->fetch('CRM/Core/Calendar/ICal.tpl');
$calendar = preg_replace('/(?<!\r)\n/', "\r\n", $calendar);
}
// Push output for feed or download
if ($iCalPage == 1) {
if ($gData || $rss) {
CRM_Utils_ICalendar::send($calendar, 'text/xml', 'utf-8');
}
else {
CRM_Utils_ICalendar::send($calendar, 'text/plain', 'utf-8');
}
}
else {
CRM_Utils_ICalendar::send($calendar, 'text/calendar', 'utf-8', 'civicrm_ical.ics', 'attachment');
}
CRM_Utils_System::civiExit();
}
}

View file

@ -0,0 +1,565 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* Page for displaying list of events
*/
class CRM_Event_Page_ManageEvent extends CRM_Core_Page {
/**
* The action links that we need to display for the browse screen.
*
* @var array
*/
static $_actionLinks = NULL;
static $_links = NULL;
static $_tabLinks = NULL;
protected $_pager = NULL;
protected $_sortByCharacter;
protected $_isTemplate = FALSE;
/**
* Get action Links.
*
* @return array
* (reference) of action links
*/
public function &links() {
if (!(self::$_actionLinks)) {
// helper variable for nicer formatting
$copyExtra = ts('Are you sure you want to make a copy of this Event?');
$deleteExtra = ts('Are you sure you want to delete this Event?');
self::$_actionLinks = array(
CRM_Core_Action::DISABLE => array(
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable Event'),
),
CRM_Core_Action::ENABLE => array(
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable Event'),
),
CRM_Core_Action::DELETE => array(
'name' => ts('Delete'),
'url' => CRM_Utils_System::currentPath(),
'qs' => 'action=delete&id=%%id%%',
'extra' => 'onclick = "return confirm(\'' . $deleteExtra . '\');"',
'title' => ts('Delete Event'),
),
CRM_Core_Action::COPY => array(
'name' => ts('Copy'),
'url' => CRM_Utils_System::currentPath(),
'qs' => 'reset=1&action=copy&id=%%id%%',
'extra' => 'onclick = "return confirm(\'' . $copyExtra . '\');"',
'title' => ts('Copy Event'),
),
);
}
return self::$_actionLinks;
}
/**
* Get tab Links for events.
*
* @param $enableCart
*
* @return array
* (reference) of tab links
*/
public static function &tabs($enableCart) {
$cacheKey = $enableCart ? 1 : 0;
if (!(self::$_tabLinks)) {
self::$_tabLinks = array();
}
if (!isset(self::$_tabLinks[$cacheKey])) {
self::$_tabLinks[$cacheKey]['settings']
= array(
'title' => ts('Info and Settings'),
'url' => 'civicrm/event/manage/settings',
'field' => 'id',
);
self::$_tabLinks[$cacheKey]['location']
= array(
'title' => ts('Location'),
'url' => 'civicrm/event/manage/location',
'field' => 'loc_block_id',
);
self::$_tabLinks[$cacheKey]['fee']
= array(
'title' => ts('Fees'),
'url' => 'civicrm/event/manage/fee',
'field' => 'is_monetary',
);
self::$_tabLinks[$cacheKey]['registration']
= array(
'title' => ts('Online Registration'),
'url' => 'civicrm/event/manage/registration',
'field' => 'is_online_registration',
);
if (CRM_Core_Permission::check('administer CiviCRM') || CRM_Event_BAO_Event::checkPermission(NULL, CRM_Core_Permission::EDIT)) {
self::$_tabLinks[$cacheKey]['reminder']
= array(
'title' => ts('Schedule Reminders'),
'url' => 'civicrm/event/manage/reminder',
'field' => 'reminder',
);
}
self::$_tabLinks[$cacheKey]['conference']
= array(
'title' => ts('Conference Slots'),
'url' => 'civicrm/event/manage/conference',
'field' => 'slot_label_id',
);
self::$_tabLinks[$cacheKey]['friend']
= array(
'title' => ts('Tell a Friend'),
'url' => 'civicrm/event/manage/friend',
'field' => 'friend',
);
self::$_tabLinks[$cacheKey]['pcp']
= array(
'title' => ts('Personal Campaign Pages'),
'url' => 'civicrm/event/manage/pcp',
'field' => 'is_pcp_enabled',
);
self::$_tabLinks[$cacheKey]['repeat']
= array(
'title' => ts('Repeat'),
'url' => 'civicrm/event/manage/repeat',
'field' => 'is_repeating_event',
);
}
if (!$enableCart) {
unset(self::$_tabLinks[$cacheKey]['conference']);
}
CRM_Utils_Hook::tabset('civicrm/event/manage', self::$_tabLinks[$cacheKey], array());
return self::$_tabLinks[$cacheKey];
}
/**
* Run the page.
*
* This method is called after the page is created. It checks for the
* type of action and executes that action.
* Finally it calls the parent's run method.
*
* @return void
*/
public function run() {
// get the requested action
$action = CRM_Utils_Request::retrieve('action', 'String',
// default to 'browse'
$this, FALSE, 'browse'
);
// assign vars to templates
$this->assign('action', $action);
$id = CRM_Utils_Request::retrieve('id', 'Positive',
$this, FALSE, 0, 'REQUEST'
);
// figure out whether were handling an event or an event template
if ($id) {
$this->_isTemplate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $id, 'is_template');
}
elseif ($action & CRM_Core_Action::ADD) {
$this->_isTemplate = CRM_Utils_Request::retrieve('is_template', 'Boolean', $this);
}
if (!$this->_isTemplate && $id) {
$breadCrumb = array(
array(
'title' => ts('Manage Events'),
'url' => CRM_Utils_System::url(CRM_Utils_System::currentPath(), 'reset=1'),
),
);
CRM_Utils_System::appendBreadCrumb($breadCrumb);
}
// what action to take ?
if ($action & CRM_Core_Action::DELETE) {
$session = CRM_Core_Session::singleton();
$session->pushUserContext(CRM_Utils_System::url(CRM_Utils_System::currentPath(), 'reset=1&action=browse'));
$controller = new CRM_Core_Controller_Simple('CRM_Event_Form_ManageEvent_Delete',
'Delete Event',
$action
);
$controller->set('id', $id);
$controller->process();
return $controller->run();
}
elseif ($action & CRM_Core_Action::COPY) {
$this->copy();
}
// finally browse the custom groups
$this->browse();
// parent run
return parent::run();
}
/**
* Browse all events.
*
* @return void
*/
public function browse() {
Civi::resources()->addStyleFile('civicrm', 'css/searchForm.css', 1, 'html-header');
$this->_sortByCharacter = CRM_Utils_Request::retrieve('sortByCharacter',
'String',
$this
);
$createdId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, FALSE, 0);
if (strtolower($this->_sortByCharacter) == 'all' ||
!empty($_POST)
) {
$this->_sortByCharacter = '';
$this->set('sortByCharacter', '');
}
$this->_force = $this->_searchResult = NULL;
$this->search();
$params = array();
$this->_force = CRM_Utils_Request::retrieve('force', 'Boolean',
$this, FALSE
);
$this->_searchResult = CRM_Utils_Request::retrieve('searchResult', 'Boolean', $this);
$whereClause = $this->whereClause($params, FALSE, $this->_force);
$this->pagerAToZ($whereClause, $params);
$params = array();
$whereClause = $this->whereClause($params, TRUE, $this->_force);
// because is_template != 1 would be to simple
$whereClause .= ' AND (is_template = 0 OR is_template IS NULL)';
$this->pager($whereClause, $params);
list($offset, $rowCount) = $this->_pager->getOffsetAndRowCount();
// get all custom groups sorted by weight
$manageEvent = array();
$query = "
SELECT *
FROM civicrm_event
WHERE $whereClause
ORDER BY start_date desc
LIMIT $offset, $rowCount";
$dao = CRM_Core_DAO::executeQuery($query, $params, TRUE, 'CRM_Event_DAO_Event');
$permissions = CRM_Event_BAO_Event::checkPermission();
//get all campaigns.
$allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
// get the list of active event pcps
$eventPCPS = array();
$pcpDao = new CRM_PCP_DAO_PCPBlock();
$pcpDao->entity_table = 'civicrm_event';
$pcpDao->find();
while ($pcpDao->fetch()) {
$eventPCPS[$pcpDao->entity_id] = $pcpDao->entity_id;
}
// check if we're in shopping cart mode for events
$enableCart = Civi::settings()->get('enable_cart');
$this->assign('eventCartEnabled', $enableCart);
$mapping = CRM_Utils_Array::first(CRM_Core_BAO_ActionSchedule::getMappings(array(
'id' => CRM_Event_ActionMapping::EVENT_NAME_MAPPING_ID,
)));
$eventType = CRM_Core_OptionGroup::values('event_type');
while ($dao->fetch()) {
if (in_array($dao->id, $permissions[CRM_Core_Permission::VIEW])) {
$manageEvent[$dao->id] = array();
$repeat = CRM_Core_BAO_RecurringEntity::getPositionAndCount($dao->id, 'civicrm_event');
$manageEvent[$dao->id]['repeat'] = '';
if ($repeat) {
$manageEvent[$dao->id]['repeat'] = ts('Repeating (%1 of %2)', array(1 => $repeat[0], 2 => $repeat[1]));
}
CRM_Core_DAO::storeValues($dao, $manageEvent[$dao->id]);
// form all action links
$action = array_sum(array_keys($this->links()));
if ($dao->is_active) {
$action -= CRM_Core_Action::ENABLE;
}
else {
$action -= CRM_Core_Action::DISABLE;
}
if (!in_array($dao->id, $permissions[CRM_Core_Permission::DELETE])) {
$action -= CRM_Core_Action::DELETE;
}
if (!in_array($dao->id, $permissions[CRM_Core_Permission::EDIT])) {
$action -= CRM_Core_Action::UPDATE;
}
$manageEvent[$dao->id]['action'] = CRM_Core_Action::formLink(self::links(),
$action,
array('id' => $dao->id),
ts('more'),
TRUE,
'event.manage.list',
'Event',
$dao->id
);
$params = array(
'entity_id' => $dao->id,
'entity_table' => 'civicrm_event',
'is_active' => 1,
);
$defaults['location'] = CRM_Core_BAO_Location::getValues($params, TRUE);
$manageEvent[$dao->id]['friend'] = CRM_Friend_BAO_Friend::getValues($params);
if (isset($defaults['location']['address'][1]['city'])) {
$manageEvent[$dao->id]['city'] = $defaults['location']['address'][1]['city'];
}
if (isset($defaults['location']['address'][1]['state_province_id'])) {
$manageEvent[$dao->id]['state_province'] = CRM_Core_PseudoConstant::stateProvince($defaults['location']['address'][1]['state_province_id']);
}
//show campaigns on selector.
$manageEvent[$dao->id]['campaign'] = CRM_Utils_Array::value($dao->campaign_id, $allCampaigns);
$manageEvent[$dao->id]['reminder'] = CRM_Core_BAO_ActionSchedule::isConfigured($dao->id, $mapping->getId());
$manageEvent[$dao->id]['is_pcp_enabled'] = CRM_Utils_Array::value($dao->id, $eventPCPS);
$manageEvent[$dao->id]['event_type'] = CRM_Utils_Array::value($manageEvent[$dao->id]['event_type_id'], $eventType);
$manageEvent[$dao->id]['is_repeating_event'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_RecurringEntity', $dao->id, 'parent_id', 'entity_id');
// allow hooks to set 'field' value which allows configuration pop-up to show a tab as enabled/disabled
CRM_Utils_Hook::tabset('civicrm/event/manage/rows', $manageEvent, array('event_id' => $dao->id));
}
}
$manageEvent['tab'] = self::tabs($enableCart);
$this->assign('rows', $manageEvent);
$statusTypes = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 1', 'label');
$statusTypesPending = CRM_Event_PseudoConstant::participantStatus(NULL, 'is_counted = 0', 'label');
$findParticipants['statusCounted'] = implode(', ', array_values($statusTypes));
$findParticipants['statusNotCounted'] = implode(', ', array_values($statusTypesPending));
$this->assign('findParticipants', $findParticipants);
}
/**
* make a copy of a Event, including
* all the fields in the event wizard
*
* @return void
*/
public function copy() {
$id = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE, 0, 'GET');
$urlString = 'civicrm/event/manage';
$copyEvent = CRM_Event_BAO_Event::copy($id);
$urlParams = 'reset=1';
// Redirect to Copied Event Configuration
if ($copyEvent->id) {
$urlString = 'civicrm/event/manage/settings';
$urlParams .= '&action=update&id=' . $copyEvent->id;
}
return CRM_Utils_System::redirect(CRM_Utils_System::url($urlString, $urlParams));
}
public function search() {
if (isset($this->_action) & (CRM_Core_Action::ADD |
CRM_Core_Action::UPDATE |
CRM_Core_Action::DELETE
)
) {
return;
}
$form = new CRM_Core_Controller_Simple('CRM_Event_Form_SearchEvent', ts('Search Events'), CRM_Core_Action::ADD);
$form->setEmbedded(TRUE);
$form->setParent($this);
$form->process();
$form->run();
}
/**
* @param array $params
* @param bool $sortBy
* @param $force
*
* @return string
*/
public function whereClause(&$params, $sortBy = TRUE, $force) {
$values = array();
$clauses = array();
$title = $this->get('title');
$createdId = $this->get('cid');
if ($createdId) {
$clauses[] = "(created_id = {$createdId})";
}
if ($title) {
$clauses[] = "title LIKE %1";
if (strpos($title, '%') !== FALSE) {
$params[1] = array(trim($title), 'String', FALSE);
}
else {
$params[1] = array(trim($title), 'String', TRUE);
}
}
$value = $this->get('event_type_id');
if ($value) {
if (is_array($value)) {
$type = implode(',', $value);
}
$clauses[] = "event_type_id IN ({$type})";
}
$eventsByDates = $this->get('eventsByDates');
if ($this->_searchResult) {
if ($eventsByDates) {
$from = $this->get('start_date');
if (!CRM_Utils_System::isNull($from)) {
$clauses[] = '( end_date >= %3 OR end_date IS NULL )';
$params[3] = array($from, 'String');
}
$to = $this->get('end_date');
if (!CRM_Utils_System::isNull($to)) {
$clauses[] = '( start_date <= %4 OR start_date IS NULL )';
$params[4] = array($to, 'String');
}
}
else {
$curDate = date('YmdHis');
$clauses[] = "(end_date >= {$curDate} OR end_date IS NULL)";
}
}
else {
$curDate = date('YmdHis');
$clauses[] = "(end_date >= {$curDate} OR end_date IS NULL)";
}
if ($sortBy &&
$this->_sortByCharacter !== NULL
) {
$clauses[] = "title LIKE '" . strtolower(CRM_Core_DAO::escapeWildCardString($this->_sortByCharacter)) . "%'";
}
$campaignIds = $this->get('campaign_id');
if (!CRM_Utils_System::isNull($campaignIds)) {
if (!is_array($campaignIds)) {
$campaignIds = array($campaignIds);
}
$clauses[] = '( campaign_id IN ( ' . implode(' , ', array_values($campaignIds)) . ' ) )';
}
// don't do a the below assignment when doing a
// AtoZ pager clause
if ($sortBy) {
if (count($clauses) > 1 || $eventsByDates) {
$this->assign('isSearch', 1);
}
else {
$this->assign('isSearch', 0);
}
}
return !empty($clauses) ? implode(' AND ', $clauses) : '(1)';
}
/**
* @param $whereClause
* @param array $whereParams
*/
public function pager($whereClause, $whereParams) {
$params['status'] = ts('Event %%StatusMessage%%');
$params['csvString'] = NULL;
$params['buttonTop'] = 'PagerTopButton';
$params['buttonBottom'] = 'PagerBottomButton';
$params['rowCount'] = $this->get(CRM_Utils_Pager::PAGE_ROWCOUNT);
if (!$params['rowCount']) {
$params['rowCount'] = CRM_Utils_Pager::ROWCOUNT;
}
$query = "
SELECT count(id)
FROM civicrm_event
WHERE $whereClause";
$params['total'] = CRM_Core_DAO::singleValueQuery($query, $whereParams);
$this->_pager = new CRM_Utils_Pager($params);
$this->assign_by_ref('pager', $this->_pager);
}
/**
* @param $whereClause
* @param array $whereParams
*/
public function pagerAtoZ($whereClause, $whereParams) {
$query = "
SELECT DISTINCT UPPER(LEFT(title, 1)) as sort_name
FROM civicrm_event
WHERE $whereClause
ORDER BY UPPER(LEFT(title, 1))
";
$dao = CRM_Core_DAO::executeQuery($query, $whereParams);
$aToZBar = CRM_Utils_PagerAToZ::getAToZBar($dao, $this->_sortByCharacter, TRUE);
$this->assign('aToZ', $aToZBar);
}
}

View file

@ -0,0 +1,105 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
class CRM_Event_Page_ParticipantListing extends CRM_Core_Page {
protected $_id;
protected $_participantListingID;
protected $_eventTitle;
protected $_pager;
public function preProcess() {
$this->_id = CRM_Utils_Request::retrieve('id', 'Integer', $this, TRUE);
// ensure that there is a particpant type for this
$this->_participantListingID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event',
$this->_id,
'participant_listing_id'
);
if (!$this->_participantListingID) {
CRM_Core_Error::fatal(ts('The Participant Listing feature is not currently enabled for this event.'));
}
// retrieve Event Title and include it in page title
$this->_eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event',
$this->_id,
'title'
);
CRM_Utils_System::setTitle(ts('%1 - Participants', array(1 => $this->_eventTitle)));
// we do not want to display recently viewed contacts since this is potentially a public page
$this->assign('displayRecent', FALSE);
}
/**
* Run listing page.
*
* @throws \Exception
*/
public function run() {
$this->preProcess();
// get the class name from the participantListingID
$className = CRM_Core_OptionGroup::getValue('participant_listing',
$this->_participantListingID,
'value',
'Integer',
'description'
);
if ($className == 'CRM_Event_Page_ParticipantListing') {
CRM_Core_Error::fatal(ts("Participant listing code file cannot be '%1'",
array(1 => $className)
));
}
$classFile = str_replace('_',
DIRECTORY_SEPARATOR,
$className
) . '.php';
$error = include_once $classFile;
if ($error == FALSE) {
CRM_Core_Error::fatal('Participant listing code file: ' . $classFile . ' does not exist. Please verify your custom particpant listing settings in CiviCRM administrative panel.');
}
$participantListingClass = new $className();
$participantListingClass->preProcess();
$participantListingClass->run();
}
}

View file

@ -0,0 +1,42 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
class CRM_Event_Page_ParticipantListing_Name extends CRM_Event_Page_ParticipantListing_Simple {
public function preProcess() {
$this->_participantListingType = 'Name';
parent::preProcess();
}
}

View file

@ -0,0 +1,42 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
class CRM_Event_Page_ParticipantListing_NameAndEmail extends CRM_Event_Page_ParticipantListing_Simple {
public function preProcess() {
$this->_participantListingType = 'Name and Email';
parent::preProcess();
}
}

View file

@ -0,0 +1,193 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
class CRM_Event_Page_ParticipantListing_NameStatusAndDate extends CRM_Core_Page {
protected $_id;
protected $_participantListingID;
protected $_eventTitle;
protected $_pager;
public function preProcess() {
$this->_id = CRM_Utils_Request::retrieve('id', 'Integer', $this, TRUE);
// ensure that there is a particpant type for this
$this->_participantListingID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event',
$this->_id,
'participant_listing_id'
);
if (!$this->_participantListingID) {
CRM_Core_Error::fatal(ts("The Participant Listing feature is not currently enabled for this event."));
}
// retrieve Event Title and include it in page title
$this->_eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event',
$this->_id,
'title'
);
CRM_Utils_System::setTitle(ts('%1 - Participants', array(1 => $this->_eventTitle)));
// we do not want to display recently viewed contacts since this is potentially a public page
$this->assign('displayRecent', FALSE);
}
/**
* @return string
*/
public function run() {
$this->preProcess();
$fromClause = "
FROM civicrm_contact
INNER JOIN civicrm_participant ON civicrm_contact.id = civicrm_participant.contact_id
INNER JOIN civicrm_event ON civicrm_participant.event_id = civicrm_event.id
";
$whereClause = "
WHERE civicrm_event.id = %1";
$params = array(1 => array($this->_id, 'Integer'));
$this->pager($fromClause, $whereClause, $params);
$orderBy = $this->orderBy();
list($offset, $rowCount) = $this->_pager->getOffsetAndRowCount();
$query = "
SELECT civicrm_contact.id as contact_id ,
civicrm_contact.display_name as name ,
civicrm_contact.sort_name as sort_name ,
civicrm_participant.id as participant_id,
civicrm_participant.status_id as status_id ,
civicrm_participant.register_date as register_date
$fromClause
$whereClause
ORDER BY $orderBy
LIMIT $offset, $rowCount";
$rows = array();
$object = CRM_Core_DAO::executeQuery($query, $params);
$statusLookup = CRM_Event_PseudoConstant::participantStatus();
while ($object->fetch()) {
$status = CRM_Utils_Array::value($object->status_id, $statusLookup);
if ($status) {
$status = ts($status);
}
$row = array(
'id' => $object->contact_id,
'participantID' => $object->participant_id,
'name' => $object->name,
'status' => $status,
'date' => $object->register_date,
);
$rows[] = $row;
}
$this->assign_by_ref('rows', $rows);
return parent::run();
}
/**
* @param $fromClause
* @param $whereClause
* @param array $whereParams
*/
public function pager($fromClause, $whereClause, $whereParams) {
$params = array();
$params['status'] = ts('Group') . ' %%StatusMessage%%';
$params['csvString'] = NULL;
$params['buttonTop'] = 'PagerTopButton';
$params['buttonBottom'] = 'PagerBottomButton';
$params['rowCount'] = $this->get(CRM_Utils_Pager::PAGE_ROWCOUNT);
if (!$params['rowCount']) {
$params['rowCount'] = CRM_Utils_Pager::ROWCOUNT;
}
$query = "
SELECT count( civicrm_contact.id )
$fromClause
$whereClause";
$params['total'] = CRM_Core_DAO::singleValueQuery($query, $whereParams);
$this->_pager = new CRM_Utils_Pager($params);
$this->assign_by_ref('pager', $this->_pager);
}
/**
* @return string
*/
public function orderBy() {
static $headers = NULL;
if (!$headers) {
$headers = array();
$headers[1] = array(
'name' => ts('Name'),
'sort' => 'civicrm_contact.sort_name',
'direction' => CRM_Utils_Sort::ASCENDING,
);
$headers[2] = array(
'name' => ts('Status'),
'sort' => 'civicrm_participant.status_id',
'direction' => CRM_Utils_Sort::DONTCARE,
);
$headers[3] = array(
'name' => ts('Register Date'),
'sort' => 'civicrm_participant.register_date',
'direction' => CRM_Utils_Sort::DONTCARE,
);
}
$sortID = NULL;
if ($this->get(CRM_Utils_Sort::SORT_ID)) {
$sortID = CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID),
$this->get(CRM_Utils_Sort::SORT_DIRECTION)
);
}
$sort = new CRM_Utils_Sort($headers, $sortID);
$this->assign_by_ref('headers', $headers);
$this->assign_by_ref('sort', $sort);
$this->set(CRM_Utils_Sort::SORT_ID,
$sort->getCurrentSortID()
);
$this->set(CRM_Utils_Sort::SORT_DIRECTION,
$sort->getCurrentSortDirection()
);
return $sort->orderBy();
}
}

View file

@ -0,0 +1,178 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
class CRM_Event_Page_ParticipantListing_Simple extends CRM_Core_Page {
protected $_id;
protected $_participantListingType;
protected $_eventTitle;
protected $_pager;
public function preProcess() {
$this->_id = CRM_Utils_Request::retrieve('id', 'Integer', $this, TRUE);
// retrieve Event Title and include it in page title
$this->_eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event',
$this->_id,
'title'
);
CRM_Utils_System::setTitle(ts('%1 - Participants', array(1 => $this->_eventTitle)));
// we do not want to display recently viewed contacts since this is potentially a public page
$this->assign('displayRecent', FALSE);
}
/**
* @return string
*/
public function run() {
$this->preProcess();
$fromClause = "
FROM civicrm_contact
INNER JOIN civicrm_participant ON ( civicrm_contact.id = civicrm_participant.contact_id
AND civicrm_contact.is_deleted = 0 )
INNER JOIN civicrm_event ON civicrm_participant.event_id = civicrm_event.id
LEFT JOIN civicrm_email ON ( civicrm_contact.id = civicrm_email.contact_id AND civicrm_email.is_primary = 1 )
";
$whereClause = "
WHERE civicrm_event.id = %1
AND civicrm_participant.is_test = 0
AND civicrm_participant.status_id IN ( 1, 2 )";
$params = array(1 => array($this->_id, 'Integer'));
$this->pager($fromClause, $whereClause, $params);
$orderBy = $this->orderBy();
list($offset, $rowCount) = $this->_pager->getOffsetAndRowCount();
$query = "
SELECT civicrm_contact.id as contact_id ,
civicrm_contact.display_name as name ,
civicrm_contact.sort_name as sort_name ,
civicrm_participant.id as participant_id,
civicrm_email.email as email
$fromClause
$whereClause
ORDER BY $orderBy
LIMIT $offset, $rowCount";
$rows = array();
$object = CRM_Core_DAO::executeQuery($query, $params);
while ($object->fetch()) {
$row = array(
'id' => $object->contact_id,
'participantID' => $object->participant_id,
'name' => $object->name,
'email' => $object->email,
);
$rows[] = $row;
}
$this->assign_by_ref('rows', $rows);
return parent::run();
}
/**
* @param $fromClause
* @param $whereClause
* @param array $whereParams
*/
public function pager($fromClause, $whereClause, $whereParams) {
$params = array();
$params['status'] = ts('Group') . ' %%StatusMessage%%';
$params['csvString'] = NULL;
$params['buttonTop'] = 'PagerTopButton';
$params['buttonBottom'] = 'PagerBottomButton';
$params['rowCount'] = $this->get(CRM_Utils_Pager::PAGE_ROWCOUNT);
if (!$params['rowCount']) {
$params['rowCount'] = CRM_Utils_Pager::ROWCOUNT;
}
$query = "
SELECT count( civicrm_contact.id )
$fromClause
$whereClause
";
$params['total'] = CRM_Core_DAO::singleValueQuery($query, $whereParams);
$this->_pager = new CRM_Utils_Pager($params);
$this->assign_by_ref('pager', $this->_pager);
}
/**
* @return string
*/
public function orderBy() {
static $headers = NULL;
if (!$headers) {
$headers = array();
$headers[1] = array(
'name' => ts('Name'),
'sort' => 'civicrm_contact.sort_name',
'direction' => CRM_Utils_Sort::ASCENDING,
);
if ($this->_participantListingType == 'Name and Email') {
$headers[2] = array(
'name' => ts('Email'),
'sort' => 'civicrm_email.email',
'direction' => CRM_Utils_Sort::DONTCARE,
);
}
}
$sortID = NULL;
if ($this->get(CRM_Utils_Sort::SORT_ID)) {
$sortID = CRM_Utils_Sort::sortIDValue($this->get(CRM_Utils_Sort::SORT_ID),
$this->get(CRM_Utils_Sort::SORT_DIRECTION)
);
}
$sort = new CRM_Utils_Sort($headers, $sortID);
$this->assign_by_ref('headers', $headers);
$this->assign_by_ref('sort', $sort);
$this->set(CRM_Utils_Sort::SORT_ID,
$sort->getCurrentSortID()
);
$this->set(CRM_Utils_Sort::SORT_DIRECTION,
$sort->getCurrentSortDirection()
);
return $sort->orderBy();
}
}

View file

@ -0,0 +1,307 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
class CRM_Event_Page_Tab extends CRM_Core_Page {
public $_permission = NULL;
public $_contactId = NULL;
/**
* called when action is browse.
*/
public function browse() {
$controller = new CRM_Core_Controller_Simple(
'CRM_Event_Form_Search',
ts('Events'),
$this->_action
);
$controller->setEmbedded(TRUE);
$controller->reset();
$controller->set('cid', $this->_contactId);
$controller->set('context', 'participant');
$controller->process();
$controller->run();
if ($this->_contactId) {
$displayName = CRM_Contact_BAO_Contact::displayName($this->_contactId);
$this->assign('displayName', $displayName);
$this->ajaxResponse['tabCount'] = CRM_Contact_BAO_Contact::getCountComponent('participant', $this->_contactId);
// Refresh other tabs with related data
$this->ajaxResponse['updateTabs'] = array(
'#tab_activity' => CRM_Contact_BAO_Contact::getCountComponent('activity', $this->_contactId),
);
if (CRM_Core_Permission::access('CiviContribute')) {
$this->ajaxResponse['updateTabs']['#tab_contribute'] = CRM_Contact_BAO_Contact::getCountComponent('contribution', $this->_contactId);
}
}
}
/**
* called when action is view.
*
* @return null
*/
public function view() {
// build associated contributions
$this->associatedContribution();
$controller = new CRM_Core_Controller_Simple(
'CRM_Event_Form_ParticipantView',
ts('View Participant'),
$this->_action
);
$controller->setEmbedded(TRUE);
$controller->set('id', $this->_id);
$controller->set('cid', $this->_contactId);
return $controller->run();
}
/**
* called when action is update or new.
*
* @return null
*/
public function edit() {
// set https for offline cc transaction
$mode = CRM_Utils_Request::retrieve('mode', 'String', $this);
if ($mode == 'test' || $mode == 'live') {
CRM_Utils_System::redirectToSSL();
}
if ($this->_action != CRM_Core_Action::ADD) {
// get associated contributions only on edit/delete
$this->associatedContribution();
}
$controller = new CRM_Core_Controller_Simple(
'CRM_Event_Form_Participant',
'Create Participation',
$this->_action
);
$controller->setEmbedded(TRUE);
$controller->set('id', $this->_id);
$controller->set('cid', $this->_contactId);
return $controller->run();
}
public function preProcess() {
$context = CRM_Utils_Request::retrieve('context', 'String', $this);
$this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
if ($context == 'standalone') {
$this->_action = CRM_Core_Action::ADD;
}
else {
$this->_contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
$this->assign('contactId', $this->_contactId);
// check logged in url permission
CRM_Contact_Page_View::checkUserPermission($this);
}
$this->assign('action', $this->_action);
if ($this->_permission == CRM_Core_Permission::EDIT && !CRM_Core_Permission::check('edit event participants')) {
// demote to view since user does not have edit event participants rights
$this->_permission = CRM_Core_Permission::VIEW;
$this->assign('permission', 'view');
}
}
/**
* the main function that is called when the page loads, it decides the which action has to be taken for the page.
*
* @return null
*/
public function run() {
$this->preProcess();
// check if we can process credit card registration
$this->assign('newCredit', CRM_Core_Config::isEnabledBackOfficeCreditCardPayments());
// Only show credit card registration button if user has CiviContribute permission
if (CRM_Core_Permission::access('CiviContribute')) {
$this->assign('accessContribution', TRUE);
}
else {
$this->assign('accessContribution', FALSE);
}
$this->setContext();
if ($this->_action & CRM_Core_Action::VIEW) {
$this->view();
}
elseif ($this->_action & (CRM_Core_Action::UPDATE |
CRM_Core_Action::ADD |
CRM_Core_Action::DELETE
)
) {
$this->edit();
}
else {
$this->browse();
}
return parent::run();
}
public function setContext() {
$context = CRM_Utils_Request::retrieve('context',
'String', $this, FALSE, 'search'
);
$compContext = CRM_Utils_Request::retrieve('compContext',
'String', $this
);
$searchContext = CRM_Utils_Request::retrieve('searchContext', 'String', $this);
$qfKey = CRM_Utils_Request::retrieve('key', 'String', $this);
//validate the qfKey
if (!CRM_Utils_Rule::qfKey($qfKey)) {
$qfKey = NULL;
}
switch ($context) {
case 'dashboard':
$url = CRM_Utils_System::url('civicrm/event', 'reset=1');
break;
case 'search':
$urlParams = 'force=1';
if ($qfKey) {
$urlParams .= "&qfKey=$qfKey";
}
$this->assign('searchKey', $qfKey);
if ($compContext == 'advanced') {
$url = CRM_Utils_System::url('civicrm/contact/search/advanced', $urlParams);
}
elseif ($searchContext) {
$url = CRM_Utils_System::url("civicrm/$searchContext/search", $urlParams);
}
else {
$url = CRM_Utils_System::url('civicrm/event/search', $urlParams);
}
break;
case 'user':
$url = CRM_Utils_System::url('civicrm/user', 'reset=1');
break;
case 'participant':
$url = CRM_Utils_System::url('civicrm/contact/view',
"reset=1&force=1&cid={$this->_contactId}&selectedChild=participant"
);
break;
case 'home':
$url = CRM_Utils_System::url('civicrm/dashboard', 'force=1');
break;
case 'activity':
$url = CRM_Utils_System::url('civicrm/contact/view',
"reset=1&force=1&cid={$this->_contactId}&selectedChild=activity"
);
break;
case 'standalone':
$url = CRM_Utils_System::url('civicrm/dashboard', 'reset=1');
break;
case 'fulltext':
$keyName = '&qfKey';
$urlParams = 'force=1';
$urlString = 'civicrm/contact/search/custom';
if ($this->_action == CRM_Core_Action::UPDATE) {
if ($this->_contactId) {
$urlParams .= '&cid=' . $this->_contactId;
}
$keyName = '&key';
$urlParams .= '&context=fulltext&action=view';
$urlString = 'civicrm/contact/view/participant';
}
if ($qfKey) {
$urlParams .= "$keyName=$qfKey";
}
$this->assign('searchKey', $qfKey);
$url = CRM_Utils_System::url($urlString, $urlParams);
break;
default:
$cid = NULL;
if ($this->_contactId) {
$cid = '&cid=' . $this->_contactId;
}
$url = CRM_Utils_System::url('civicrm/event/search',
'force=1' . $cid
);
break;
}
$session = CRM_Core_Session::singleton();
$session->pushUserContext($url);
}
/**
* used for the to show the associated
* contribution for the participant
*/
public function associatedContribution() {
if (CRM_Core_Permission::access('CiviContribute')) {
$this->assign('accessContribution', TRUE);
$controller = new CRM_Core_Controller_Simple(
'CRM_Contribute_Form_Search',
ts('Contributions'),
NULL,
FALSE, FALSE, TRUE
);
$controller->setEmbedded(TRUE);
$controller->set('force', 1);
$controller->set('cid', $this->_contactId);
$controller->set('participantId', $this->_id);
$controller->set('context', 'contribution');
$controller->process();
$controller->run();
}
else {
$this->assign('accessContribution', FALSE);
}
}
}

View file

@ -0,0 +1,71 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class is for building event(participation) block on user dashboard
*/
class CRM_Event_Page_UserDashboard extends CRM_Contact_Page_View_UserDashBoard {
/**
* List participations for the UF user.
*
*/
public function listParticipations() {
$controller = new CRM_Core_Controller_Simple(
'CRM_Event_Form_Search',
ts('Events'),
NULL,
FALSE, FALSE, TRUE, FALSE
);
$controller->setEmbedded(TRUE);
$controller->reset();
$controller->set('context', 'user');
$controller->set('cid', $this->_contactId);
$controller->set('force', 1);
$controller->process();
$controller->run();
}
/**
* the main function that is called when the page
* loads, it decides the which action has to be taken for the page.
*
*/
public function run() {
parent::preProcess();
$this->listParticipations();
}
}

View file

@ -0,0 +1,322 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class holds all the Pseudo constants that are specific to Event. This avoids
* polluting the core class and isolates the Event
*/
class CRM_Event_PseudoConstant extends CRM_Core_PseudoConstant {
/**
* Event
*
* @var array
*/
private static $event;
/**
* Participant Status
*
* @var array
*/
private static $participantStatus;
/**
* Participant Role
*
* @var array
*/
private static $participantRole;
/**
* Participant Listing
*
* @var array
*/
private static $participantListing;
/**
* Event Type.
*
* @var array
*/
private static $eventType;
/**
* Event template titles
* @var array
*/
private static $eventTemplates;
/**
* Personal campaign pages
* @var array
*/
private static $pcPage;
/**
* Get all the n events
*
*
* @param int $id
* @param bool $all
* @param null $condition
*
* @return array
* array of all events if any
*/
public static function event($id = NULL, $all = FALSE, $condition = NULL) {
$key = "{$id}_{$all}_{$condition}";
if (!isset(self::$event[$key])) {
self::$event[$key] = array();
}
if (!self::$event[$key]) {
CRM_Core_PseudoConstant::populate(self::$event[$key],
'CRM_Event_DAO_Event',
$all, 'title', 'is_active', $condition, NULL
);
}
if ($id) {
if (array_key_exists($id, self::$event[$key])) {
return self::$event[$key][$id];
}
else {
return NULL;
}
}
return self::$event[$key];
}
/**
* Get all the n participant statuses.
*
*
* @param int $id
* @param null $cond
* @param string $retColumn
* Tells populate() whether to return 'name' (default) or 'label' values.
*
* @return array
* array reference of all participant statuses if any
*/
public static function &participantStatus($id = NULL, $cond = NULL, $retColumn = 'name') {
if (self::$participantStatus === NULL) {
self::$participantStatus = array();
}
$index = $cond ? $cond : 'No Condition';
$index = "{$index}_{$retColumn}";
if (!CRM_Utils_Array::value($index, self::$participantStatus)) {
self::$participantStatus[$index] = array();
CRM_Core_PseudoConstant::populate(self::$participantStatus[$index],
'CRM_Event_DAO_ParticipantStatusType',
FALSE, $retColumn, 'is_active', $cond, 'weight'
);
}
if ($id) {
return self::$participantStatus[$index][$id];
}
return self::$participantStatus[$index];
}
/**
* Get participant status class options.
*
* @return array
*/
public static function participantStatusClassOptions() {
return array(
'Positive' => ts('Positive'),
'Pending' => ts('Pending'),
'Waiting' => ts('Waiting'),
'Negative' => ts('Negative'),
);
}
/**
* Return a status-type-keyed array of status classes
*
* @return array
* Array of status classes, keyed by status type
*/
public static function &participantStatusClass() {
static $statusClasses = NULL;
if ($statusClasses === NULL) {
self::populate($statusClasses, 'CRM_Event_DAO_ParticipantStatusType', TRUE, 'class');
}
return $statusClasses;
}
/**
* Get all the n participant roles.
*
*
* @param int $id
* @param null $cond
*
* @return array
* array reference of all participant roles if any
*/
public static function &participantRole($id = NULL, $cond = NULL) {
$index = $cond ? $cond : 'No Condition';
if (!CRM_Utils_Array::value($index, self::$participantRole)) {
self::$participantRole[$index] = array();
$condition = NULL;
if ($cond) {
$condition = "AND $cond";
}
self::$participantRole[$index] = CRM_Core_OptionGroup::values('participant_role', FALSE, FALSE,
FALSE, $condition
);
}
if ($id) {
return self::$participantRole[$index][$id];
}
return self::$participantRole[$index];
}
/**
* Get all the participant listings.
*
*
* @param int $id
*
* @return array
* array reference of all participant listings if any
*/
public static function &participantListing($id = NULL) {
if (!self::$participantListing) {
self::$participantListing = array();
self::$participantListing = CRM_Core_OptionGroup::values('participant_listing');
}
if ($id) {
return self::$participantListing[$id];
}
return self::$participantListing;
}
/**
* Get all event types.
*
*
* @param int $id
* @return array
* array reference of all event types.
*/
public static function &eventType($id = NULL) {
if (!self::$eventType) {
self::$eventType = array();
self::$eventType = CRM_Core_OptionGroup::values('event_type');
}
if ($id) {
return self::$eventType[$id];
}
return self::$eventType;
}
/**
* Get event template titles.
*
* @param int $id
*
* @return array
* Array of event id template title pairs
*/
public static function &eventTemplates($id = NULL) {
if (!self::$eventTemplates) {
CRM_Core_PseudoConstant::populate(self::$eventTemplates,
'CRM_Event_DAO_Event',
FALSE,
'template_title',
'is_active',
'is_template = 1'
);
}
if ($id) {
return self::$eventTemplates[$id];
}
return self::$eventTemplates;
}
/**
* Flush given pseudoconstant so it can be reread from db
* nex time it's requested.
*
*
* @param bool|string $name pseudoconstant to be flushed
*/
public static function flush($name = 'cache') {
if (isset(self::$$name)) {
self::$$name = NULL;
}
}
/**
* Get all the Personal campaign pages.
*
*
* @param int $id
* @return array
* array reference of all pcp if any
*/
public static function &pcPage($id = NULL) {
if (!self::$pcPage) {
CRM_Core_PseudoConstant::populate(self::$pcPage,
'CRM_PCP_DAO_PCP',
FALSE, 'title'
);
}
if ($id) {
return CRM_Utils_Array::value($id, self::$pcPage);
}
return self::$pcPage;
}
}

View file

@ -0,0 +1,542 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* This class is used to retrieve and display a range of
* contacts that match the given criteria (specifically for
* results of advanced search options.
*
*/
class CRM_Event_Selector_Search extends CRM_Core_Selector_Base implements CRM_Core_Selector_API {
/**
* This defines two actions- View and Edit.
*
* @var array
*/
static $_links = NULL;
/**
* We use desc to remind us what that column is, name is used in the tpl
*
* @var array
*/
static $_columnHeaders;
/**
* Properties of contact we're interested in displaying
* @var array
*/
static $_properties = array(
'contact_id',
'contact_type',
'sort_name',
'event_id',
'participant_status_id',
'event_title',
'participant_fee_level',
'participant_id',
'event_start_date',
'event_end_date',
'event_type_id',
'modified_date',
'participant_is_test',
'participant_role_id',
'participant_register_date',
'participant_fee_amount',
'participant_fee_currency',
'participant_status',
'participant_role',
'participant_campaign_id',
);
/**
* Are we restricting ourselves to a single contact
*
* @var boolean
*/
protected $_single = FALSE;
/**
* Are we restricting ourselves to a single contact
*
* @var boolean
*/
protected $_limit = NULL;
/**
* What context are we being invoked from
*
* @var string
*/
protected $_context = NULL;
/**
* What component context are we being invoked from
*
* @var string
*/
protected $_compContext = NULL;
/**
* QueryParams is the array returned by exportValues called on
* the HTML_QuickForm_Controller for that page.
*
* @var array
*/
public $_queryParams;
/**
* Represent the type of selector.
*
* @var int
*/
protected $_action;
/**
* The additional clause that we restrict the search with.
*
* @var string
*/
protected $_eventClause = NULL;
/**
* The query object.
*
* @var string
*/
protected $_query;
/**
* Class constructor.
*
* @param array $queryParams
* Array of parameters for query.
* @param \const|int $action - action of search basic or advanced.
* @param string $eventClause
* If the caller wants to further restrict the search (used in participations).
* @param bool $single
* Are we dealing only with one contact?.
* @param int $limit
* How many participations do we want returned.
*
* @param string $context
* @param null $compContext
*
* @return \CRM_Event_Selector_Search
*/
public function __construct(
&$queryParams,
$action = CRM_Core_Action::NONE,
$eventClause = NULL,
$single = FALSE,
$limit = NULL,
$context = 'search',
$compContext = NULL
) {
// submitted form values
$this->_queryParams = &$queryParams;
$this->_single = $single;
$this->_limit = $limit;
$this->_context = $context;
$this->_compContext = $compContext;
$this->_eventClause = $eventClause;
// type of selector
$this->_action = $action;
$this->_query = new CRM_Contact_BAO_Query($this->_queryParams,
CRM_Event_BAO_Query::defaultReturnProperties(CRM_Contact_BAO_Query::MODE_EVENT,
FALSE
),
NULL, FALSE, FALSE,
CRM_Contact_BAO_Query::MODE_EVENT
);
$this->_query->_distinctComponentClause = " civicrm_participant.id";
$this->_query->_groupByComponentClause = " GROUP BY civicrm_participant.id ";
}
/**
* Can be used to alter the number of participation returned from a buildForm hook.
*
* @param int $limit
* How many participations do we want returned.
*/
public function setLimit($limit) {
$this->_limit = $limit;
}
/**
* This method returns the links that are given for each search row.
* currently the links added for each row are
*
* - View
* - Edit
*
* @param null $qfKey
* @param null $context
* @param null $compContext
*
* @return array
*/
public static function &links($qfKey = NULL, $context = NULL, $compContext = NULL) {
$extraParams = NULL;
if ($compContext) {
$extraParams .= "&compContext={$compContext}";
}
elseif ($context == 'search') {
$extraParams .= '&compContext=participant';
}
if ($qfKey) {
$extraParams .= "&key={$qfKey}";
}
if (!(self::$_links)) {
self::$_links = array(
CRM_Core_Action::VIEW => array(
'name' => ts('View'),
'url' => 'civicrm/contact/view/participant',
'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=view&context=%%cxt%%&selectedChild=event' . $extraParams,
'title' => ts('View Participation'),
),
CRM_Core_Action::UPDATE => array(
'name' => ts('Edit'),
'url' => 'civicrm/contact/view/participant',
'qs' => 'reset=1&action=update&id=%%id%%&cid=%%cid%%&context=%%cxt%%' . $extraParams,
'title' => ts('Edit Participation'),
),
CRM_Core_Action::DELETE => array(
'name' => ts('Delete'),
'url' => 'civicrm/contact/view/participant',
'qs' => 'reset=1&action=delete&id=%%id%%&cid=%%cid%%&context=%%cxt%%' . $extraParams,
'title' => ts('Delete Participation'),
),
);
}
return self::$_links;
}
/**
* Getter for array of the parameters required for creating pager.
*
* @param $action
* @param array $params
*/
public function getPagerParams($action, &$params) {
$params['status'] = ts('Event') . ' %%StatusMessage%%';
$params['csvString'] = NULL;
if ($this->_limit) {
$params['rowCount'] = $this->_limit;
}
else {
$params['rowCount'] = CRM_Utils_Pager::ROWCOUNT;
}
$params['buttonTop'] = 'PagerTopButton';
$params['buttonBottom'] = 'PagerBottomButton';
}
/**
* Returns total number of rows for the query.
*
* @param int $action
*
* @return int
* Total number of rows
*/
public function getTotalCount($action) {
return $this->_query->searchQuery(0, 0, NULL,
TRUE, FALSE,
FALSE, FALSE,
FALSE,
$this->_eventClause
);
}
/**
* Returns all the rows in the given offset and rowCount.
*
* @param string $action
* The action being performed.
* @param int $offset
* The row number to start from.
* @param int $rowCount
* The number of rows to return.
* @param string $sort
* The sql string that describes the sort order.
* @param string $output
* What should the result set include (web/email/csv).
*
* @return array
* rows in the given offset and rowCount
*/
public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
$result = $this->_query->searchQuery($offset, $rowCount, $sort,
FALSE, FALSE,
FALSE, FALSE,
FALSE,
$this->_eventClause
);
// process the result of the query
$rows = array();
//lets handle view, edit and delete separately. CRM-4418
$permissions = array(CRM_Core_Permission::VIEW);
if (CRM_Core_Permission::check('edit event participants')) {
$permissions[] = CRM_Core_Permission::EDIT;
}
if (CRM_Core_Permission::check('delete in CiviEvent')) {
$permissions[] = CRM_Core_Permission::DELETE;
}
$mask = CRM_Core_Action::mask($permissions);
$statusTypes = CRM_Event_PseudoConstant::participantStatus();
$statusClasses = CRM_Event_PseudoConstant::participantStatusClass();
$participantRoles = CRM_Event_PseudoConstant::participantRole();
$sep = CRM_Core_DAO::VALUE_SEPARATOR;
//get all campaigns.
$allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
while ($result->fetch()) {
$row = array();
// the columns we are interested in
foreach (self::$_properties as $property) {
if (isset($result->$property)) {
$row[$property] = $result->$property;
}
}
// Skip registration if event_id is NULL
if (empty($row['event_id'])) {
Civi::log()->warning('Participant record without event ID. You have invalid data in your database!');
continue;
}
//carry campaign on selectors.
$row['campaign'] = CRM_Utils_Array::value($result->participant_campaign_id, $allCampaigns);
$row['campaign_id'] = $result->participant_campaign_id;
// gross hack to show extra information for pending status
$statusClass = NULL;
if ((isset($row['participant_status_id'])) &&
($statusId = array_search($row['participant_status_id'], $statusTypes))
) {
$statusClass = $statusClasses[$statusId];
}
$row['showConfirmUrl'] = ($statusClass == 'Pending') ? TRUE : FALSE;
if (!empty($row['participant_is_test'])) {
$row['participant_status'] .= ' (' . ts('test') . ')';
}
$row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->participant_id;
$links = self::links($this->_key, $this->_context, $this->_compContext);
if ($statusTypes[$row['participant_status_id']] == 'Partially paid') {
$links[CRM_Core_Action::ADD] = array(
'name' => ts('Record Payment'),
'url' => 'civicrm/payment',
'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=add&component=event',
'title' => ts('Record Payment'),
);
if (CRM_Core_Config::isEnabledBackOfficeCreditCardPayments()) {
$links[CRM_Core_Action::BASIC] = array(
'name' => ts('Submit Credit Card payment'),
'url' => 'civicrm/payment/add',
'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=add&component=event&mode=live',
'title' => ts('Submit Credit Card payment'),
);
}
}
if ($statusTypes[$row['participant_status_id']] == 'Pending refund') {
$links[CRM_Core_Action::ADD] = array(
'name' => ts('Record Refund'),
'url' => 'civicrm/payment',
'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=add&component=event',
'title' => ts('Record Refund'),
);
}
$row['action'] = CRM_Core_Action::formLink($links,
$mask,
array(
'id' => $result->participant_id,
'cid' => $result->contact_id,
'cxt' => $this->_context,
),
ts('more'),
FALSE,
'participant.selector.row',
'Participant',
$result->participant_id
);
$row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type, FALSE, $result->contact_id
);
$row['paid'] = CRM_Event_BAO_Event::isMonetary($row['event_id']);
if (!empty($row['participant_fee_level'])) {
CRM_Event_BAO_Participant::fixEventLevel($row['participant_fee_level']);
}
if (CRM_Event_BAO_Event::usesPriceSet($row['event_id'])) {
// add line item details if applicable
$lineItems[$row['participant_id']] = CRM_Price_BAO_LineItem::getLineItems($row['participant_id']);
}
if (!empty($row['participant_role_id'])) {
$viewRoles = array();
foreach (explode($sep, $row['participant_role_id']) as $k => $v) {
$viewRoles[] = $participantRoles[$v];
}
$row['participant_role_id'] = implode(', ', $viewRoles);
}
$rows[] = $row;
}
CRM_Core_Selector_Controller::$_template->assign_by_ref('lineItems', $lineItems);
return $rows;
}
/**
* @inheritDoc
*/
public function getQILL() {
return $this->_query->qill();
}
/**
* Returns the column headers as an array of tuples:
* (name, sortName (key to the sort array))
*
* @param string $action
* The action being performed.
* @param string $output
* What should the result set include (web/email/csv).
*
* @return array
* the column headers that need to be displayed
*/
public function &getColumnHeaders($action = NULL, $output = NULL) {
if (!isset(self::$_columnHeaders)) {
self::$_columnHeaders = array(
array(
'name' => ts('Event'),
'sort' => 'event_title',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Fee Level'),
'sort' => 'participant_fee_level',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Amount'),
'sort' => 'participant_fee_amount',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Registered'),
'sort' => 'participant_register_date',
'direction' => CRM_Utils_Sort::DESCENDING,
),
array(
'name' => ts('Event Date(s)'),
'sort' => 'event_start_date',
'direction' => CRM_Utils_Sort::DESCENDING,
),
array(
'name' => ts('Status'),
'sort' => 'participant_status',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Role'),
'sort' => 'participant_role_id',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array('desc' => ts('Actions')),
);
if (!$this->_single) {
$pre = array(
array('desc' => ts('Contact Type')),
array(
'name' => ts('Participant'),
'sort' => 'sort_name',
'direction' => CRM_Utils_Sort::DONTCARE,
),
);
self::$_columnHeaders = array_merge($pre, self::$_columnHeaders);
}
}
return self::$_columnHeaders;
}
/**
* @return mixed
*/
public function alphabetQuery() {
return $this->_query->searchQuery(NULL, NULL, NULL, FALSE, FALSE, TRUE);
}
/**
* @return string
*/
public function &getQuery() {
return $this->_query;
}
/**
* Name of export file.
*
* @param string $output
* Type of output.
*
* @return string
* name of the file
*/
public function getExportFileName($output = 'csv') {
return ts('CiviCRM Event Search');
}
}

View file

@ -0,0 +1,101 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* State machine for managing different states of the EventWizard process.
*
*/
class CRM_Event_StateMachine_Registration extends CRM_Core_StateMachine {
/**
* Class constructor.
*
* @param object $controller
* @param \const|int $action
*
* @return \CRM_Event_StateMachine_Registration CRM_Event_StateMachine
*/
public function __construct($controller, $action = CRM_Core_Action::NONE) {
parent::__construct($controller, $action);
$id = CRM_Utils_Request::retrieve('id', 'Positive', $controller, TRUE);
$is_monetary = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $id, 'is_monetary');
$is_confirm_enabled = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $id, 'is_confirm_enabled');
$pages = array('CRM_Event_Form_Registration_Register' => NULL);
//handle additional participant scenario, where we need to insert participant pages on runtime
$additionalParticipant = NULL;
// check that the controller has some data, hence we dont send the form name
// which results in an invalid argument error
$values = $controller->exportValues();
//first check POST value then QF
if (isset($_POST['additional_participants']) && CRM_Utils_Rule::positiveInteger($_POST['additional_participants'])) {
// we need to use $_POST since the QF framework has not yet been called
// and the additional participants page is the next one, so need to set this up
// now
$additionalParticipant = $_POST['additional_participants'];
}
elseif (isset($values['additional_participants']) && CRM_Utils_Rule::positiveInteger($values['additional_participants'])) {
$additionalParticipant = $values['additional_participants'];
}
if ($additionalParticipant) {
$additionalParticipant = CRM_Utils_Type::escape($additionalParticipant, 'Integer');
$controller->set('addParticipant', $additionalParticipant);
}
//to add instances of Additional Participant page, only if user has entered any additional participants
if ($additionalParticipant) {
$extraPages = CRM_Event_Form_Registration_AdditionalParticipant::getPages($additionalParticipant);
$pages = array_merge($pages, $extraPages);
}
$additionalPages = array(
'CRM_Event_Form_Registration_Confirm' => NULL,
'CRM_Event_Form_Registration_ThankYou' => NULL,
);
$pages = array_merge($pages, $additionalPages);
// CRM-11182 - Optional confirmation screen
if (!$is_confirm_enabled && !$is_monetary) {
unset($pages['CRM_Event_Form_Registration_Confirm']);
}
$this->addSequentialPages($pages, $action);
}
}

View file

@ -0,0 +1,115 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
class CRM_Event_StateMachine_Search extends CRM_Core_StateMachine {
/**
* The task that the wizard is currently processing.
*
* @var string
*/
protected $_task;
/**
* Class constructor.
*
* @param object $controller
* @param \const|int $action
*/
public function __construct($controller, $action = CRM_Core_Action::NONE) {
parent::__construct($controller, $action);
$this->_pages = array();
$this->_pages['CRM_Event_Form_Search'] = NULL;
list($task, $result) = $this->taskName($controller, 'Search');
$this->_task = $task;
if (is_array($task)) {
foreach ($task as $t) {
$this->_pages[$t] = NULL;
}
}
else {
$this->_pages[$task] = NULL;
}
if ($result) {
$this->_pages['CRM_Event_Form_Task_Result'] = NULL;
}
$this->addSequentialPages($this->_pages, $action);
}
/**
* Determine the form name based on the action. This allows us
* to avoid using conditional state machine, much more efficient
* and simpler
*
* @param CRM_Core_Controller $controller
* The controller object.
*
* @param string $formName
*
* @return string
* the name of the form that will handle the task
*/
public function taskName($controller, $formName = 'Search') {
// total hack, check POST vars and then session to determine stuff
$value = CRM_Utils_Array::value('task', $_POST);
if (!isset($value)) {
$value = $this->_controller->get('task');
}
$this->_controller->set('task', $value);
return CRM_Event_Task::getTask($value);
}
/**
* Return the form name of the task.
*
* @return string
*/
public function getTaskFormName() {
return CRM_Utils_String::getClassName($this->_task);
}
/**
* Since this is a state machine for search and we want to come back to the same state
* we dont want to issue a reset of the state session when we are done processing a task
*/
public function shouldReset() {
return FALSE;
}
}

View file

@ -0,0 +1,239 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* class to represent the actions that can be performed on a group of contacts
* used by the search forms
*
*/
class CRM_Event_Task {
// Value for SAVE_SEARCH is set to 13 in accordance with CRM_Contact_Task::SAVE_SEARCH
const DELETE_EVENTS = 1, PRINT_EVENTS = 2, EXPORT_EVENTS = 3, BATCH_EVENTS = 4, CANCEL_REGISTRATION = 5, EMAIL_CONTACTS = 6,
// Value for LABEL_CONTACTS is set to 16 in accordance with CRM_Contact_Task::LABEL_CONTACTS
SAVE_SEARCH = 13, SAVE_SEARCH_UPDATE = 14, PARTICIPANT_STATUS = 15,
LABEL_CONTACTS = 16, GROUP_CONTACTS = 20;
/**
* The task array
*
* @var array
*/
static $_tasks = NULL;
/**
* The optional task array
*
* @var array
*/
static $_optionalTasks = NULL;
/**
* These tasks are the core set of tasks that the user can perform
* on a contact / group of contacts
*
* @return array
* the set of tasks for a group of contacts
*/
public static function &tasks() {
if (!(self::$_tasks)) {
self::$_tasks = array(
1 => array(
'title' => ts('Delete participants from event'),
'class' => 'CRM_Event_Form_Task_Delete',
'result' => FALSE,
),
2 => array(
'title' => ts('Print selected rows'),
'class' => 'CRM_Event_Form_Task_Print',
'result' => FALSE,
),
3 => array(
'title' => ts('Export participants'),
'class' => array(
'CRM_Export_Form_Select',
'CRM_Export_Form_Map',
),
'result' => FALSE,
),
4 => array(
'title' => ts('Update multiple participants'),
'class' => array(
'CRM_Event_Form_Task_PickProfile',
'CRM_Event_Form_Task_Batch',
),
'result' => TRUE,
),
5 => array(
'title' => ts('Cancel registration'),
'class' => 'CRM_Event_Form_Task_Cancel',
'result' => FALSE,
),
6 => array(
'title' => ts('Email - send now'),
'class' => 'CRM_Event_Form_Task_Email',
'result' => TRUE,
),
13 => array(
'title' => ts('Group - create smart group'),
'class' => 'CRM_Event_Form_Task_SaveSearch',
'result' => TRUE,
),
14 => array(
'title' => ts('Group - update smart group'),
'class' => 'CRM_Event_Form_Task_SaveSearch_Update',
'result' => TRUE,
),
15 => array(
'title' => ts('Participant status - change'),
'class' => 'CRM_Event_Form_Task_ParticipantStatus',
'result' => TRUE,
),
16 => array(
'title' => ts('Name badges - print'),
'class' => 'CRM_Event_Form_Task_Badge',
'result' => FALSE,
),
17 => array(
'title' => ts('PDF letter - print for participants'),
'class' => 'CRM_Event_Form_Task_PDF',
'result' => TRUE,
),
20 => array(
'title' => ts('Group - add contacts'),
'class' => 'CRM_Event_Form_Task_AddToGroup',
'result' => FALSE,
),
);
//CRM-4418, check for delete
if (!CRM_Core_Permission::check('delete in CiviEvent')) {
unset(self::$_tasks[1]);
}
//CRM-12920 - check for edit permission
if (!CRM_Core_Permission::check('edit event participants')) {
unset(self::$_tasks[4], self::$_tasks[5], self::$_tasks[15]);
}
CRM_Utils_Hook::searchTasks('event', self::$_tasks);
}
return self::$_tasks;
}
/**
* These tasks are the core set of task titles
* for participants
*
* @return array
* the set of task titles
*/
public static function &taskTitles() {
self::tasks();
$titles = array();
foreach (self::$_tasks as $id => $value) {
// skip Update Smart Group task
if ($id != self::SAVE_SEARCH_UPDATE) {
$titles[$id] = $value['title'];
}
}
return $titles;
}
/**
* These tasks get added based on the context the user is in.
*
* @return array
* the set of optional tasks for a group of contacts
*/
public static function &optionalTaskTitle() {
$tasks = array(
14 => self::$_tasks[14]['title'],
);
return $tasks;
}
/**
* Show tasks selectively based on the permission level
* of the user
*
* @param int $permission
*
* @return array
* set of tasks that are valid for the user
*/
public static function &permissionedTaskTitles($permission) {
$tasks = array();
if (($permission == CRM_Core_Permission::EDIT)
|| CRM_Core_Permission::check('edit event participants')
) {
$tasks = self::taskTitles();
}
else {
$tasks = array(
3 => self::$_tasks[3]['title'],
6 => self::$_tasks[6]['title'],
);
//CRM-4418,
if (CRM_Core_Permission::check('delete in CiviEvent')) {
$tasks[1] = self::$_tasks[1]['title'];
}
}
return $tasks;
}
/**
* These tasks are the core set of tasks that the user can perform
* on participants
*
* @param int $value
*
* @return array
* the set of tasks for a group of participants
*/
public static function getTask($value) {
self::tasks();
if (!$value || !CRM_Utils_Array::value($value, self::$_tasks)) {
// make the print task by default
$value = 2;
}
asort(self::$_tasks);
return array(
self::$_tasks[$value]['class'],
self::$_tasks[$value]['result'],
);
}
}

Some files were not shown because too many files have changed in this diff Show more