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,224 @@
<?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_Contribute_ActionMapping_ByPage
*
* This defines the scheduled-reminder functionality for contribution
* entities. It is useful for sending a reminder based on:
* - The receipt-date, cancel-date, or thankyou-date.
* - The page on which the contribution was made.
*/
class CRM_Contribute_ActionMapping_ByPage implements \Civi\ActionSchedule\MappingInterface {
/**
* The value for civicrm_action_schedule.mapping_id which identifies the
* "Contribution Page" mapping.
*/
const MAPPING_ID = 'contribpage';
/**
* Register Activity-related action mappings.
*
* @param \Civi\ActionSchedule\Event\MappingRegisterEvent $registrations
*/
public static function onRegisterActionMappings(\Civi\ActionSchedule\Event\MappingRegisterEvent $registrations) {
$registrations->register(new static());
}
/**
* @return mixed
*/
public function getId() {
return self::MAPPING_ID;
}
/**
* @return string
*/
public function getEntity() {
return 'civicrm_contribution';
}
/**
* Get a printable label for this mapping type.
*
* @return string
*/
public function getLabel() {
return ts('Contribution Page');
}
/**
* Get a printable label to use as the header on the 'value' filter.
*
* @return string
*/
public function getValueHeader() {
return ts('Contribution Page');
}
/**
* Get a printable label to use as the header on the 'status' filter.
*
* @return string
*/
public function getStatusHeader() {
return ts('Contribution Status');
}
/**
* Get a list of value options.
*
* @return array
* Array(string $value => string $label).
* Ex: array(123 => 'Phone Call', 456 => 'Meeting').
* @throws CRM_Core_Exception
*/
public function getValueLabels() {
return CRM_Contribute_BAO_Contribution::buildOptions('contribution_page_id', 'get', array());
}
/**
* Get a list of status options.
*
* @param string|int $value
* The list of status options may be contingent upon the selected filter value.
* This is the selected filter value.
* @return array
* Array(string $value => string $label).
* Ex: Array(123 => 'Completed', 456 => 'Scheduled').
* @throws CRM_Core_Exception
*/
public function getStatusLabels($value) {
return CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'get', array());
}
/**
* Get a list of available date fields.
*
* @return array
* Array(string $fieldName => string $fieldLabel).
*/
public function getDateFields() {
return array(
'receive_date' => ts('Receive Date'),
'cancel_date' => ts('Cancel Date'),
'receipt_date' => ts('Receipt Date'),
'thankyou_date' => ts('Thank You 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 array();
}
/**
* 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) {
return array();
}
/**
* Determine whether a schedule based on this mapping is sufficiently
* complete.
*
* @param \CRM_Core_DAO_ActionSchedule $schedule
* @return array
* Array (string $code => string $message).
* List of error messages.
*/
public function validateSchedule($schedule) {
return array();
}
/**
* Generate a query to locate contacts who match the given
* schedule.
*
* @param \CRM_Core_DAO_ActionSchedule $schedule
* @param string $phase
* See, e.g., RecipientBuilder::PHASE_RELATION_FIRST.
* @param array $defaultParams
* Default parameters that should be included with query.
* @return \CRM_Utils_SQL_Select
* @see RecipientBuilder
* @throws CRM_Core_Exception
*/
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("civicrm_contribution e")->param($defaultParams);;
$query['casAddlCheckFrom'] = 'civicrm_contribution e';
$query['casContactIdField'] = 'e.contact_id';
$query['casEntityIdField'] = 'e.id';
$query['casContactTableAlias'] = NULL;
// $schedule->start_action_date is user-supplied data. validate.
if (!array_key_exists($schedule->start_action_date, $this->getDateFields())) {
throw new CRM_Core_Exception("Invalid date field");
}
$query['casDateField'] = $schedule->start_action_date;
// build where clause
if (!empty($selectedValues)) {
$query->where("e.contribution_page_id IN (@selectedValues)")
->param('selectedValues', $selectedValues);
}
if (!empty($selectedStatuses)) {
$query->where("e.contribution_status_id IN (#selectedStatuses)")
->param('selectedStatuses', $selectedStatuses);
}
return $query;
}
}

View file

@ -0,0 +1,243 @@
<?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_Contribute_ActionMapping_ByType
*
* This defines the scheduled-reminder functionality for contribution
* entities. It is useful for sending a reminder based on:
* - The receipt-date, cancel-date, or thankyou-date.
* - The type of contribution.
*/
class CRM_Contribute_ActionMapping_ByType implements \Civi\ActionSchedule\MappingInterface {
/**
* The value for civicrm_action_schedule.mapping_id which identifies the
* "Contribution Page" mapping.
*/
const MAPPING_ID = 'contribtype';
/**
* Register Activity-related action mappings.
*
* @param \Civi\ActionSchedule\Event\MappingRegisterEvent $registrations
*/
public static function onRegisterActionMappings(\Civi\ActionSchedule\Event\MappingRegisterEvent $registrations) {
$registrations->register(new static());
}
/**
* @return mixed
*/
public function getId() {
return self::MAPPING_ID;
}
/**
* @return string
*/
public function getEntity() {
return 'civicrm_contribution';
}
/**
* Get a printable label for this mapping type.
*
* @return string
*/
public function getLabel() {
return ts('Contribution Type');
}
/**
* Get a printable label to use as the header on the 'value' filter.
*
* @return string
*/
public function getValueHeader() {
return ts('Financial Type');
}
/**
* Get a printable label to use as the header on the 'status' filter.
*
* @return string
*/
public function getStatusHeader() {
return ts('Contribution Status');
}
/**
* Get a list of value options.
*
* @return array
* Array(string $value => string $label).
* Ex: array(123 => 'Phone Call', 456 => 'Meeting').
* @throws CRM_Core_Exception
*/
public function getValueLabels() {
return CRM_Contribute_BAO_Contribution::buildOptions('financial_type_id', 'get', array());
}
/**
* Get a list of status options.
*
* @param string|int $value
* The list of status options may be contingent upon the selected filter value.
* This is the selected filter value.
* @return array
* Array(string $value => string $label).
* Ex: Array(123 => 'Completed', 456 => 'Scheduled').
* @throws CRM_Core_Exception
*/
public function getStatusLabels($value) {
return CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'get', array());
}
/**
* Get a list of available date fields.
*
* @return array
* Array(string $fieldName => string $fieldLabel).
*/
public function getDateFields() {
return array(
'receive_date' => ts('Receive Date'),
'cancel_date' => ts('Cancel Date'),
'receipt_date' => ts('Receipt Date'),
'thankyou_date' => ts('Thank You 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 array(
'soft_credit_type' => ts('Soft Credit Role'),
);
}
/**
* 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 'soft_credit_type':
return \CRM_Core_OptionGroup::values('soft_credit_type', FALSE, FALSE, FALSE, NULL, 'label', TRUE, FALSE, 'name');
default:
return array();
}
}
/**
* Determine whether a schedule based on this mapping is sufficiently
* complete.
*
* @param \CRM_Core_DAO_ActionSchedule $schedule
* @return array
* Array (string $code => string $message).
* List of error messages.
*/
public function validateSchedule($schedule) {
return array();
}
/**
* Generate a query to locate contacts who match the given
* schedule.
*
* @param \CRM_Core_DAO_ActionSchedule $schedule
* @param string $phase
* See, e.g., RecipientBuilder::PHASE_RELATION_FIRST.
* @param array $defaultParams
* Default parameters that should be included with query.
* @return \CRM_Utils_SQL_Select
* @see RecipientBuilder
* @throws CRM_Core_Exception
*/
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("civicrm_contribution e")->param($defaultParams);;
$query['casAddlCheckFrom'] = 'civicrm_contribution e';
$query['casContactIdField'] = 'e.contact_id';
$query['casEntityIdField'] = 'e.id';
$query['casContactTableAlias'] = NULL;
// $schedule->start_action_date is user-supplied data. validate.
if (!array_key_exists($schedule->start_action_date, $this->getDateFields())) {
throw new CRM_Core_Exception("Invalid date field");
}
$query['casDateField'] = $schedule->start_action_date;
// build where clause
if (!empty($selectedValues)) {
$query->where("e.financial_type_id IN (@selectedValues)")
->param('selectedValues', $selectedValues);
}
if (!empty($selectedStatuses)) {
$query->where("e.contribution_status_id IN (#selectedStatuses)")
->param('selectedStatuses', $selectedStatuses);
}
if ($schedule->recipient_listing && $schedule->limit_to) {
switch ($schedule->recipient) {
case 'soft_credit_type':
$query['casContactIdField'] = 'soft.contact_id';
$query->join('soft', 'INNER JOIN civicrm_contribution_soft soft ON soft.contribution_id = e.id')
->where("soft.soft_credit_type_id IN (#recipList)")
->param('recipList', \CRM_Utils_Array::explodePadded($schedule->recipient_listing));
break;
}
}
return $query;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,625 @@
<?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
*/
class CRM_Contribute_BAO_Contribution_Utils {
/**
* Process payment after confirmation.
*
* @param CRM_Core_Form $form
* Form object.
* @param array $paymentParams
* Array with payment related key.
* value pairs
* @param int $contactID
* Contact id.
* @param int $financialTypeID
* Financial type id.
* @param bool $isTest
* @param bool $isRecur
*
* @throws CRM_Core_Exception
* @throws Exception
* @return array
* associated array
*
*/
public static function processConfirm(
&$form,
&$paymentParams,
$contactID,
$financialTypeID,
$isTest,
$isRecur
) {
CRM_Core_Payment_Form::mapParams($form->_bltID, $form->_params, $paymentParams, TRUE);
$isPaymentTransaction = self::isPaymentTransaction($form);
$financialType = new CRM_Financial_DAO_FinancialType();
$financialType->id = $financialTypeID;
$financialType->find(TRUE);
if ($financialType->is_deductible) {
$form->assign('is_deductible', TRUE);
$form->set('is_deductible', TRUE);
}
// add some financial type details to the params list
// if folks need to use it
//CRM-15297 - contributionType is obsolete - pass financial type as well so people can deprecate it
$paymentParams['financialType_name'] = $paymentParams['contributionType_name'] = $form->_params['contributionType_name'] = $financialType->name;
//CRM-11456
$paymentParams['financialType_accounting_code'] = $paymentParams['contributionType_accounting_code'] = $form->_params['contributionType_accounting_code'] = CRM_Financial_BAO_FinancialAccount::getAccountingCode($financialTypeID);
$paymentParams['contributionPageID'] = $form->_params['contributionPageID'] = $form->_values['id'];
$paymentParams['contactID'] = $form->_params['contactID'] = $contactID;
//fix for CRM-16317
if (empty($form->_params['receive_date'])) {
$form->_params['receive_date'] = date('YmdHis');
}
if (!empty($form->_params['start_date'])) {
$form->_params['start_date'] = date('YmdHis');
}
$form->assign('receive_date',
CRM_Utils_Date::mysqlToIso($form->_params['receive_date'])
);
if (empty($form->_values['amount'])) {
// If the amount is not in _values[], set it
$form->_values['amount'] = $form->_params['amount'];
}
if ($isPaymentTransaction) {
$contributionParams = array(
'id' => CRM_Utils_Array::value('contribution_id', $paymentParams),
'contact_id' => $contactID,
'is_test' => $isTest,
'campaign_id' => CRM_Utils_Array::value('campaign_id', $paymentParams, CRM_Utils_Array::value('campaign_id', $form->_values)),
'contribution_page_id' => $form->_id,
'source' => CRM_Utils_Array::value('source', $paymentParams, CRM_Utils_Array::value('description', $paymentParams)),
);
if (isset($paymentParams['line_item'])) {
// @todo make sure this is consisently set at this point.
$contributionParams['line_item'] = $paymentParams['line_item'];
}
if (!empty($form->_paymentProcessor)) {
$contributionParams['payment_instrument_id'] = $paymentParams['payment_instrument_id'] = $form->_paymentProcessor['payment_instrument_id'];
}
// @todo this is the wrong place for this - it should be done as close to form submission
// as possible
$paymentParams['amount'] = CRM_Utils_Rule::cleanMoney($paymentParams['amount']);
$contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution(
$form,
$paymentParams,
NULL,
$contributionParams,
$financialType,
TRUE,
$form->_bltID,
$isRecur
);
$paymentParams['item_name'] = $form->_params['description'];
$paymentParams['qfKey'] = $form->controller->_key;
if ($paymentParams['skipLineItem']) {
// We are not processing the line item here because we are processing a membership.
// Do not continue with contribution processing in this function.
return array('contribution' => $contribution);
}
$paymentParams['contributionID'] = $contribution->id;
//CRM-15297 deprecate contributionTypeID
$paymentParams['financialTypeID'] = $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
$paymentParams['contributionPageID'] = $contribution->contribution_page_id;
if (isset($paymentParams['contribution_source'])) {
$paymentParams['source'] = $paymentParams['contribution_source'];
}
if (CRM_Utils_Array::value('is_recur', $form->_params) && $contribution->contribution_recur_id) {
$paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
}
if (isset($paymentParams['contribution_source'])) {
$form->_params['source'] = $paymentParams['contribution_source'];
}
// get the price set values for receipt.
if ($form->_priceSetId && $form->_lineItem) {
$form->_values['lineItem'] = $form->_lineItem;
$form->_values['priceSetID'] = $form->_priceSetId;
}
$form->_values['contribution_id'] = $contribution->id;
$form->_values['contribution_page_id'] = $contribution->contribution_page_id;
if (!empty($form->_paymentProcessor)) {
try {
$payment = Civi\Payment\System::singleton()->getByProcessor($form->_paymentProcessor);
if ($form->_contributeMode == 'notify') {
// We want to get rid of this & make it generic - eg. by making payment processing the last thing
// and always calling it first.
$form->postProcessHook();
}
$result = $payment->doPayment($paymentParams);
$form->_params = array_merge($form->_params, $result);
$form->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $result));
if (!empty($result['trxn_id'])) {
$contribution->trxn_id = $result['trxn_id'];
}
if (!empty($result['payment_status_id'])) {
$contribution->payment_status_id = $result['payment_status_id'];
}
$result['contribution'] = $contribution;
if ($result['payment_status_id'] == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution',
'status_id', 'Pending') && $payment->isSendReceiptForPending()) {
CRM_Contribute_BAO_ContributionPage::sendMail($contactID,
$form->_values,
$contribution->is_test
);
}
return $result;
}
catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
// Clean up DB as appropriate.
if (!empty($paymentParams['contributionID'])) {
CRM_Contribute_BAO_Contribution::failPayment($paymentParams['contributionID'],
$paymentParams['contactID'], $e->getMessage());
}
if (!empty($paymentParams['contributionRecurID'])) {
CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
}
$result['is_payment_failure'] = TRUE;
$result['error'] = $e;
return $result;
}
}
}
// Only pay later or unpaid should reach this point, although pay later likely does not & is handled via the
// manual processor, so it's unclear what this set is for and whether the following send ever fires.
$form->set('params', $form->_params);
if ($form->_params['amount'] == 0) {
// This is kind of a back-up for pay-later $0 transactions.
// In other flows they pick up the manual processor & get dealt with above (I
// think that might be better...).
return array(
'payment_status_id' => 1,
'contribution' => $contribution,
'payment_processor_id' => 0,
);
}
CRM_Contribute_BAO_ContributionPage::sendMail($contactID,
$form->_values,
$contribution->is_test
);
}
/**
* Is a payment being made.
* Note that setting is_monetary on the form is somewhat legacy and the behaviour around this setting is confusing. It would be preferable
* to look for the amount only (assuming this cannot refer to payment in goats or other non-monetary currency
* @param CRM_Core_Form $form
*
* @return bool
*/
static protected function isPaymentTransaction($form) {
return ($form->_amount >= 0.0) ? TRUE : FALSE;
}
/**
* Get the contribution details by month of the year.
*
* @param int $param
* Year.
*
* @return array
* associated array
*/
public static function contributionChartMonthly($param) {
if ($param) {
$param = array(1 => array($param, 'Integer'));
}
else {
$param = date("Y");
$param = array(1 => array($param, 'Integer'));
}
$query = "
SELECT sum(contrib.total_amount) AS ctAmt,
MONTH( contrib.receive_date) AS contribMonth
FROM civicrm_contribution AS contrib
INNER JOIN civicrm_contact AS contact ON ( contact.id = contrib.contact_id )
WHERE contrib.contact_id = contact.id
AND ( contrib.is_test = 0 OR contrib.is_test IS NULL )
AND contrib.contribution_status_id = 1
AND date_format(contrib.receive_date,'%Y') = %1
AND contact.is_deleted = 0
GROUP BY contribMonth
ORDER BY month(contrib.receive_date)";
$dao = CRM_Core_DAO::executeQuery($query, $param);
$params = NULL;
while ($dao->fetch()) {
if ($dao->contribMonth) {
$params['By Month'][$dao->contribMonth] = $dao->ctAmt;
}
}
return $params;
}
/**
* Get the contribution details by year.
*
* @return array
* associated array
*/
public static function contributionChartYearly() {
$config = CRM_Core_Config::singleton();
$yearClause = "year(contrib.receive_date) as contribYear";
if (!empty($config->fiscalYearStart) && ($config->fiscalYearStart['M'] != 1 || $config->fiscalYearStart['d'] != 1)) {
$yearClause = "CASE
WHEN (MONTH(contrib.receive_date)>= " . $config->fiscalYearStart['M'] . "
&& DAYOFMONTH(contrib.receive_date)>= " . $config->fiscalYearStart['d'] . " )
THEN
concat(YEAR(contrib.receive_date), '-',YEAR(contrib.receive_date)+1)
ELSE
concat(YEAR(contrib.receive_date)-1,'-', YEAR(contrib.receive_date))
END AS contribYear";
}
$query = "
SELECT sum(contrib.total_amount) AS ctAmt,
{$yearClause}
FROM civicrm_contribution AS contrib
INNER JOIN civicrm_contact contact ON ( contact.id = contrib.contact_id )
WHERE ( contrib.is_test = 0 OR contrib.is_test IS NULL )
AND contrib.contribution_status_id = 1
AND contact.is_deleted = 0
GROUP BY contribYear
ORDER BY contribYear";
$dao = CRM_Core_DAO::executeQuery($query);
$params = NULL;
while ($dao->fetch()) {
if (!empty($dao->contribYear)) {
$params['By Year'][$dao->contribYear] = $dao->ctAmt;
}
}
return $params;
}
/**
* @param array $params
* @param int $contactID
* @param $mail
*/
public static function createCMSUser(&$params, $contactID, $mail) {
// lets ensure we only create one CMS user
static $created = FALSE;
if ($created) {
return;
}
$created = TRUE;
if (!empty($params['cms_create_account'])) {
$params['contactID'] = !empty($params['onbehalf_contact_id']) ? $params['onbehalf_contact_id'] : $contactID;
if (!CRM_Core_BAO_CMSUser::create($params, $mail)) {
CRM_Core_Error::statusBounce(ts('Your profile is not saved and Account is not created.'));
}
}
}
/**
* @param array $params
* @param string $type
*
* @return bool
*/
public static function _fillCommonParams(&$params, $type = 'paypal') {
if (array_key_exists('transaction', $params)) {
$transaction = &$params['transaction'];
}
else {
$transaction = &$params;
}
$params['contact_type'] = 'Individual';
$billingLocTypeId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType', 'Billing', 'id', 'name');
if (!$billingLocTypeId) {
$billingLocTypeId = 1;
}
if (!CRM_Utils_System::isNull($params['address'])) {
$params['address'][1]['is_primary'] = 1;
$params['address'][1]['location_type_id'] = $billingLocTypeId;
}
if (!CRM_Utils_System::isNull($params['email'])) {
$params['email'] = array(
1 => array(
'email' => $params['email'],
'location_type_id' => $billingLocTypeId,
),
);
}
if (isset($transaction['trxn_id'])) {
// set error message if transaction has already been processed.
$contribution = new CRM_Contribute_DAO_Contribution();
$contribution->trxn_id = $transaction['trxn_id'];
if ($contribution->find(TRUE)) {
$params['error'][] = ts('transaction already processed.');
}
}
else {
// generate a new transaction id, if not already exist
$transaction['trxn_id'] = md5(uniqid(rand(), TRUE));
}
if (!isset($transaction['financial_type_id'])) {
$contributionTypes = array_keys(CRM_Contribute_PseudoConstant::financialType());
$transaction['financial_type_id'] = $contributionTypes[0];
}
if (($type == 'paypal') && (!isset($transaction['net_amount']))) {
$transaction['net_amount'] = $transaction['total_amount'] - CRM_Utils_Array::value('fee_amount', $transaction, 0);
}
if (!isset($transaction['invoice_id'])) {
$transaction['invoice_id'] = $transaction['trxn_id'];
}
$source = ts('ContributionProcessor: %1 API',
array(1 => ucfirst($type))
);
if (isset($transaction['source'])) {
$transaction['source'] = $source . ':: ' . $transaction['source'];
}
else {
$transaction['source'] = $source;
}
return TRUE;
}
/**
* @param int $contactID
*
* @return mixed
*/
public static function getFirstLastDetails($contactID) {
static $_cache;
if (!$_cache) {
$_cache = array();
}
if (!isset($_cache[$contactID])) {
$sql = "
SELECT total_amount, receive_date
FROM civicrm_contribution c
WHERE contact_id = %1
ORDER BY receive_date ASC
LIMIT 1
";
$params = array(1 => array($contactID, 'Integer'));
$dao = CRM_Core_DAO::executeQuery($sql, $params);
$details = array(
'first' => NULL,
'last' => NULL,
);
if ($dao->fetch()) {
$details['first'] = array(
'total_amount' => $dao->total_amount,
'receive_date' => $dao->receive_date,
);
}
// flip asc and desc to get the last query
$sql = str_replace('ASC', 'DESC', $sql);
$dao = CRM_Core_DAO::executeQuery($sql, $params);
if ($dao->fetch()) {
$details['last'] = array(
'total_amount' => $dao->total_amount,
'receive_date' => $dao->receive_date,
);
}
$_cache[$contactID] = $details;
}
return $_cache[$contactID];
}
/**
* Calculate the tax amount based on given tax rate.
*
* @param float $amount
* Amount of field.
* @param float $taxRate
* Tax rate of selected financial account for field.
* @param bool $ugWeDoNotKnowIfItNeedsCleaning_Help
* This should ALWAYS BE FALSE and then be removed. A 'clean' money string uses a standardised format
* such as '1000.99' for one thousand $/Euro/CUR and ninety nine cents/units.
* However, we are in the habit of not necessarily doing that so need to grandfather in
* the new expectation.
*
* @return array
* array of tax amount
*
*/
public static function calculateTaxAmount($amount, $taxRate, $ugWeDoNotKnowIfItNeedsCleaning_Help = FALSE) {
$taxAmount = array();
if ($ugWeDoNotKnowIfItNeedsCleaning_Help) {
Civi::log()->warning('Deprecated function, make sure money is in usable format before calling this.', array('civi.tag' => 'deprecated'));
$amount = CRM_Utils_Rule::cleanMoney($amount);
}
// There can not be any rounding at this stage - as this is prior to quantity multiplication
$taxAmount['tax_amount'] = ($taxRate / 100) * $amount;
return $taxAmount;
}
/**
* Format monetary amount: round and return to desired decimal place
* CRM-20145
*
* @param float $amount
* Monetary amount
* @param int $decimals
* How many decimal places to round to and return
*
* @return float
* Amount rounded and returned with the desired decimal places
*/
public static function formatAmount($amount, $decimals = 2) {
return number_format((float) round($amount, (int) $decimals), (int) $decimals, '.', '');
}
/**
* Get contribution statuses by entity e.g. contribution, membership or 'participant'
*
* @param string $usedFor
* @param int $id
* Contribution ID
*
* @return array $statuses
* Array of contribution statuses in array('status id' => 'label') format
*/
public static function getContributionStatuses($usedFor = 'contribution', $id = NULL) {
if ($usedFor == 'pledge') {
$statusNames = CRM_Pledge_BAO_Pledge::buildOptions('status_id', 'validate');
}
else {
$statusNames = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id', 'validate');
}
$statusNamesToUnset = array();
// on create fetch statuses on basis of component
if (!$id) {
$statusNamesToUnset = array(
'Refunded',
'Chargeback',
'Pending refund',
);
// Event registration and New Membership backoffice form support partially paid payment,
// so exclude this status only for 'New Contribution' form
if ($usedFor == 'contribution') {
$statusNamesToUnset = array_merge($statusNamesToUnset, array(
'In Progress',
'Overdue',
'Partially paid',
));
}
elseif ($usedFor == 'participant') {
$statusNamesToUnset = array_merge($statusNamesToUnset, array(
'Cancelled',
'Failed',
));
}
elseif ($usedFor == 'membership') {
$statusNamesToUnset = array_merge($statusNamesToUnset, array(
'In Progress',
'Overdue',
));
}
}
else {
$contributionStatus = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $id, 'contribution_status_id');
$name = CRM_Utils_Array::value($contributionStatus, $statusNames);
switch ($name) {
case 'Completed':
// [CRM-17498] Removing unsupported status change options.
$statusNamesToUnset = array_merge($statusNamesToUnset, array(
'Pending',
'Failed',
'Partially paid',
'Pending refund',
));
break;
case 'Cancelled':
case 'Chargeback':
case 'Refunded':
$statusNamesToUnset = array_merge($statusNamesToUnset, array(
'Pending',
'Failed',
));
break;
case 'Pending':
case 'In Progress':
$statusNamesToUnset = array_merge($statusNamesToUnset, array(
'Refunded',
'Chargeback',
));
break;
case 'Failed':
$statusNamesToUnset = array_merge($statusNamesToUnset, array(
'Pending',
'Refunded',
'Chargeback',
'Completed',
'In Progress',
'Cancelled',
));
break;
}
}
foreach ($statusNamesToUnset as $name) {
unset($statusNames[CRM_Utils_Array::key($name, $statusNames)]);
}
// based on filtered statuse names fetch the final list of statuses in array('id' => 'label') format
if ($usedFor == 'pledge') {
$statuses = CRM_Pledge_BAO_Pledge::buildOptions('status_id');
}
else {
$statuses = CRM_Contribute_BAO_Contribution::buildOptions('contribution_status_id');
}
foreach ($statuses as $statusID => $label) {
if (!array_key_exists($statusID, $statusNames)) {
unset($statuses[$statusID]);
}
}
return $statuses;
}
}

View file

@ -0,0 +1,987 @@
<?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 contains Contribution Page related functions.
*/
class CRM_Contribute_BAO_ContributionPage extends CRM_Contribute_DAO_ContributionPage {
/**
* Creates a contribution page.
*
* @param array $params
*
* @return CRM_Contribute_DAO_ContributionPage
*/
public static function create($params) {
$financialTypeId = NULL;
if (!empty($params['id']) && !CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $params['id'], NULL, 1)) {
$financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $params['id'], 'financial_type_id');
}
if (isset($params['payment_processor']) && is_array($params['payment_processor'])) {
$params['payment_processor'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $params['payment_processor']);
}
$hook = empty($params['id']) ? 'create' : 'edit';
CRM_Utils_Hook::pre($hook, 'ContributionPage', CRM_Utils_Array::value('id', $params), $params);
$dao = new CRM_Contribute_DAO_ContributionPage();
$dao->copyValues($params);
$dao->save();
if ($financialTypeId && !empty($params['financial_type_id']) && $financialTypeId != $params['financial_type_id']) {
CRM_Price_BAO_PriceFieldValue::updateFinancialType($params['id'], 'civicrm_contribution_page', $params['financial_type_id']);
}
CRM_Utils_Hook::post($hook, 'ContributionPage', $dao->id, $dao);
return $dao;
}
/**
* Update the is_active flag in the db.
*
* @deprecated - this bypasses hooks.
*
* @param int $id
* Id of the database record.
* @param bool $is_active
* Value we want to set the is_active field.
*
* @return Object
* DAO object on success, null otherwise
*/
public static function setIsActive($id, $is_active) {
return CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_ContributionPage', $id, 'is_active', $is_active);
}
/**
* Load values for a contribution page.
*
* @param int $id
* @param array $values
*/
public static function setValues($id, &$values) {
$modules = array('CiviContribute', 'soft_credit', 'on_behalf');
$values['custom_pre_id'] = $values['custom_post_id'] = NULL;
$params = array('id' => $id);
CRM_Core_DAO::commonRetrieve('CRM_Contribute_DAO_ContributionPage', $params, $values);
// get the profile ids
$ufJoinParams = array(
'entity_table' => 'civicrm_contribution_page',
'entity_id' => $id,
);
// retrieve profile id as also unserialize module_data corresponding to each $module
foreach ($modules as $module) {
$ufJoinParams['module'] = $module;
$ufJoin = new CRM_Core_DAO_UFJoin();
$ufJoin->copyValues($ufJoinParams);
if ($module == 'CiviContribute') {
$ufJoin->orderBy('weight asc');
$ufJoin->find();
while ($ufJoin->fetch()) {
if ($ufJoin->weight == 1) {
$values['custom_pre_id'] = $ufJoin->uf_group_id;
}
else {
$values['custom_post_id'] = $ufJoin->uf_group_id;
}
}
}
else {
$ufJoin->find(TRUE);
if (!$ufJoin->is_active) {
continue;
}
$params = CRM_Contribute_BAO_ContributionPage::formatModuleData($ufJoin->module_data, TRUE, $module);
$values = array_merge($params, $values);
if ($module == 'soft_credit') {
$values['honoree_profile_id'] = $ufJoin->uf_group_id;
$values['honor_block_is_active'] = $ufJoin->is_active;
}
else {
$values['onbehalf_profile_id'] = $ufJoin->uf_group_id;
}
}
}
}
/**
* Send the emails.
*
* @param int $contactID
* Contact id.
* @param array $values
* Associated array of fields.
* @param bool $isTest
* If in test mode.
* @param bool $returnMessageText
* Return the message text instead of sending the mail.
*
* @param array $fieldTypes
*/
public static function sendMail($contactID, $values, $isTest = FALSE, $returnMessageText = FALSE, $fieldTypes = NULL) {
$gIds = array();
$params = array('custom_pre_id' => array(), 'custom_post_id' => array());
$email = NULL;
// We are trying to fight the good fight against leaky variables (CRM-17519) so let's get really explicit
// about ensuring the variables we want for the template are defined.
// @todo add to this until all tpl params are explicit in this function and not waltzing around the codebase.
// Next stage is to remove this & ensure there are no e-notices - ie. all are set before they hit this fn.
$valuesRequiredForTemplate = array(
'customPre',
'customPost',
'customPre_grouptitle',
'customPost_grouptitle',
'useForMember',
'membership_assign',
'amount',
'receipt_date',
'is_pay_later',
);
foreach ($valuesRequiredForTemplate as $valueRequiredForTemplate) {
if (!isset($values[$valueRequiredForTemplate])) {
$values[$valueRequiredForTemplate] = NULL;
}
}
if (isset($values['custom_pre_id'])) {
$preProfileType = CRM_Core_BAO_UFField::getProfileType($values['custom_pre_id']);
if ($preProfileType == 'Membership' && !empty($values['membership_id'])) {
$params['custom_pre_id'] = array(
array(
'member_id',
'=',
$values['membership_id'],
0,
0,
),
);
}
elseif ($preProfileType == 'Contribution' && !empty($values['contribution_id'])) {
$params['custom_pre_id'] = array(
array(
'contribution_id',
'=',
$values['contribution_id'],
0,
0,
),
);
}
$gIds['custom_pre_id'] = $values['custom_pre_id'];
}
if (isset($values['custom_post_id'])) {
$postProfileType = CRM_Core_BAO_UFField::getProfileType($values['custom_post_id']);
if ($postProfileType == 'Membership' && !empty($values['membership_id'])) {
$params['custom_post_id'] = array(
array(
'member_id',
'=',
$values['membership_id'],
0,
0,
),
);
}
elseif ($postProfileType == 'Contribution' && !empty($values['contribution_id'])) {
$params['custom_post_id'] = array(
array(
'contribution_id',
'=',
$values['contribution_id'],
0,
0,
),
);
}
$gIds['custom_post_id'] = $values['custom_post_id'];
}
if (!empty($values['is_for_organization'])) {
if (!empty($values['membership_id'])) {
$params['onbehalf_profile'] = array(
array(
'member_id',
'=',
$values['membership_id'],
0,
0,
),
);
}
elseif (!empty($values['contribution_id'])) {
$params['onbehalf_profile'] = array(
array(
'contribution_id',
'=',
$values['contribution_id'],
0,
0,
),
);
}
}
//check whether it is a test drive
if ($isTest && !empty($params['custom_pre_id'])) {
$params['custom_pre_id'][] = array(
'contribution_test',
'=',
1,
0,
0,
);
}
if ($isTest && !empty($params['custom_post_id'])) {
$params['custom_post_id'][] = array(
'contribution_test',
'=',
1,
0,
0,
);
}
if (!$returnMessageText && !empty($gIds)) {
//send notification email if field values are set (CRM-1941)
foreach ($gIds as $key => $gId) {
if ($gId) {
$email = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify');
if ($email) {
$val = CRM_Core_BAO_UFGroup::checkFieldsEmptyValues($gId, $contactID, CRM_Utils_Array::value($key, $params), TRUE);
CRM_Core_BAO_UFGroup::commonSendMail($contactID, $val);
}
}
}
}
if (!empty($values['is_email_receipt']) || !empty($values['onbehalf_dupe_alert']) ||
$returnMessageText
) {
$template = CRM_Core_Smarty::singleton();
// get the billing location type
if (!array_key_exists('related_contact', $values)) {
$billingLocationTypeId = CRM_Core_BAO_LocationType::getBilling();
}
else {
// presence of related contact implies onbehalf of org case,
// where location type is set to default.
$locType = CRM_Core_BAO_LocationType::getDefault();
$billingLocationTypeId = $locType->id;
}
if (!array_key_exists('related_contact', $values)) {
list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID, FALSE, $billingLocationTypeId);
}
// get primary location email if no email exist( for billing location).
if (!$email) {
list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
}
if (empty($displayName)) {
list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
}
//for display profile need to get individual contact id,
//hence get it from related_contact if on behalf of org true CRM-3767
//CRM-5001 Contribution/Membership:: On Behalf of Organization,
//If profile GROUP contain the Individual type then consider the
//profile is of Individual ( including the custom data of membership/contribution )
//IF Individual type not present in profile then it is consider as Organization data.
$userID = $contactID;
if ($preID = CRM_Utils_Array::value('custom_pre_id', $values)) {
if (!empty($values['related_contact'])) {
$preProfileTypes = CRM_Core_BAO_UFGroup::profileGroups($preID);
//@todo - following line should not refer to undefined $postProfileTypes? figure out way to test
if (in_array('Individual', $preProfileTypes) || in_array('Contact', $postProfileTypes)) {
//Take Individual contact ID
$userID = CRM_Utils_Array::value('related_contact', $values);
}
}
list($values['customPre_grouptitle'], $values['customPre']) = self::getProfileNameAndFields($preID, $userID, $params['custom_pre_id']);
}
$userID = $contactID;
if ($postID = CRM_Utils_Array::value('custom_post_id', $values)) {
if (!empty($values['related_contact'])) {
$postProfileTypes = CRM_Core_BAO_UFGroup::profileGroups($postID);
if (in_array('Individual', $postProfileTypes) || in_array('Contact', $postProfileTypes)) {
//Take Individual contact ID
$userID = CRM_Utils_Array::value('related_contact', $values);
}
}
list($values['customPost_grouptitle'], $values['customPost']) = self::getProfileNameAndFields($postID, $userID, $params['custom_post_id']);
}
if (isset($values['honor'])) {
$honorValues = $values['honor'];
$template->_values = array('honoree_profile_id' => $values['honoree_profile_id']);
CRM_Contribute_BAO_ContributionSoft::formatHonoreeProfileFields(
$template,
$honorValues['honor_profile_values'],
$honorValues['honor_id']
);
}
$title = isset($values['title']) ? $values['title'] : CRM_Contribute_PseudoConstant::contributionPage($values['contribution_page_id']);
// Set email variables explicitly to avoid leaky smarty variables.
// All of these will be assigned to the template, replacing any that might be assigned elsewhere.
$tplParams = array(
'email' => $email,
'receiptFromEmail' => CRM_Utils_Array::value('receipt_from_email', $values),
'contactID' => $contactID,
'displayName' => $displayName,
'contributionID' => CRM_Utils_Array::value('contribution_id', $values),
'contributionOtherID' => CRM_Utils_Array::value('contribution_other_id', $values),
// CRM-5095
'lineItem' => CRM_Utils_Array::value('lineItem', $values),
// CRM-5095
'priceSetID' => CRM_Utils_Array::value('priceSetID', $values),
'title' => $title,
'isShare' => CRM_Utils_Array::value('is_share', $values),
'thankyou_title' => CRM_Utils_Array::value('thankyou_title', $values),
'customPre' => $values['customPre'],
'customPre_grouptitle' => $values['customPre_grouptitle'],
'customPost' => $values['customPost'],
'customPost_grouptitle' => $values['customPost_grouptitle'],
'useForMember' => $values['useForMember'],
'membership_assign' => $values['membership_assign'],
'amount' => $values['amount'],
'is_pay_later' => $values['is_pay_later'],
'receipt_date' => !$values['receipt_date'] ? NULL : date('YmdHis', strtotime($values['receipt_date'])),
'pay_later_receipt' => CRM_Utils_Array::value('pay_later_receipt', $values),
'honor_block_is_active' => CRM_Utils_Array::value('honor_block_is_active', $values),
'contributionStatus' => CRM_Utils_Array::value('contribution_status', $values),
);
if ($contributionTypeId = CRM_Utils_Array::value('financial_type_id', $values)) {
$tplParams['financialTypeId'] = $contributionTypeId;
$tplParams['financialTypeName'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType',
$contributionTypeId);
// Legacy support
$tplParams['contributionTypeName'] = $tplParams['financialTypeName'];
$tplParams['contributionTypeId'] = $contributionTypeId;
}
if ($contributionPageId = CRM_Utils_Array::value('id', $values)) {
$tplParams['contributionPageId'] = $contributionPageId;
}
// address required during receipt processing (pdf and email receipt)
if ($displayAddress = CRM_Utils_Array::value('address', $values)) {
$tplParams['address'] = $displayAddress;
}
// CRM-6976
$originalCCReceipt = CRM_Utils_Array::value('cc_receipt', $values);
// cc to related contacts of contributor OR the one who
// signs up. Is used for cases like - on behalf of
// contribution / signup ..etc
if (array_key_exists('related_contact', $values)) {
list($ccDisplayName, $ccEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($values['related_contact']);
$ccMailId = "{$ccDisplayName} <{$ccEmail}>";
//@todo - this is the only place in this function where $values is altered - but I can't find any evidence it is used
$values['cc_receipt'] = !empty($values['cc_receipt']) ? ($values['cc_receipt'] . ',' . $ccMailId) : $ccMailId;
// reset primary-email in the template
$tplParams['email'] = $ccEmail;
$tplParams['onBehalfName'] = $displayName;
$tplParams['onBehalfEmail'] = $email;
if (!empty($values['onbehalf_profile_id'])) {
self::buildCustomDisplay($values['onbehalf_profile_id'], 'onBehalfProfile', $contactID, $template, $params['onbehalf_profile'], $fieldTypes);
}
}
// use either the contribution or membership receipt, based on whether its a membership-related contrib or not
$sendTemplateParams = array(
'groupName' => !empty($values['isMembership']) ? 'msg_tpl_workflow_membership' : 'msg_tpl_workflow_contribution',
'valueName' => !empty($values['isMembership']) ? 'membership_online_receipt' : 'contribution_online_receipt',
'contactId' => $contactID,
'tplParams' => $tplParams,
'isTest' => $isTest,
'PDFFilename' => 'receipt.pdf',
);
if ($returnMessageText) {
list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
return array(
'subject' => $subject,
'body' => $message,
'to' => $displayName,
'html' => $html,
);
}
if (empty($values['receipt_from_name']) && empty($values['receipt_from_name'])) {
list($values['receipt_from_name'], $values['receipt_from_email']) = CRM_Core_BAO_Domain::getNameAndEmail();
}
if ($values['is_email_receipt']) {
$sendTemplateParams['from'] = CRM_Utils_Array::value('receipt_from_name', $values) . ' <' . $values['receipt_from_email'] . '>';
$sendTemplateParams['toName'] = $displayName;
$sendTemplateParams['toEmail'] = $email;
$sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_receipt', $values);
$sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $values);
//send email with pdf invoice
$template = CRM_Core_Smarty::singleton();
$taxAmt = $template->get_template_vars('dataArray');
$prefixValue = Civi::settings()->get('contribution_invoice_settings');
$invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
if (isset($invoicing) && isset($prefixValue['is_email_pdf'])) {
$sendTemplateParams['isEmailPdf'] = TRUE;
$sendTemplateParams['contributionId'] = $values['contribution_id'];
}
list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
}
// send duplicate alert, if dupe match found during on-behalf-of processing.
if (!empty($values['onbehalf_dupe_alert'])) {
$sendTemplateParams['groupName'] = 'msg_tpl_workflow_contribution';
$sendTemplateParams['valueName'] = 'contribution_dupalert';
$sendTemplateParams['from'] = ts('Automatically Generated') . " <{$values['receipt_from_email']}>";
$sendTemplateParams['toName'] = CRM_Utils_Array::value('receipt_from_name', $values);
$sendTemplateParams['toEmail'] = CRM_Utils_Array::value('receipt_from_email', $values);
$sendTemplateParams['tplParams']['onBehalfID'] = $contactID;
$sendTemplateParams['tplParams']['receiptMessage'] = $message;
// fix cc and reset back to original, CRM-6976
$sendTemplateParams['cc'] = $originalCCReceipt;
CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
}
}
}
/**
* Get the profile title and fields.
*
* @param int $gid
* @param int $cid
* @param array $params
* @param array $fieldTypes
*
* @return array
*/
protected static function getProfileNameAndFields($gid, $cid, &$params, $fieldTypes = array()) {
$groupTitle = NULL;
$values = array();
if ($gid) {
if (CRM_Core_BAO_UFGroup::filterUFGroups($gid, $cid)) {
$fields = CRM_Core_BAO_UFGroup::getFields($gid, FALSE, CRM_Core_Action::VIEW, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission::CREATE, NULL);
foreach ($fields as $k => $v) {
if (!$groupTitle) {
$groupTitle = $v["groupTitle"];
}
// suppress all file fields from display and formatting fields
if (
CRM_Utils_Array::value('data_type', $v, '') == 'File' ||
CRM_Utils_Array::value('name', $v, '') == 'image_URL' ||
CRM_Utils_Array::value('field_type', $v) == 'Formatting'
) {
unset($fields[$k]);
}
if (!empty($fieldTypes) && (!in_array($v['field_type'], $fieldTypes))) {
unset($fields[$k]);
}
}
CRM_Core_BAO_UFGroup::getValues($cid, $fields, $values, FALSE, $params);
}
}
return array($groupTitle, $values);
}
/**
* Send the emails for Recurring Contribution Notification.
*
* @param string $type
* TxnType.
* @param int $contactID
* Contact id for contributor.
* @param int $pageID
* Contribution page id.
* @param object $recur
* Object of recurring contribution table.
* @param bool|object $autoRenewMembership is it a auto renew membership.
*/
public static function recurringNotify($type, $contactID, $pageID, $recur, $autoRenewMembership = FALSE) {
$value = array();
$isEmailReceipt = FALSE;
if ($pageID) {
CRM_Core_DAO::commonRetrieveAll('CRM_Contribute_DAO_ContributionPage', 'id', $pageID, $value, array(
'title',
'is_email_receipt',
'receipt_from_name',
'receipt_from_email',
'cc_receipt',
'bcc_receipt',
));
$isEmailReceipt = CRM_Utils_Array::value('is_email_receipt', $value[$pageID]);
}
elseif ($recur->id) {
// This means we are coming from back-office - ie. no page ID, but recurring.
// Ideally this information would be passed into the function clearly rather than guessing by convention.
$isEmailReceipt = TRUE;
}
if ($isEmailReceipt) {
if ($pageID) {
$receiptFrom = '"' . CRM_Utils_Array::value('receipt_from_name', $value[$pageID]) . '" <' . $value[$pageID]['receipt_from_email'] . '>';
$receiptFromName = $value[$pageID]['receipt_from_name'];
$receiptFromEmail = $value[$pageID]['receipt_from_email'];
}
else {
$domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
$receiptFrom = "$domainValues[0] <$domainValues[1]>";
$receiptFromName = $domainValues[0];
$receiptFromEmail = $domainValues[1];
}
list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID, FALSE);
$templatesParams = array(
'groupName' => 'msg_tpl_workflow_contribution',
'valueName' => 'contribution_recurring_notify',
'contactId' => $contactID,
'tplParams' => array(
'recur_frequency_interval' => $recur->frequency_interval,
'recur_frequency_unit' => $recur->frequency_unit,
'recur_installments' => $recur->installments,
'recur_start_date' => $recur->start_date,
'recur_end_date' => $recur->end_date,
'recur_amount' => $recur->amount,
'recur_txnType' => $type,
'displayName' => $displayName,
'receipt_from_name' => $receiptFromName,
'receipt_from_email' => $receiptFromEmail,
'auto_renew_membership' => $autoRenewMembership,
),
'from' => $receiptFrom,
'toName' => $displayName,
'toEmail' => $email,
);
//CRM-13811
if ($pageID) {
$templatesParams['cc'] = CRM_Utils_Array::value('cc_receipt', $value[$pageID]);
$templatesParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $value[$pageID]);
}
if ($recur->id) {
// in some cases its just recurringNotify() thats called for the first time and these urls don't get set.
// like in PaypalPro, & therefore we set it here additionally.
$template = CRM_Core_Smarty::singleton();
$paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($recur->id, 'recur', 'obj');
$url = $paymentProcessor->subscriptionURL($recur->id, 'recur', 'cancel');
$template->assign('cancelSubscriptionUrl', $url);
$url = $paymentProcessor->subscriptionURL($recur->id, 'recur', 'billing');
$template->assign('updateSubscriptionBillingUrl', $url);
$url = $paymentProcessor->subscriptionURL($recur->id, 'recur', 'update');
$template->assign('updateSubscriptionUrl', $url);
}
list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($templatesParams);
if ($sent) {
CRM_Core_Error::debug_log_message('Success: mail sent for recurring notification.');
}
else {
CRM_Core_Error::debug_log_message('Failure: mail not sent for recurring notification.');
}
}
}
/**
* Add the custom fields for contribution page (ie profile).
*
* @deprecated assigning values to smarty like this is risky because
* - it is hard to debug since $name is used in the assign
* - it is potentially 'leaky' - it's better to do this on the form
* or close to where it is used / required. See CRM-17519 for leakage e.g.
*
* @param int $gid
* Uf group id.
* @param string $name
* @param int $cid
* Contact id.
* @param $template
* @param array $params
* Params to build component whereclause.
*
* @param array|null $fieldTypes
*/
public static function buildCustomDisplay($gid, $name, $cid, &$template, &$params, $fieldTypes = NULL) {
list($groupTitle, $values) = self::getProfileNameAndFields($gid, $cid, $params, $fieldTypes);
if (!empty($values)) {
$template->assign($name, $values);
}
$template->assign($name . "_grouptitle", $groupTitle);
}
/**
* Make a copy of a contribution page, including all the blocks in the page.
*
* @param int $id
* The contribution page id to copy.
*
* @return CRM_Contribute_DAO_ContributionPage
*/
public static function copy($id) {
$fieldsFix = array(
'prefix' => array(
'title' => ts('Copy of') . ' ',
),
);
$copy = &CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_ContributionPage', array(
'id' => $id,
), NULL, $fieldsFix);
//copying all the blocks pertaining to the contribution page
$copyPledgeBlock = &CRM_Core_DAO::copyGeneric('CRM_Pledge_DAO_PledgeBlock', array(
'entity_id' => $id,
'entity_table' => 'civicrm_contribution_page',
), array(
'entity_id' => $copy->id,
));
$copyMembershipBlock = &CRM_Core_DAO::copyGeneric('CRM_Member_DAO_MembershipBlock', array(
'entity_id' => $id,
'entity_table' => 'civicrm_contribution_page',
), array(
'entity_id' => $copy->id,
));
$copyUFJoin = &CRM_Core_DAO::copyGeneric('CRM_Core_DAO_UFJoin', array(
'entity_id' => $id,
'entity_table' => 'civicrm_contribution_page',
), array(
'entity_id' => $copy->id,
));
$copyWidget = &CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_Widget', array(
'contribution_page_id' => $id,
), array(
'contribution_page_id' => $copy->id,
));
//copy price sets
CRM_Price_BAO_PriceSet::copyPriceSet('civicrm_contribution_page', $id, $copy->id);
$copyTellFriend = &CRM_Core_DAO::copyGeneric('CRM_Friend_DAO_Friend', array(
'entity_id' => $id,
'entity_table' => 'civicrm_contribution_page',
), array(
'entity_id' => $copy->id,
));
$copyPersonalCampaignPages = &CRM_Core_DAO::copyGeneric('CRM_PCP_DAO_PCPBlock', array(
'entity_id' => $id,
'entity_table' => 'civicrm_contribution_page',
), array(
'entity_id' => $copy->id,
'target_entity_id' => $copy->id,
));
$copyPremium = &CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_Premium', array(
'entity_id' => $id,
'entity_table' => 'civicrm_contribution_page',
), array(
'entity_id' => $copy->id,
));
$premiumQuery = "
SELECT id
FROM civicrm_premiums
WHERE entity_table = 'civicrm_contribution_page'
AND entity_id ={$id}";
$premiumDao = CRM_Core_DAO::executeQuery($premiumQuery, CRM_Core_DAO::$_nullArray);
while ($premiumDao->fetch()) {
if ($premiumDao->id) {
CRM_Core_DAO::copyGeneric('CRM_Contribute_DAO_PremiumsProduct', array(
'premiums_id' => $premiumDao->id,
), array(
'premiums_id' => $copyPremium->id,
));
}
}
$copy->save();
CRM_Utils_Hook::copy('ContributionPage', $copy);
return $copy;
}
/**
* Get info for all sections enable/disable.
*
* @param array $contribPageIds
* @return array
* info regarding all sections.
*/
public static function getSectionInfo($contribPageIds = array()) {
$info = array();
$whereClause = NULL;
if (is_array($contribPageIds) && !empty($contribPageIds)) {
$whereClause = 'WHERE civicrm_contribution_page.id IN ( ' . implode(', ', $contribPageIds) . ' )';
}
$sections = array(
'settings',
'amount',
'membership',
'custom',
'thankyou',
'friend',
'pcp',
'widget',
'premium',
);
$query = "
SELECT civicrm_contribution_page.id as id,
civicrm_contribution_page.financial_type_id as settings,
amount_block_is_active as amount,
civicrm_membership_block.id as membership,
civicrm_uf_join.id as custom,
civicrm_contribution_page.thankyou_title as thankyou,
civicrm_tell_friend.id as friend,
civicrm_pcp_block.id as pcp,
civicrm_contribution_widget.id as widget,
civicrm_premiums.id as premium
FROM civicrm_contribution_page
LEFT JOIN civicrm_membership_block ON ( civicrm_membership_block.entity_id = civicrm_contribution_page.id
AND civicrm_membership_block.entity_table = 'civicrm_contribution_page'
AND civicrm_membership_block.is_active = 1 )
LEFT JOIN civicrm_uf_join ON ( civicrm_uf_join.entity_id = civicrm_contribution_page.id
AND civicrm_uf_join.entity_table = 'civicrm_contribution_page'
AND module = 'CiviContribute'
AND civicrm_uf_join.is_active = 1 )
LEFT JOIN civicrm_tell_friend ON ( civicrm_tell_friend.entity_id = civicrm_contribution_page.id
AND civicrm_tell_friend.entity_table = 'civicrm_contribution_page'
AND civicrm_tell_friend.is_active = 1)
LEFT JOIN civicrm_pcp_block ON ( civicrm_pcp_block.entity_id = civicrm_contribution_page.id
AND civicrm_pcp_block.entity_table = 'civicrm_contribution_page'
AND civicrm_pcp_block.is_active = 1 )
LEFT JOIN civicrm_contribution_widget ON ( civicrm_contribution_widget.contribution_page_id = civicrm_contribution_page.id
AND civicrm_contribution_widget.is_active = 1 )
LEFT JOIN civicrm_premiums ON ( civicrm_premiums.entity_id = civicrm_contribution_page.id
AND civicrm_premiums.entity_table = 'civicrm_contribution_page'
AND civicrm_premiums.premiums_active = 1 )
$whereClause";
$contributionPage = CRM_Core_DAO::executeQuery($query);
while ($contributionPage->fetch()) {
if (!isset($info[$contributionPage->id]) || !is_array($info[$contributionPage->id])) {
$info[$contributionPage->id] = array_fill_keys(array_values($sections), FALSE);
}
foreach ($sections as $section) {
if ($contributionPage->$section) {
$info[$contributionPage->id][$section] = TRUE;
}
}
}
return $info;
}
/**
* Get options for a given field.
* @see CRM_Core_DAO::buildOptions
*
* @param string $fieldName
* @param string $context : @see CRM_Core_DAO::buildOptionsContext
* @param array $props : whatever is known about this dao object
*
* @return array|bool
*/
public static function buildOptions($fieldName, $context = NULL, $props = array()) {
$params = array();
// Special logic for fields whose options depend on context or properties
switch ($fieldName) {
case 'financial_type_id':
// Fixme - this is going to ignore context, better to get conditions, add params, and call PseudoConstant::get
return CRM_Financial_BAO_FinancialType::getIncomeFinancialType();
break;
}
return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
}
/**
* Get or Set honor/on_behalf params for processing module_data or setting default values.
*
* @param array $params :
* @param bool $setDefault : If yes then returns array to used for setting default value afterward
* @param string $module : processing module_data for which module? e.g. soft_credit, on_behalf
*
* @return array|string
*/
public static function formatModuleData($params, $setDefault = FALSE, $module) {
$tsLocale = CRM_Core_I18n::getLocale();
$config = CRM_Core_Config::singleton();
$json = $jsonDecode = NULL;
$domain = new CRM_Core_DAO_Domain();
$domain->find(TRUE);
$moduleDataFormat = array(
'soft_credit' => array(
1 => 'soft_credit_types',
'multilingual' => array(
'honor_block_title',
'honor_block_text',
),
),
'on_behalf' => array(
1 => 'is_for_organization',
'multilingual' => array(
'for_organization',
),
),
);
//When we are fetching the honor params respecting both multi and mono lingual state
//and setting it to default param of Contribution Page's Main and Setting form
if ($setDefault) {
$jsonDecode = json_decode($params);
$jsonDecode = (array) $jsonDecode->$module;
if (!$domain->locales && !empty($jsonDecode['default'])) {
//monolingual state
$jsonDecode += (array) $jsonDecode['default'];
unset($jsonDecode['default']);
}
elseif (!empty($jsonDecode[$tsLocale])) {
//multilingual state
foreach ($jsonDecode[$tsLocale] as $column => $value) {
$jsonDecode[$column] = $value;
}
unset($jsonDecode[$tsLocale]);
}
return $jsonDecode;
}
//check and handle multilingual honoree params
if (!$domain->locales) {
//if in singlelingual state simply return the array format
$json = array($module => NULL);
foreach ($moduleDataFormat[$module] as $key => $attribute) {
if ($key === 'multilingual') {
$json[$module]['default'] = array();
foreach ($attribute as $attr) {
$json[$module]['default'][$attr] = $params[$attr];
}
}
else {
$json[$module][$attribute] = $params[$attribute];
}
}
$json = json_encode($json);
}
else {
//if in multilingual state then retrieve the module_data against this contribution and
//merge with earlier module_data json data to current so not to lose earlier multilingual module_data information
$json = array($module => NULL);
foreach ($moduleDataFormat[$module] as $key => $attribute) {
if ($key === 'multilingual') {
$json[$module][$config->lcMessages] = array();
foreach ($attribute as $attr) {
$json[$module][$config->lcMessages][$attr] = $params[$attr];
}
}
else {
$json[$module][$attribute] = $params[$attribute];
}
}
$ufJoinDAO = new CRM_Core_DAO_UFJoin();
$ufJoinDAO->module = $module;
$ufJoinDAO->entity_id = $params['id'];
$ufJoinDAO->find(TRUE);
$jsonData = json_decode($ufJoinDAO->module_data);
if ($jsonData) {
$json[$module] = array_merge((array) $jsonData->$module, $json[$module]);
}
$json = json_encode($json);
}
return $json;
}
/**
* Generate html for pdf in confirmation receipt email attachment.
* @param int $contributionId
* Contribution Page Id.
* @param int $userID
* Contact id for contributor.
* @return array
*/
public static function addInvoicePdfToEmail($contributionId, $userID) {
$contributionID = array($contributionId);
$contactId = array($userID);
$pdfParams = array(
'output' => 'pdf_invoice',
'forPage' => 'confirmpage',
);
$pdfHtml = CRM_Contribute_Form_Task_Invoice::printPDF($contributionID, $pdfParams, $contactId);
return $pdfHtml;
}
/**
* Helper to determine if the page supports separate membership payments.
*
* @param int $id form id
*
* @return bool
* isSeparateMembershipPayment
*/
public static function getIsMembershipPayment($id) {
$membershipBlocks = civicrm_api3('membership_block', 'get', array(
'entity_table' => 'civicrm_contribution_page',
'entity_id' => $id,
'sequential' => TRUE,
));
if (!$membershipBlocks['count']) {
return FALSE;
}
return $membershipBlocks['values'][0]['is_separate_payment'];
}
}

View file

@ -0,0 +1,931 @@
<?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
*/
class CRM_Contribute_BAO_ContributionRecur extends CRM_Contribute_DAO_ContributionRecur {
/**
* Create recurring contribution.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
*
* @return object
* activity contact object
*/
public static function create(&$params) {
return self::add($params);
}
/**
* Takes an associative array and creates a contribution object.
*
* the function extract all the params it needs to initialize the create a
* contribution object. the params array could contain additional unused name/value
* pairs
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
*
* @return CRM_Contribute_BAO_Contribution
* @todo move hook calls / extended logic to create - requires changing calls to call create not add
*/
public static function add(&$params) {
if (!empty($params['id'])) {
CRM_Utils_Hook::pre('edit', 'ContributionRecur', $params['id'], $params);
}
else {
CRM_Utils_Hook::pre('create', 'ContributionRecur', NULL, $params);
}
// make sure we're not creating a new recurring contribution with the same transaction ID
// or invoice ID as an existing recurring contribution
$duplicates = array();
if (self::checkDuplicate($params, $duplicates)) {
$error = CRM_Core_Error::singleton();
$d = implode(', ', $duplicates);
$error->push(CRM_Core_Error::DUPLICATE_CONTRIBUTION,
'Fatal',
array($d),
"Found matching recurring contribution(s): $d"
);
return $error;
}
$recurring = new CRM_Contribute_BAO_ContributionRecur();
$recurring->copyValues($params);
$recurring->id = CRM_Utils_Array::value('id', $params);
// set currency for CRM-1496
if (empty($params['id']) && !isset($recurring->currency)) {
$config = CRM_Core_Config::singleton();
$recurring->currency = $config->defaultCurrency;
}
$result = $recurring->save();
if (!empty($params['id'])) {
CRM_Utils_Hook::post('edit', 'ContributionRecur', $recurring->id, $recurring);
}
else {
CRM_Utils_Hook::post('create', 'ContributionRecur', $recurring->id, $recurring);
}
if (!empty($params['custom']) &&
is_array($params['custom'])
) {
CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution_recur', $recurring->id);
}
return $result;
}
/**
* Check if there is a recurring contribution with the same trxn_id or invoice_id.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $duplicates
* (reference ) store ids of duplicate contributions.
*
* @return bool
* true if duplicate, false otherwise
*/
public static function checkDuplicate($params, &$duplicates) {
$id = CRM_Utils_Array::value('id', $params);
$trxn_id = CRM_Utils_Array::value('trxn_id', $params);
$invoice_id = CRM_Utils_Array::value('invoice_id', $params);
$clause = array();
$params = array();
if ($trxn_id) {
$clause[] = "trxn_id = %1";
$params[1] = array($trxn_id, 'String');
}
if ($invoice_id) {
$clause[] = "invoice_id = %2";
$params[2] = array($invoice_id, 'String');
}
if (empty($clause)) {
return FALSE;
}
$clause = implode(' OR ', $clause);
if ($id) {
$clause = "( $clause ) AND id != %3";
$params[3] = array($id, 'Integer');
}
$query = "SELECT id FROM civicrm_contribution_recur WHERE $clause";
$dao = CRM_Core_DAO::executeQuery($query, $params);
$result = FALSE;
while ($dao->fetch()) {
$duplicates[] = $dao->id;
$result = TRUE;
}
return $result;
}
/**
* Get the payment processor (array) for a recurring processor.
*
* @param int $id
* @param string $mode
* - Test or NULL - all other variants are ignored.
*
* @return array|null
*/
public static function getPaymentProcessor($id, $mode = NULL) {
$sql = "
SELECT r.payment_processor_id
FROM civicrm_contribution_recur r
WHERE r.id = %1";
$params = array(1 => array($id, 'Integer'));
$paymentProcessorID = CRM_Core_DAO::singleValueQuery($sql,
$params
);
if (!$paymentProcessorID) {
return NULL;
}
return CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID, $mode);
}
/**
* Get the number of installment done/completed for each recurring contribution.
*
* @param array $ids
* (reference ) an array of recurring contribution ids.
*
* @return array
* an array of recurring ids count
*/
public static function getCount(&$ids) {
$recurID = implode(',', $ids);
$totalCount = array();
$query = "
SELECT contribution_recur_id, count( contribution_recur_id ) as commpleted
FROM civicrm_contribution
WHERE contribution_recur_id IN ( {$recurID}) AND is_test = 0
GROUP BY contribution_recur_id";
$res = CRM_Core_DAO::executeQuery($query);
while ($res->fetch()) {
$totalCount[$res->contribution_recur_id] = $res->commpleted;
}
return $totalCount;
}
/**
* Delete Recurring contribution.
*
* @param int $recurId
*
* @return bool
*/
public static function deleteRecurContribution($recurId) {
$result = FALSE;
if (!$recurId) {
return $result;
}
$recur = new CRM_Contribute_DAO_ContributionRecur();
$recur->id = $recurId;
$result = $recur->delete();
return $result;
}
/**
* Cancel Recurring contribution.
*
* @param int $recurId
* Recur contribution id.
* @param array $objects
* An array of objects that is to be cancelled like.
* contribution, membership, event. At least contribution object is a must.
*
* @param array $activityParams
*
* @return bool
*/
public static function cancelRecurContribution($recurId, $objects, $activityParams = array()) {
if (!$recurId) {
return FALSE;
}
$contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
$canceledId = array_search('Cancelled', $contributionStatus);
$recur = new CRM_Contribute_DAO_ContributionRecur();
$recur->id = $recurId;
$recur->whereAdd("contribution_status_id != $canceledId");
if ($recur->find(TRUE)) {
$transaction = new CRM_Core_Transaction();
$recur->contribution_status_id = $canceledId;
$recur->start_date = CRM_Utils_Date::isoToMysql($recur->start_date);
$recur->create_date = CRM_Utils_Date::isoToMysql($recur->create_date);
$recur->modified_date = CRM_Utils_Date::isoToMysql($recur->modified_date);
$recur->cancel_date = date('YmdHis');
$recur->save();
$dao = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($recurId);
if ($dao && $dao->recur_id) {
$details = CRM_Utils_Array::value('details', $activityParams);
if ($dao->auto_renew && $dao->membership_id) {
// its auto-renewal membership mode
$membershipTypes = CRM_Member_PseudoConstant::membershipType();
$membershipType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $dao->membership_id, 'membership_type_id');
$membershipType = CRM_Utils_Array::value($membershipType, $membershipTypes);
$details .= '
<br/>' . ts('Automatic renewal of %1 membership cancelled.', array(1 => $membershipType));
}
else {
$details .= '
<br/>' . ts('The recurring contribution of %1, every %2 %3 has been cancelled.', array(
1 => $dao->amount,
2 => $dao->frequency_interval,
3 => $dao->frequency_unit,
));
}
$activityParams = array(
'source_contact_id' => $dao->contact_id,
'source_record_id' => CRM_Utils_Array::value('source_record_id', $activityParams),
'activity_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Cancel Recurring Contribution'),
'subject' => CRM_Utils_Array::value('subject', $activityParams, ts('Recurring contribution cancelled')),
'details' => $details,
'activity_date_time' => date('YmdHis'),
'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', 'Completed'),
);
$session = CRM_Core_Session::singleton();
$cid = $session->get('userID');
if ($cid) {
$activityParams['target_contact_id'][] = $activityParams['source_contact_id'];
$activityParams['source_contact_id'] = $cid;
}
// @todo use the api & do less wrangling above
CRM_Activity_BAO_Activity::create($activityParams);
}
// if there are associated objects, cancel them as well
if (!$objects) {
$transaction->commit();
return TRUE;
}
else {
// @todo - this is bad! Get the function out of the ipn.
$baseIPN = new CRM_Core_Payment_BaseIPN();
return $baseIPN->cancelled($objects, $transaction);
}
}
else {
// if already cancelled, return true
$recur->whereAdd();
$recur->whereAdd("contribution_status_id = $canceledId");
if ($recur->find(TRUE)) {
return TRUE;
}
}
return FALSE;
}
/**
* Get list of recurring contribution of contact Ids.
*
* @param int $contactId
* Contact ID.
*
* @return array
* list of recurring contribution fields
*
*/
public static function getRecurContributions($contactId) {
$params = array();
$recurDAO = new CRM_Contribute_DAO_ContributionRecur();
$recurDAO->contact_id = $contactId;
$recurDAO->find();
$contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
while ($recurDAO->fetch()) {
$params[$recurDAO->id]['id'] = $recurDAO->id;
$params[$recurDAO->id]['contactId'] = $recurDAO->contact_id;
$params[$recurDAO->id]['start_date'] = $recurDAO->start_date;
$params[$recurDAO->id]['end_date'] = $recurDAO->end_date;
$params[$recurDAO->id]['next_sched_contribution_date'] = $recurDAO->next_sched_contribution_date;
$params[$recurDAO->id]['amount'] = $recurDAO->amount;
$params[$recurDAO->id]['currency'] = $recurDAO->currency;
$params[$recurDAO->id]['frequency_unit'] = $recurDAO->frequency_unit;
$params[$recurDAO->id]['frequency_interval'] = $recurDAO->frequency_interval;
$params[$recurDAO->id]['installments'] = $recurDAO->installments;
$params[$recurDAO->id]['contribution_status_id'] = $recurDAO->contribution_status_id;
$params[$recurDAO->id]['contribution_status'] = CRM_Utils_Array::value($recurDAO->contribution_status_id, $contributionStatus);
$params[$recurDAO->id]['is_test'] = $recurDAO->is_test;
$params[$recurDAO->id]['payment_processor_id'] = $recurDAO->payment_processor_id;
}
return $params;
}
/**
* @param int $entityID
* @param string $entity
*
* @return null|Object
*/
public static function getSubscriptionDetails($entityID, $entity = 'recur') {
$sql = "
SELECT rec.id as recur_id,
rec.processor_id as subscription_id,
rec.frequency_interval,
rec.installments,
rec.frequency_unit,
rec.amount,
rec.is_test,
rec.auto_renew,
rec.currency,
rec.campaign_id,
rec.financial_type_id,
rec.next_sched_contribution_date,
rec.failure_retry_date,
rec.cycle_day,
con.id as contribution_id,
con.contribution_page_id,
rec.contact_id,
mp.membership_id";
if ($entity == 'recur') {
$sql .= "
FROM civicrm_contribution_recur rec
LEFT JOIN civicrm_contribution con ON ( con.contribution_recur_id = rec.id )
LEFT JOIN civicrm_membership_payment mp ON ( mp.contribution_id = con.id )
WHERE rec.id = %1";
}
elseif ($entity == 'contribution') {
$sql .= "
FROM civicrm_contribution con
INNER JOIN civicrm_contribution_recur rec ON ( con.contribution_recur_id = rec.id )
LEFT JOIN civicrm_membership_payment mp ON ( mp.contribution_id = con.id )
WHERE con.id = %1";
}
elseif ($entity == 'membership') {
$sql .= "
FROM civicrm_membership_payment mp
INNER JOIN civicrm_membership mem ON ( mp.membership_id = mem.id )
INNER JOIN civicrm_contribution_recur rec ON ( mem.contribution_recur_id = rec.id )
INNER JOIN civicrm_contribution con ON ( con.id = mp.contribution_id )
WHERE mp.membership_id = %1";
}
$dao = CRM_Core_DAO::executeQuery($sql, array(1 => array($entityID, 'Integer')));
if ($dao->fetch()) {
return $dao;
}
else {
return NULL;
}
}
/**
* Does the recurring contribution support financial type change.
*
* This is conditional on there being only one line item or if there are no contributions as yet.
*
* (This second is a bit of an unusual condition but might occur in the context of a
*
* @param int $id
*
* @return bool
*/
public static function supportsFinancialTypeChange($id) {
// At this stage only sites with no Financial ACLs will have the opportunity to edit the financial type.
// this is to limit the scope of the change and because financial ACLs are still fairly new & settling down.
if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
return FALSE;
}
$contribution = self::getTemplateContribution($id);
return CRM_Contribute_BAO_Contribution::isSingleLineItem($contribution['id']);
}
/**
* Get the contribution to be used as the template for later contributions.
*
* Later we might merge in data stored against the contribution recur record rather than just return the contribution.
*
* @param int $id
* @param array $overrides
* Parameters that should be overriden. Add unit tests if using parameters other than total_amount & financial_type_id.
*
* @return array
* @throws \CiviCRM_API3_Exception
*/
public static function getTemplateContribution($id, $overrides = array()) {
$templateContribution = civicrm_api3('Contribution', 'get', array(
'contribution_recur_id' => $id,
'options' => array('limit' => 1, 'sort' => array('id DESC')),
'sequential' => 1,
'contribution_test' => '',
));
if ($templateContribution['count']) {
$result = array_merge($templateContribution['values'][0], $overrides);
$result['line_item'] = CRM_Contribute_BAO_ContributionRecur::calculateRecurLineItems($id, $result['total_amount'], $result['financial_type_id']);
return $result;
}
return array();
}
public static function setSubscriptionContext() {
// handle context redirection for subscription url
$session = CRM_Core_Session::singleton();
if ($session->get('userID')) {
$url = FALSE;
$cid = CRM_Utils_Request::retrieve('cid', 'Integer');
$mid = CRM_Utils_Request::retrieve('mid', 'Integer');
$qfkey = CRM_Utils_Request::retrieve('key', 'String');
$context = CRM_Utils_Request::retrieve('context', 'String');
if ($cid) {
switch ($context) {
case 'contribution':
$url = CRM_Utils_System::url('civicrm/contact/view',
"reset=1&selectedChild=contribute&cid={$cid}"
);
break;
case 'membership':
$url = CRM_Utils_System::url('civicrm/contact/view',
"reset=1&selectedChild=member&cid={$cid}"
);
break;
case 'dashboard':
$url = CRM_Utils_System::url('civicrm/user', "reset=1&id={$cid}");
break;
}
}
if ($mid) {
switch ($context) {
case 'dashboard':
$url = CRM_Utils_System::url('civicrm/member', "force=1&context={$context}&key={$qfkey}");
break;
case 'search':
$url = CRM_Utils_System::url('civicrm/member/search', "force=1&context={$context}&key={$qfkey}");
break;
}
}
if ($url) {
$session->pushUserContext($url);
}
}
}
/**
* CRM-16285 - Function to handle validation errors on form, for recurring contribution field.
*
* @param array $fields
* The input form values.
* @param array $files
* The uploaded files if any.
* @param CRM_Core_Form $self
* @param array $errors
*/
public static function validateRecurContribution($fields, $files, $self, &$errors) {
if (!empty($fields['is_recur'])) {
if ($fields['frequency_interval'] <= 0) {
$errors['frequency_interval'] = ts('Please enter a number for how often you want to make this recurring contribution (EXAMPLE: Every 3 months).');
}
if ($fields['frequency_unit'] == '0') {
$errors['frequency_unit'] = ts('Please select a period (e.g. months, years ...) for how often you want to make this recurring contribution (EXAMPLE: Every 3 MONTHS).');
}
}
}
/**
* Send start or end notification for recurring payments.
*
* @param array $ids
* @param CRM_Contribute_BAO_ContributionRecur $recur
* @param bool $isFirstOrLastRecurringPayment
*/
public static function sendRecurringStartOrEndNotification($ids, $recur, $isFirstOrLastRecurringPayment) {
if ($isFirstOrLastRecurringPayment) {
$autoRenewMembership = FALSE;
if ($recur->id &&
isset($ids['membership']) && $ids['membership']
) {
$autoRenewMembership = TRUE;
}
//send recurring Notification email for user
CRM_Contribute_BAO_ContributionPage::recurringNotify($isFirstOrLastRecurringPayment,
$ids['contact'],
$ids['contributionPage'],
$recur,
$autoRenewMembership
);
}
}
/**
* Copy custom data of the initial contribution into its recurring contributions.
*
* @param int $recurId
* @param int $targetContributionId
*/
static public function copyCustomValues($recurId, $targetContributionId) {
if ($recurId && $targetContributionId) {
// get the initial contribution id of recur id
$sourceContributionId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
// if the same contribution is being processed then return
if ($sourceContributionId == $targetContributionId) {
return;
}
// check if proper recurring contribution record is being processed
$targetConRecurId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $targetContributionId, 'contribution_recur_id');
if ($targetConRecurId != $recurId) {
return;
}
// copy custom data
$extends = array('Contribution');
$groupTree = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, NULL, $extends);
if ($groupTree) {
foreach ($groupTree as $groupID => $group) {
$table[$groupTree[$groupID]['table_name']] = array('entity_id');
foreach ($group['fields'] as $fieldID => $field) {
$table[$groupTree[$groupID]['table_name']][] = $groupTree[$groupID]['fields'][$fieldID]['column_name'];
}
}
foreach ($table as $tableName => $tableColumns) {
$insert = 'INSERT IGNORE INTO ' . $tableName . ' (' . implode(', ', $tableColumns) . ') ';
$tableColumns[0] = $targetContributionId;
$select = 'SELECT ' . implode(', ', $tableColumns);
$from = ' FROM ' . $tableName;
$where = " WHERE {$tableName}.entity_id = {$sourceContributionId}";
$query = $insert . $select . $from . $where;
CRM_Core_DAO::executeQuery($query);
}
}
}
}
/**
* Add soft credit to for recurring payment.
*
* copy soft credit record of first recurring contribution.
* and add new soft credit against $targetContributionId
*
* @param int $recurId
* @param int $targetContributionId
*/
public static function addrecurSoftCredit($recurId, $targetContributionId) {
$soft_contribution = new CRM_Contribute_DAO_ContributionSoft();
$soft_contribution->contribution_id = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
// Check if first recurring contribution has any associated soft credit.
if ($soft_contribution->find(TRUE)) {
$soft_contribution->contribution_id = $targetContributionId;
unset($soft_contribution->id);
$soft_contribution->save();
}
}
/**
* Add line items for recurring contribution.
*
* @param int $recurId
* @param $contribution
*
* @return array
*/
public static function addRecurLineItems($recurId, $contribution) {
$foundLineItems = FALSE;
$lineSets = self::calculateRecurLineItems($recurId, $contribution->total_amount, $contribution->financial_type_id);
foreach ($lineSets as $lineItems) {
if (!empty($lineItems)) {
foreach ($lineItems as $key => $value) {
if ($value['entity_table'] == 'civicrm_membership') {
try {
// @todo this should be done by virtue of editing the line item as this link
// is deprecated. This may be the case but needs testing.
civicrm_api3('membership_payment', 'create', array(
'membership_id' => $value['entity_id'],
'contribution_id' => $contribution->id,
'is_transactional' => FALSE,
));
}
catch (CiviCRM_API3_Exception $e) {
// we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data
// this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated
}
}
}
$foundLineItems = TRUE;
}
}
if (!$foundLineItems) {
CRM_Price_BAO_LineItem::processPriceSet($contribution->id, $lineSets, $contribution);
}
return $lineSets;
}
/**
* Update pledge associated with a recurring contribution.
*
* If the contribution has a pledge_payment record pledge, then update the pledge_payment record & pledge based on that linkage.
*
* If a previous contribution in the recurring contribution sequence is linked with a pledge then we assume this contribution
* should be linked with the same pledge also. Currently only back-office users can apply a recurring payment to a pledge &
* it should be assumed they
* do so with the intention that all payments will be linked
*
* The pledge payment record should already exist & will need to be updated with the new contribution ID.
* If not the contribution will also need to be linked to the pledge
*
* @param int $contributionID
* @param int $contributionRecurID
* @param int $contributionStatusID
* @param float $contributionAmount
*
* @throws \CiviCRM_API3_Exception
*/
public static function updateRecurLinkedPledge($contributionID, $contributionRecurID, $contributionStatusID, $contributionAmount) {
$returnProperties = array('id', 'pledge_id');
$paymentDetails = $paymentIDs = array();
if (CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contributionID,
$paymentDetails, $returnProperties
)
) {
foreach ($paymentDetails as $key => $value) {
$paymentIDs[] = $value['id'];
$pledgeId = $value['pledge_id'];
}
}
else {
//payment is not already linked - if it is linked with a pledge we need to create a link.
// return if it is not recurring contribution
if (!$contributionRecurID) {
return;
}
$relatedContributions = new CRM_Contribute_DAO_Contribution();
$relatedContributions->contribution_recur_id = $contributionRecurID;
$relatedContributions->find();
while ($relatedContributions->fetch()) {
CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id,
$paymentDetails, $returnProperties
);
}
if (empty($paymentDetails)) {
// payment is not linked with a pledge and neither are any other contributions on this
return;
}
foreach ($paymentDetails as $key => $value) {
$pledgeId = $value['pledge_id'];
}
// we have a pledge now we need to get the oldest unpaid payment
$paymentDetails = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
if (empty($paymentDetails['id'])) {
// we can assume this pledge is now completed
// return now so we don't create a core error & roll back
return;
}
$paymentDetails['contribution_id'] = $contributionID;
$paymentDetails['status_id'] = $contributionStatusID;
$paymentDetails['actual_amount'] = $contributionAmount;
// put contribution against it
$payment = civicrm_api3('PledgePayment', 'create', $paymentDetails);
$paymentIDs[] = $payment['id'];
}
// update pledge and corresponding payment statuses
CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contributionStatusID,
NULL, $contributionAmount
);
}
/**
* @param $form
*/
public static function recurringContribution(&$form) {
// Recurring contribution fields
foreach (self::getRecurringFields() as $key => $label) {
if ($key == 'contribution_recur_payment_made' && !empty($form->_formValues) &&
!CRM_Utils_System::isNull(CRM_Utils_Array::value($key, $form->_formValues))
) {
$form->assign('contribution_recur_pane_open', TRUE);
break;
}
CRM_Core_Form_Date::buildDateRange($form, $key, 1, '_low', '_high');
// If data has been entered for a recurring field, tell the tpl layer to open the pane
if (!empty($form->_formValues) && !empty($form->_formValues[$key . '_relative']) || !empty($form->_formValues[$key . '_low']) || !empty($form->_formValues[$key . '_high'])) {
$form->assign('contribution_recur_pane_open', TRUE);
break;
}
}
// Add field to check if payment is made for recurring contribution
$recurringPaymentOptions = array(
1 => ts('All recurring contributions'),
2 => ts('Recurring contributions with at least one payment'),
);
$form->addRadio('contribution_recur_payment_made', NULL, $recurringPaymentOptions, array('allowClear' => TRUE));
CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_start_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_end_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_modified_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_next_sched_contribution_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_failure_retry_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
CRM_Core_Form_Date::buildDateRange($form, 'contribution_recur_cancel_date', 1, '_low', '_high', ts('From'), FALSE, FALSE, 'birth');
// Add field for contribution status
$form->addSelect('contribution_recur_contribution_status_id',
array('entity' => 'contribution', 'multiple' => 'multiple', 'context' => 'search', 'options' => CRM_Contribute_PseudoConstant::contributionStatus())
);
$form->addElement('text', 'contribution_recur_processor_id', ts('Processor ID'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionRecur', 'processor_id'));
$form->addElement('text', 'contribution_recur_trxn_id', ts('Transaction ID'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionRecur', 'trxn_id'));
CRM_Core_BAO_Query::addCustomFormFields($form, array('ContributionRecur'));
}
/**
* Get fields for recurring contributions.
*
* @return array
*/
public static function getRecurringFields() {
return array(
'contribution_recur_payment_made' => ts(''),
'contribution_recur_start_date' => ts('Recurring Contribution Start Date'),
'contribution_recur_next_sched_contribution_date' => ts('Next Scheduled Recurring Contribution'),
'contribution_recur_cancel_date' => ts('Recurring Contribution Cancel Date'),
'contribution_recur_end_date' => ts('Recurring Contribution End Date'),
'contribution_recur_create_date' => ('Recurring Contribution Create Date'),
'contribution_recur_modified_date' => ('Recurring Contribution Modified Date'),
'contribution_recur_failure_retry_date' => ts('Failed Recurring Contribution Retry Date'),
);
}
/**
* Update recurring contribution based on incoming payment.
*
* Do not rename or move this function without updating https://issues.civicrm.org/jira/browse/CRM-17655.
*
* @param int $recurringContributionID
* @param string $paymentStatus
* Payment status - this correlates to the machine name of the contribution status ID ie
* - Completed
* - Failed
*
* @throws \CiviCRM_API3_Exception
*/
public static function updateOnNewPayment($recurringContributionID, $paymentStatus, $effectiveDate) {
$effectiveDate = $effectiveDate ? date('Y-m-d', strtotime($effectiveDate)) : date('Y-m-d');
if (!in_array($paymentStatus, array('Completed', 'Failed'))) {
return;
}
$params = array(
'id' => $recurringContributionID,
'return' => array(
'contribution_status_id',
'next_sched_contribution_date',
'frequency_unit',
'frequency_interval',
'installments',
'failure_count',
),
);
$existing = civicrm_api3('ContributionRecur', 'getsingle', $params);
if ($paymentStatus == 'Completed'
&& CRM_Contribute_PseudoConstant::contributionStatus($existing['contribution_status_id'], 'name') == 'Pending') {
$params['contribution_status_id'] = 'In Progress';
}
if ($paymentStatus == 'Failed') {
$params['failure_count'] = $existing['failure_count'];
}
$params['modified_date'] = date('Y-m-d H:i:s');
if (!empty($existing['installments']) && self::isComplete($recurringContributionID, $existing['installments'])) {
$params['contribution_status_id'] = 'Completed';
}
else {
// Only update next sched date if it's empty or 'just now' because payment processors may be managing
// the scheduled date themselves as core did not previously provide any help.
if (empty($existing['next_sched_contribution_date']) || strtotime($existing['next_sched_contribution_date']) ==
strtotime($effectiveDate)) {
$params['next_sched_contribution_date'] = date('Y-m-d', strtotime('+' . $existing['frequency_interval'] . ' ' . $existing['frequency_unit'], strtotime($effectiveDate)));
}
}
civicrm_api3('ContributionRecur', 'create', $params);
}
/**
* Is this recurring contribution now complete.
*
* Have all the payments expected been received now.
*
* @param int $recurringContributionID
* @param int $installments
*
* @return bool
*/
protected static function isComplete($recurringContributionID, $installments) {
$paidInstallments = CRM_Core_DAO::singleValueQuery(
'SELECT count(*) FROM civicrm_contribution
WHERE contribution_recur_id = %1
AND contribution_status_id = ' . CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed'),
array(1 => array($recurringContributionID, 'Integer'))
);
if ($paidInstallments >= $installments) {
return TRUE;
}
return FALSE;
}
/**
* Calculate line items for the relevant recurring calculation.
*
* @param int $recurId
* @param string $total_amount
* @param int $financial_type_id
*
* @return array
*/
public static function calculateRecurLineItems($recurId, $total_amount, $financial_type_id) {
$originalContributionID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $recurId, 'id', 'contribution_recur_id');
$lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($originalContributionID);
$lineSets = array();
if (count($lineItems) == 1) {
foreach ($lineItems as $index => $lineItem) {
if ($financial_type_id) {
// CRM-17718 allow for possibility of changed financial type ID having been set prior to calling this.
$lineItem['financial_type_id'] = $financial_type_id;
}
if ($lineItem['line_total'] != $total_amount) {
// We are dealing with a changed amount! Per CRM-16397 we can work out what to do with these
// if there is only one line item, and the UI should prevent this situation for those with more than one.
$lineItem['line_total'] = $total_amount;
$lineItem['unit_price'] = round($total_amount / $lineItem['qty'], 2);
}
$priceField = new CRM_Price_DAO_PriceField();
$priceField->id = $lineItem['price_field_id'];
$priceField->find(TRUE);
$lineSets[$priceField->price_set_id][] = $lineItem;
}
}
// CRM-19309 if more than one then just pass them through:
elseif (count($lineItems) > 1) {
foreach ($lineItems as $index => $lineItem) {
$lineSets[$index][] = $lineItem;
}
}
return $lineSets;
}
}

View file

@ -0,0 +1,602 @@
<?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
*/
class CRM_Contribute_BAO_ContributionSoft extends CRM_Contribute_DAO_ContributionSoft {
/**
* Construct method.
*/
public function __construct() {
parent::__construct();
}
/**
* Add contribution soft credit record.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
*
* @return object
* soft contribution of object that is added
*/
public static function add(&$params) {
$contributionSoft = new CRM_Contribute_DAO_ContributionSoft();
$contributionSoft->copyValues($params);
// set currency for CRM-1496
if (!isset($contributionSoft->currency)) {
$config = CRM_Core_Config::singleton();
$contributionSoft->currency = $config->defaultCurrency;
}
return $contributionSoft->save();
}
/**
* Process the soft contribution and/or link to personal campaign page.
*
* @param array $params
* @param object $contribution CRM_Contribute_DAO_Contribution
*
*/
public static function processSoftContribution($params, $contribution) {
//retrieve existing soft-credit and pcp id(s) if any against $contribution
$softIDs = self::getSoftCreditIds($contribution->id);
$pcpId = self::getSoftCreditIds($contribution->id, TRUE);
if ($pcp = CRM_Utils_Array::value('pcp', $params)) {
$softParams = array();
$softParams['id'] = $pcpId ? $pcpId : NULL;
$softParams['contribution_id'] = $contribution->id;
$softParams['pcp_id'] = $pcp['pcp_made_through_id'];
$softParams['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP',
$pcp['pcp_made_through_id'], 'contact_id'
);
$softParams['currency'] = $contribution->currency;
$softParams['amount'] = $contribution->total_amount;
$softParams['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $pcp);
$softParams['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $pcp);
$softParams['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $pcp);
$softParams['soft_credit_type_id'] = CRM_Core_OptionGroup::getValue('soft_credit_type', 'pcp', 'name');
$contributionSoft = self::add($softParams);
//Send notification to owner for PCP
if ($contributionSoft->pcp_id && empty($pcpId)) {
CRM_Contribute_Form_Contribution_Confirm::pcpNotifyOwner($contribution, $contributionSoft);
}
}
//Delete PCP against this contribution and create new on submitted PCP information
elseif (array_key_exists('pcp', $params) && $pcpId) {
civicrm_api3('ContributionSoft', 'delete', array('id' => $pcpId));
}
if (isset($params['soft_credit'])) {
$softParams = $params['soft_credit'];
foreach ($softParams as $softParam) {
if (!empty($softIDs)) {
$key = key($softIDs);
$softParam['id'] = $softIDs[$key];
unset($softIDs[$key]);
}
$softParam['contribution_id'] = $contribution->id;
$softParam['currency'] = $contribution->currency;
//case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
if (empty($softParam['amount'])) {
$softParam['amount'] = $contribution->total_amount;
}
CRM_Contribute_BAO_ContributionSoft::add($softParam);
}
// delete any extra soft-credit while updating back-office contribution
foreach ((array) $softIDs as $softID) {
if (!in_array($softID, $params['soft_credit_ids'])) {
civicrm_api3('ContributionSoft', 'delete', array('id' => $softID));
}
}
}
}
/**
* Function used to save pcp / soft credit entry.
*
* This is used by contribution and also event pcps
*
* @param array $params
* @param object $form
* Form object.
*/
public static function formatSoftCreditParams(&$params, &$form) {
$pcp = $softParams = $softIDs = array();
if (!empty($params['pcp_made_through_id'])) {
$fields = array(
'pcp_made_through_id',
'pcp_display_in_roll',
'pcp_roll_nickname',
'pcp_personal_note',
);
foreach ($fields as $f) {
$pcp[$f] = CRM_Utils_Array::value($f, $params);
}
}
if (!empty($form->_values['honoree_profile_id']) && !empty($params['soft_credit_type_id'])) {
$honorId = NULL;
// @todo fix use of deprecated function.
$contributionSoftParams['soft_credit_type_id'] = CRM_Core_OptionGroup::getValue('soft_credit_type', 'pcp', 'name');
//check if there is any duplicate contact
// honoree should never be the donor
$exceptKeys = array(
'contactID' => 0,
'onbehalf_contact_id' => 0,
);
$except = array_values(array_intersect_key($params, $exceptKeys));
$ids = CRM_Contact_BAO_Contact::getDuplicateContacts(
$params['honor'],
CRM_Core_BAO_UFGroup::getContactType($form->_values['honoree_profile_id']),
'Unsupervised',
$except,
FALSE
);
if (count($ids)) {
$honorId = CRM_Utils_Array::value(0, $ids);
}
$honorId = CRM_Contact_BAO_Contact::createProfileContact(
$params['honor'], CRM_Core_DAO::$_nullArray,
$honorId, NULL,
$form->_values['honoree_profile_id']
);
$softParams[] = array(
'contact_id' => $honorId,
'soft_credit_type_id' => $params['soft_credit_type_id'],
);
if (CRM_Utils_Array::value('is_email_receipt', $form->_values)) {
$form->_values['honor'] = array(
'soft_credit_type' => CRM_Utils_Array::value(
$params['soft_credit_type_id'],
CRM_Core_OptionGroup::values("soft_credit_type")
),
'honor_id' => $honorId,
'honor_profile_id' => $form->_values['honoree_profile_id'],
'honor_profile_values' => $params['honor'],
);
}
}
elseif (!empty($params['soft_credit_contact_id'])) {
//build soft credit params
foreach ($params['soft_credit_contact_id'] as $key => $val) {
if ($val && $params['soft_credit_amount'][$key]) {
$softParams[$key]['contact_id'] = $val;
$softParams[$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
$softParams[$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
if (!empty($params['soft_credit_id'][$key])) {
$softIDs[] = $softParams[$key]['id'] = $params['soft_credit_id'][$key];
}
}
}
}
$params['pcp'] = !empty($pcp) ? $pcp : NULL;
$params['soft_credit'] = $softParams;
$params['soft_credit_ids'] = $softIDs;
}
/**
* Fetch object based on array of properties.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $defaults
* (reference ) an assoc array to hold the flattened values.
*
* @return CRM_Contribute_BAO_ContributionSoft
*/
public static function retrieve(&$params, &$defaults) {
$contributionSoft = new CRM_Contribute_DAO_ContributionSoft();
$contributionSoft->copyValues($params);
if ($contributionSoft->find(TRUE)) {
CRM_Core_DAO::storeValues($contributionSoft, $defaults);
return $contributionSoft;
}
return NULL;
}
/**
* @param int $contact_id
* @param int $isTest
*
* @return array
*/
public static function getSoftContributionTotals($contact_id, $isTest = 0) {
$whereClause = "AND cc.cancel_date IS NULL";
$query = "
SELECT SUM(amount) as amount, AVG(total_amount) as average, cc.currency
FROM civicrm_contribution_soft ccs
LEFT JOIN civicrm_contribution cc ON ccs.contribution_id = cc.id
WHERE cc.is_test = %2 AND ccs.contact_id = %1 {$whereClause}
GROUP BY currency";
$params = array(
1 => array($contact_id, 'Integer'),
2 => array($isTest, 'Integer'),
);
$cs = CRM_Core_DAO::executeQuery($query, $params);
$count = 0;
$amount = $average = $cancelAmount = array();
while ($cs->fetch()) {
if ($cs->amount > 0) {
$count++;
$amount[] = $cs->amount;
$average[] = $cs->average;
$currency[] = $cs->currency;
}
}
//to get cancel amount
$cancelAmountWhereClause = "AND cc.cancel_date IS NOT NULL";
$query = str_replace($whereClause, $cancelAmountWhereClause, $query);
$cancelAmountSQL = CRM_Core_DAO::executeQuery($query, $params);
while ($cancelAmountSQL->fetch()) {
if ($cancelAmountSQL->amount > 0) {
$count++;
$cancelAmount[] = $cancelAmountSQL->amount;
}
}
if ($count > 0) {
return array(
implode(',&nbsp;', $amount),
implode(',&nbsp;', $average),
implode(',&nbsp;', $currency),
implode(',&nbsp;', $cancelAmount),
);
}
return array(0, 0);
}
/**
* Retrieve soft contributions for contribution record.
*
* @param int $contributionID
* @param bool $all
* Include PCP data.
*
* @return array
* Array of soft contribution ids, amounts, and associated contact ids
*/
public static function getSoftContribution($contributionID, $all = FALSE) {
$pcpFields = array(
'pcp_id',
'pcp_title',
'pcp_display_in_roll',
'pcp_roll_nickname',
'pcp_personal_note',
);
$query = '
SELECT ccs.id, pcp_id, cpcp.title as pcp_title, pcp_display_in_roll, pcp_roll_nickname, pcp_personal_note, ccs.currency as currency, amount, ccs.contact_id as contact_id, c.display_name, ccs.soft_credit_type_id
FROM civicrm_contribution_soft ccs INNER JOIN civicrm_contact c on c.id = ccs.contact_id
LEFT JOIN civicrm_pcp cpcp ON ccs.pcp_id = cpcp.id
WHERE contribution_id = %1;
';
$params = array(1 => array($contributionID, 'Integer'));
$dao = CRM_Core_DAO::executeQuery($query, $params);
$softContribution = array();
$count = 1;
while ($dao->fetch()) {
if ($dao->pcp_id) {
if ($all) {
foreach ($pcpFields as $val) {
$softContribution[$val] = $dao->$val;
}
$softContribution['pcp_soft_credit_to_name'] = $dao->display_name;
$softContribution['pcp_soft_credit_to_id'] = $dao->contact_id;
}
}
else {
$softContribution['soft_credit'][$count] = array(
'contact_id' => $dao->contact_id,
'soft_credit_id' => $dao->id,
'currency' => $dao->currency,
'amount' => $dao->amount,
'contact_name' => $dao->display_name,
'soft_credit_type' => $dao->soft_credit_type_id,
'soft_credit_type_label' => CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $dao->soft_credit_type_id),
);
$count++;
}
}
return $softContribution;
}
/**
* @param int $contributionID
* @param bool $isPCP
*
* @return array
*/
public static function getSoftCreditIds($contributionID, $isPCP = FALSE) {
$query = "
SELECT id
FROM civicrm_contribution_soft
WHERE contribution_id = %1
";
if ($isPCP) {
$query .= " AND pcp_id IS NOT NULL";
}
else {
$query .= " AND pcp_id IS NULL";
}
$params = array(1 => array($contributionID, 'Integer'));
$dao = CRM_Core_DAO::executeQuery($query, $params);
$id = array();
$type = '';
while ($dao->fetch()) {
if ($isPCP) {
return $dao->id;
}
$id[] = $dao->id;
}
return $id;
}
/**
* Wrapper for ajax soft contribution selector.
*
* @param array $params
* Associated array for params.
*
* @return array
* Associated array of soft contributions
*/
public static function getSoftContributionSelector($params) {
$isTest = 0;
if (!empty($params['isTest'])) {
$isTest = $params['isTest'];
}
// Format the params.
$params['offset'] = ($params['page'] - 1) * $params['rp'];
$params['rowCount'] = $params['rp'];
$params['sort'] = CRM_Utils_Array::value('sortBy', $params);
$contactId = $params['cid'];
$filter = NULL;
if ($params['context'] == 'membership' && !empty($params['entityID']) && $contactId) {
$filter = " AND cc.id IN (SELECT contribution_id FROM civicrm_membership_payment WHERE membership_id = {$params['entityID']})";
}
$softCreditList = self::getSoftContributionList($contactId, $filter, $isTest, $params);
$softCreditListDT = array();
$softCreditListDT['data'] = array_values($softCreditList);
$softCreditListDT['recordsTotal'] = $params['total'];
$softCreditListDT['recordsFiltered'] = $params['total'];
return $softCreditListDT;
}
/**
* Function to retrieve the list of soft contributions for given contact.
*
* @param int $contact_id
* Contact id.
* @param string $filter
* @param int $isTest
* Additional filter criteria, later used in where clause.
* @param array $dTParams
*
* @return array
*/
public static function getSoftContributionList($contact_id, $filter = NULL, $isTest = 0, &$dTParams = NULL) {
$config = CRM_Core_Config::singleton();
$links = array(
CRM_Core_Action::VIEW => array(
'name' => ts('View'),
'url' => 'civicrm/contact/view/contribution',
'qs' => 'reset=1&id=%%contributionid%%&cid=%%contactId%%&action=view&context=contribution&selectedChild=contribute',
'title' => ts('View related contribution'),
),
);
$orderBy = 'cc.receive_date DESC';
if (!empty($dTParams['sort'])) {
$orderBy = $dTParams['sort'];
}
$limit = '';
if (!empty($dTParams['rowCount']) && $dTParams['rowCount'] > 0) {
$limit = " LIMIT {$dTParams['offset']}, {$dTParams['rowCount']} ";
}
$softOgId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'soft_credit_type', 'id', 'name');
$statusOgId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionGroup', 'contribution_status', 'id', 'name');
$query = '
SELECT SQL_CALC_FOUND_ROWS ccs.id, ccs.amount as amount,
ccs.contribution_id,
ccs.pcp_id,
ccs.pcp_display_in_roll,
ccs.pcp_roll_nickname,
ccs.pcp_personal_note,
ccs.soft_credit_type_id,
sov.label as sct_label,
cc.receive_date,
cc.contact_id as contributor_id,
cc.contribution_status_id as contribution_status_id,
cov.label as contribution_status,
cp.title as pcp_title,
cc.currency,
contact.display_name as contributor_name,
cct.name as financial_type
FROM civicrm_contribution_soft ccs
LEFT JOIN civicrm_contribution cc
ON ccs.contribution_id = cc.id
LEFT JOIN civicrm_pcp cp
ON ccs.pcp_id = cp.id
LEFT JOIN civicrm_contact contact ON
ccs.contribution_id = cc.id AND cc.contact_id = contact.id
LEFT JOIN civicrm_financial_type cct ON cc.financial_type_id = cct.id
LEFT JOIN civicrm_option_value sov ON sov.option_group_id = %3 AND ccs.soft_credit_type_id = sov.value
LEFT JOIN civicrm_option_value cov ON cov.option_group_id = %4 AND cc.contribution_status_id = cov.value
';
$where = "
WHERE cc.is_test = %2 AND ccs.contact_id = %1";
if ($filter) {
$where .= $filter;
}
$query .= "{$where} ORDER BY {$orderBy} {$limit}";
$params = array(
1 => array($contact_id, 'Integer'),
2 => array($isTest, 'Integer'),
3 => array($softOgId, 'Integer'),
4 => array($statusOgId, 'Integer'),
);
$cs = CRM_Core_DAO::executeQuery($query, $params);
$dTParams['total'] = CRM_Core_DAO::singleValueQuery('SELECT FOUND_ROWS()');
$result = array();
while ($cs->fetch()) {
$result[$cs->id]['amount'] = CRM_Utils_Money::format($cs->amount, $cs->currency);
$result[$cs->id]['currency'] = $cs->currency;
$result[$cs->id]['contributor_id'] = $cs->contributor_id;
$result[$cs->id]['contribution_id'] = $cs->contribution_id;
$result[$cs->id]['contributor_name'] = CRM_Utils_System::href(
$cs->contributor_name,
'civicrm/contact/view',
"reset=1&cid={$cs->contributor_id}"
);
$result[$cs->id]['financial_type'] = $cs->financial_type;
$result[$cs->id]['receive_date'] = CRM_Utils_Date::customFormat($cs->receive_date, $config->dateformatDatetime);
$result[$cs->id]['pcp_id'] = $cs->pcp_id;
$result[$cs->id]['pcp_title'] = ($cs->pcp_title) ? $cs->pcp_title : 'n/a';
$result[$cs->id]['pcp_display_in_roll'] = $cs->pcp_display_in_roll;
$result[$cs->id]['pcp_roll_nickname'] = $cs->pcp_roll_nickname;
$result[$cs->id]['pcp_personal_note'] = $cs->pcp_personal_note;
$result[$cs->id]['contribution_status'] = $cs->contribution_status;
$result[$cs->id]['sct_label'] = $cs->sct_label;
$replace = array(
'contributionid' => $cs->contribution_id,
'contactId' => $cs->contributor_id,
);
$result[$cs->id]['links'] = CRM_Core_Action::formLink($links, NULL, $replace);
if ($isTest) {
$result[$cs->id]['contribution_status'] = $result[$cs->id]['contribution_status'] . '<br /> (test)';
}
}
return $result;
}
/**
* Function to assign honor profile fields to template/form, if $honorId (as soft-credit's contact_id)
* is passed then whole honoreeprofile fields with title/value assoc array assigned or only honoreeName
* is assigned
*
* @param CRM_Core_Form $form
* @param array $params
* @param int $honorId
*/
public static function formatHonoreeProfileFields($form, $params, $honorId = NULL) {
if (empty($form->_values['honoree_profile_id'])) {
return;
}
$profileContactType = CRM_Core_BAO_UFGroup::getContactType($form->_values['honoree_profile_id']);
$profileFields = CRM_Core_BAO_UFGroup::getFields($form->_values['honoree_profile_id']);
$honoreeProfileFields = $values = array();
$honorName = NULL;
if ($honorId) {
CRM_Core_BAO_UFGroup::getValues($honorId, $profileFields, $values, FALSE, $params);
if (empty($params)) {
foreach ($profileFields as $name => $field) {
$title = $field['title'];
$params[$field['name']] = $values[$title];
}
}
}
//remove name related fields and construct name string with prefix/suffix
//which will be later assigned to template
switch ($profileContactType) {
case 'Individual':
if (array_key_exists('prefix_id', $params)) {
$honorName = CRM_Utils_Array::value(CRM_Utils_Array::value('prefix_id', $params),
CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id')
);
unset($profileFields['prefix_id']);
}
$honorName .= ' ' . $params['first_name'] . ' ' . $params['last_name'];
unset($profileFields['first_name']);
unset($profileFields['last_name']);
if (array_key_exists('suffix_id', $params)) {
$honorName .= ' ' . CRM_Utils_Array::value(CRM_Utils_Array::value('suffix_id', $params),
CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'suffix_id')
);
unset($profileFields['suffix_id']);
}
break;
case 'Organization':
$honorName = $params['organization_name'];
unset($profileFields['organization_name']);
break;
case 'Household':
$honorName = $params['household_name'];
unset($profileFields['household_name']);
break;
}
if ($honorId) {
$honoreeProfileFields['Name'] = $honorName;
foreach ($profileFields as $name => $field) {
$title = $field['title'];
$honoreeProfileFields[$title] = $values[$title];
}
$form->assign('honoreeProfile', $honoreeProfileFields);
}
else {
$form->assign('honorName', $honorName);
}
}
}

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
*/
class CRM_Contribute_BAO_ManagePremiums extends CRM_Contribute_DAO_Product {
/**
* Static holder for the default LT.
*/
static $_defaultContributionType = NULL;
/**
* Class constructor.
*/
public function __construct() {
parent::__construct();
}
/**
* Fetch object based on array of properties.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $defaults
* (reference ) an assoc array to hold the flattened values.
*
* @return CRM_Contribute_BAO_ManagePremium
*/
public static function retrieve(&$params, &$defaults) {
$premium = new CRM_Contribute_DAO_Product();
$premium->copyValues($params);
if ($premium->find(TRUE)) {
$premium->product_name = $premium->name;
CRM_Core_DAO::storeValues($premium, $defaults);
return $premium;
}
return NULL;
}
/**
* Update the is_active flag in the db.
*
* @param int $id
* Id of the database record.
* @param bool $is_active
* Value we want to set the is_active field.
*
* @return Object
* DAO object on success, null otherwise
*/
public static function setIsActive($id, $is_active) {
if (!$is_active) {
$dao = new CRM_Contribute_DAO_PremiumsProduct();
$dao->product_id = $id;
$dao->delete();
}
return CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Product', $id, 'is_active', $is_active);
}
/**
* Add a premium product to the database, and return it.
*
* @param array $params
* Reference array contains the values submitted by the form.
* @param array $ids
* Reference array contains the id.
*
* @return CRM_Contribute_DAO_Product
*/
public static function add(&$params, &$ids) {
$params = array_merge(array(
'id' => CRM_Utils_Array::value('premium', $ids),
'image' => '',
'thumbnail' => '',
'is_active' => 0,
'is_deductible' => FALSE,
'currency' => CRM_Core_Config::singleton()->defaultCurrency,
), $params);
// Modify the submitted values for 'image' and 'thumbnail' so that we use
// local URLs for these images when possible.
$params['image'] = CRM_Utils_String::simplifyURL($params['image'], TRUE);
$params['thumbnail'] = CRM_Utils_String::simplifyURL($params['thumbnail'], TRUE);
// Save and return
$premium = new CRM_Contribute_DAO_Product();
$premium->copyValues($params);
$premium->save();
return $premium;
}
/**
* Delete premium Types.
*
* @param int $productID
*/
public static function del($productID) {
//check dependencies
$premiumsProduct = new CRM_Contribute_DAO_PremiumsProduct();
$premiumsProduct->product_id = $productID;
if ($premiumsProduct->find(TRUE)) {
$session = CRM_Core_Session::singleton();
$message .= ts('This Premium is being linked to <a href=\'%1\'>Online Contribution page</a>. Please remove it in order to delete this Premium.', array(1 => CRM_Utils_System::url('civicrm/admin/contribute', 'reset=1')), ts('Deletion Error'), 'error');
CRM_Core_Session::setStatus($message);
return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/admin/contribute/managePremiums', 'reset=1&action=browse'));
}
//delete from financial Type table
$premium = new CRM_Contribute_DAO_Product();
$premium->id = $productID;
$premium->delete();
}
}

View file

@ -0,0 +1,269 @@
<?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
*/
class CRM_Contribute_BAO_Premium extends CRM_Contribute_DAO_Premium {
/**
* Product information.
*
* @var array
*/
private static $productInfo;
/**
* Class constructor.
*/
public function __construct() {
parent::__construct();
}
/**
* Fetch object based on array of properties.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $defaults
* (reference ) an assoc array to hold the flattened values.
*
* @return CRM_Contribute_DAO_Product
*/
public static function retrieve(&$params, &$defaults) {
$premium = new CRM_Contribute_DAO_Product();
$premium->copyValues($params);
if ($premium->find(TRUE)) {
CRM_Core_DAO::storeValues($premium, $defaults);
return $premium;
}
return NULL;
}
/**
* Update the is_active flag in the db.
*
* @param int $id
* Id of the database record.
* @param bool $is_active
* Value we want to set the is_active field.
*
* @return Object
* DAO object on success, null otherwise
*/
public static function setIsActive($id, $is_active) {
return CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Premium', $id, 'premiums_active ', $is_active);
}
/**
* Delete financial Types.
*
* @param int $premiumID
*/
public static function del($premiumID) {
$premium = new CRM_Contribute_DAO_Premium();
$premium->id = $premiumID;
$premium->delete();
}
/**
* Build Premium Block im Contribution Pages.
*
* @param CRM_Core_Form $form
* @param int $pageID
* @param bool $formItems
* @param int $selectedProductID
* @param string $selectedOption
*/
public static function buildPremiumBlock(&$form, $pageID, $formItems = FALSE, $selectedProductID = NULL, $selectedOption = NULL) {
$form->add('hidden', "selectProduct", $selectedProductID, array('id' => 'selectProduct'));
$dao = new CRM_Contribute_DAO_Premium();
$dao->entity_table = 'civicrm_contribution_page';
$dao->entity_id = $pageID;
$dao->premiums_active = 1;
CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, CRM_Core_Action::ADD);
$addWhere = "financial_type_id IN (0)";
if (!empty($financialTypes)) {
$addWhere = "financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
}
if ($dao->find(TRUE)) {
$premiumID = $dao->id;
$premiumBlock = array();
CRM_Core_DAO::storeValues($dao, $premiumBlock);
$dao = new CRM_Contribute_DAO_PremiumsProduct();
$dao->premiums_id = $premiumID;
$dao->whereAdd($addWhere);
$dao->orderBy('weight');
$dao->find();
$products = array();
$radio = array();
while ($dao->fetch()) {
$productDAO = new CRM_Contribute_DAO_Product();
$productDAO->id = $dao->product_id;
$productDAO->is_active = 1;
if ($productDAO->find(TRUE)) {
if ($selectedProductID != NULL) {
if ($selectedProductID == $productDAO->id) {
if ($selectedOption) {
$productDAO->options = ts('Selected Option') . ': ' . $selectedOption;
}
else {
$productDAO->options = NULL;
}
CRM_Core_DAO::storeValues($productDAO, $products[$productDAO->id]);
}
}
else {
CRM_Core_DAO::storeValues($productDAO, $products[$productDAO->id]);
}
}
$options = $temp = array();
$temp = explode(',', $productDAO->options);
foreach ($temp as $value) {
$options[trim($value)] = trim($value);
}
if ($temp[0] != '') {
$form->addElement('select', 'options_' . $productDAO->id, NULL, $options);
}
}
if (count($products)) {
$form->assign('showPremium', $formItems);
$form->assign('showSelectOptions', $formItems);
$form->assign('products', $products);
$form->assign('premiumBlock', $premiumBlock);
}
}
}
/**
* Build Premium B im Contribution Pages.
*
* @param CRM_Core_Form $form
* @param int $productID
* @param int $premiumProductID
*/
public function buildPremiumPreviewBlock($form, $productID, $premiumProductID = NULL) {
if ($premiumProductID) {
$dao = new CRM_Contribute_DAO_PremiumsProduct();
$dao->id = $premiumProductID;
$dao->find(TRUE);
$productID = $dao->product_id;
}
$productDAO = new CRM_Contribute_DAO_Product();
$productDAO->id = $productID;
$productDAO->is_active = 1;
if ($productDAO->find(TRUE)) {
CRM_Core_DAO::storeValues($productDAO, $products[$productDAO->id]);
}
$radio[$productDAO->id] = $form->createElement('radio', NULL, NULL, NULL, $productDAO->id, NULL);
$options = $temp = array();
$temp = explode(',', $productDAO->options);
foreach ($temp as $value) {
$options[$value] = $value;
}
if ($temp[0] != '') {
$form->add('select', 'options_' . $productDAO->id, NULL, $options);
}
$form->addGroup($radio, 'selectProduct', NULL);
$form->assign('showRadio', TRUE);
$form->assign('showSelectOptions', TRUE);
$form->assign('products', $products);
$form->assign('preview', TRUE);
}
/**
* Delete premium associated w/ contribution page.
*
* @param int $contributionPageID
*/
public static function deletePremium($contributionPageID) {
if (!$contributionPageID) {
return;
}
//need to delete entries from civicrm_premiums
//as well as from civicrm_premiums_product, CRM-4586
$params = array(
'entity_id' => $contributionPageID,
'entity_table' => 'civicrm_contribution_page',
);
$premium = new CRM_Contribute_DAO_Premium();
$premium->copyValues($params);
$premium->find();
while ($premium->fetch()) {
//lets delete from civicrm_premiums_product
$premiumsProduct = new CRM_Contribute_DAO_PremiumsProduct();
$premiumsProduct->premiums_id = $premium->id;
$premiumsProduct->delete();
//now delete premium
$premium->delete();
}
}
/**
* Retrieve premium product and their options.
*
* @return array
* product and option arrays
*/
public static function getPremiumProductInfo() {
if (!self::$productInfo) {
$products = $options = array();
$dao = new CRM_Contribute_DAO_Product();
$dao->is_active = 1;
$dao->find();
while ($dao->fetch()) {
$products[$dao->id] = $dao->name . " ( " . $dao->sku . " )";
$opts = explode(',', $dao->options);
foreach ($opts as $k => $v) {
$ops[$k] = trim($v);
}
if ($ops[0] != '') {
$options[$dao->id] = $opts;
}
}
self::$productInfo = array($products, $options);
}
return self::$productInfo;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,210 @@
<?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
*/
/**
* Class to retrieve information about a contribution page.
*/
class CRM_Contribute_BAO_Widget extends CRM_Contribute_DAO_Widget {
/**
* Gets all campaign related data and returns it as a std class.
*
* @param int $contributionPageID
* @param int $widgetID
* @param bool $includePending
*
* @return object
*/
public static function getContributionPageData($contributionPageID, $widgetID, $includePending = FALSE) {
$config = CRM_Core_Config::singleton();
$data = array();
$data['currencySymbol'] = $config->defaultCurrencySymbol;
if (empty($contributionPageID) ||
CRM_Utils_Type::validate($contributionPageID, 'Integer') == NULL
) {
$data['is_error'] = TRUE;
CRM_Core_Error::debug_log_message("$contributionPageID is not set");
return $data;
}
$widget = new CRM_Contribute_DAO_Widget();
$widget->contribution_page_id = $contributionPageID;
if (!$widget->find(TRUE)) {
$data['is_error'] = TRUE;
CRM_Core_Error::debug_log_message("$contributionPageID is not found");
return $data;
}
$data['is_error'] = FALSE;
if (!$widget->is_active) {
$data['is_active'] = FALSE;
}
$data['is_active'] = TRUE;
$data['title'] = $widget->title;
$data['logo'] = $widget->url_logo;
$data['button_title'] = $widget->button_title;
$data['about'] = $widget->about;
//check if pending status needs to be included
$status = '1';
if ($includePending) {
$status = '1,2';
}
$query = "
SELECT count( id ) as count,
sum( total_amount) as amount
FROM civicrm_contribution
WHERE is_test = 0
AND contribution_status_id IN ({$status})
AND contribution_page_id = %1";
$params = array(1 => array($contributionPageID, 'Integer'));
$dao = CRM_Core_DAO::executeQuery($query, $params);
if ($dao->fetch()) {
$data['num_donors'] = (int) $dao->count;
$data['money_raised'] = (int) $dao->amount;
}
else {
$data['num_donors'] = $data['money_raised'] = $data->money_raised = 0;
}
$query = "
SELECT goal_amount, start_date, end_date, is_active
FROM civicrm_contribution_page
WHERE id = %1";
$params = array(1 => array($contributionPageID, 'Integer'));
$dao = CRM_Core_DAO::executeQuery($query, $params);
$data['campaign_start'] = '';
$startDate = NULL;
if ($dao->fetch()) {
$data['money_target'] = (int) $dao->goal_amount;
// conditions that needs to be handled
// 1. Campaign is not active - no text
// 2. Campaign start date greater than today - show start date
// 3. Campaign end date is set and greater than today - show end date
// 4. If no start and end date or no end date and start date greater than today, then it's ongoing
if ($dao->is_active) {
$data['campaign_start'] = ts('Campaign is ongoing');
// check for time being between start and end date
$now = time();
if ($dao->start_date) {
$startDate = CRM_Utils_Date::unixTime($dao->start_date);
if ($startDate &&
$startDate >= $now
) {
$data['is_active'] = FALSE;
$data['campaign_start'] = ts('Campaign starts on %1', array(
1 => CRM_Utils_Date::customFormat($dao->start_date, $config->dateformatFull),
)
);
}
}
if ($dao->end_date) {
$endDate = CRM_Utils_Date::unixTime($dao->end_date);
if ($endDate &&
$endDate < $now
) {
$data['is_active'] = FALSE;
$data['campaign_start'] = ts('Campaign ended on %1',
array(
1 => CRM_Utils_Date::customFormat($dao->end_date, $config->dateformatFull),
)
);
}
elseif ($startDate >= $now) {
$data['campaign_start'] = ts('Campaign starts on %1',
array(
1 => CRM_Utils_Date::customFormat($dao->start_date, $config->dateformatFull),
)
);
}
else {
$data['campaign_start'] = ts('Campaign ends on %1',
array(
1 => CRM_Utils_Date::customFormat($dao->end_date, $config->dateformatFull),
)
);
}
}
}
else {
$data['is_active'] = FALSE;
}
}
else {
$data['is_active'] = FALSE;
}
$data['money_raised_percentage'] = 0;
if ($data['money_target'] > 0) {
$percent = $data['money_raised'] / $data['money_target'];
$data['money_raised_percentage'] = (round($percent, 2)) * 100 . "%";
$data['money_target_display'] = CRM_Utils_Money::format($data['money_target']);
$data['money_raised'] = ts('Raised %1 of %2', array(
1 => CRM_Utils_Money::format($data['money_raised']),
2 => $data['money_target_display'],
));
}
else {
$data['money_raised'] = ts('Raised %1', array(1 => CRM_Utils_Money::format($data['money_raised'])));
}
$data['money_low'] = 0;
$data['num_donors'] = $data['num_donors'] . " " . ts('Donors');
$data['home_url'] = "<a href='{$config->userFrameworkBaseURL}' class='crm-home-url' style='color:" . $widget->color_homepage_link . "'>" . ts('Learn more.') . "</a>";
// if is_active is false, show this link and hide the contribute button
$data['homepage_link'] = $widget->url_homepage;
$data['colors'] = array();
$data['colors']["title"] = $widget->color_title;
$data['colors']["button"] = $widget->color_button;
$data['colors']["bar"] = $widget->color_bar;
$data['colors']["main_text"] = $widget->color_main_text;
$data['colors']["main"] = $widget->color_main;
$data['colors']["main_bg"] = $widget->color_main_bg;
$data['colors']["bg"] = $widget->color_bg;
$data['colors']["about_link"] = $widget->color_about_link;
return $data;
}
}

View file

@ -0,0 +1,77 @@
<?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 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 it's results
*
* The second form is used to process search results with the associated actions
*
*/
class CRM_Contribute_Controller_Contribution 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_Contribute_StateMachine_Contribution($this, $action);
// create and instantiate the pages
$this->addPages($this->_stateMachine, $action);
// add all the actions
$uploadNames = $this->get('uploadNames');
if (!empty($uploadNames)) {
$config = CRM_Core_Config::singleton();
$this->addActions($config->customFileUploadDir, $uploadNames);
}
else {
$this->addActions();
}
}
public function invalidKey() {
$this->invalidKeyRedirect();
}
}

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
*/
/**
* 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_Contribute_Controller_ContributionPage 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_Contribute_StateMachine_ContributionPage($this, $action);
// Create and instantiate the pages.
$this->addPages($this->_stateMachine, $action);
$this->addActions();
}
}

View file

@ -0,0 +1,61 @@
<?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 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_Contribute_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_Contribute_StateMachine_Search($this, $action);
$this->addPages($this->_stateMachine, $action);
$this->addActions();
}
}

View file

@ -0,0 +1,999 @@
<?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/Contribute/Contribution.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:45a20d00d01766a61687cbac5cef1482)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Contribute_DAO_Contribution constructor.
*/
class CRM_Contribute_DAO_Contribution extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_contribution';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = true;
/**
* Contribution ID
*
* @var int unsigned
*/
public $id;
/**
* FK to Contact ID
*
* @var int unsigned
*/
public $contact_id;
/**
* FK to Financial Type for (total_amount - non_deductible_amount).
*
* @var int unsigned
*/
public $financial_type_id;
/**
* The Contribution Page which triggered this contribution
*
* @var int unsigned
*/
public $contribution_page_id;
/**
* FK to Payment Instrument
*
* @var int unsigned
*/
public $payment_instrument_id;
/**
* Date contribution was received - not necessarily the creation date of the record
*
* @var datetime
*/
public $receive_date;
/**
* Portion of total amount which is NOT tax deductible. Equal to total_amount for non-deductible financial types.
*
* @var float
*/
public $non_deductible_amount;
/**
* Total amount of this contribution. Use market value for non-monetary gifts.
*
* @var float
*/
public $total_amount;
/**
* actual processor fee if known - may be 0.
*
* @var float
*/
public $fee_amount;
/**
* actual funds transfer amount. total less fees. if processor does not report actual fee during transaction, this is set to total_amount.
*
* @var float
*/
public $net_amount;
/**
* unique transaction id. may be processor id, bank id + trans id, or account number + check number... depending on payment_method
*
* @var string
*/
public $trxn_id;
/**
* unique invoice id, system generated or passed in
*
* @var string
*/
public $invoice_id;
/**
* Human readable invoice number
*
* @var string
*/
public $invoice_number;
/**
* 3 character string, value from config setting or input via user.
*
* @var string
*/
public $currency;
/**
* when was gift cancelled
*
* @var datetime
*/
public $cancel_date;
/**
*
* @var text
*/
public $cancel_reason;
/**
* when (if) receipt was sent. populated automatically for online donations w/ automatic receipting
*
* @var datetime
*/
public $receipt_date;
/**
* when (if) was donor thanked
*
* @var datetime
*/
public $thankyou_date;
/**
* Origin of this Contribution.
*
* @var string
*/
public $source;
/**
*
* @var text
*/
public $amount_level;
/**
* Conditional foreign key to civicrm_contribution_recur id. Each contribution made in connection with a recurring contribution carries a foreign key to the recurring contribution record. This assumes we can track these processor initiated events.
*
* @var int unsigned
*/
public $contribution_recur_id;
/**
*
* @var boolean
*/
public $is_test;
/**
*
* @var boolean
*/
public $is_pay_later;
/**
*
* @var int unsigned
*/
public $contribution_status_id;
/**
* Conditional foreign key to civicrm_address.id. We insert an address record for each contribution when we have associated billing name and address data.
*
* @var int unsigned
*/
public $address_id;
/**
*
* @var string
*/
public $check_number;
/**
* The campaign for which this contribution has been triggered.
*
* @var int unsigned
*/
public $campaign_id;
/**
* unique credit note id, system generated or passed in
*
* @var string
*/
public $creditnote_id;
/**
* Total tax amount of this contribution.
*
* @var float
*/
public $tax_amount;
/**
* Stores the date when revenue should be recognized.
*
* @var datetime
*/
public $revenue_recognition_date;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_contribution';
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() , 'financial_type_id', 'civicrm_financial_type', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contribution_page_id', 'civicrm_contribution_page', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'contribution_recur_id', 'civicrm_contribution_recur', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'address_id', 'civicrm_address', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'campaign_id', 'civicrm_campaign', '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(
'contribution_id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Contribution ID') ,
'description' => 'Contribution ID',
'required' => true,
'import' => true,
'where' => 'civicrm_contribution.id',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
) ,
'contribution_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_contribution.contact_id',
'headerPattern' => '/contact(.?id)?/i',
'dataPattern' => '/^\d+$/',
'export' => true,
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
'html' => array(
'type' => 'EntityRef',
) ,
) ,
'financial_type_id' => array(
'name' => 'financial_type_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Financial Type') ,
'description' => 'FK to Financial Type for (total_amount - non_deductible_amount).',
'export' => true,
'where' => 'civicrm_contribution.financial_type_id',
'headerPattern' => '',
'dataPattern' => '',
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialType',
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'table' => 'civicrm_financial_type',
'keyColumn' => 'id',
'labelColumn' => 'name',
)
) ,
'contribution_page_id' => array(
'name' => 'contribution_page_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Contribution Page ID') ,
'description' => 'The Contribution Page which triggered this contribution',
'import' => true,
'where' => 'civicrm_contribution.contribution_page_id',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'FKClassName' => 'CRM_Contribute_DAO_ContributionPage',
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'table' => 'civicrm_contribution_page',
'keyColumn' => 'id',
'labelColumn' => 'title',
)
) ,
'payment_instrument_id' => array(
'name' => 'payment_instrument_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Payment Method ID') ,
'description' => 'FK to Payment Instrument',
'export' => true,
'where' => 'civicrm_contribution.payment_instrument_id',
'headerPattern' => '/^payment|(p(ayment\s)?instrument)$/i',
'dataPattern' => '',
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'optionGroupName' => 'payment_instrument',
'optionEditPath' => 'civicrm/admin/options/payment_instrument',
)
) ,
'receive_date' => array(
'name' => 'receive_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Date Received') ,
'description' => 'Date contribution was received - not necessarily the creation date of the record',
'import' => true,
'where' => 'civicrm_contribution.receive_date',
'headerPattern' => '/receive(.?date)?/i',
'dataPattern' => '/^\d{4}-?\d{2}-?\d{2} ?(\d{2}:?\d{2}:?(\d{2})?)?$/',
'export' => true,
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'html' => array(
'type' => 'Select Date',
'formatType' => 'activityDateTime',
) ,
) ,
'non_deductible_amount' => array(
'name' => 'non_deductible_amount',
'type' => CRM_Utils_Type::T_MONEY,
'title' => ts('Non-deductible Amount') ,
'description' => 'Portion of total amount which is NOT tax deductible. Equal to total_amount for non-deductible financial types.',
'precision' => array(
20,
2
) ,
'import' => true,
'where' => 'civicrm_contribution.non_deductible_amount',
'headerPattern' => '/non?.?deduct/i',
'dataPattern' => '/^\d+(\.\d{2})?$/',
'export' => true,
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'total_amount' => array(
'name' => 'total_amount',
'type' => CRM_Utils_Type::T_MONEY,
'title' => ts('Total Amount') ,
'description' => 'Total amount of this contribution. Use market value for non-monetary gifts.',
'required' => true,
'precision' => array(
20,
2
) ,
'import' => true,
'where' => 'civicrm_contribution.total_amount',
'headerPattern' => '/^total|(.?^am(ou)?nt)/i',
'dataPattern' => '/^\d+(\.\d{2})?$/',
'export' => true,
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'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_contribution.fee_amount',
'headerPattern' => '/fee(.?am(ou)?nt)?/i',
'dataPattern' => '/^\d+(\.\d{2})?$/',
'export' => true,
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'net_amount' => array(
'name' => 'net_amount',
'type' => CRM_Utils_Type::T_MONEY,
'title' => ts('Net Amount') ,
'description' => 'actual funds transfer amount. total less fees. if processor does not report actual fee during transaction, this is set to total_amount.',
'precision' => array(
20,
2
) ,
'import' => true,
'where' => 'civicrm_contribution.net_amount',
'headerPattern' => '/net(.?am(ou)?nt)?/i',
'dataPattern' => '/^\d+(\.\d{2})?$/',
'export' => true,
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'trxn_id' => array(
'name' => 'trxn_id',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Transaction ID') ,
'description' => 'unique transaction id. may be processor id, bank id + trans id, or account number + check number... depending on payment_method',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'import' => true,
'where' => 'civicrm_contribution.trxn_id',
'headerPattern' => '/tr(ansactio|x)n(.?id)?/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'invoice_id' => array(
'name' => 'invoice_id',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Invoice Reference') ,
'description' => 'unique invoice id, system generated or passed in',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'import' => true,
'where' => 'civicrm_contribution.invoice_id',
'headerPattern' => '/invoice(.?id)?/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'invoice_number' => array(
'name' => 'invoice_number',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Invoice Number') ,
'description' => 'Human readable invoice number',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'import' => true,
'where' => 'civicrm_contribution.invoice_number',
'headerPattern' => '/invoice(.?number)?/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'currency' => array(
'name' => 'currency',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Currency') ,
'description' => '3 character string, value from config setting or input via user.',
'maxlength' => 3,
'size' => CRM_Utils_Type::FOUR,
'import' => true,
'where' => 'civicrm_contribution.currency',
'headerPattern' => '/cur(rency)?/i',
'dataPattern' => '/^[A-Z]{3}$/i',
'export' => true,
'default' => 'NULL',
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
)
) ,
'cancel_date' => array(
'name' => 'cancel_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Cancel Date') ,
'description' => 'when was gift cancelled',
'import' => true,
'where' => 'civicrm_contribution.cancel_date',
'headerPattern' => '/cancel(.?date)?/i',
'dataPattern' => '/^\d{4}-?\d{2}-?\d{2} ?(\d{2}:?\d{2}:?(\d{2})?)?$/',
'export' => true,
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'html' => array(
'type' => 'Select Date',
'formatType' => 'activityDateTime',
) ,
) ,
'cancel_reason' => array(
'name' => 'cancel_reason',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Cancel Reason') ,
'import' => true,
'where' => 'civicrm_contribution.cancel_reason',
'headerPattern' => '/(cancel.?)?reason/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'receipt_date' => array(
'name' => 'receipt_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Receipt Date') ,
'description' => 'when (if) receipt was sent. populated automatically for online donations w/ automatic receipting',
'import' => true,
'where' => 'civicrm_contribution.receipt_date',
'headerPattern' => '/receipt(.?date)?/i',
'dataPattern' => '/^\d{4}-?\d{2}-?\d{2} ?(\d{2}:?\d{2}:?(\d{2})?)?$/',
'export' => true,
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'html' => array(
'type' => 'Select Date',
'formatType' => 'activityDateTime',
) ,
) ,
'thankyou_date' => array(
'name' => 'thankyou_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Thank-you Date') ,
'description' => 'when (if) was donor thanked',
'import' => true,
'where' => 'civicrm_contribution.thankyou_date',
'headerPattern' => '/thank(s|(.?you))?(.?date)?/i',
'dataPattern' => '/^\d{4}-?\d{2}-?\d{2} ?(\d{2}:?\d{2}:?(\d{2})?)?$/',
'export' => true,
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'html' => array(
'type' => 'Select Date',
'formatType' => 'activityDateTime',
) ,
) ,
'contribution_source' => array(
'name' => 'source',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Contribution Source') ,
'description' => 'Origin of this Contribution.',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'import' => true,
'where' => 'civicrm_contribution.source',
'headerPattern' => '/source/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'amount_level' => array(
'name' => 'amount_level',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Amount Label') ,
'import' => true,
'where' => 'civicrm_contribution.amount_level',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'contribution_recur_id' => array(
'name' => 'contribution_recur_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Recurring Contribution ID') ,
'description' => 'Conditional foreign key to civicrm_contribution_recur id. Each contribution made in connection with a recurring contribution carries a foreign key to the recurring contribution record. This assumes we can track these processor initiated events.',
'export' => true,
'where' => 'civicrm_contribution.contribution_recur_id',
'headerPattern' => '',
'dataPattern' => '',
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'FKClassName' => 'CRM_Contribute_DAO_ContributionRecur',
) ,
'is_test' => array(
'name' => 'is_test',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Test') ,
'import' => true,
'where' => 'civicrm_contribution.is_test',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'html' => array(
'type' => 'CheckBox',
) ,
) ,
'is_pay_later' => array(
'name' => 'is_pay_later',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Is Pay Later') ,
'import' => true,
'where' => 'civicrm_contribution.is_pay_later',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'html' => array(
'type' => 'CheckBox',
) ,
) ,
'contribution_status_id' => array(
'name' => 'contribution_status_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Contribution Status ID') ,
'import' => true,
'where' => 'civicrm_contribution.contribution_status_id',
'headerPattern' => '/status/i',
'dataPattern' => '',
'export' => true,
'default' => '1',
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'optionGroupName' => 'contribution_status',
'optionEditPath' => 'civicrm/admin/options/contribution_status',
)
) ,
'contribution_address_id' => array(
'name' => 'address_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Contribution Address') ,
'description' => 'Conditional foreign key to civicrm_address.id. We insert an address record for each contribution when we have associated billing name and address data.',
'export' => true,
'where' => 'civicrm_contribution.address_id',
'headerPattern' => '',
'dataPattern' => '',
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'FKClassName' => 'CRM_Core_DAO_Address',
) ,
'contribution_check_number' => array(
'name' => 'check_number',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Check Number') ,
'maxlength' => 255,
'size' => 6,
'import' => true,
'where' => 'civicrm_contribution.check_number',
'headerPattern' => '/check(.?number)?/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'contribution_campaign_id' => array(
'name' => 'campaign_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Campaign') ,
'description' => 'The campaign for which this contribution has been triggered.',
'import' => true,
'where' => 'civicrm_contribution.campaign_id',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'FKClassName' => 'CRM_Campaign_DAO_Campaign',
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'table' => 'civicrm_campaign',
'keyColumn' => 'id',
'labelColumn' => 'title',
)
) ,
'creditnote_id' => array(
'name' => 'creditnote_id',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Credit Note ID') ,
'description' => 'unique credit note id, system generated or passed in',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'import' => true,
'where' => 'civicrm_contribution.creditnote_id',
'headerPattern' => '/creditnote(.?id)?/i',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'tax_amount' => array(
'name' => 'tax_amount',
'type' => CRM_Utils_Type::T_MONEY,
'title' => ts('Tax Amount') ,
'description' => 'Total tax amount of this contribution.',
'precision' => array(
20,
2
) ,
'import' => true,
'where' => 'civicrm_contribution.tax_amount',
'headerPattern' => '/tax(.?am(ou)?nt)?/i',
'dataPattern' => '/^\d+(\.\d{2})?$/',
'export' => true,
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'revenue_recognition_date' => array(
'name' => 'revenue_recognition_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Revenue Recognition Date') ,
'description' => 'Stores the date when revenue should be recognized.',
'import' => true,
'where' => 'civicrm_contribution.revenue_recognition_date',
'headerPattern' => '/revenue(.?date)?/i',
'dataPattern' => '/^\d{4}-?\d{2}-?\d{2} ?(\d{2}:?\d{2}:?(\d{2})?)?$/',
'export' => true,
'table_name' => 'civicrm_contribution',
'entity' => 'Contribution',
'bao' => 'CRM_Contribute_BAO_Contribution',
'localizable' => 0,
'html' => array(
'type' => 'Select Date',
'formatType' => 'activityDateTime',
) ,
) ,
);
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__, 'contribution', $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__, 'contribution', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array(
'UI_contrib_payment_instrument_id' => array(
'name' => 'UI_contrib_payment_instrument_id',
'field' => array(
0 => 'payment_instrument_id',
) ,
'localizable' => false,
'sig' => 'civicrm_contribution::0::payment_instrument_id',
) ,
'index_total_amount_receive_date' => array(
'name' => 'index_total_amount_receive_date',
'field' => array(
0 => 'total_amount',
1 => 'receive_date',
) ,
'localizable' => false,
'sig' => 'civicrm_contribution::0::total_amount::receive_date',
) ,
'index_source' => array(
'name' => 'index_source',
'field' => array(
0 => 'source',
) ,
'localizable' => false,
'sig' => 'civicrm_contribution::0::source',
) ,
'UI_contrib_trxn_id' => array(
'name' => 'UI_contrib_trxn_id',
'field' => array(
0 => 'trxn_id',
) ,
'localizable' => false,
'unique' => true,
'sig' => 'civicrm_contribution::1::trxn_id',
) ,
'UI_contrib_invoice_id' => array(
'name' => 'UI_contrib_invoice_id',
'field' => array(
0 => 'invoice_id',
) ,
'localizable' => false,
'unique' => true,
'sig' => 'civicrm_contribution::1::invoice_id',
) ,
'index_contribution_status' => array(
'name' => 'index_contribution_status',
'field' => array(
0 => 'contribution_status_id',
) ,
'localizable' => false,
'sig' => 'civicrm_contribution::0::contribution_status_id',
) ,
'received_date' => array(
'name' => 'received_date',
'field' => array(
0 => 'receive_date',
) ,
'localizable' => false,
'sig' => 'civicrm_contribution::0::receive_date',
) ,
'check_number' => array(
'name' => 'check_number',
'field' => array(
0 => 'check_number',
) ,
'localizable' => false,
'sig' => 'civicrm_contribution::0::check_number',
) ,
'index_creditnote_id' => array(
'name' => 'index_creditnote_id',
'field' => array(
0 => 'creditnote_id',
) ,
'localizable' => false,
'sig' => 'civicrm_contribution::0::creditnote_id',
) ,
);
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,966 @@
<?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/Contribute/ContributionPage.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:00d0eb39eb657241b67e9d5b12bc09d8)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Contribute_DAO_ContributionPage constructor.
*/
class CRM_Contribute_DAO_ContributionPage extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_contribution_page';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = true;
/**
* Contribution Id
*
* @var int unsigned
*/
public $id;
/**
* Contribution Page title. For top of page display
*
* @var string
*/
public $title;
/**
* Text and html allowed. Displayed below title.
*
* @var text
*/
public $intro_text;
/**
* default financial type assigned to contributions submitted via this page, e.g. Contribution, Campaign Contribution
*
* @var int unsigned
*/
public $financial_type_id;
/**
* Payment Processors configured for this contribution Page
*
* @var string
*/
public $payment_processor;
/**
* if true - processing logic must reject transaction at confirmation stage if pay method != credit card
*
* @var boolean
*/
public $is_credit_card_only;
/**
* if true - allows real-time monetary transactions otherwise non-monetary transactions
*
* @var boolean
*/
public $is_monetary;
/**
* if true - allows recurring contributions, valid only for PayPal_Standard
*
* @var boolean
*/
public $is_recur;
/**
* if false, the confirm page in contribution pages gets skipped
*
* @var boolean
*/
public $is_confirm_enabled;
/**
* Supported recurring frequency units.
*
* @var string
*/
public $recur_frequency_unit;
/**
* if true - supports recurring intervals
*
* @var boolean
*/
public $is_recur_interval;
/**
* if true - asks user for recurring installments
*
* @var boolean
*/
public $is_recur_installments;
/**
* if true - user is able to adjust payment start date
*
* @var boolean
*/
public $adjust_recur_start_date;
/**
* if true - allows the user to send payment directly to the org later
*
* @var boolean
*/
public $is_pay_later;
/**
* The text displayed to the user in the main form
*
* @var text
*/
public $pay_later_text;
/**
* The receipt sent to the user instead of the normal receipt text
*
* @var text
*/
public $pay_later_receipt;
/**
* is partial payment enabled for this online contribution page
*
* @var boolean
*/
public $is_partial_payment;
/**
* Initial amount label for partial payment
*
* @var string
*/
public $initial_amount_label;
/**
* Initial amount help text for partial payment
*
* @var text
*/
public $initial_amount_help_text;
/**
* Minimum initial amount for partial payment
*
* @var float
*/
public $min_initial_amount;
/**
* if true, page will include an input text field where user can enter their own amount
*
* @var boolean
*/
public $is_allow_other_amount;
/**
* FK to civicrm_option_value.
*
* @var int unsigned
*/
public $default_amount_id;
/**
* if other amounts allowed, user can configure minimum allowed.
*
* @var float
*/
public $min_amount;
/**
* if other amounts allowed, user can configure maximum allowed.
*
* @var float
*/
public $max_amount;
/**
* The target goal for this page, allows people to build a goal meter
*
* @var float
*/
public $goal_amount;
/**
* Title for Thank-you page (header title tag, and display at the top of the page).
*
* @var string
*/
public $thankyou_title;
/**
* text and html allowed. displayed above result on success page
*
* @var text
*/
public $thankyou_text;
/**
* Text and html allowed. displayed at the bottom of the success page. Common usage is to include link(s) to other pages such as tell-a-friend, etc.
*
* @var text
*/
public $thankyou_footer;
/**
* if true, receipt is automatically emailed to contact on success
*
* @var boolean
*/
public $is_email_receipt;
/**
* FROM email name used for receipts generated by contributions to this contribution page.
*
* @var string
*/
public $receipt_from_name;
/**
* FROM email address used for receipts generated by contributions to this contribution page.
*
* @var string
*/
public $receipt_from_email;
/**
* comma-separated list of email addresses to cc each time a receipt is sent
*
* @var string
*/
public $cc_receipt;
/**
* comma-separated list of email addresses to bcc each time a receipt is sent
*
* @var string
*/
public $bcc_receipt;
/**
* text to include above standard receipt info on receipt email. emails are text-only, so do not allow html for now
*
* @var text
*/
public $receipt_text;
/**
* Is this property active?
*
* @var boolean
*/
public $is_active;
/**
* Text and html allowed. Displayed at the bottom of the first page of the contribution wizard.
*
* @var text
*/
public $footer_text;
/**
* Is this property active?
*
* @var boolean
*/
public $amount_block_is_active;
/**
* Date and time that this page starts.
*
* @var datetime
*/
public $start_date;
/**
* Date and time that this page ends. May be NULL if no defined end date/time
*
* @var datetime
*/
public $end_date;
/**
* FK to civicrm_contact, who created this contribution page
*
* @var int unsigned
*/
public $created_id;
/**
* Date and time that contribution page was created.
*
* @var datetime
*/
public $created_date;
/**
* 3 character string, value from config setting or input via user.
*
* @var string
*/
public $currency;
/**
* The campaign for which we are collecting contributions with this page.
*
* @var int unsigned
*/
public $campaign_id;
/**
* Can people share the contribution page through social media?
*
* @var boolean
*/
public $is_share;
/**
* if true - billing block is required for online contribution page
*
* @var boolean
*/
public $is_billing_required;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_contribution_page';
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() , 'financial_type_id', 'civicrm_financial_type', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'created_id', 'civicrm_contact', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'campaign_id', 'civicrm_campaign', '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('Contribution Page ID') ,
'description' => 'Contribution Id',
'required' => true,
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
) ,
'title' => array(
'name' => 'title',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Contribution Page Title') ,
'description' => 'Contribution Page title. For top of page display',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 1,
) ,
'intro_text' => array(
'name' => 'intro_text',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Contribution Page Introduction Text') ,
'description' => 'Text and html allowed. Displayed below title.',
'rows' => 6,
'cols' => 50,
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 1,
'html' => array(
'type' => 'RichTextEditor',
) ,
) ,
'financial_type_id' => array(
'name' => 'financial_type_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Financial Type') ,
'description' => 'default financial type assigned to contributions submitted via this page, e.g. Contribution, Campaign Contribution',
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialType',
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'table' => 'civicrm_financial_type',
'keyColumn' => 'id',
'labelColumn' => 'name',
)
) ,
'payment_processor' => array(
'name' => 'payment_processor',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Payment Processor') ,
'description' => 'Payment Processors configured for this contribution Page',
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'table' => 'civicrm_payment_processor',
'keyColumn' => 'id',
'labelColumn' => 'name',
)
) ,
'is_credit_card_only' => array(
'name' => 'is_credit_card_only',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Is Credit Card Only?') ,
'description' => 'if true - processing logic must reject transaction at confirmation stage if pay method != credit card',
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
) ,
'is_monetary' => array(
'name' => 'is_monetary',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Is Monetary') ,
'description' => 'if true - allows real-time monetary transactions otherwise non-monetary transactions',
'default' => '1',
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
) ,
'is_recur' => array(
'name' => 'is_recur',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Is Recurring') ,
'description' => 'if true - allows recurring contributions, valid only for PayPal_Standard',
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
) ,
'is_confirm_enabled' => array(
'name' => 'is_confirm_enabled',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Confirmation Page?') ,
'description' => 'if false, the confirm page in contribution pages gets skipped',
'default' => '1',
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
) ,
'recur_frequency_unit' => array(
'name' => 'recur_frequency_unit',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Recurring Frequency') ,
'description' => 'Supported recurring frequency units.',
'maxlength' => 128,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
) ,
'is_recur_interval' => array(
'name' => 'is_recur_interval',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Support Recurring Intervals') ,
'description' => 'if true - supports recurring intervals',
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
) ,
'is_recur_installments' => array(
'name' => 'is_recur_installments',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Recurring Installments?') ,
'description' => 'if true - asks user for recurring installments',
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
) ,
'adjust_recur_start_date' => array(
'name' => 'adjust_recur_start_date',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Adjust Recurring Start Date') ,
'description' => 'if true - user is able to adjust payment start date',
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
) ,
'is_pay_later' => array(
'name' => 'is_pay_later',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Pay Later') ,
'description' => 'if true - allows the user to send payment directly to the org later',
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
) ,
'pay_later_text' => array(
'name' => 'pay_later_text',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Pay Later Text') ,
'description' => 'The text displayed to the user in the main form',
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 1,
) ,
'pay_later_receipt' => array(
'name' => 'pay_later_receipt',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Pay Later Receipt') ,
'description' => 'The receipt sent to the user instead of the normal receipt text',
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 1,
) ,
'is_partial_payment' => array(
'name' => 'is_partial_payment',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Allow Partial Payment') ,
'description' => 'is partial payment enabled for this online contribution page',
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
) ,
'initial_amount_label' => array(
'name' => 'initial_amount_label',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Initial Amount Label') ,
'description' => 'Initial amount label for partial payment',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 1,
) ,
'initial_amount_help_text' => array(
'name' => 'initial_amount_help_text',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Initial Amount Help Text') ,
'description' => 'Initial amount help text for partial payment',
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 1,
) ,
'min_initial_amount' => array(
'name' => 'min_initial_amount',
'type' => CRM_Utils_Type::T_MONEY,
'title' => ts('Min Initial Amount') ,
'description' => 'Minimum initial amount for partial payment',
'precision' => array(
20,
2
) ,
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
) ,
'is_allow_other_amount' => array(
'name' => 'is_allow_other_amount',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Allow Other Amounts') ,
'description' => 'if true, page will include an input text field where user can enter their own amount',
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
) ,
'default_amount_id' => array(
'name' => 'default_amount_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Default Amount') ,
'description' => 'FK to civicrm_option_value.',
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
) ,
'min_amount' => array(
'name' => 'min_amount',
'type' => CRM_Utils_Type::T_MONEY,
'title' => ts('Minimum Amount') ,
'description' => 'if other amounts allowed, user can configure minimum allowed.',
'precision' => array(
20,
2
) ,
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
) ,
'max_amount' => array(
'name' => 'max_amount',
'type' => CRM_Utils_Type::T_MONEY,
'title' => ts('Maximum Amount') ,
'description' => 'if other amounts allowed, user can configure maximum allowed.',
'precision' => array(
20,
2
) ,
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
) ,
'goal_amount' => array(
'name' => 'goal_amount',
'type' => CRM_Utils_Type::T_MONEY,
'title' => ts('Goal Amount') ,
'description' => 'The target goal for this page, allows people to build a goal meter',
'precision' => array(
20,
2
) ,
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
) ,
'thankyou_title' => array(
'name' => 'thankyou_title',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Thank-you Title') ,
'description' => 'Title for Thank-you page (header title tag, and display at the top of the page).',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 1,
) ,
'thankyou_text' => array(
'name' => 'thankyou_text',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Thank-you Text') ,
'description' => 'text and html allowed. displayed above result on success page',
'rows' => 8,
'cols' => 60,
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 1,
'html' => array(
'type' => 'RichTextEditor',
) ,
) ,
'thankyou_footer' => array(
'name' => 'thankyou_footer',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Thank-you Footer') ,
'description' => 'Text and html allowed. displayed at the bottom of the success page. Common usage is to include link(s) to other pages such as tell-a-friend, etc.',
'rows' => 8,
'cols' => 60,
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 1,
'html' => array(
'type' => 'RichTextEditor',
) ,
) ,
'is_email_receipt' => array(
'name' => 'is_email_receipt',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Send email Receipt') ,
'description' => 'if true, receipt is automatically emailed to contact on success',
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
) ,
'receipt_from_name' => array(
'name' => 'receipt_from_name',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Receipt From') ,
'description' => 'FROM email name used for receipts generated by contributions to this contribution page.',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 1,
) ,
'receipt_from_email' => array(
'name' => 'receipt_from_email',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Receipt From email') ,
'description' => 'FROM email address used for receipts generated by contributions to this contribution page.',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
) ,
'cc_receipt' => array(
'name' => 'cc_receipt',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Receipt cc') ,
'description' => 'comma-separated list of email addresses to cc each time a receipt is sent',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
) ,
'bcc_receipt' => array(
'name' => 'bcc_receipt',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Receipt bcc') ,
'description' => 'comma-separated list of email addresses to bcc each time a receipt is sent',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
) ,
'receipt_text' => array(
'name' => 'receipt_text',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Receipt Text') ,
'description' => 'text to include above standard receipt info on receipt email. emails are text-only, so do not allow html for now',
'rows' => 6,
'cols' => 50,
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 1,
'html' => array(
'type' => 'TextArea',
) ,
) ,
'is_active' => array(
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Is Page Active?') ,
'description' => 'Is this property active?',
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
) ,
'footer_text' => array(
'name' => 'footer_text',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Footer Text') ,
'description' => 'Text and html allowed. Displayed at the bottom of the first page of the contribution wizard.',
'rows' => 6,
'cols' => 50,
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 1,
'html' => array(
'type' => 'RichTextEditor',
) ,
) ,
'amount_block_is_active' => array(
'name' => 'amount_block_is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Is Amount Block Active?') ,
'description' => 'Is this property active?',
'default' => '1',
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
) ,
'start_date' => array(
'name' => 'start_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Contribution Page Start Date') ,
'description' => 'Date and time that this page starts.',
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
) ,
'end_date' => array(
'name' => 'end_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Contribution Page End Date') ,
'description' => 'Date and time that this page ends. May be NULL if no defined end date/time',
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
) ,
'created_id' => array(
'name' => 'created_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Contribution Page Created By') ,
'description' => 'FK to civicrm_contact, who created this contribution page',
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
) ,
'created_date' => array(
'name' => 'created_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Contribution Page Created Date') ,
'description' => 'Date and time that contribution page was created.',
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
) ,
'currency' => array(
'name' => 'currency',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Contribution Page Currency') ,
'description' => '3 character string, value from config setting or input via user.',
'maxlength' => 3,
'size' => CRM_Utils_Type::FOUR,
'default' => 'NULL',
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
)
) ,
'campaign_id' => array(
'name' => 'campaign_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Contribution Page Campaign ID') ,
'description' => 'The campaign for which we are collecting contributions with this page.',
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
'FKClassName' => 'CRM_Campaign_DAO_Campaign',
'pseudoconstant' => array(
'table' => 'civicrm_campaign',
'keyColumn' => 'id',
'labelColumn' => 'title',
)
) ,
'is_share' => array(
'name' => 'is_share',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Is Contribution Page Shared?') ,
'description' => 'Can people share the contribution page through social media?',
'default' => '1',
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'localizable' => 0,
) ,
'is_billing_required' => array(
'name' => 'is_billing_required',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Is billing block required') ,
'description' => 'if true - billing block is required for online contribution page',
'table_name' => 'civicrm_contribution_page',
'entity' => 'ContributionPage',
'bao' => 'CRM_Contribute_BAO_ContributionPage',
'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 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__, 'contribution_page', $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__, 'contribution_page', $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,328 @@
<?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/Contribute/ContributionProduct.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:8ef29c5c92b3ffb2a678bd4c585a3d0e)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Contribute_DAO_ContributionProduct constructor.
*/
class CRM_Contribute_DAO_ContributionProduct extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_contribution_product';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = true;
/**
*
* @var int unsigned
*/
public $id;
/**
*
* @var int unsigned
*/
public $product_id;
/**
*
* @var int unsigned
*/
public $contribution_id;
/**
* Option value selected if applicable - e.g. color, size etc.
*
* @var string
*/
public $product_option;
/**
*
* @var int
*/
public $quantity;
/**
* Optional. Can be used to record the date this product was fulfilled or shipped.
*
* @var date
*/
public $fulfilled_date;
/**
* Actual start date for a time-delimited premium (subscription, service or membership)
*
* @var date
*/
public $start_date;
/**
* Actual end date for a time-delimited premium (subscription, service or membership)
*
* @var date
*/
public $end_date;
/**
*
* @var text
*/
public $comment;
/**
* FK to Financial Type(for membership price sets only).
*
* @var int unsigned
*/
public $financial_type_id;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_contribution_product';
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() , 'contribution_id', 'civicrm_contribution', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'financial_type_id', 'civicrm_financial_type', '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('Contribution Product ID') ,
'required' => true,
'table_name' => 'civicrm_contribution_product',
'entity' => 'ContributionProduct',
'bao' => 'CRM_Contribute_DAO_ContributionProduct',
'localizable' => 0,
) ,
'product_id' => array(
'name' => 'product_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Product ID') ,
'required' => true,
'table_name' => 'civicrm_contribution_product',
'entity' => 'ContributionProduct',
'bao' => 'CRM_Contribute_DAO_ContributionProduct',
'localizable' => 0,
) ,
'contribution_id' => array(
'name' => 'contribution_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Contribution ID') ,
'required' => true,
'table_name' => 'civicrm_contribution_product',
'entity' => 'ContributionProduct',
'bao' => 'CRM_Contribute_DAO_ContributionProduct',
'localizable' => 0,
'FKClassName' => 'CRM_Contribute_DAO_Contribution',
) ,
'product_option' => array(
'name' => 'product_option',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Product Option') ,
'description' => 'Option value selected if applicable - e.g. color, size etc.',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'export' => true,
'where' => 'civicrm_contribution_product.product_option',
'headerPattern' => '',
'dataPattern' => '',
'table_name' => 'civicrm_contribution_product',
'entity' => 'ContributionProduct',
'bao' => 'CRM_Contribute_DAO_ContributionProduct',
'localizable' => 0,
) ,
'quantity' => array(
'name' => 'quantity',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Quantity') ,
'export' => true,
'where' => 'civicrm_contribution_product.quantity',
'headerPattern' => '',
'dataPattern' => '',
'table_name' => 'civicrm_contribution_product',
'entity' => 'ContributionProduct',
'bao' => 'CRM_Contribute_DAO_ContributionProduct',
'localizable' => 0,
) ,
'fulfilled_date' => array(
'name' => 'fulfilled_date',
'type' => CRM_Utils_Type::T_DATE,
'title' => ts('Fulfilled Date') ,
'description' => 'Optional. Can be used to record the date this product was fulfilled or shipped.',
'export' => true,
'where' => 'civicrm_contribution_product.fulfilled_date',
'headerPattern' => '',
'dataPattern' => '',
'table_name' => 'civicrm_contribution_product',
'entity' => 'ContributionProduct',
'bao' => 'CRM_Contribute_DAO_ContributionProduct',
'localizable' => 0,
) ,
'contribution_start_date' => array(
'name' => 'start_date',
'type' => CRM_Utils_Type::T_DATE,
'title' => ts('Start date for premium') ,
'description' => 'Actual start date for a time-delimited premium (subscription, service or membership)',
'export' => true,
'where' => 'civicrm_contribution_product.start_date',
'headerPattern' => '',
'dataPattern' => '',
'table_name' => 'civicrm_contribution_product',
'entity' => 'ContributionProduct',
'bao' => 'CRM_Contribute_DAO_ContributionProduct',
'localizable' => 0,
) ,
'contribution_end_date' => array(
'name' => 'end_date',
'type' => CRM_Utils_Type::T_DATE,
'title' => ts('End date for premium') ,
'description' => 'Actual end date for a time-delimited premium (subscription, service or membership)',
'export' => true,
'where' => 'civicrm_contribution_product.end_date',
'headerPattern' => '',
'dataPattern' => '',
'table_name' => 'civicrm_contribution_product',
'entity' => 'ContributionProduct',
'bao' => 'CRM_Contribute_DAO_ContributionProduct',
'localizable' => 0,
) ,
'comment' => array(
'name' => 'comment',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Premium comment') ,
'table_name' => 'civicrm_contribution_product',
'entity' => 'ContributionProduct',
'bao' => 'CRM_Contribute_DAO_ContributionProduct',
'localizable' => 0,
) ,
'financial_type_id' => array(
'name' => 'financial_type_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Financial Type') ,
'description' => 'FK to Financial Type(for membership price sets only).',
'default' => 'NULL',
'table_name' => 'civicrm_contribution_product',
'entity' => 'ContributionProduct',
'bao' => 'CRM_Contribute_DAO_ContributionProduct',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialType',
'pseudoconstant' => array(
'table' => 'civicrm_financial_type',
'keyColumn' => 'id',
'labelColumn' => 'name',
)
) ,
);
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__, 'contribution_product', $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__, 'contribution_product', $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,761 @@
<?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/Contribute/ContributionRecur.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:a1007a4585bac4fcb04ce47535aecec0)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Contribute_DAO_ContributionRecur constructor.
*/
class CRM_Contribute_DAO_ContributionRecur extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_contribution_recur';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = true;
/**
* Contribution Recur ID
*
* @var int unsigned
*/
public $id;
/**
* Foreign key to civicrm_contact.id .
*
* @var int unsigned
*/
public $contact_id;
/**
* Amount to be contributed or charged each recurrence.
*
* @var float
*/
public $amount;
/**
* 3 character string, value from config setting or input via user.
*
* @var string
*/
public $currency;
/**
* Time units for recurrence of payment.
*
* @var string
*/
public $frequency_unit;
/**
* Number of time units for recurrence of payment.
*
* @var int unsigned
*/
public $frequency_interval;
/**
* Total number of payments to be made. Set this to 0 if this is an open-ended commitment i.e. no set end date.
*
* @var int unsigned
*/
public $installments;
/**
* The date the first scheduled recurring contribution occurs.
*
* @var datetime
*/
public $start_date;
/**
* When this recurring contribution record was created.
*
* @var datetime
*/
public $create_date;
/**
* Last updated date for this record. mostly the last time a payment was received
*
* @var datetime
*/
public $modified_date;
/**
* Date this recurring contribution was cancelled by contributor- if we can get access to it
*
* @var datetime
*/
public $cancel_date;
/**
* Date this recurring contribution finished successfully
*
* @var datetime
*/
public $end_date;
/**
* Possibly needed to store a unique identifier for this recurring payment order - if this is available from the processor??
*
* @var string
*/
public $processor_id;
/**
* Optionally used to store a link to a payment token used for this recurring contribution.
*
* @var int unsigned
*/
public $payment_token_id;
/**
* unique transaction id. may be processor id, bank id + trans id, or account number + check number... depending on payment_method
*
* @var string
*/
public $trxn_id;
/**
* unique invoice id, system generated or passed in
*
* @var string
*/
public $invoice_id;
/**
*
* @var int unsigned
*/
public $contribution_status_id;
/**
*
* @var boolean
*/
public $is_test;
/**
* Day in the period when the payment should be charged e.g. 1st of month, 15th etc.
*
* @var int unsigned
*/
public $cycle_day;
/**
* Next scheduled date
*
* @var datetime
*/
public $next_sched_contribution_date;
/**
* Number of failed charge attempts since last success. Business rule could be set to deactivate on more than x failures.
*
* @var int unsigned
*/
public $failure_count;
/**
* Date to retry failed attempt
*
* @var datetime
*/
public $failure_retry_date;
/**
* Some systems allow contributor to set a number of installments - but then auto-renew the subscription or commitment if they do not cancel.
*
* @var boolean
*/
public $auto_renew;
/**
* Foreign key to civicrm_payment_processor.id
*
* @var int unsigned
*/
public $payment_processor_id;
/**
* FK to Financial Type
*
* @var int unsigned
*/
public $financial_type_id;
/**
* FK to Payment Instrument
*
* @var int unsigned
*/
public $payment_instrument_id;
/**
* The campaign for which this contribution has been triggered.
*
* @var int unsigned
*/
public $campaign_id;
/**
* if true, receipt is automatically emailed to contact on each successful payment
*
* @var boolean
*/
public $is_email_receipt;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_contribution_recur';
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() , 'payment_token_id', 'civicrm_payment_token', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'payment_processor_id', 'civicrm_payment_processor', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'financial_type_id', 'civicrm_financial_type', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'campaign_id', 'civicrm_campaign', '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('Recurring Contribution ID') ,
'description' => 'Contribution Recur ID',
'required' => true,
'table_name' => 'civicrm_contribution_recur',
'entity' => 'ContributionRecur',
'bao' => 'CRM_Contribute_BAO_ContributionRecur',
'localizable' => 0,
) ,
'contact_id' => array(
'name' => 'contact_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Contact ID') ,
'description' => 'Foreign key to civicrm_contact.id .',
'required' => true,
'table_name' => 'civicrm_contribution_recur',
'entity' => 'ContributionRecur',
'bao' => 'CRM_Contribute_BAO_ContributionRecur',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
) ,
'amount' => array(
'name' => 'amount',
'type' => CRM_Utils_Type::T_MONEY,
'title' => ts('Amount') ,
'description' => 'Amount to be contributed or charged each recurrence.',
'required' => true,
'precision' => array(
20,
2
) ,
'table_name' => 'civicrm_contribution_recur',
'entity' => 'ContributionRecur',
'bao' => 'CRM_Contribute_BAO_ContributionRecur',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'currency' => array(
'name' => 'currency',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Currency') ,
'description' => '3 character string, value from config setting or input via user.',
'maxlength' => 3,
'size' => CRM_Utils_Type::FOUR,
'default' => 'NULL',
'table_name' => 'civicrm_contribution_recur',
'entity' => 'ContributionRecur',
'bao' => 'CRM_Contribute_BAO_ContributionRecur',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
)
) ,
'frequency_unit' => array(
'name' => 'frequency_unit',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Frequency Unit') ,
'description' => 'Time units for recurrence of payment.',
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
'default' => 'month',
'table_name' => 'civicrm_contribution_recur',
'entity' => 'ContributionRecur',
'bao' => 'CRM_Contribute_BAO_ContributionRecur',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'optionGroupName' => 'recur_frequency_units',
'keyColumn' => 'name',
'optionEditPath' => 'civicrm/admin/options/recur_frequency_units',
)
) ,
'frequency_interval' => array(
'name' => 'frequency_interval',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Interval (number of units)') ,
'description' => 'Number of time units for recurrence of payment.',
'required' => true,
'table_name' => 'civicrm_contribution_recur',
'entity' => 'ContributionRecur',
'bao' => 'CRM_Contribute_BAO_ContributionRecur',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'installments' => array(
'name' => 'installments',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Number of Installments') ,
'description' => 'Total number of payments to be made. Set this to 0 if this is an open-ended commitment i.e. no set end date.',
'table_name' => 'civicrm_contribution_recur',
'entity' => 'ContributionRecur',
'bao' => 'CRM_Contribute_BAO_ContributionRecur',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'start_date' => array(
'name' => 'start_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Recurring Contribution Started Date') ,
'description' => 'The date the first scheduled recurring contribution occurs.',
'required' => true,
'table_name' => 'civicrm_contribution_recur',
'entity' => 'ContributionRecur',
'bao' => 'CRM_Contribute_BAO_ContributionRecur',
'localizable' => 0,
'html' => array(
'type' => 'Select Date',
) ,
) ,
'create_date' => array(
'name' => 'create_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Recurring Contribution Created Date') ,
'description' => 'When this recurring contribution record was created.',
'required' => true,
'table_name' => 'civicrm_contribution_recur',
'entity' => 'ContributionRecur',
'bao' => 'CRM_Contribute_BAO_ContributionRecur',
'localizable' => 0,
'html' => array(
'type' => 'Select Date',
) ,
) ,
'modified_date' => array(
'name' => 'modified_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Recurring Contribution Modified Date') ,
'description' => 'Last updated date for this record. mostly the last time a payment was received',
'table_name' => 'civicrm_contribution_recur',
'entity' => 'ContributionRecur',
'bao' => 'CRM_Contribute_BAO_ContributionRecur',
'localizable' => 0,
'html' => array(
'type' => 'Select Date',
) ,
) ,
'cancel_date' => array(
'name' => 'cancel_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Recurring Contribution Cancel Date') ,
'description' => 'Date this recurring contribution was cancelled by contributor- if we can get access to it',
'table_name' => 'civicrm_contribution_recur',
'entity' => 'ContributionRecur',
'bao' => 'CRM_Contribute_BAO_ContributionRecur',
'localizable' => 0,
'html' => array(
'type' => 'Select Date',
) ,
) ,
'end_date' => array(
'name' => 'end_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Recurring Contribution End Date') ,
'description' => 'Date this recurring contribution finished successfully',
'table_name' => 'civicrm_contribution_recur',
'entity' => 'ContributionRecur',
'bao' => 'CRM_Contribute_BAO_ContributionRecur',
'localizable' => 0,
'html' => array(
'type' => 'Select Date',
) ,
) ,
'processor_id' => array(
'name' => 'processor_id',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Processor ID') ,
'description' => 'Possibly needed to store a unique identifier for this recurring payment order - if this is available from the processor??',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_contribution_recur',
'entity' => 'ContributionRecur',
'bao' => 'CRM_Contribute_BAO_ContributionRecur',
'localizable' => 0,
) ,
'payment_token_id' => array(
'name' => 'payment_token_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Payment Token ID') ,
'description' => 'Optionally used to store a link to a payment token used for this recurring contribution.',
'table_name' => 'civicrm_contribution_recur',
'entity' => 'ContributionRecur',
'bao' => 'CRM_Contribute_BAO_ContributionRecur',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_PaymentToken',
) ,
'trxn_id' => array(
'name' => 'trxn_id',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Transaction ID') ,
'description' => 'unique transaction id. may be processor id, bank id + trans id, or account number + check number... depending on payment_method',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_contribution_recur',
'entity' => 'ContributionRecur',
'bao' => 'CRM_Contribute_BAO_ContributionRecur',
'localizable' => 0,
) ,
'invoice_id' => array(
'name' => 'invoice_id',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Invoice ID') ,
'description' => 'unique invoice id, system generated or passed in',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_contribution_recur',
'entity' => 'ContributionRecur',
'bao' => 'CRM_Contribute_BAO_ContributionRecur',
'localizable' => 0,
) ,
'contribution_status_id' => array(
'name' => 'contribution_status_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Recurring Contribution Status') ,
'import' => true,
'where' => 'civicrm_contribution_recur.contribution_status_id',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'default' => '1',
'table_name' => 'civicrm_contribution_recur',
'entity' => 'ContributionRecur',
'bao' => 'CRM_Contribute_BAO_ContributionRecur',
'localizable' => 0,
'pseudoconstant' => array(
'optionGroupName' => 'contribution_status',
'optionEditPath' => 'civicrm/admin/options/contribution_status',
)
) ,
'is_test' => array(
'name' => 'is_test',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Test') ,
'import' => true,
'where' => 'civicrm_contribution_recur.is_test',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_contribution_recur',
'entity' => 'ContributionRecur',
'bao' => 'CRM_Contribute_BAO_ContributionRecur',
'localizable' => 0,
'html' => array(
'type' => 'CheckBox',
) ,
) ,
'cycle_day' => array(
'name' => 'cycle_day',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Number of Cycle Day') ,
'description' => 'Day in the period when the payment should be charged e.g. 1st of month, 15th etc.',
'required' => true,
'default' => '1',
'table_name' => 'civicrm_contribution_recur',
'entity' => 'ContributionRecur',
'bao' => 'CRM_Contribute_BAO_ContributionRecur',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'next_sched_contribution_date' => array(
'name' => 'next_sched_contribution_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Next Scheduled Contribution Date') ,
'description' => 'Next scheduled date',
'table_name' => 'civicrm_contribution_recur',
'entity' => 'ContributionRecur',
'bao' => 'CRM_Contribute_BAO_ContributionRecur',
'localizable' => 0,
'html' => array(
'type' => 'Select Date',
) ,
) ,
'failure_count' => array(
'name' => 'failure_count',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Number of Failures') ,
'description' => 'Number of failed charge attempts since last success. Business rule could be set to deactivate on more than x failures.',
'table_name' => 'civicrm_contribution_recur',
'entity' => 'ContributionRecur',
'bao' => 'CRM_Contribute_BAO_ContributionRecur',
'localizable' => 0,
'html' => array(
'type' => 'Text',
) ,
) ,
'failure_retry_date' => array(
'name' => 'failure_retry_date',
'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
'title' => ts('Retry Failed Attempt Date') ,
'description' => 'Date to retry failed attempt',
'table_name' => 'civicrm_contribution_recur',
'entity' => 'ContributionRecur',
'bao' => 'CRM_Contribute_BAO_ContributionRecur',
'localizable' => 0,
'html' => array(
'type' => 'Select Date',
) ,
) ,
'auto_renew' => array(
'name' => 'auto_renew',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Auto Renew') ,
'description' => 'Some systems allow contributor to set a number of installments - but then auto-renew the subscription or commitment if they do not cancel.',
'required' => true,
'table_name' => 'civicrm_contribution_recur',
'entity' => 'ContributionRecur',
'bao' => 'CRM_Contribute_BAO_ContributionRecur',
'localizable' => 0,
'html' => array(
'type' => 'CheckBox',
) ,
) ,
'payment_processor_id' => array(
'name' => 'payment_processor_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Payment Processor') ,
'description' => 'Foreign key to civicrm_payment_processor.id',
'table_name' => 'civicrm_contribution_recur',
'entity' => 'ContributionRecur',
'bao' => 'CRM_Contribute_BAO_ContributionRecur',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_PaymentProcessor',
) ,
'financial_type_id' => array(
'name' => 'financial_type_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Financial Type') ,
'description' => 'FK to Financial Type',
'export' => false,
'where' => 'civicrm_contribution_recur.financial_type_id',
'headerPattern' => '',
'dataPattern' => '',
'table_name' => 'civicrm_contribution_recur',
'entity' => 'ContributionRecur',
'bao' => 'CRM_Contribute_BAO_ContributionRecur',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialType',
'pseudoconstant' => array(
'table' => 'civicrm_financial_type',
'keyColumn' => 'id',
'labelColumn' => 'name',
)
) ,
'payment_instrument_id' => array(
'name' => 'payment_instrument_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Payment Method') ,
'description' => 'FK to Payment Instrument',
'table_name' => 'civicrm_contribution_recur',
'entity' => 'ContributionRecur',
'bao' => 'CRM_Contribute_BAO_ContributionRecur',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'optionGroupName' => 'payment_instrument',
'optionEditPath' => 'civicrm/admin/options/payment_instrument',
)
) ,
'contribution_campaign_id' => array(
'name' => 'campaign_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Campaign') ,
'description' => 'The campaign for which this contribution has been triggered.',
'import' => true,
'where' => 'civicrm_contribution_recur.campaign_id',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_contribution_recur',
'entity' => 'ContributionRecur',
'bao' => 'CRM_Contribute_BAO_ContributionRecur',
'localizable' => 0,
'FKClassName' => 'CRM_Campaign_DAO_Campaign',
'pseudoconstant' => array(
'table' => 'civicrm_campaign',
'keyColumn' => 'id',
'labelColumn' => 'title',
)
) ,
'is_email_receipt' => array(
'name' => 'is_email_receipt',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Send email Receipt?') ,
'description' => 'if true, receipt is automatically emailed to contact on each successful payment',
'default' => '1',
'table_name' => 'civicrm_contribution_recur',
'entity' => 'ContributionRecur',
'bao' => 'CRM_Contribute_BAO_ContributionRecur',
'localizable' => 0,
'html' => array(
'type' => 'CheckBox',
) ,
) ,
);
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__, 'contribution_recur', $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__, 'contribution_recur', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array(
'UI_contrib_trxn_id' => array(
'name' => 'UI_contrib_trxn_id',
'field' => array(
0 => 'trxn_id',
) ,
'localizable' => false,
'unique' => true,
'sig' => 'civicrm_contribution_recur::1::trxn_id',
) ,
'UI_contrib_invoice_id' => array(
'name' => 'UI_contrib_invoice_id',
'field' => array(
0 => 'invoice_id',
) ,
'localizable' => false,
'unique' => true,
'sig' => 'civicrm_contribution_recur::1::invoice_id',
) ,
'index_contribution_status' => array(
'name' => 'index_contribution_status',
'field' => array(
0 => 'contribution_status_id',
) ,
'localizable' => false,
'sig' => 'civicrm_contribution_recur::0::contribution_status_id',
) ,
'UI_contribution_recur_payment_instrument_id' => array(
'name' => 'UI_contribution_recur_payment_instrument_id',
'field' => array(
0 => 'payment_instrument_id',
) ,
'localizable' => false,
'sig' => 'civicrm_contribution_recur::0::payment_instrument_id',
) ,
);
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,364 @@
<?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/Contribute/ContributionSoft.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:eb1e493dc7ff4da34167ad0828d61fd4)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Contribute_DAO_ContributionSoft constructor.
*/
class CRM_Contribute_DAO_ContributionSoft extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_contribution_soft';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = true;
/**
* Soft Contribution ID
*
* @var int unsigned
*/
public $id;
/**
* FK to contribution table.
*
* @var int unsigned
*/
public $contribution_id;
/**
* FK to Contact ID
*
* @var int unsigned
*/
public $contact_id;
/**
* Amount of this soft contribution.
*
* @var float
*/
public $amount;
/**
* 3 character string, value from config setting or input via user.
*
* @var string
*/
public $currency;
/**
* FK to civicrm_pcp.id
*
* @var int unsigned
*/
public $pcp_id;
/**
*
* @var boolean
*/
public $pcp_display_in_roll;
/**
*
* @var string
*/
public $pcp_roll_nickname;
/**
*
* @var string
*/
public $pcp_personal_note;
/**
* Soft Credit Type ID.Implicit FK to civicrm_option_value where option_group = soft_credit_type.
*
* @var int unsigned
*/
public $soft_credit_type_id;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_contribution_soft';
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() , 'contribution_id', 'civicrm_contribution', 'id');
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() , 'pcp_id', 'civicrm_pcp', '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(
'contribution_soft_id' => array(
'name' => 'id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Soft Contribution ID') ,
'description' => 'Soft Contribution ID',
'required' => true,
'import' => true,
'where' => 'civicrm_contribution_soft.id',
'headerPattern' => '',
'dataPattern' => '',
'export' => true,
'table_name' => 'civicrm_contribution_soft',
'entity' => 'ContributionSoft',
'bao' => 'CRM_Contribute_BAO_ContributionSoft',
'localizable' => 0,
) ,
'contribution_id' => array(
'name' => 'contribution_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Soft Contribution - Contribution') ,
'description' => 'FK to contribution table.',
'required' => true,
'table_name' => 'civicrm_contribution_soft',
'entity' => 'ContributionSoft',
'bao' => 'CRM_Contribute_BAO_ContributionSoft',
'localizable' => 0,
'FKClassName' => 'CRM_Contribute_DAO_Contribution',
) ,
'contribution_soft_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_contribution_soft.contact_id',
'headerPattern' => '/contact(.?id)?/i',
'dataPattern' => '/^\d+$/',
'export' => true,
'table_name' => 'civicrm_contribution_soft',
'entity' => 'ContributionSoft',
'bao' => 'CRM_Contribute_BAO_ContributionSoft',
'localizable' => 0,
'FKClassName' => 'CRM_Contact_DAO_Contact',
) ,
'amount' => array(
'name' => 'amount',
'type' => CRM_Utils_Type::T_MONEY,
'title' => ts('Soft Contribution Amount') ,
'description' => 'Amount of this soft contribution.',
'required' => true,
'precision' => array(
20,
2
) ,
'import' => true,
'where' => 'civicrm_contribution_soft.amount',
'headerPattern' => '/total(.?am(ou)?nt)?/i',
'dataPattern' => '/^\d+(\.\d{2})?$/',
'export' => true,
'table_name' => 'civicrm_contribution_soft',
'entity' => 'ContributionSoft',
'bao' => 'CRM_Contribute_BAO_ContributionSoft',
'localizable' => 0,
) ,
'currency' => array(
'name' => 'currency',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Soft Contribution Currency') ,
'description' => '3 character string, value from config setting or input via user.',
'maxlength' => 3,
'size' => CRM_Utils_Type::FOUR,
'default' => 'NULL',
'table_name' => 'civicrm_contribution_soft',
'entity' => 'ContributionSoft',
'bao' => 'CRM_Contribute_BAO_ContributionSoft',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
)
) ,
'pcp_id' => array(
'name' => 'pcp_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Soft Contribution PCP') ,
'description' => 'FK to civicrm_pcp.id',
'default' => 'NULL',
'table_name' => 'civicrm_contribution_soft',
'entity' => 'ContributionSoft',
'bao' => 'CRM_Contribute_BAO_ContributionSoft',
'localizable' => 0,
'FKClassName' => 'CRM_PCP_DAO_PCP',
'pseudoconstant' => array(
'table' => 'civicrm_pcp',
'keyColumn' => 'id',
'labelColumn' => 'title',
)
) ,
'pcp_display_in_roll' => array(
'name' => 'pcp_display_in_roll',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Soft Contribution Display on PCP') ,
'table_name' => 'civicrm_contribution_soft',
'entity' => 'ContributionSoft',
'bao' => 'CRM_Contribute_BAO_ContributionSoft',
'localizable' => 0,
) ,
'pcp_roll_nickname' => array(
'name' => 'pcp_roll_nickname',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Soft Contribution PCP Nickname') ,
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'default' => 'NULL',
'table_name' => 'civicrm_contribution_soft',
'entity' => 'ContributionSoft',
'bao' => 'CRM_Contribute_BAO_ContributionSoft',
'localizable' => 0,
) ,
'pcp_personal_note' => array(
'name' => 'pcp_personal_note',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Soft Contribution PCP Note') ,
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'default' => 'NULL',
'table_name' => 'civicrm_contribution_soft',
'entity' => 'ContributionSoft',
'bao' => 'CRM_Contribute_BAO_ContributionSoft',
'localizable' => 0,
) ,
'soft_credit_type_id' => array(
'name' => 'soft_credit_type_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Soft Credit Type') ,
'description' => 'Soft Credit Type ID.Implicit FK to civicrm_option_value where option_group = soft_credit_type.',
'default' => 'NULL',
'table_name' => 'civicrm_contribution_soft',
'entity' => 'ContributionSoft',
'bao' => 'CRM_Contribute_BAO_ContributionSoft',
'localizable' => 0,
'pseudoconstant' => array(
'optionGroupName' => 'soft_credit_type',
'optionEditPath' => 'civicrm/admin/options/soft_credit_type',
)
) ,
);
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__, 'contribution_soft', $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__, 'contribution_soft', $prefix, array());
return $r;
}
/**
* Returns the list of indices
*/
public static function indices($localize = TRUE) {
$indices = array(
'index_id' => array(
'name' => 'index_id',
'field' => array(
0 => 'pcp_id',
) ,
'localizable' => false,
'sig' => 'civicrm_contribution_soft::0::pcp_id',
) ,
);
return ($localize && !empty($indices)) ? CRM_Core_DAO_AllCoreTables::multilingualize(__CLASS__, $indices) : $indices;
}
}

View file

@ -0,0 +1,330 @@
<?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/Contribute/Premium.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:86a5118380bd35cee851da735f699ac2)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Contribute_DAO_Premium constructor.
*/
class CRM_Contribute_DAO_Premium extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_premiums';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = true;
/**
*
* @var int unsigned
*/
public $id;
/**
* Joins these premium settings to another object. Always civicrm_contribution_page for now.
*
* @var string
*/
public $entity_table;
/**
*
* @var int unsigned
*/
public $entity_id;
/**
* Is the Premiums feature enabled for this page?
*
* @var boolean
*/
public $premiums_active;
/**
* Title for Premiums section.
*
* @var string
*/
public $premiums_intro_title;
/**
* Displayed in <div> at top of Premiums section of page. Text and HTML allowed.
*
* @var text
*/
public $premiums_intro_text;
/**
* This email address is included in receipts if it is populated and a premium has been selected.
*
* @var string
*/
public $premiums_contact_email;
/**
* This phone number is included in receipts if it is populated and a premium has been selected.
*
* @var string
*/
public $premiums_contact_phone;
/**
* Boolean. Should we automatically display minimum contribution amount text after the premium descriptions.
*
* @var boolean
*/
public $premiums_display_min_contribution;
/**
* Label displayed for No Thank-you option in premiums block (e.g. No thank you)
*
* @var string
*/
public $premiums_nothankyou_label;
/**
*
* @var int unsigned
*/
public $premiums_nothankyou_position;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_premiums';
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_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table');
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('Premium ID') ,
'required' => true,
'table_name' => 'civicrm_premiums',
'entity' => 'Premium',
'bao' => 'CRM_Contribute_BAO_Premium',
'localizable' => 0,
) ,
'entity_table' => array(
'name' => 'entity_table',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Premium Entity') ,
'description' => 'Joins these premium settings to another object. Always civicrm_contribution_page for now.',
'required' => true,
'maxlength' => 64,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_premiums',
'entity' => 'Premium',
'bao' => 'CRM_Contribute_BAO_Premium',
'localizable' => 0,
) ,
'entity_id' => array(
'name' => 'entity_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Premium entity ID') ,
'required' => true,
'table_name' => 'civicrm_premiums',
'entity' => 'Premium',
'bao' => 'CRM_Contribute_BAO_Premium',
'localizable' => 0,
) ,
'premiums_active' => array(
'name' => 'premiums_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Is Premium Active?') ,
'description' => 'Is the Premiums feature enabled for this page?',
'required' => true,
'table_name' => 'civicrm_premiums',
'entity' => 'Premium',
'bao' => 'CRM_Contribute_BAO_Premium',
'localizable' => 0,
) ,
'premiums_intro_title' => array(
'name' => 'premiums_intro_title',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Title for Premiums section') ,
'description' => 'Title for Premiums section.',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_premiums',
'entity' => 'Premium',
'bao' => 'CRM_Contribute_BAO_Premium',
'localizable' => 1,
) ,
'premiums_intro_text' => array(
'name' => 'premiums_intro_text',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Premium Introductory Text') ,
'description' => 'Displayed in <div> at top of Premiums section of page. Text and HTML allowed.',
'table_name' => 'civicrm_premiums',
'entity' => 'Premium',
'bao' => 'CRM_Contribute_BAO_Premium',
'localizable' => 1,
) ,
'premiums_contact_email' => array(
'name' => 'premiums_contact_email',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Premium Contact Email') ,
'description' => 'This email address is included in receipts if it is populated and a premium has been selected.',
'maxlength' => 100,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_premiums',
'entity' => 'Premium',
'bao' => 'CRM_Contribute_BAO_Premium',
'localizable' => 0,
) ,
'premiums_contact_phone' => array(
'name' => 'premiums_contact_phone',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Premiums Contact Phone') ,
'description' => 'This phone number is included in receipts if it is populated and a premium has been selected.',
'maxlength' => 50,
'size' => CRM_Utils_Type::BIG,
'table_name' => 'civicrm_premiums',
'entity' => 'Premium',
'bao' => 'CRM_Contribute_BAO_Premium',
'localizable' => 0,
) ,
'premiums_display_min_contribution' => array(
'name' => 'premiums_display_min_contribution',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Display Minimum Contribution?') ,
'description' => 'Boolean. Should we automatically display minimum contribution amount text after the premium descriptions.',
'required' => true,
'table_name' => 'civicrm_premiums',
'entity' => 'Premium',
'bao' => 'CRM_Contribute_BAO_Premium',
'localizable' => 0,
) ,
'premiums_nothankyou_label' => array(
'name' => 'premiums_nothankyou_label',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('No Thank-you Text') ,
'description' => 'Label displayed for No Thank-you option in premiums block (e.g. No thank you)',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_premiums',
'entity' => 'Premium',
'bao' => 'CRM_Contribute_BAO_Premium',
'localizable' => 1,
) ,
'premiums_nothankyou_position' => array(
'name' => 'premiums_nothankyou_position',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('No Thank-you Position') ,
'default' => '1',
'table_name' => 'civicrm_premiums',
'entity' => 'Premium',
'bao' => 'CRM_Contribute_BAO_Premium',
'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 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__, 'premiums', $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__, 'premiums', $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,237 @@
<?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/Contribute/PremiumsProduct.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:6c90561115f3fbe406af545ef055f79c)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Contribute_DAO_PremiumsProduct constructor.
*/
class CRM_Contribute_DAO_PremiumsProduct extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_premiums_product';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = true;
/**
* Contribution ID
*
* @var int unsigned
*/
public $id;
/**
* Foreign key to premiums settings record.
*
* @var int unsigned
*/
public $premiums_id;
/**
* Foreign key to each product object.
*
* @var int unsigned
*/
public $product_id;
/**
*
* @var int unsigned
*/
public $weight;
/**
* FK to Financial Type.
*
* @var int unsigned
*/
public $financial_type_id;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_premiums_product';
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() , 'premiums_id', 'civicrm_premiums', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'product_id', 'civicrm_product', 'id');
Civi::$statics[__CLASS__]['links'][] = new CRM_Core_Reference_Basic(self::getTableName() , 'financial_type_id', 'civicrm_financial_type', '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('Premium Product ID') ,
'description' => 'Contribution ID',
'required' => true,
'table_name' => 'civicrm_premiums_product',
'entity' => 'PremiumsProduct',
'bao' => 'CRM_Contribute_DAO_PremiumsProduct',
'localizable' => 0,
) ,
'premiums_id' => array(
'name' => 'premiums_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Premium') ,
'description' => 'Foreign key to premiums settings record.',
'required' => true,
'table_name' => 'civicrm_premiums_product',
'entity' => 'PremiumsProduct',
'bao' => 'CRM_Contribute_DAO_PremiumsProduct',
'localizable' => 0,
'FKClassName' => 'CRM_Contribute_DAO_Premium',
) ,
'product_id' => array(
'name' => 'product_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Product') ,
'description' => 'Foreign key to each product object.',
'required' => true,
'table_name' => 'civicrm_premiums_product',
'entity' => 'PremiumsProduct',
'bao' => 'CRM_Contribute_DAO_PremiumsProduct',
'localizable' => 0,
'FKClassName' => 'CRM_Contribute_DAO_Product',
) ,
'weight' => array(
'name' => 'weight',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Order') ,
'required' => true,
'table_name' => 'civicrm_premiums_product',
'entity' => 'PremiumsProduct',
'bao' => 'CRM_Contribute_DAO_PremiumsProduct',
'localizable' => 0,
) ,
'financial_type_id' => array(
'name' => 'financial_type_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Financial Type') ,
'description' => 'FK to Financial Type.',
'default' => 'NULL',
'table_name' => 'civicrm_premiums_product',
'entity' => 'PremiumsProduct',
'bao' => 'CRM_Contribute_DAO_PremiumsProduct',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialType',
'pseudoconstant' => array(
'table' => 'civicrm_financial_type',
'keyColumn' => 'id',
'labelColumn' => 'name',
)
) ,
);
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__, 'premiums_product', $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__, 'premiums_product', $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,524 @@
<?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/Contribute/Product.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:81e315b903d403508f379dc9c0fcf532)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Contribute_DAO_Product constructor.
*/
class CRM_Contribute_DAO_Product extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_product';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = true;
/**
*
* @var int unsigned
*/
public $id;
/**
* Required product/premium name
*
* @var string
*/
public $name;
/**
* Optional description of the product/premium.
*
* @var text
*/
public $description;
/**
* Optional product sku or code.
*
* @var string
*/
public $sku;
/**
* Store comma-delimited list of color, size, etc. options for the product.
*
* @var text
*/
public $options;
/**
* Full or relative URL to uploaded image - fullsize.
*
* @var string
*/
public $image;
/**
* Full or relative URL to image thumbnail.
*
* @var string
*/
public $thumbnail;
/**
* Sell price or market value for premiums. For tax-deductible contributions, this will be stored as non_deductible_amount in the contribution record.
*
* @var float
*/
public $price;
/**
* 3 character string, value from config setting or input via user.
*
* @var string
*/
public $currency;
/**
* FK to Financial Type.
*
* @var int unsigned
*/
public $financial_type_id;
/**
* Minimum contribution required to be eligible to select this premium.
*
* @var float
*/
public $min_contribution;
/**
* Actual cost of this product. Useful to determine net return from sale or using this as an incentive.
*
* @var float
*/
public $cost;
/**
* Disabling premium removes it from the premiums_premium join table below.
*
* @var boolean
*/
public $is_active;
/**
* Rolling means we set start/end based on current day, fixed means we set start/end for current year or month
(e.g. 1 year + fixed -> we would set start/end for 1/1/06 thru 12/31/06 for any premium chosen in 2006)
*
* @var string
*/
public $period_type;
/**
* Month and day (MMDD) that fixed period type subscription or membership starts.
*
* @var int
*/
public $fixed_period_start_day;
/**
*
* @var string
*/
public $duration_unit;
/**
* Number of units for total duration of subscription, service, membership (e.g. 12 Months).
*
* @var int
*/
public $duration_interval;
/**
* Frequency unit and interval allow option to store actual delivery frequency for a subscription or service.
*
* @var string
*/
public $frequency_unit;
/**
* Number of units for delivery frequency of subscription, service, membership (e.g. every 3 Months).
*
* @var int
*/
public $frequency_interval;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_product';
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() , 'financial_type_id', 'civicrm_financial_type', '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('Product ID') ,
'required' => true,
'table_name' => 'civicrm_product',
'entity' => 'Product',
'bao' => 'CRM_Contribute_DAO_Product',
'localizable' => 0,
) ,
'product_name' => array(
'name' => 'name',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Product Name') ,
'description' => 'Required product/premium name',
'required' => true,
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'export' => true,
'where' => 'civicrm_product.name',
'headerPattern' => '',
'dataPattern' => '',
'table_name' => 'civicrm_product',
'entity' => 'Product',
'bao' => 'CRM_Contribute_DAO_Product',
'localizable' => 1,
) ,
'description' => array(
'name' => 'description',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Description') ,
'description' => 'Optional description of the product/premium.',
'table_name' => 'civicrm_product',
'entity' => 'Product',
'bao' => 'CRM_Contribute_DAO_Product',
'localizable' => 1,
) ,
'sku' => array(
'name' => 'sku',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('SKU') ,
'description' => 'Optional product sku or code.',
'maxlength' => 50,
'size' => CRM_Utils_Type::BIG,
'export' => true,
'where' => 'civicrm_product.sku',
'headerPattern' => '',
'dataPattern' => '',
'table_name' => 'civicrm_product',
'entity' => 'Product',
'bao' => 'CRM_Contribute_DAO_Product',
'localizable' => 0,
) ,
'options' => array(
'name' => 'options',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Options') ,
'description' => 'Store comma-delimited list of color, size, etc. options for the product.',
'table_name' => 'civicrm_product',
'entity' => 'Product',
'bao' => 'CRM_Contribute_DAO_Product',
'localizable' => 1,
) ,
'image' => array(
'name' => 'image',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Image') ,
'description' => 'Full or relative URL to uploaded image - fullsize.',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_product',
'entity' => 'Product',
'bao' => 'CRM_Contribute_DAO_Product',
'localizable' => 0,
) ,
'thumbnail' => array(
'name' => 'thumbnail',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Thumbnail') ,
'description' => 'Full or relative URL to image thumbnail.',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_product',
'entity' => 'Product',
'bao' => 'CRM_Contribute_DAO_Product',
'localizable' => 0,
) ,
'price' => array(
'name' => 'price',
'type' => CRM_Utils_Type::T_MONEY,
'title' => ts('Price') ,
'description' => 'Sell price or market value for premiums. For tax-deductible contributions, this will be stored as non_deductible_amount in the contribution record.',
'precision' => array(
20,
2
) ,
'table_name' => 'civicrm_product',
'entity' => 'Product',
'bao' => 'CRM_Contribute_DAO_Product',
'localizable' => 0,
) ,
'currency' => array(
'name' => 'currency',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Currency') ,
'description' => '3 character string, value from config setting or input via user.',
'maxlength' => 3,
'size' => CRM_Utils_Type::FOUR,
'default' => 'NULL',
'table_name' => 'civicrm_product',
'entity' => 'Product',
'bao' => 'CRM_Contribute_DAO_Product',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'table' => 'civicrm_currency',
'keyColumn' => 'name',
'labelColumn' => 'full_name',
'nameColumn' => 'name',
)
) ,
'financial_type_id' => array(
'name' => 'financial_type_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Financial Type') ,
'description' => 'FK to Financial Type.',
'default' => 'NULL',
'table_name' => 'civicrm_product',
'entity' => 'Product',
'bao' => 'CRM_Contribute_DAO_Product',
'localizable' => 0,
'FKClassName' => 'CRM_Financial_DAO_FinancialType',
'pseudoconstant' => array(
'table' => 'civicrm_financial_type',
'keyColumn' => 'id',
'labelColumn' => 'name',
)
) ,
'min_contribution' => array(
'name' => 'min_contribution',
'type' => CRM_Utils_Type::T_MONEY,
'title' => ts('Minimum Contribution') ,
'description' => 'Minimum contribution required to be eligible to select this premium.',
'precision' => array(
20,
2
) ,
'table_name' => 'civicrm_product',
'entity' => 'Product',
'bao' => 'CRM_Contribute_DAO_Product',
'localizable' => 0,
) ,
'cost' => array(
'name' => 'cost',
'type' => CRM_Utils_Type::T_MONEY,
'title' => ts('Cost') ,
'description' => 'Actual cost of this product. Useful to determine net return from sale or using this as an incentive.',
'precision' => array(
20,
2
) ,
'table_name' => 'civicrm_product',
'entity' => 'Product',
'bao' => 'CRM_Contribute_DAO_Product',
'localizable' => 0,
) ,
'is_active' => array(
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Is Active') ,
'description' => 'Disabling premium removes it from the premiums_premium join table below.',
'required' => true,
'table_name' => 'civicrm_product',
'entity' => 'Product',
'bao' => 'CRM_Contribute_DAO_Product',
'localizable' => 0,
) ,
'period_type' => array(
'name' => 'period_type',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Period Type') ,
'description' => 'Rolling means we set start/end based on current day, fixed means we set start/end for current year or month
(e.g. 1 year + fixed -> we would set start/end for 1/1/06 thru 12/31/06 for any premium chosen in 2006) ',
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
'default' => 'rolling',
'table_name' => 'civicrm_product',
'entity' => 'Product',
'bao' => 'CRM_Contribute_DAO_Product',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'callback' => 'CRM_Core_SelectValues::periodType',
)
) ,
'fixed_period_start_day' => array(
'name' => 'fixed_period_start_day',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Fixed Period Start Day') ,
'description' => 'Month and day (MMDD) that fixed period type subscription or membership starts.',
'default' => '0101',
'table_name' => 'civicrm_product',
'entity' => 'Product',
'bao' => 'CRM_Contribute_DAO_Product',
'localizable' => 0,
) ,
'duration_unit' => array(
'name' => 'duration_unit',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Duration Unit') ,
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
'default' => 'year',
'table_name' => 'civicrm_product',
'entity' => 'Product',
'bao' => 'CRM_Contribute_DAO_Product',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'callback' => 'CRM_Core_SelectValues::getPremiumUnits',
)
) ,
'duration_interval' => array(
'name' => 'duration_interval',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Duration Interval') ,
'description' => 'Number of units for total duration of subscription, service, membership (e.g. 12 Months).',
'table_name' => 'civicrm_product',
'entity' => 'Product',
'bao' => 'CRM_Contribute_DAO_Product',
'localizable' => 0,
) ,
'frequency_unit' => array(
'name' => 'frequency_unit',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Frequency Unit') ,
'description' => 'Frequency unit and interval allow option to store actual delivery frequency for a subscription or service.',
'maxlength' => 8,
'size' => CRM_Utils_Type::EIGHT,
'default' => 'month',
'table_name' => 'civicrm_product',
'entity' => 'Product',
'bao' => 'CRM_Contribute_DAO_Product',
'localizable' => 0,
'html' => array(
'type' => 'Select',
) ,
'pseudoconstant' => array(
'callback' => 'CRM_Core_SelectValues::getPremiumUnits',
)
) ,
'frequency_interval' => array(
'name' => 'frequency_interval',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Frequency Interval') ,
'description' => 'Number of units for delivery frequency of subscription, service, membership (e.g. every 3 Months).',
'table_name' => 'civicrm_product',
'entity' => 'Product',
'bao' => 'CRM_Contribute_DAO_Product',
'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 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__, 'product', $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__, 'product', $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,426 @@
<?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/Contribute/Widget.xml
* DO NOT EDIT. Generated by CRM_Core_CodeGen
* (GenCodeChecksum:b47ae223e6fd74db68394139a309be31)
*/
require_once 'CRM/Core/DAO.php';
require_once 'CRM/Utils/Type.php';
/**
* CRM_Contribute_DAO_Widget constructor.
*/
class CRM_Contribute_DAO_Widget extends CRM_Core_DAO {
/**
* Static instance to hold the table name.
*
* @var string
*/
static $_tableName = 'civicrm_contribution_widget';
/**
* Should CiviCRM log any modifications to this table in the civicrm_log table.
*
* @var boolean
*/
static $_log = true;
/**
* Contribution Id
*
* @var int unsigned
*/
public $id;
/**
* The Contribution Page which triggered this contribution
*
* @var int unsigned
*/
public $contribution_page_id;
/**
* Is this property active?
*
* @var boolean
*/
public $is_active;
/**
* Widget title.
*
* @var string
*/
public $title;
/**
* URL to Widget logo
*
* @var string
*/
public $url_logo;
/**
* Button title.
*
* @var string
*/
public $button_title;
/**
* About description.
*
* @var text
*/
public $about;
/**
* URL to Homepage.
*
* @var string
*/
public $url_homepage;
/**
*
* @var string
*/
public $color_title;
/**
*
* @var string
*/
public $color_button;
/**
*
* @var string
*/
public $color_bar;
/**
*
* @var string
*/
public $color_main_text;
/**
*
* @var string
*/
public $color_main;
/**
*
* @var string
*/
public $color_main_bg;
/**
*
* @var string
*/
public $color_bg;
/**
*
* @var string
*/
public $color_about_link;
/**
*
* @var string
*/
public $color_homepage_link;
/**
* Class constructor.
*/
function __construct() {
$this->__table = 'civicrm_contribution_widget';
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() , 'contribution_page_id', 'civicrm_contribution_page', '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('Widget ID') ,
'description' => 'Contribution Id',
'required' => true,
'table_name' => 'civicrm_contribution_widget',
'entity' => 'Widget',
'bao' => 'CRM_Contribute_BAO_Widget',
'localizable' => 0,
) ,
'contribution_page_id' => array(
'name' => 'contribution_page_id',
'type' => CRM_Utils_Type::T_INT,
'title' => ts('Contribution Page') ,
'description' => 'The Contribution Page which triggered this contribution',
'table_name' => 'civicrm_contribution_widget',
'entity' => 'Widget',
'bao' => 'CRM_Contribute_BAO_Widget',
'localizable' => 0,
'FKClassName' => 'CRM_Contribute_DAO_ContributionPage',
) ,
'is_active' => array(
'name' => 'is_active',
'type' => CRM_Utils_Type::T_BOOLEAN,
'title' => ts('Enabled?') ,
'description' => 'Is this property active?',
'table_name' => 'civicrm_contribution_widget',
'entity' => 'Widget',
'bao' => 'CRM_Contribute_BAO_Widget',
'localizable' => 0,
) ,
'title' => array(
'name' => 'title',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Widget Title') ,
'description' => 'Widget title.',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_contribution_widget',
'entity' => 'Widget',
'bao' => 'CRM_Contribute_BAO_Widget',
'localizable' => 0,
) ,
'url_logo' => array(
'name' => 'url_logo',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Widget Image Url') ,
'description' => 'URL to Widget logo',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_contribution_widget',
'entity' => 'Widget',
'bao' => 'CRM_Contribute_BAO_Widget',
'localizable' => 0,
) ,
'button_title' => array(
'name' => 'button_title',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Button Title') ,
'description' => 'Button title.',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_contribution_widget',
'entity' => 'Widget',
'bao' => 'CRM_Contribute_BAO_Widget',
'localizable' => 0,
) ,
'about' => array(
'name' => 'about',
'type' => CRM_Utils_Type::T_TEXT,
'title' => ts('Description') ,
'description' => 'About description.',
'table_name' => 'civicrm_contribution_widget',
'entity' => 'Widget',
'bao' => 'CRM_Contribute_BAO_Widget',
'localizable' => 0,
) ,
'url_homepage' => array(
'name' => 'url_homepage',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Homepage Url') ,
'description' => 'URL to Homepage.',
'maxlength' => 255,
'size' => CRM_Utils_Type::HUGE,
'table_name' => 'civicrm_contribution_widget',
'entity' => 'Widget',
'bao' => 'CRM_Contribute_BAO_Widget',
'localizable' => 0,
) ,
'color_title' => array(
'name' => 'color_title',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Title Color') ,
'maxlength' => 10,
'size' => CRM_Utils_Type::TWELVE,
'table_name' => 'civicrm_contribution_widget',
'entity' => 'Widget',
'bao' => 'CRM_Contribute_BAO_Widget',
'localizable' => 0,
) ,
'color_button' => array(
'name' => 'color_button',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Button Colour') ,
'maxlength' => 10,
'size' => CRM_Utils_Type::TWELVE,
'table_name' => 'civicrm_contribution_widget',
'entity' => 'Widget',
'bao' => 'CRM_Contribute_BAO_Widget',
'localizable' => 0,
) ,
'color_bar' => array(
'name' => 'color_bar',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Bar Color') ,
'maxlength' => 10,
'size' => CRM_Utils_Type::TWELVE,
'table_name' => 'civicrm_contribution_widget',
'entity' => 'Widget',
'bao' => 'CRM_Contribute_BAO_Widget',
'localizable' => 0,
) ,
'color_main_text' => array(
'name' => 'color_main_text',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Main Text Color') ,
'maxlength' => 10,
'size' => CRM_Utils_Type::TWELVE,
'table_name' => 'civicrm_contribution_widget',
'entity' => 'Widget',
'bao' => 'CRM_Contribute_BAO_Widget',
'localizable' => 0,
) ,
'color_main' => array(
'name' => 'color_main',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Main Colour') ,
'maxlength' => 10,
'size' => CRM_Utils_Type::TWELVE,
'table_name' => 'civicrm_contribution_widget',
'entity' => 'Widget',
'bao' => 'CRM_Contribute_BAO_Widget',
'localizable' => 0,
) ,
'color_main_bg' => array(
'name' => 'color_main_bg',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Backgroup Color') ,
'maxlength' => 10,
'size' => CRM_Utils_Type::TWELVE,
'table_name' => 'civicrm_contribution_widget',
'entity' => 'Widget',
'bao' => 'CRM_Contribute_BAO_Widget',
'localizable' => 0,
) ,
'color_bg' => array(
'name' => 'color_bg',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Other Backgroun Colour') ,
'maxlength' => 10,
'size' => CRM_Utils_Type::TWELVE,
'table_name' => 'civicrm_contribution_widget',
'entity' => 'Widget',
'bao' => 'CRM_Contribute_BAO_Widget',
'localizable' => 0,
) ,
'color_about_link' => array(
'name' => 'color_about_link',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('About Link Colour') ,
'maxlength' => 10,
'size' => CRM_Utils_Type::TWELVE,
'table_name' => 'civicrm_contribution_widget',
'entity' => 'Widget',
'bao' => 'CRM_Contribute_BAO_Widget',
'localizable' => 0,
) ,
'color_homepage_link' => array(
'name' => 'color_homepage_link',
'type' => CRM_Utils_Type::T_STRING,
'title' => ts('Homepage Link Colour') ,
'maxlength' => 10,
'size' => CRM_Utils_Type::TWELVE,
'table_name' => 'civicrm_contribution_widget',
'entity' => 'Widget',
'bao' => 'CRM_Contribute_BAO_Widget',
'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__, 'contribution_widget', $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__, 'contribution_widget', $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,31 @@
<?php
/**
* Created by PhpStorm.
* User: eileen
* Date: 8/12/2014
* Time: 10:33 AM
*/
class CRM_Contribute_Exception_InactiveContributionPageException extends Exception {
private $id;
/**
* @param string $message
* @param int $id
*/
public function __construct($message, $id) {
parent::__construct(ts($message));
$this->id = $id;
CRM_Core_Error::debug_log_message('inactive contribution page access attempted - page number ' . $id);
}
/**
* Get Contribution page ID.
*
* @return int
*/
public function getID() {
return $this->id;
}
}

View file

@ -0,0 +1,78 @@
<?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 generic to Contribution admin.
*/
class CRM_Contribute_Form extends CRM_Admin_Form {
/**
* Set default values for the form.
*
* @return array
*/
public function setDefaultValues() {
$defaults = array();
if (isset($this->_id)) {
$params = array('id' => $this->_id);
if (!empty($this->_BAOName)) {
$baoName = $this->_BAOName;
$baoName::retrieve($params, $defaults);
}
}
if ($this->_action == CRM_Core_Action::DELETE && !empty($defaults['name'])) {
$this->assign('delName', $defaults['name']);
}
elseif ($this->_action == CRM_Core_Action::ADD) {
$condition = " AND is_default = 1";
$values = CRM_Core_OptionGroup::values('financial_account_type', FALSE, FALSE, FALSE, $condition);
$defaults['financial_account_type_id'] = array_keys($values);
$defaults['is_active'] = 1;
}
elseif ($this->_action & CRM_Core_Action::UPDATE) {
if (!empty($defaults['contact_id']) || !empty($defaults['created_id'])) {
$contactID = !empty($defaults['created_id']) ? $defaults['created_id'] : $defaults['contact_id'];
$this->assign('created_id', $contactID);
$this->assign('organisationId', $contactID);
}
if ($parentId = CRM_Utils_Array::value('parent_id', $defaults)) {
$this->assign('parentId', $parentId);
}
}
return $defaults;
}
}

View file

@ -0,0 +1,690 @@
<?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
*/
/**
* This class generates form components for processing a contribution
* CRM-16229 - During the event registration bulk action via search we
* need to inherit CRM_Contact_Form_Task so that we can inherit functions
* like getContactIds and make use of controller state. But this is not possible
* because CRM_Event_Form_Participant inherits this class.
* Ideal situation would be something like
* CRM_Event_Form_Participant extends CRM_Contact_Form_Task,
* CRM_Contribute_Form_AbstractEditPayment
* However this is not possible. Currently PHP does not support multiple
* inheritance. So work around solution is to extend this class with
* CRM_Contact_Form_Task which further extends CRM_Core_Form.
*
*/
class CRM_Contribute_Form_AbstractEditPayment extends CRM_Contact_Form_Task {
public $_mode;
public $_action;
public $_bltID;
public $_fields = array();
/**
* @var array current payment processor including a copy of the object in 'object' key
*/
public $_paymentProcessor;
/**
* Available recurring processors.
*
* @var array
*/
public $_recurPaymentProcessors = array();
/**
* Array of processor options in the format id => array($id => $label)
* WARNING it appears that the format used to differ to this and there are places in the code that
* expect the old format. $this->_paymentProcessors provides the additional data which this
* array seems to have provided in the past
* @var array
*/
public $_processors;
/**
* Available payment processors with full details including the key 'object' indexed by their id
* @var array
*/
protected $_paymentProcessors = array();
/**
* Instance of the payment processor object.
*
* @var CRM_Core_Payment
*/
protected $_paymentObject;
/**
* The id of the contribution that we are processing.
*
* @var int
*/
public $_id;
/**
* The id of the premium that we are proceessing.
*
* @var int
*/
public $_premiumID = NULL;
/**
* @var CRM_Contribute_DAO_ContributionProduct
*/
public $_productDAO = NULL;
/**
* The id of the note
*
* @var int
*/
public $_noteID;
/**
* The id of the contact associated with this contribution
*
* @var int
*/
public $_contactID;
/**
* The id of the pledge payment that we are processing
*
* @var int
*/
public $_ppID;
/**
* The id of the pledge that we are processing
*
* @var int
*/
public $_pledgeID;
/**
* Is this contribution associated with an online
* financial transaction
*
* @var boolean
*/
public $_online = FALSE;
/**
* Stores all product option
*
* @var array
*/
public $_options;
/**
* Stores the honor id
*
* @var int
*/
public $_honorID = NULL;
/**
* Store the financial Type ID
*
* @var array
*/
public $_contributionType;
/**
* The contribution values if an existing contribution
*/
public $_values;
/**
* The pledge values if this contribution is associated with pledge
*/
public $_pledgeValues;
public $_contributeMode = 'direct';
public $_context;
public $_compId;
/**
* Store the line items if price set used.
*/
public $_lineItems;
/**
* Is this a backoffice form
*
* @var bool
*/
public $isBackOffice = TRUE;
protected $_formType;
/**
* Payment instrument id for the transaction.
*
* @var int
*/
public $paymentInstrumentID;
/**
* Array of fields to display on billingBlock.tpl - this is not fully implemented but basically intent is the panes/fieldsets on this page should
* be all in this array in order like
* 'credit_card' => array('credit_card_number' ...
* 'billing_details' => array('first_name' ...
*
* such that both the fields and the order can be more easily altered by payment processors & other extensions
* @var array
*/
public $billingFieldSets = array();
/**
* Pre process function with common actions.
*/
public function preProcess() {
$this->_contactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
$this->assign('contactID', $this->_contactID);
CRM_Core_Resources::singleton()->addVars('coreForm', array('contact_id' => (int) $this->_contactID));
$this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'add');
$this->_mode = empty($this->_mode) ? CRM_Utils_Request::retrieve('mode', 'String', $this) : $this->_mode;
$this->assign('isBackOffice', $this->isBackOffice);
$this->assignPaymentRelatedVariables();
}
/**
* @param int $id
*/
public function showRecordLinkMesssage($id) {
$statusId = CRM_Core_DAO::getFieldValue('CRM_Contribute_BAO_Contribution', $id, 'contribution_status_id');
if (CRM_Contribute_PseudoConstant::contributionStatus($statusId, 'name') == 'Partially paid') {
if ($pid = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'participant_id', 'contribution_id')) {
$recordPaymentLink = CRM_Utils_System::url('civicrm/payment',
"reset=1&id={$pid}&cid={$this->_contactID}&action=add&component=event"
);
CRM_Core_Session::setStatus(ts('Please use the <a href="%1">Record Payment</a> form if you have received an additional payment for this Partially paid contribution record.', array(1 => $recordPaymentLink)), ts('Notice'), 'alert');
}
}
}
/**
* @param int $id
* @param $values
*/
public function buildValuesAndAssignOnline_Note_Type($id, &$values) {
$ids = array();
$params = array('id' => $id);
CRM_Contribute_BAO_Contribution::getValues($params, $values, $ids);
//Check if this is an online transaction (financial_trxn.payment_processor_id NOT NULL)
$this->_online = FALSE;
$fids = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($id);
if (!empty($fids['financialTrxnId'])) {
$this->_online = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $fids['financialTrxnId'], 'payment_processor_id');
}
// Also don't allow user to update some fields for recurring contributions.
if (!$this->_online) {
$this->_online = CRM_Utils_Array::value('contribution_recur_id', $values);
}
$this->assign('isOnline', $this->_online ? TRUE : FALSE);
//to get note id
$daoNote = new CRM_Core_BAO_Note();
$daoNote->entity_table = 'civicrm_contribution';
$daoNote->entity_id = $id;
if ($daoNote->find(TRUE)) {
$this->_noteID = $daoNote->id;
$values['note'] = $daoNote->note;
}
$this->_contributionType = $values['financial_type_id'];
}
/**
* @param string $type
* Eg 'Contribution'.
* @param string $subType
* @param int $entityId
*/
public function applyCustomData($type, $subType, $entityId) {
$this->set('type', $type);
$this->set('subType', $subType);
$this->set('entityId', $entityId);
CRM_Custom_Form_CustomData::preProcess($this, NULL, $subType, 1, $type, $entityId);
CRM_Custom_Form_CustomData::buildQuickForm($this);
CRM_Custom_Form_CustomData::setDefaultValues($this);
}
/**
* @param int $id
* @todo - this function is a long way, non standard of saying $dao = new CRM_Contribute_DAO_ContributionProduct(); $dao->id = $id; $dao->find();
*/
public function assignPremiumProduct($id) {
$sql = "
SELECT *
FROM civicrm_contribution_product
WHERE contribution_id = {$id}
";
$dao = CRM_Core_DAO::executeQuery($sql,
CRM_Core_DAO::$_nullArray
);
if ($dao->fetch()) {
$this->_premiumID = $dao->id;
$this->_productDAO = $dao;
}
$dao->free();
}
/**
* @return array
* Array of valid processors. The array resembles the DB table but also has 'object' as a key
* @throws Exception
*/
public function getValidProcessors() {
$capabilities = array('BackOffice');
if ($this->_mode) {
$capabilities[] = (ucfirst($this->_mode) . 'Mode');
}
$processors = CRM_Financial_BAO_PaymentProcessor::getPaymentProcessors($capabilities);
return $processors;
}
/**
* Assign $this->processors, $this->recurPaymentProcessors, and related Smarty variables
*/
public function assignProcessors() {
//ensure that processor has a valid config
//only valid processors get display to user
$this->assign('processorSupportsFutureStartDate', CRM_Financial_BAO_PaymentProcessor::hasPaymentProcessorSupporting(array('FutureRecurStartDate')));
$this->_paymentProcessors = $this->getValidProcessors();
if (!isset($this->_paymentProcessor['id'])) {
// if the payment processor isn't set yet (as indicated by the presence of an id,) we'll grab the first one which should be the default
$this->_paymentProcessor = reset($this->_paymentProcessors);
}
if (!$this->_mode) {
$this->_paymentProcessor = $this->_paymentProcessors[0];
}
elseif (empty($this->_paymentProcessors) || array_keys($this->_paymentProcessors) === array(0)) {
throw new CRM_Core_Exception(ts('You will need to configure the %1 settings for your Payment Processor before you can submit a credit card transactions.', array(1 => $this->_mode)));
}
$this->_processors = array();
foreach ($this->_paymentProcessors as $id => $processor) {
// @todo review this. The inclusion of this IF was to address test processors being incorrectly loaded.
// However the function $this->getValidProcessors() is expected to only return the processors relevant
// to the mode (using the actual id - ie. the id of the test processor for the test processor).
// for some reason there was a need to filter here per commit history - but this indicates a problem
// somewhere else.
if ($processor['is_test'] == ($this->_mode == 'test')) {
$this->_processors[$id] = ts($processor['name']);
if (!empty($processor['description'])) {
$this->_processors[$id] .= ' : ' . ts($processor['description']);
}
if ($processor['is_recur']) {
$this->_recurPaymentProcessors[$id] = $this->_processors[$id];
}
}
}
// CRM-21002: pass the default payment processor ID whose credit card type icons should be populated first
CRM_Financial_Form_Payment::addCreditCardJs($this->_paymentProcessor['id']);
$this->assign('recurringPaymentProcessorIds',
empty($this->_recurPaymentProcessors) ? '' : implode(',', array_keys($this->_recurPaymentProcessors))
);
// this required to show billing block
// @todo remove this assignment the billing block is now designed to be always included but will not show fieldsets unless those sets of fields are assigned
$this->assign_by_ref('paymentProcessor', $this->_paymentProcessor);
}
/**
* Get current currency from DB or use default currency.
*
* @param $submittedValues
*
* @return mixed
*/
public function getCurrency($submittedValues) {
$config = CRM_Core_Config::singleton();
$currentCurrency = CRM_Utils_Array::value('currency',
$this->_values,
$config->defaultCurrency
);
// use submitted currency if present else use current currency
$result = CRM_Utils_Array::value('currency',
$submittedValues,
$currentCurrency
);
return $result;
}
public function preProcessPledge() {
//get the payment values associated with given pledge payment id OR check for payments due.
$this->_pledgeValues = array();
if ($this->_ppID) {
$payParams = array('id' => $this->_ppID);
CRM_Pledge_BAO_PledgePayment::retrieve($payParams, $this->_pledgeValues['pledgePayment']);
$this->_pledgeID = CRM_Utils_Array::value('pledge_id', $this->_pledgeValues['pledgePayment']);
$paymentStatusID = CRM_Utils_Array::value('status_id', $this->_pledgeValues['pledgePayment']);
$this->_id = CRM_Utils_Array::value('contribution_id', $this->_pledgeValues['pledgePayment']);
//get all status
$allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
if (!($paymentStatusID == array_search('Pending', $allStatus) || $paymentStatusID == array_search('Overdue', $allStatus))) {
CRM_Core_Error::fatal(ts("Pledge payment status should be 'Pending' or 'Overdue'."));
}
//get the pledge values associated with given pledge payment.
$ids = array();
$pledgeParams = array('id' => $this->_pledgeID);
CRM_Pledge_BAO_Pledge::getValues($pledgeParams, $this->_pledgeValues, $ids);
$this->assign('ppID', $this->_ppID);
}
else {
// Not making a pledge payment, so if adding a new contribution we should check if pledge payment(s) are due for this contact so we can alert the user. CRM-5206
if (isset($this->_contactID)) {
$contactPledges = CRM_Pledge_BAO_Pledge::getContactPledges($this->_contactID);
if (!empty($contactPledges)) {
$payments = $paymentsDue = NULL;
$multipleDue = FALSE;
foreach ($contactPledges as $key => $pledgeId) {
$payments = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
if ($payments) {
if ($paymentsDue) {
$multipleDue = TRUE;
break;
}
else {
$paymentsDue = $payments;
}
}
}
if ($multipleDue) {
// Show link to pledge tab since more than one pledge has a payment due
$pledgeTab = CRM_Utils_System::url('civicrm/contact/view',
"reset=1&force=1&cid={$this->_contactID}&selectedChild=pledge"
);
CRM_Core_Session::setStatus(ts('This contact has pending or overdue pledge payments. <a href="%1">Click here to view their Pledges tab</a> and verify whether this contribution should be applied as a pledge payment.', array(1 => $pledgeTab)), ts('Notice'), 'alert');
}
elseif ($paymentsDue) {
// Show user link to oldest Pending or Overdue pledge payment
$ppAmountDue = CRM_Utils_Money::format($payments['amount'], $payments['currency']);
$ppSchedDate = CRM_Utils_Date::customFormat(CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $payments['id'], 'scheduled_date'));
if ($this->_mode) {
$ppUrl = CRM_Utils_System::url('civicrm/contact/view/contribution',
"reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge&mode=live"
);
}
else {
$ppUrl = CRM_Utils_System::url('civicrm/contact/view/contribution',
"reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge"
);
}
CRM_Core_Session::setStatus(ts('This contact has a pending or overdue pledge payment of %2 which is scheduled for %3. <a href="%1">Click here to enter a pledge payment</a>.', array(
1 => $ppUrl,
2 => $ppAmountDue,
3 => $ppSchedDate,
)), ts('Notice'), 'alert');
}
}
}
}
}
/**
* @param array $submittedValues
*
* @return mixed
*/
public function unsetCreditCardFields($submittedValues) {
//Offline Contribution.
$unsetParams = array(
'payment_processor_id',
"email-{$this->_bltID}",
'hidden_buildCreditCard',
'hidden_buildDirectDebit',
'billing_first_name',
'billing_middle_name',
'billing_last_name',
'street_address-5',
"city-{$this->_bltID}",
"state_province_id-{$this->_bltID}",
"postal_code-{$this->_bltID}",
"country_id-{$this->_bltID}",
'credit_card_number',
'cvv2',
'credit_card_exp_date',
'credit_card_type',
);
foreach ($unsetParams as $key) {
if (isset($submittedValues[$key])) {
unset($submittedValues[$key]);
}
}
return $submittedValues;
}
/**
* Common block for setting up the parts of a form that relate to credit / debit card
* @throws Exception
*/
protected function assignPaymentRelatedVariables() {
try {
if ($this->_contactID) {
list($this->userDisplayName, $this->userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
$this->assign('displayName', $this->userDisplayName);
}
$this->assignProcessors();
$this->assignBillingType();
CRM_Core_Payment_Form::setPaymentFieldsByProcessor($this, $this->_paymentProcessor, FALSE, TRUE, CRM_Utils_Request::retrieve('payment_instrument_id', 'Integer', $this));
}
catch (CRM_Core_Exception $e) {
CRM_Core_Error::statusBounce($e->getMessage());
}
}
/**
* Begin post processing.
*
* This function aims to start to bring together common postProcessing functions.
*
* Eventually these are also shared with the front end forms & may need to be moved to where they can also
* access this function.
*/
protected function beginPostProcess() {
if ($this->_mode) {
$this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment(
$this->_params['payment_processor_id'],
($this->_mode == 'test')
);
if (in_array('credit_card_exp_date', array_keys($this->_params))) {
$this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
$this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
}
$this->assign('credit_card_exp_date', CRM_Utils_Date::mysqlToIso(CRM_Utils_Date::format($this->_params['credit_card_exp_date'])));
$this->assign('credit_card_number',
CRM_Utils_System::mungeCreditCard($this->_params['credit_card_number'])
);
$this->assign('credit_card_type', CRM_Utils_Array::value('credit_card_type', $this->_params));
}
$this->_params['ip_address'] = CRM_Utils_System::ipAddress();
self::formatCreditCardDetails($this->_params);
}
/**
* Format credit card details like:
* 1. Retrieve last 4 digit from credit card number as pan_truncation
* 2. Retrieve credit card type id from name
*
* @param array $params
*
* @return void
*/
public static function formatCreditCardDetails(&$params) {
if (in_array('credit_card_type', array_keys($params))) {
$params['card_type_id'] = CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_FinancialTrxn', 'card_type_id', $params['credit_card_type']);
}
if (!empty($params['credit_card_number']) && empty($params['pan_truncation'])) {
$params['pan_truncation'] = substr($params['credit_card_number'], -4);
}
}
/**
* Add the billing address to the contact who paid.
*
* Note that this function works based on the presence or otherwise of billing fields & can be called regardless of
* whether they are 'expected' (due to assumptions about the payment processor type or the setting to collect billing
* for pay later.
*/
protected function processBillingAddress() {
$fields = array();
$fields['email-Primary'] = 1;
$this->_params['email-5'] = $this->_params['email-Primary'] = $this->_contributorEmail;
// now set the values for the billing location.
foreach (array_keys($this->_fields) as $name) {
$fields[$name] = 1;
}
$fields["address_name-{$this->_bltID}"] = 1;
//ensure we don't over-write the payer's email with the member's email
if ($this->_contributorContactID == $this->_contactID) {
$fields["email-{$this->_bltID}"] = 1;
}
list($hasBillingField, $addressParams) = CRM_Contribute_BAO_Contribution::getPaymentProcessorReadyAddressParams($this->_params, $this->_bltID);
$fields = $this->formatParamsForPaymentProcessor($fields);
if ($hasBillingField) {
$addressParams = array_merge($this->_params, $addressParams);
// CRM-18277 don't let this get passed in because we don't want contribution source to override contact source.
// Ideally we wouldn't just randomly merge everything into addressParams but just pass in a relevant array.
// Note this source field is covered by a unit test.
if (isset($addressParams['source'])) {
unset($addressParams['source']);
}
//here we are setting up the billing contact - if different from the member they are already created
// but they will get billing details assigned
CRM_Contact_BAO_Contact::createProfileContact($addressParams, $fields,
$this->_contributorContactID, NULL, NULL,
CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type')
);
}
$this->assignBillingName($this->_params);
}
/**
* Get default values for billing fields.
*
* @todo this function still replicates code in several other places in the code.
*
* Also - the call to getProfileDefaults possibly covers the state_province & country already.
*
* @param $defaults
*
* @return array
*/
protected function getBillingDefaults($defaults) {
// set default country from config if no country set
$config = CRM_Core_Config::singleton();
if (empty($defaults["billing_country_id-{$this->_bltID}"])) {
$defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
}
if (empty($defaults["billing_state_province_id-{$this->_bltID}"])) {
$defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince;
}
$billingDefaults = $this->getProfileDefaults('Billing', $this->_contactID);
return array_merge($defaults, $billingDefaults);
}
/**
* Get the default payment instrument id.
*
* @return int
*/
protected 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'));
}
/**
* Add the payment processor select to the form.
*
* @param bool $isRequired
* Is it a mandatory field.
* @param bool $isBuildRecurBlock
* True if we want to build recur on change
* @param bool $isBuildAutoRenewBlock
* True if we want to build autorenew on change.
*/
protected function addPaymentProcessorSelect($isRequired, $isBuildRecurBlock = FALSE, $isBuildAutoRenewBlock = FALSE) {
if (!$this->_mode) {
return;
}
$js = ($isBuildRecurBlock ? array('onChange' => "buildRecurBlock( this.value ); return false;") : NULL);
if ($isBuildAutoRenewBlock) {
$js = array('onChange' => "buildAutoRenew( null, this.value, '{$this->_mode}');");
}
$element = $this->add('select',
'payment_processor_id',
ts('Payment Processor'),
array_diff_key($this->_processors, array(0 => 1)),
$isRequired,
$js
);
// The concept of _online is not really explained & the code is old
// @todo figure out & document.
if ($this->_online) {
$element->freeze();
}
}
}

View file

@ -0,0 +1,488 @@
<?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
*/
class CRM_Contribute_Form_AdditionalInfo {
/**
* Build the form object for Premium Information.
*
* Called from the CRM_Contribute_Form_Contribute function and seemingly nowhere else.
*
* Probably this should be on the form that uses it since it is not used on multiple forms.
*
* Putting it on this class doesn't seem to reduce complexity.
*
* @param CRM_Core_Form $form
*/
public static function buildPremium(&$form) {
//premium section
$form->add('hidden', 'hidden_Premium', 1);
$sel1 = $sel2 = array();
$dao = new CRM_Contribute_DAO_Product();
$dao->is_active = 1;
$dao->find();
$min_amount = array();
$sel1[0] = ts('-select product-');
while ($dao->fetch()) {
$sel1[$dao->id] = $dao->name . " ( " . $dao->sku . " )";
$min_amount[$dao->id] = $dao->min_contribution;
$options = explode(',', $dao->options);
foreach ($options as $k => $v) {
$options[$k] = trim($v);
}
if ($options[0] != '') {
$sel2[$dao->id] = $options;
}
$form->assign('premiums', TRUE);
}
$form->_options = $sel2;
$form->assign('mincontribution', $min_amount);
$sel = &$form->addElement('hierselect', "product_name", ts('Premium'), 'onclick="showMinContrib();"');
$js = "<script type='text/javascript'>\n";
$formName = 'document.forms.' . $form->getName();
for ($k = 1; $k < 2; $k++) {
if (!isset($defaults['product_name'][$k]) || (!$defaults['product_name'][$k])) {
$js .= "{$formName}['product_name[$k]'].style.display = 'none';\n";
}
}
$sel->setOptions(array($sel1, $sel2));
$js .= "</script>\n";
$form->assign('initHideBoxes', $js);
$form->addDate('fulfilled_date', ts('Fulfilled'), FALSE, array('formatType' => 'activityDate'));
$form->addElement('text', 'min_amount', ts('Minimum Contribution Amount'));
}
/**
* Build the form object for Additional Details.
*
* @param CRM_Core_Form $form
*/
public static function buildAdditionalDetail(&$form) {
//Additional information section
$form->add('hidden', 'hidden_AdditionalDetail', 1);
$attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution');
$form->addDateTime('thankyou_date', ts('Thank-you Sent'), FALSE, array('formatType' => 'activityDateTime'));
// add various amounts
$nonDeductAmount = &$form->add('text', 'non_deductible_amount', ts('Non-deductible Amount'),
$attributes['non_deductible_amount']
);
$form->addRule('non_deductible_amount', ts('Please enter a valid monetary value for Non-deductible Amount.'), 'money');
if ($form->_online) {
$nonDeductAmount->freeze();
}
$feeAmount = &$form->add('text', 'fee_amount', ts('Fee Amount'),
$attributes['fee_amount']
);
$form->addRule('fee_amount', ts('Please enter a valid monetary value for Fee Amount.'), 'money');
if ($form->_online) {
$feeAmount->freeze();
}
$netAmount = &$form->add('text', 'net_amount', ts('Net Amount'),
$attributes['net_amount']
);
$form->addRule('net_amount', ts('Please enter a valid monetary value for Net Amount.'), 'money');
if ($form->_online) {
$netAmount->freeze();
}
$element = &$form->add('text', 'invoice_id', ts('Invoice ID'),
$attributes['invoice_id']
);
if ($form->_online) {
$element->freeze();
}
else {
$form->addRule('invoice_id',
ts('This Invoice ID already exists in the database.'),
'objectExists',
array('CRM_Contribute_DAO_Contribution', $form->_id, 'invoice_id')
);
}
$element = $form->add('text', 'creditnote_id', ts('Credit Note ID'),
$attributes['creditnote_id']
);
if ($form->_online) {
$element->freeze();
}
else {
$form->addRule('creditnote_id',
ts('This Credit Note ID already exists in the database.'),
'objectExists',
array('CRM_Contribute_DAO_Contribution', $form->_id, 'creditnote_id')
);
}
$form->add('select', 'contribution_page_id',
ts('Online Contribution Page'),
array(
'' => ts('- select -'),
) +
CRM_Contribute_PseudoConstant::contributionPage()
);
$form->add('textarea', 'note', ts('Notes'), array("rows" => 4, "cols" => 60));
$statusName = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
if ($form->_id && $form->_values['contribution_status_id'] == array_search('Cancelled', $statusName)) {
$netAmount->freeze();
$feeAmount->freeze();
}
}
/**
* used by CRM/Pledge/Form/Pledge.php
*
* Build the form object for PaymentReminders Information.
*
* @param CRM_Core_Form $form
*/
public static function buildPaymentReminders(&$form) {
//PaymentReminders section
$form->add('hidden', 'hidden_PaymentReminders', 1);
$form->add('text', 'initial_reminder_day', ts('Send Initial Reminder'), array('size' => 3));
$form->addRule('initial_reminder_day', ts('Please enter a valid reminder day.'), 'positiveInteger');
$form->add('text', 'max_reminders', ts('Send up to'), array('size' => 3));
$form->addRule('max_reminders', ts('Please enter a valid No. of reminders.'), 'positiveInteger');
$form->add('text', 'additional_reminder_day', ts('Send additional reminders'), array('size' => 3));
$form->addRule('additional_reminder_day', ts('Please enter a valid additional reminder day.'), 'positiveInteger');
}
/**
* Process the Premium Information.
*
* @param array $params
* @param int $contributionID
* @param int $premiumID
* @param array $options
*/
public static function processPremium($params, $contributionID, $premiumID = NULL, $options = array()) {
$selectedProductID = $params['product_name'][0];
$selectedProductOptionID = CRM_Utils_Array::value(1, $params['product_name']);
$dao = new CRM_Contribute_DAO_ContributionProduct();
$dao->contribution_id = $contributionID;
$dao->product_id = $selectedProductID;
$dao->fulfilled_date = CRM_Utils_Date::processDate($params['fulfilled_date'], NULL, TRUE);
$isDeleted = FALSE;
//CRM-11106
$premiumParams = array(
'id' => $selectedProductID,
);
$productDetails = array();
CRM_Contribute_BAO_ManagePremiums::retrieve($premiumParams, $productDetails);
$dao->financial_type_id = CRM_Utils_Array::value('financial_type_id', $productDetails);
if (!empty($options[$selectedProductID])) {
$dao->product_option = $options[$selectedProductID][$selectedProductOptionID];
}
if ($premiumID) {
$ContributionProduct = new CRM_Contribute_DAO_ContributionProduct();
$ContributionProduct->id = $premiumID;
$ContributionProduct->find(TRUE);
if ($ContributionProduct->product_id == $selectedProductID) {
$dao->id = $premiumID;
}
else {
$ContributionProduct->delete();
$isDeleted = TRUE;
}
}
$dao->save();
//CRM-11106
if ($premiumID == NULL || $isDeleted) {
$premiumParams = array(
'cost' => CRM_Utils_Array::value('cost', $productDetails),
'currency' => CRM_Utils_Array::value('currency', $productDetails),
'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $productDetails),
'contributionId' => $contributionID,
);
if ($isDeleted) {
$premiumParams['oldPremium']['product_id'] = $ContributionProduct->product_id;
$premiumParams['oldPremium']['contribution_id'] = $ContributionProduct->contribution_id;
}
CRM_Core_BAO_FinancialTrxn::createPremiumTrxn($premiumParams);
}
}
/**
* Process the Note.
*
*
* @param array $params
* @param int $contactID
* @param int $contributionID
* @param int $contributionNoteID
*/
public static function processNote($params, $contactID, $contributionID, $contributionNoteID = NULL) {
//process note
$noteParams = array(
'entity_table' => 'civicrm_contribution',
'note' => $params['note'],
'entity_id' => $contributionID,
'contact_id' => $contactID,
);
$noteID = array();
if ($contributionNoteID) {
$noteID = array("id" => $contributionNoteID);
$noteParams['note'] = $noteParams['note'] ? $noteParams['note'] : "null";
}
CRM_Core_BAO_Note::add($noteParams, $noteID);
}
/**
* Process the Common data.
*
* @param array $params
* @param array $formatted
* @param CRM_Core_Form $form
*/
public static function postProcessCommon(&$params, &$formatted, &$form) {
$fields = array(
'non_deductible_amount',
'total_amount',
'fee_amount',
'net_amount',
'trxn_id',
'invoice_id',
'creditnote_id',
'campaign_id',
'contribution_page_id',
);
foreach ($fields as $f) {
$formatted[$f] = CRM_Utils_Array::value($f, $params);
}
if (!empty($params['thankyou_date']) && !CRM_Utils_System::isNull($params['thankyou_date'])) {
$formatted['thankyou_date'] = CRM_Utils_Date::processDate($params['thankyou_date'], $params['thankyou_date_time']);
}
else {
$formatted['thankyou_date'] = 'null';
}
if (!empty($params['is_email_receipt'])) {
$params['receipt_date'] = $formatted['receipt_date'] = date('YmdHis');
}
//special case to handle if all checkboxes are unchecked
$customFields = CRM_Core_BAO_CustomField::getFields('Contribution',
FALSE,
FALSE,
CRM_Utils_Array::value('financial_type_id',
$params
)
);
$formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($params,
CRM_Utils_Array::value('id', $params, NULL),
'Contribution'
);
}
/**
* Send email receipt.
*
* @param CRM_Core_Form $form
* instance of Contribution form.
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param bool $ccContribution
* is it credit card contribution.
*
* @return array
*/
public static function emailReceipt(&$form, &$params, $ccContribution = FALSE) {
$form->assign('receiptType', 'contribution');
// Retrieve Financial Type Name from financial_type_id
$params['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType',
$params['financial_type_id']);
if (!empty($params['payment_instrument_id'])) {
$paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
$params['paidBy'] = $paymentInstrument[$params['payment_instrument_id']];
if ($params['paidBy'] != 'Check' && isset($params['check_number'])) {
unset($params['check_number']);
}
}
// retrieve individual prefix value for honoree
if (isset($params['soft_credit'])) {
$softCreditTypes = $softCredits = array();
foreach ($params['soft_credit'] as $key => $softCredit) {
$softCredits[$key] = array(
'Name' => $softCredit['contact_name'],
'Amount' => CRM_Utils_Money::format($softCredit['amount'], $softCredit['currency']),
);
$softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
}
$form->assign('softCreditTypes', $softCreditTypes);
$form->assign('softCredits', $softCredits);
}
// retrieve premium product name and assigned fulfilled
// date to template
if (!empty($params['hidden_Premium'])) {
if (isset($params['product_name']) &&
is_array($params['product_name']) &&
!empty($params['product_name'])
) {
$productDAO = new CRM_Contribute_DAO_Product();
$productDAO->id = $params['product_name'][0];
$productOptionID = $params['product_name'][1];
$productDAO->find(TRUE);
$params['product_name'] = $productDAO->name;
$params['product_sku'] = $productDAO->sku;
if (empty($params['product_option']) && !empty($form->_options[$productDAO->id])) {
$params['product_option'] = $form->_options[$productDAO->id][$productOptionID];
}
}
if (!empty($params['fulfilled_date'])) {
$form->assign('fulfilled_date', CRM_Utils_Date::processDate($params['fulfilled_date']));
}
}
$form->assign('ccContribution', $ccContribution);
if ($ccContribution) {
$form->assignBillingName($params);
$form->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters(
$params,
$form->_bltID
));
$date = CRM_Utils_Date::format($params['credit_card_exp_date']);
$date = CRM_Utils_Date::mysqlToIso($date);
$form->assign('credit_card_type', CRM_Utils_Array::value('credit_card_type', $params));
$form->assign('credit_card_exp_date', $date);
$form->assign('credit_card_number',
CRM_Utils_System::mungeCreditCard($params['credit_card_number'])
);
}
else {
//offline contribution
// assigned various dates to the templates
$form->assign('receipt_date', CRM_Utils_Date::processDate($params['receipt_date']));
if (!empty($params['cancel_date'])) {
$form->assign('cancel_date', CRM_Utils_Date::processDate($params['cancel_date']));
}
if (!empty($params['thankyou_date'])) {
$form->assign('thankyou_date', CRM_Utils_Date::processDate($params['thankyou_date']));
}
if ($form->_action & CRM_Core_Action::UPDATE) {
$form->assign('lineItem', empty($form->_lineItems) ? FALSE : $form->_lineItems);
}
}
//handle custom data
if (!empty($params['hidden_custom'])) {
$contribParams = array(array('contribution_id', '=', $params['contribution_id'], 0, 0));
if ($form->_mode == 'test') {
$contribParams[] = array('contribution_test', '=', 1, 0, 0);
}
//retrieve custom data
$customGroup = array();
foreach ($form->_groupTree as $groupID => $group) {
$customFields = $customValues = array();
if ($groupID == 'info') {
continue;
}
foreach ($group['fields'] as $k => $field) {
$field['title'] = $field['label'];
$customFields["custom_{$k}"] = $field;
}
//build the array of customgroup contain customfields.
CRM_Core_BAO_UFGroup::getValues($params['contact_id'], $customFields, $customValues, FALSE, $contribParams);
$customGroup[$group['title']] = $customValues;
}
//assign all custom group and corresponding fields to template.
$form->assign('customGroup', $customGroup);
}
$form->assign_by_ref('formValues', $params);
list($contributorDisplayName,
$contributorEmail
) = CRM_Contact_BAO_Contact_Location::getEmailDetails($params['contact_id']);
$form->assign('contactID', $params['contact_id']);
$form->assign('contributionID', $params['contribution_id']);
if (!empty($params['currency'])) {
$form->assign('currency', $params['currency']);
}
if (!empty($params['receive_date'])) {
$form->assign('receive_date', CRM_Utils_Date::processDate($params['receive_date']));
}
$template = CRM_Core_Smarty::singleton();
$taxAmt = $template->get_template_vars('dataArray');
$eventTaxAmt = $template->get_template_vars('totalTaxAmount');
$prefixValue = Civi::settings()->get('contribution_invoice_settings');
$invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
if ((!empty($taxAmt) || isset($eventTaxAmt)) && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
$isEmailPdf = TRUE;
}
else {
$isEmailPdf = FALSE;
}
list($sendReceipt, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(
array(
'groupName' => 'msg_tpl_workflow_contribution',
'valueName' => 'contribution_offline_receipt',
'contactId' => $params['contact_id'],
'contributionId' => $params['contribution_id'],
'from' => $params['from_email_address'],
'toName' => $contributorDisplayName,
'toEmail' => $contributorEmail,
'isTest' => $form->_mode == 'test',
'PDFFilename' => ts('receipt') . '.pdf',
'isEmailPdf' => $isEmailPdf,
)
);
return $sendReceipt;
}
}

View file

@ -0,0 +1,649 @@
<?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 form records additional payments needed when event/contribution is partially paid.
*/
class CRM_Contribute_Form_AdditionalPayment extends CRM_Contribute_Form_AbstractEditPayment {
public $_contributeMode = 'direct';
/**
* Related component whose financial payment is being processed.
*
* @var string
*/
protected $_component = NULL;
/**
* Id of the component entity
*/
public $_id = NULL;
protected $_owed = NULL;
protected $_refund = NULL;
/**
* @deprecated - use parent $this->contactID
*
* @var int
*/
protected $_contactId = NULL;
protected $_contributorDisplayName = NULL;
protected $_contributorEmail = NULL;
protected $_toDoNotEmail = NULL;
protected $_paymentType = NULL;
protected $_contributionId = NULL;
protected $fromEmailId = NULL;
protected $_fromEmails = NULL;
protected $_view = NULL;
public $_action = NULL;
public function preProcess() {
parent::preProcess();
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
// @todo don't set this - rely on parent $this->contactID
$this->_contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, TRUE);
$this->_component = CRM_Utils_Request::retrieve('component', 'String', $this, TRUE);
$this->_view = CRM_Utils_Request::retrieve('view', 'String', $this, FALSE);
$this->assign('component', $this->_component);
$this->assign('id', $this->_id);
$this->assign('suppressPaymentFormButtons', $this->isBeingCalledFromSelectorContext());
if ($this->_view == 'transaction' && ($this->_action & CRM_Core_Action::BROWSE)) {
$paymentInfo = CRM_Contribute_BAO_Contribution::getPaymentInfo($this->_id, $this->_component, TRUE);
$title = ts('View Payment');
if ($this->_component == 'event') {
$info = CRM_Event_BAO_Participant::participantDetails($this->_id);
$title .= " - {$info['title']}";
}
CRM_Utils_System::setTitle($title);
$this->assign('transaction', TRUE);
$this->assign('payments', $paymentInfo['transaction']);
return;
}
$this->_fromEmails = CRM_Core_BAO_Email::getFromEmail();
$entityType = 'contribution';
if ($this->_component == 'event') {
$entityType = 'participant';
$this->_contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'contribution_id', 'participant_id');
$eventId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'event_id', 'id');
$this->_fromEmails = CRM_Event_BAO_Event::getFromEmailIds($eventId);
}
else {
$this->_contributionId = $this->_id;
$this->_fromEmails['from_email_id'] = CRM_Core_BAO_Email::getFromEmail();
}
$paymentInfo = CRM_Core_BAO_FinancialTrxn::getPartialPaymentWithType($this->_id, $entityType);
$paymentDetails = CRM_Contribute_BAO_Contribution::getPaymentInfo($this->_id, $this->_component, FALSE, TRUE);
$this->_amtPaid = $paymentDetails['paid'];
$this->_amtTotal = $paymentDetails['total'];
if (!empty($paymentInfo['refund_due'])) {
$paymentAmt = $this->_refund = $paymentInfo['refund_due'];
$this->_paymentType = 'refund';
}
elseif (!empty($paymentInfo['amount_owed'])) {
$paymentAmt = $this->_owed = $paymentInfo['amount_owed'];
$this->_paymentType = 'owed';
}
else {
CRM_Core_Error::fatal(ts('No payment information found for this record'));
}
if (!empty($this->_mode) && $this->_paymentType == 'refund') {
CRM_Core_Error::fatal(ts('Credit card payment is not for Refund payments use'));
}
list($this->_contributorDisplayName, $this->_contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactId);
$this->assign('contributionMode', $this->_mode);
$this->assign('contactId', $this->_contactId);
$this->assign('paymentType', $this->_paymentType);
$this->assign('paymentAmt', abs($paymentAmt));
$this->setPageTitle($this->_refund ? ts('Refund') : ts('Payment'));
}
/**
* Is this function being called from a datatable selector.
*
* If so we don't want to show the buttons.
*/
protected function isBeingCalledFromSelectorContext() {
return CRM_Utils_Request::retrieve('selector', 'Positive');
}
/**
* This virtual function is used to set the default values of
* various form elements
*
* access public
*
* @return array
* reference to the array of default values
*/
/**
* @return array
*/
public function setDefaultValues() {
if ($this->_view == 'transaction' && ($this->_action & CRM_Core_Action::BROWSE)) {
return NULL;
}
$defaults = array();
if ($this->_mode) {
CRM_Core_Payment_Form::setDefaultValues($this, $this->_contactId);
$defaults = array_merge($defaults, $this->_defaults);
}
if (empty($defaults['trxn_date'])) {
$defaults['trxn_date'] = date('Y-m-d H:i:s');
}
if ($this->_refund) {
$defaults['total_amount'] = abs($this->_refund);
}
elseif ($this->_owed) {
$defaults['total_amount'] = number_format($this->_owed, 2);
}
// Set $newCredit variable in template to control whether link to credit card mode is included
$this->assign('newCredit', CRM_Core_Config::isEnabledBackOfficeCreditCardPayments());
return $defaults;
}
/**
* Build the form object.
*/
public function buildQuickForm() {
if ($this->_view == 'transaction' && ($this->_action & CRM_Core_Action::BROWSE)) {
$this->addButtons(array(
array(
'type' => 'cancel',
'name' => ts('Done'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
'isDefault' => TRUE,
),
)
);
return;
}
CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, FALSE, TRUE, CRM_Utils_Request::retrieve('payment_instrument_id', 'Integer'));
$this->add('select', 'payment_processor_id', ts('Payment Processor'), $this->_processors, NULL);
$attributes = CRM_Core_DAO::getAttribute('CRM_Financial_DAO_FinancialTrxn');
$label = ($this->_refund) ? ts('Refund Amount') : ts('Payment Amount');
$this->addMoney('total_amount',
$label,
TRUE,
$attributes['total_amount'],
TRUE, 'currency', NULL
);
//add receipt for offline contribution
$this->addElement('checkbox', 'is_email_receipt', ts('Send Receipt?'));
$this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails['from_email_id']);
$this->add('textarea', 'receipt_text', ts('Confirmation Message'));
$dateLabel = ($this->_refund) ? ts('Refund Date') : ts('Date Received');
$this->addField('trxn_date', array('entity' => 'FinancialTrxn', 'label' => $dateLabel, 'context' => 'Contribution'), FALSE, FALSE);
if ($this->_contactId && $this->_id) {
if ($this->_component == 'event') {
$eventId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $this->_id, 'event_id', 'id');
$event = CRM_Event_BAO_Event::getEvents(0, $eventId);
$this->assign('eventName', $event[$eventId]);
}
}
$this->assign('displayName', $this->_contributorDisplayName);
$this->assign('component', $this->_component);
$this->assign('email', $this->_contributorEmail);
$js = NULL;
// render backoffice payment fields only on offline mode
if (!$this->_mode) {
$js = array('onclick' => "return verify( );");
$this->add('select', 'payment_instrument_id',
ts('Payment Method'),
array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(),
TRUE,
array('onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);")
);
$this->add('text', 'check_number', ts('Check Number'), $attributes['financial_trxn_check_number']);
$this->add('text', 'trxn_id', ts('Transaction ID'), array('class' => 'twelve') + $attributes['trxn_id']);
$this->add('text', 'fee_amount', ts('Fee Amount'),
$attributes['fee_amount']
);
$this->addRule('fee_amount', ts('Please enter a valid monetary value for Fee Amount.'), 'money');
$this->add('text', 'net_amount', ts('Net Amount'),
$attributes['net_amount']
);
$this->addRule('net_amount', ts('Please enter a valid monetary value for Net Amount.'), 'money');
}
$buttonName = $this->_refund ? 'Record Refund' : 'Record Payment';
$this->addButtons(array(
array(
'type' => 'upload',
'name' => ts('%1', array(1 => $buttonName)),
'js' => $js,
'isDefault' => TRUE,
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
)
);
$mailingInfo = Civi::settings()->get('mailing_backend');
$this->assign('outBound_option', $mailingInfo['outBound_option']);
$this->addFormRule(array('CRM_Contribute_Form_AdditionalPayment', 'formRule'), $this);
}
/**
* @param $fields
* @param $files
* @param $self
*
* @return array
*/
public static function formRule($fields, $files, $self) {
$errors = array();
if ($self->_paymentType == 'owed' && $fields['total_amount'] > $self->_owed) {
$errors['total_amount'] = ts('Payment amount cannot be greater than owed amount');
}
if ($self->_paymentType == 'refund' && $fields['total_amount'] != abs($self->_refund)) {
$errors['total_amount'] = ts('Refund amount must equal refund due amount.');
}
$netAmt = $fields['total_amount'] - CRM_Utils_Array::value('fee_amount', $fields, 0);
if (!empty($fields['net_amount']) && $netAmt != $fields['net_amount']) {
$errors['net_amount'] = ts('Net amount should be equal to the difference between payment amount and fee amount.');
}
if ($self->_paymentProcessor['id'] === 0 && empty($fields['payment_instrument_id'])) {
$errors['payment_instrument_id'] = ts('Payment method is a required field');
}
return $errors;
}
/**
* Process the form submission.
*/
public function postProcess() {
$submittedValues = $this->controller->exportValues($this->_name);
$this->submit($submittedValues);
$childTab = 'contribute';
if ($this->_component == 'event') {
$childTab = 'participant';
}
$session = CRM_Core_Session::singleton();
$session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view',
"reset=1&cid={$this->_contactId}&selectedChild={$childTab}"
));
}
/**
* Process Payments.
* @param array $submittedValues
*
*/
public function submit($submittedValues) {
$this->_params = $submittedValues;
$this->beginPostProcess();
$this->_contributorContactID = $this->_contactID;
$this->processBillingAddress();
$participantId = NULL;
if ($this->_component == 'event') {
$participantId = $this->_id;
}
$contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution',
'contribution_status_id',
array('labelColumn' => 'name')
);
$contributionStatusID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $this->_contributionId, 'contribution_status_id');
if ($contributionStatuses[$contributionStatusID] == 'Pending') {
civicrm_api3('Contribution', 'create',
array(
'id' => $this->_contributionId,
'contribution_status_id' => array_search('Partially paid', $contributionStatuses),
'is_pay_later' => 0,
)
);
}
if ($this->_mode) {
// process credit card
$this->assign('contributeMode', 'direct');
$this->processCreditCard();
}
$defaults = array();
$contribution = civicrm_api3('Contribution', 'getsingle', array(
'return' => array("contribution_status_id"),
'id' => $this->_contributionId,
));
$contributionStatusId = CRM_Utils_Array::value('contribution_status_id', $contribution);
$result = CRM_Contribute_BAO_Contribution::recordAdditionalPayment($this->_contributionId, $this->_params, $this->_paymentType, $participantId);
// Fetch the contribution & do proportional line item assignment
$params = array('id' => $this->_contributionId);
$contribution = CRM_Contribute_BAO_Contribution::retrieve($params, $defaults, $params);
CRM_Contribute_BAO_Contribution::addPayments(array($contribution), $contributionStatusId);
if ($this->_contributionId && CRM_Core_Permission::access('CiviMember')) {
$membershipPaymentCount = civicrm_api3('MembershipPayment', 'getCount', array('contribution_id' => $this->_contributionId));
if ($membershipPaymentCount) {
$this->ajaxResponse['updateTabs']['#tab_member'] = CRM_Contact_BAO_Contact::getCountComponent('membership', $this->_contactID);
}
}
if ($this->_contributionId && CRM_Core_Permission::access('CiviEvent')) {
$participantPaymentCount = civicrm_api3('ParticipantPayment', 'getCount', array('contribution_id' => $this->_contributionId));
if ($participantPaymentCount) {
$this->ajaxResponse['updateTabs']['#tab_participant'] = CRM_Contact_BAO_Contact::getCountComponent('participant', $this->_contactID);
}
}
$statusMsg = ts('The payment record has been processed.');
// send email
if (!empty($result) && !empty($this->_params['is_email_receipt'])) {
$this->_params['contact_id'] = $this->_contactId;
$this->_params['contribution_id'] = $this->_contributionId;
// to get 'from email id' for send receipt
$this->fromEmailId = $this->_params['from_email_address'];
$sendReceipt = $this->emailReceipt($this->_params);
if ($sendReceipt) {
$statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
}
}
CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
}
public function processCreditCard() {
$config = CRM_Core_Config::singleton();
$session = CRM_Core_Session::singleton();
$now = date('YmdHis');
$fields = array();
// we need to retrieve email address
if ($this->_context == 'standalone' && !empty($this->_params['is_email_receipt'])) {
list($this->userDisplayName,
$this->userEmail
) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactId);
$this->assign('displayName', $this->userDisplayName);
}
$this->formatParamsForPaymentProcessor($this->_params);
$this->_params['amount'] = $this->_params['total_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.
$this->_params['amount_level'] = 0;
$this->_params['currencyID'] = CRM_Utils_Array::value('currency',
$this->_params,
$config->defaultCurrency
);
if (!empty($this->_params['trxn_date'])) {
$this->_params['receive_date'] = $this->_params['trxn_date'];
}
if (empty($this->_params['receive_date'])) {
$this->_params['receive_date'] = date('YmdHis');
}
if (empty($this->_params['invoice_id'])) {
$this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
}
else {
$this->_params['invoiceID'] = $this->_params['invoice_id'];
}
$this->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters(
$this->_params,
$this->_bltID
));
//Add common data to formatted params
$params = $this->_params;
CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this);
// at this point we've created a contact and stored its address etc
// all the payment processors expect the name and address to be in the
// so we copy stuff over to first_name etc.
$paymentParams = $this->_params;
$paymentParams['contactID'] = $this->_contactId;
CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
$paymentParams['contributionPageID'] = NULL;
if (!empty($this->_params['is_email_receipt'])) {
$paymentParams['email'] = $this->_contributorEmail;
$paymentParams['is_email_receipt'] = TRUE;
}
else {
$paymentParams['is_email_receipt'] = $this->_params['is_email_receipt'] = FALSE;
}
$result = NULL;
if ($paymentParams['amount'] > 0.0) {
try {
// force a reget of the payment processor in case the form changed it, CRM-7179
$payment = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
$result = $payment->doPayment($paymentParams);
}
catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
Civi::log()->error('Payment processor exception: ' . $e->getMessage());
$urlParams = "action=add&cid={$this->_contactId}&id={$this->_contributionId}&component={$this->_component}&mode={$this->_mode}";
CRM_Core_Error::statusBounce(CRM_Utils_System::url($e->getMessage(), 'civicrm/payment/add', $urlParams));
}
}
if (!empty($result)) {
$this->_params = array_merge($this->_params, $result);
}
if (empty($this->_params['receive_date'])) {
$this->_params['receive_date'] = $now;
}
$this->set('params', $this->_params);
// set source if not set
if (empty($this->_params['source'])) {
$userID = $session->get('userID');
$userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID,
'sort_name'
);
$this->_params['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
}
}
/**
* Function to send email receipt.
*
* @param array $params
*
* @return bool
*/
public function emailReceipt(&$params) {
// email receipt sending
// send message template
if ($this->_component == 'event') {
// fetch event information from participant ID using API
$eventId = civicrm_api3('Participant', 'getvalue', array(
'return' => "event_id",
'id' => $this->_id,
));
$event = civicrm_api3('Event', 'getsingle', array('id' => $eventId));
$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' => $eventId,
'entity_table' => 'civicrm_event',
);
$location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
$this->assign('location', $location);
}
}
// assign payment info here
$paymentConfig['confirm_email_text'] = CRM_Utils_Array::value('confirm_email_text', $params);
$this->assign('paymentConfig', $paymentConfig);
$this->assign('totalAmount', $this->_amtTotal);
$isRefund = ($this->_paymentType == 'refund') ? TRUE : FALSE;
$this->assign('isRefund', $isRefund);
if ($isRefund) {
$this->assign('totalPaid', $this->_amtPaid);
$this->assign('refundAmount', $params['total_amount']);
}
else {
$balance = $this->_amtTotal - ($this->_amtPaid + $params['total_amount']);
$paymentsComplete = ($balance == 0) ? 1 : 0;
$this->assign('amountOwed', $balance);
$this->assign('paymentAmount', $params['total_amount']);
$this->assign('paymentsComplete', $paymentsComplete);
}
$this->assign('contactDisplayName', $this->_contributorDisplayName);
// assign trxn details
$this->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $params));
$this->assign('receive_date', CRM_Utils_Array::value('trxn_date', $params));
$this->assign('paidBy', CRM_Core_PseudoConstant::getLabel(
'CRM_Contribute_BAO_Contribution',
'payment_instrument_id',
$params['payment_instrument_id']
));
$this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
$sendTemplateParams = array(
'groupName' => 'msg_tpl_workflow_contribution',
'valueName' => 'payment_or_refund_notification',
'contactId' => $this->_contactId,
'PDFFilename' => ts('notification') . '.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) {
if (array_key_exists($params['from_email_address'], $this->_fromEmails['from_email_id'])) {
$receiptFrom = $params['from_email_address'];
}
$sendTemplateParams['from'] = $receiptFrom;
$sendTemplateParams['toName'] = $this->_contributorDisplayName;
$sendTemplateParams['toEmail'] = $this->_contributorEmail;
}
list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
return $mailSent;
}
/**
* Wrapper for unit testing the post process submit function.
*
* @param array $params
* @param string|null $creditCardMode
* @param string $entityType
*
* @throws \CiviCRM_API3_Exception
*/
public function testSubmit($params, $creditCardMode = NULL, $entityType = 'contribute') {
$this->_bltID = 5;
// Required because processCreditCard calls set method on this.
$_SERVER['REQUEST_METHOD'] = 'GET';
$this->controller = new CRM_Core_Controller();
$this->assignPaymentRelatedVariables();
if (!empty($params['contribution_id'])) {
$this->_contributionId = $params['contribution_id'];
$paymentInfo = CRM_Core_BAO_FinancialTrxn::getPartialPaymentWithType($this->_contributionId, $entityType);
$paymentDetails = CRM_Contribute_BAO_Contribution::getPaymentInfo($this->_contributionId, $entityType, FALSE, TRUE);
$this->_amtPaid = $paymentDetails['paid'];
$this->_amtTotal = $paymentDetails['total'];
if (!empty($paymentInfo['refund_due'])) {
$this->_refund = $paymentInfo['refund_due'];
$this->_paymentType = 'refund';
}
elseif (!empty($paymentInfo['amount_owed'])) {
$this->_owed = $paymentInfo['amount_owed'];
$this->_paymentType = 'owed';
}
}
if (!empty($params['contact_id'])) {
$this->_contactId = $params['contact_id'];
}
if ($creditCardMode) {
$this->_mode = $creditCardMode;
}
$this->_fields = array();
$this->set('cid', $this->_contactId);
parent::preProcess();
$this->submit($params);
}
}

View file

@ -0,0 +1,329 @@
<?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 provides support for canceling recurring subscriptions.
*/
class CRM_Contribute_Form_CancelSubscription extends CRM_Core_Form {
protected $_paymentProcessorObj = NULL;
protected $_userContext = NULL;
protected $_mode = NULL;
protected $_mid = NULL;
protected $_coid = NULL;
protected $_crid = NULL;
protected $_selfService = FALSE;
/**
* Set variables up before form is built.
*/
public function preProcess() {
$this->_mid = CRM_Utils_Request::retrieve('mid', 'Integer', $this, FALSE);
$this->_crid = CRM_Utils_Request::retrieve('crid', 'Integer', $this, FALSE);
if ($this->_crid) {
$this->_paymentProcessorObj = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_crid, 'recur', 'obj');
$this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_crid);
$this->assign('frequency_unit', $this->_subscriptionDetails->frequency_unit);
$this->assign('frequency_interval', $this->_subscriptionDetails->frequency_interval);
$this->assign('amount', $this->_subscriptionDetails->amount);
$this->assign('installments', $this->_subscriptionDetails->installments);
// Are we cancelling a recurring contribution that is linked to an auto-renew membership?
if ($this->_subscriptionDetails->membership_id) {
$this->_mid = $this->_subscriptionDetails->membership_id;
}
}
if ($this->_mid) {
$this->_mode = 'auto_renew';
// CRM-18468: crid is more accurate than mid for getting
// subscriptionDetails, so don't get them again.
if (!$this->_crid) {
$this->_paymentProcessorObj = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_mid, 'membership', 'obj');
$this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_mid, 'membership');
}
$membershipTypes = CRM_Member_PseudoConstant::membershipType();
$membershipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_mid, 'membership_type_id');
$this->assign('membershipType', CRM_Utils_Array::value($membershipTypeId, $membershipTypes));
}
$this->_coid = CRM_Utils_Request::retrieve('coid', 'Integer', $this, FALSE);
if ($this->_coid) {
if (CRM_Contribute_BAO_Contribution::isSubscriptionCancelled($this->_coid)) {
CRM_Core_Error::fatal(ts('The recurring contribution looks to have been cancelled already.'));
}
$this->_paymentProcessorObj = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'obj');
$this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_coid, 'contribution');
$this->assign('frequency_unit', $this->_subscriptionDetails->frequency_unit);
$this->assign('frequency_interval', $this->_subscriptionDetails->frequency_interval);
$this->assign('amount', $this->_subscriptionDetails->amount);
$this->assign('installments', $this->_subscriptionDetails->installments);
}
if (
(!$this->_crid && !$this->_coid && !$this->_mid) ||
(!$this->_subscriptionDetails)
) {
CRM_Core_Error::fatal('Required information missing.');
}
if (!CRM_Core_Permission::check('edit contributions')) {
$userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this, FALSE);
if (!CRM_Contact_BAO_Contact_Utils::validChecksum($this->_subscriptionDetails->contact_id, $userChecksum)) {
CRM_Core_Error::fatal(ts('You do not have permission to cancel this recurring contribution.'));
}
$this->_selfService = TRUE;
}
$this->assign('self_service', $this->_selfService);
// handle context redirection
CRM_Contribute_BAO_ContributionRecur::setSubscriptionContext();
CRM_Utils_System::setTitle($this->_mid ? ts('Cancel Auto-renewal') : ts('Cancel Recurring Contribution'));
$this->assign('mode', $this->_mode);
if ($this->_subscriptionDetails->contact_id) {
list($this->_donorDisplayName, $this->_donorEmail)
= CRM_Contact_BAO_Contact::getContactDetails($this->_subscriptionDetails->contact_id);
}
}
/**
* Build the form object.
*/
public function buildQuickForm() {
// Determine if we can cancel recurring contribution via API with this processor
$cancelSupported = $this->_paymentProcessorObj->supports('CancelRecurring');
if ($cancelSupported) {
$searchRange = array();
$searchRange[] = $this->createElement('radio', NULL, NULL, ts('Yes'), '1');
$searchRange[] = $this->createElement('radio', NULL, NULL, ts('No'), '0');
$this->addGroup(
$searchRange,
'send_cancel_request',
ts('Send cancellation request to %1 ?',
array(1 => $this->_paymentProcessorObj->_processorName))
);
}
$this->assign('cancelSupported', $cancelSupported);
if ($this->_donorEmail) {
$this->add('checkbox', 'is_notify', ts('Notify Contributor?'));
}
if ($this->_mid) {
$cancelButton = ts('Cancel Automatic Membership Renewal');
}
else {
$cancelButton = ts('Cancel Recurring Contribution');
}
$type = 'next';
if ($this->_selfService) {
$type = 'submit';
}
$this->addButtons(array(
array(
'type' => $type,
'name' => $cancelButton,
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
'isDefault' => TRUE,
),
array(
'type' => 'cancel',
'name' => ts('Not Now'),
),
)
);
}
/**
* Set default values for the form.
*
* @return array
* array of default values
*/
public function setDefaultValues() {
return array(
'is_notify' => 1,
'send_cancel_request' => 1,
);
}
/**
* Process the form submission.
*/
public function postProcess() {
$status = $message = NULL;
$cancelSubscription = TRUE;
$params = $this->controller->exportValues($this->_name);
if ($this->_selfService) {
// for self service force sending-request & notify
if ($this->_paymentProcessorObj->supports('cancelRecurring')) {
$params['send_cancel_request'] = 1;
}
if ($this->_donorEmail) {
$params['is_notify'] = 1;
}
}
if (CRM_Utils_Array::value('send_cancel_request', $params) == 1) {
$cancelParams = array('subscriptionId' => $this->_subscriptionDetails->subscription_id);
$cancelSubscription = $this->_paymentProcessorObj->cancelSubscription($message, $cancelParams);
}
if (is_a($cancelSubscription, 'CRM_Core_Error')) {
CRM_Core_Error::displaySessionError($cancelSubscription);
}
elseif ($cancelSubscription) {
$activityParams
= array(
'subject' => $this->_mid ? ts('Auto-renewal membership cancelled') : ts('Recurring contribution cancelled'),
'details' => $message,
);
$cancelStatus = CRM_Contribute_BAO_ContributionRecur::cancelRecurContribution(
$this->_subscriptionDetails->recur_id,
NULL,
$activityParams
);
if ($cancelStatus) {
$tplParams = array();
if ($this->_mid) {
$inputParams = array('id' => $this->_mid);
CRM_Member_BAO_Membership::getValues($inputParams, $tplParams);
$tplParams = $tplParams[$this->_mid];
$tplParams['membership_status']
= CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $tplParams['status_id']);
$tplParams['membershipType']
= CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $tplParams['membership_type_id']);
$status = ts('The automatic renewal of your %1 membership has been cancelled as requested. This does not affect the status of your membership - you will receive a separate notification when your membership is up for renewal.', array(1 => $tplParams['membershipType']));
$msgTitle = 'Membership Renewal Cancelled';
$msgType = 'info';
}
else {
$tplParams['recur_frequency_interval'] = $this->_subscriptionDetails->frequency_interval;
$tplParams['recur_frequency_unit'] = $this->_subscriptionDetails->frequency_unit;
$tplParams['amount'] = $this->_subscriptionDetails->amount;
$tplParams['contact'] = array('display_name' => $this->_donorDisplayName);
$status = ts('The recurring contribution of %1, every %2 %3 has been cancelled.',
array(
1 => $this->_subscriptionDetails->amount,
2 => $this->_subscriptionDetails->frequency_interval,
3 => $this->_subscriptionDetails->frequency_unit,
)
);
$msgTitle = 'Contribution Cancelled';
$msgType = 'success';
}
if (CRM_Utils_Array::value('is_notify', $params) == 1) {
if ($this->_subscriptionDetails->contribution_page_id) {
CRM_Core_DAO::commonRetrieveAll(
'CRM_Contribute_DAO_ContributionPage',
'id',
$this->_subscriptionDetails->contribution_page_id,
$value,
array('title', 'receipt_from_name', 'receipt_from_email')
);
$receiptFrom
= '"' . CRM_Utils_Array::value('receipt_from_name', $value[$this->_subscriptionDetails->contribution_page_id]) .
'" <' .
$value[$this->_subscriptionDetails->contribution_page_id]['receipt_from_email'] .
'>';
}
else {
$domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
$receiptFrom = "$domainValues[0] <$domainValues[1]>";
}
// send notification
$sendTemplateParams
= array(
'groupName' => $this->_mode == 'auto_renew' ? 'msg_tpl_workflow_membership' : 'msg_tpl_workflow_contribution',
'valueName' => $this->_mode == 'auto_renew' ? 'membership_autorenew_cancelled' : 'contribution_recurring_cancelled',
'contactId' => $this->_subscriptionDetails->contact_id,
'tplParams' => $tplParams,
//'isTest' => $isTest, set this from _objects
'PDFFilename' => 'receipt.pdf',
'from' => $receiptFrom,
'toName' => $this->_donorDisplayName,
'toEmail' => $this->_donorEmail,
);
list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
}
}
else {
$msgType = 'error';
$msgTitle = ts('Error');
if ($params['send_cancel_request'] == 1) {
$status = ts('Recurring contribution was cancelled successfully by the processor, but could not be marked as cancelled in the database.');
}
else {
$status = ts('Recurring contribution could not be cancelled in the database.');
}
}
}
else {
$status = ts('The recurring contribution could not be cancelled.');
$msgTitle = 'Error Cancelling Contribution';
$msgType = 'error';
}
$session = CRM_Core_Session::singleton();
$userID = $session->get('userID');
if ($userID && $status) {
$session->setStatus($status, $msgTitle, $msgType);
}
elseif (!$userID) {
if ($status) {
CRM_Utils_System::setUFMessage($status);
// keep result as 1, since we not displaying anything on the redirected page anyway
return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/subscriptionstatus',
"reset=1&task=cancel&result=1"));
}
}
}
}

File diff suppressed because it is too large Load diff

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,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
*/
/**
* Form for thank-you / success page - 3rd step of online contribution process.
*/
class CRM_Contribute_Form_Contribution_ThankYou extends CRM_Contribute_Form_ContributionBase {
/**
* Membership price set status.
*/
public $_useForMember;
/**
* Set variables up before form is built.
*/
public function preProcess() {
parent::preProcess();
$this->_params = $this->get('params');
$this->_lineItem = $this->get('lineItem');
$is_deductible = $this->get('is_deductible');
$this->assign('is_deductible', $is_deductible);
$this->assign('thankyou_title', CRM_Utils_Array::value('thankyou_title', $this->_values));
$this->assign('thankyou_text', CRM_Utils_Array::value('thankyou_text', $this->_values));
$this->assign('thankyou_footer', CRM_Utils_Array::value('thankyou_footer', $this->_values));
$this->assign('max_reminders', CRM_Utils_Array::value('max_reminders', $this->_values));
$this->assign('initial_reminder_day', CRM_Utils_Array::value('initial_reminder_day', $this->_values));
CRM_Utils_System::setTitle(CRM_Utils_Array::value('thankyou_title', $this->_values));
// Make the contributionPageID available to the template
$this->assign('contributionPageID', $this->_id);
$this->assign('isShare', $this->_values['is_share']);
$this->_params['is_pay_later'] = $this->get('is_pay_later');
$this->assign('is_pay_later', $this->_params['is_pay_later']);
if ($this->_params['is_pay_later']) {
$this->assign('pay_later_receipt', $this->_values['pay_later_receipt']);
}
$this->assign('is_for_organization', CRM_Utils_Array::value('is_for_organization', $this->_params));
}
/**
* 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.
*/
public function buildQuickForm() {
// FIXME: Some of this code is identical to Confirm.php and should be broken out into a shared function
$this->assignToTemplate();
$this->_ccid = $this->get('ccid');
$productID = $this->get('productID');
$option = $this->get('option');
$membershipTypeID = $this->get('membershipTypeID');
$this->assign('receiptFromEmail', CRM_Utils_Array::value('receipt_from_email', $this->_values));
if ($productID) {
CRM_Contribute_BAO_Premium::buildPremiumBlock($this, $this->_id, FALSE, $productID, $option);
}
$params = $this->_params;
$invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
$invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
// Make a copy of line items array to use for display only
$tplLineItems = $this->_lineItem;
if ($invoicing) {
$getTaxDetails = FALSE;
$taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
foreach ($this->_lineItem as $key => $value) {
foreach ($value as $k => $v) {
if (isset($v['tax_rate'])) {
if ($v['tax_rate'] != '') {
$getTaxDetails = TRUE;
// Cast to float to display without trailing zero decimals
$tplLineItems[$key][$k]['tax_rate'] = (float) $v['tax_rate'];
}
}
}
}
$this->assign('getTaxDetails', $getTaxDetails);
$this->assign('taxTerm', $taxTerm);
$this->assign('totalTaxAmount', $params['tax_amount']);
}
if ($this->_priceSetId && !CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config')) {
$this->assign('lineItem', $tplLineItems);
}
else {
if (is_array($membershipTypeID)) {
$membershipTypeID = current($membershipTypeID);
}
$this->assign('is_quick_config', 1);
$this->_params['is_quick_config'] = 1;
}
$this->assign('priceSetID', $this->_priceSetId);
$this->assign('useForMember', $this->get('useForMember'));
if (!empty($this->_values['honoree_profile_id']) && !empty($params['soft_credit_type_id'])) {
$softCreditTypes = CRM_Core_OptionGroup::values("soft_credit_type", FALSE);
$this->assign('soft_credit_type', $softCreditTypes[$params['soft_credit_type_id']]);
CRM_Contribute_BAO_ContributionSoft::formatHonoreeProfileFields($this, $params['honor']);
$fieldTypes = array('Contact');
$fieldTypes[] = CRM_Core_BAO_UFGroup::getContactType($this->_values['honoree_profile_id']);
$this->buildCustom($this->_values['honoree_profile_id'], 'honoreeProfileFields', TRUE, 'honor', $fieldTypes);
}
$qParams = "reset=1&amp;id={$this->_id}";
//pcp elements
if ($this->_pcpId) {
$qParams .= "&amp;pcpId={$this->_pcpId}";
$this->assign('pcpBlock', TRUE);
foreach (array(
'pcp_display_in_roll',
'pcp_is_anonymous',
'pcp_roll_nickname',
'pcp_personal_note',
) as $val) {
if (!empty($this->_params[$val])) {
$this->assign($val, $this->_params[$val]);
}
}
}
$this->assign('qParams', $qParams);
if ($membershipTypeID) {
$transactionID = $this->get('membership_trx_id');
$membershipAmount = $this->get('membership_amount');
$renewalMode = $this->get('renewal_mode');
$this->assign('membership_trx_id', $transactionID);
$this->assign('membership_amount', $membershipAmount);
$this->assign('renewal_mode', $renewalMode);
$this->buildMembershipBlock(
$this->_membershipContactID,
FALSE,
$membershipTypeID,
TRUE,
NULL
);
if (!empty($params['auto_renew'])) {
$this->assign('auto_renew', TRUE);
}
}
$this->_separateMembershipPayment = $this->get('separateMembershipPayment');
$this->assign("is_separate_payment", $this->_separateMembershipPayment);
if (empty($this->_ccid)) {
$this->buildCustom($this->_values['custom_pre_id'], 'customPre', TRUE);
$this->buildCustom($this->_values['custom_post_id'], 'customPost', TRUE);
}
if (!empty($this->_values['onbehalf_profile_id']) &&
!empty($params['onbehalf']) &&
($this->_values['is_for_organization'] == 2 ||
!empty($params['is_for_organization'])
) && empty($this->_ccid)
) {
$fieldTypes = array('Contact', 'Organization');
$contactSubType = CRM_Contact_BAO_ContactType::subTypes('Organization');
$fieldTypes = array_merge($fieldTypes, $contactSubType);
if (is_array($this->_membershipBlock) && !empty($this->_membershipBlock)) {
$fieldTypes = array_merge($fieldTypes, array('Membership'));
}
else {
$fieldTypes = array_merge($fieldTypes, array('Contribution'));
}
$this->buildCustom($this->_values['onbehalf_profile_id'], 'onbehalfProfile', TRUE, 'onbehalf', $fieldTypes);
}
$this->assign('trxn_id',
CRM_Utils_Array::value('trxn_id',
$this->_params
)
);
$this->assign('receive_date',
CRM_Utils_Date::mysqlToIso(CRM_Utils_Array::value('receive_date', $this->_params))
);
$defaults = array();
$fields = array();
foreach ($this->_fields as $name => $dontCare) {
if ($name != 'onbehalf' || $name != 'honor') {
$fields[$name] = 1;
}
}
$fields['state_province'] = $fields['country'] = $fields['email'] = 1;
$contact = $this->_params = $this->controller->exportValues('Main');
foreach ($fields as $name => $dontCare) {
if (isset($contact[$name])) {
$defaults[$name] = $contact[$name];
if (substr($name, 0, 7) == 'custom_') {
$timeField = "{$name}_time";
if (isset($contact[$timeField])) {
$defaults[$timeField] = $contact[$timeField];
}
}
elseif (in_array($name, array(
'addressee',
'email_greeting',
'postal_greeting',
)) && !empty($contact[$name . '_custom'])
) {
$defaults[$name . '_custom'] = $contact[$name . '_custom'];
}
}
}
$this->_submitValues = array_merge($this->_submitValues, $defaults);
$this->setDefaults($defaults);
$values['entity_id'] = $this->_id;
$values['entity_table'] = 'civicrm_contribution_page';
CRM_Friend_BAO_Friend::retrieve($values, $data);
$tellAFriend = FALSE;
if ($this->_pcpId) {
if ($this->_pcpBlock['is_tellfriend_enabled']) {
$this->assign('friendText', ts('Tell a Friend'));
$subUrl = "eid={$this->_pcpId}&blockId={$this->_pcpBlock['id']}&pcomponent=pcp";
$tellAFriend = TRUE;
}
}
elseif (!empty($data['is_active'])) {
$friendText = $data['title'];
$this->assign('friendText', $friendText);
$subUrl = "eid={$this->_id}&pcomponent=contribute";
$tellAFriend = TRUE;
}
if ($tellAFriend) {
if ($this->_action & CRM_Core_Action::PREVIEW) {
$url = CRM_Utils_System::url("civicrm/friend",
"reset=1&action=preview&{$subUrl}"
);
}
else {
$url = CRM_Utils_System::url("civicrm/friend",
"reset=1&{$subUrl}"
);
}
$this->assign('friendURL', $url);
}
$isPendingOutcome = TRUE;
try {
// A payment notification update could have come in at any time. Check at the last minute.
$contributionStatusID = civicrm_api3('Contribution', 'getvalue', array(
'id' => CRM_Utils_Array::value('contributionID', $params),
'return' => 'contribution_status_id',
'invoice_id' => CRM_Utils_Array::value('invoiceID', $params),
));
if (CRM_Core_PseudoConstant::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $contributionStatusID) === 'Pending'
&& !empty($params['payment_processor_id'])
) {
$isPendingOutcome = TRUE;
}
else {
$isPendingOutcome = FALSE;
}
}
catch (CiviCRM_API3_Exception $e) {
}
$this->assign('isPendingOutcome', $isPendingOutcome);
$this->freeze();
// can we blow away the session now to prevent hackery
// CRM-9491
$this->controller->reset();
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,238 @@
<?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
*/
class CRM_Contribute_Form_ContributionCharts extends CRM_Core_Form {
/**
* Year of chart.
*
* @var int
*/
protected $_year = NULL;
/**
* The type of chart.
*
* @var string
*/
protected $_chartType = NULL;
public function preProcess() {
$this->_year = CRM_Utils_Request::retrieve('year', 'Int', $this);
$this->_chartType = CRM_Utils_Request::retrieve('type', 'String', $this);
$buildChart = FALSE;
if ($this->_year || $this->_chartType) {
$buildChart = TRUE;
}
$this->assign('buildChart', $buildChart);
$this->postProcess();
}
/**
* Build the form object.
*/
public function buildQuickForm() {
//p3 = Three dimensional pie chart.
//bvg = Vertical bar chart
$this->addElement('select', 'chart_type', ts('Chart Style'), array(
'bvg' => ts('Bar'),
'p3' => ts('Pie'),
)
);
$defaultValues['chart_type'] = $this->_chartType;
$this->setDefaults($defaultValues);
//take available years from database to show in drop down
$currentYear = date('Y');
$years = array();
if (!empty($this->_years)) {
if (!array_key_exists($currentYear, $this->_years)) {
$this->_years[$currentYear] = $currentYear;
krsort($this->_years);
}
foreach ($this->_years as $k => $v) {
$years[substr($k, 0, 4)] = substr($k, 0, 4);
}
}
$this->addElement('select', 'select_year', ts('Select Year (for monthly breakdown)'), $years);
$this->setDefaults(array(
'select_year' => ($this->_year) ? $this->_year : $currentYear,
));
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
$config = CRM_Core_Config::singleton();
$chartType = 'bvg';
if ($this->_chartType) {
$chartType = $this->_chartType;
}
$selectedYear = date('Y');
if ($this->_year) {
$selectedYear = $this->_year;
}
//take contribution information monthly
$chartInfoMonthly = CRM_Contribute_BAO_Contribution_Utils::contributionChartMonthly($selectedYear);
$chartData = $abbrMonthNames = array();
if (is_array($chartInfoMonthly)) {
for ($i = 1; $i <= 12; $i++) {
$abbrMonthNames[$i] = strftime('%b', mktime(0, 0, 0, $i, 10, 1970));
}
foreach ($abbrMonthNames as $monthKey => $monthName) {
$val = CRM_Utils_Array::value($monthKey, $chartInfoMonthly['By Month'], 0);
// don't include zero value month.
if (!$val && ($chartType != 'bvg')) {
continue;
}
//build the params for chart.
$chartData['by_month']['values'][$monthName] = $val;
}
$chartData['by_month']['legend'] = 'By Month' . ' - ' . $selectedYear;
// handle onclick event.
$chartData['by_month']['on_click_fun_name'] = 'byMonthOnClick';
$chartData['by_month']['yname'] = ts('Contribution');
}
//take contribution information by yearly
$chartInfoYearly = CRM_Contribute_BAO_Contribution_Utils::contributionChartYearly();
//get the years.
$this->_years = $chartInfoYearly['By Year'];
$hasContributions = FALSE;
if (is_array($chartInfoYearly)) {
$hasContributions = TRUE;
$chartData['by_year']['legend'] = 'By Year';
$chartData['by_year']['values'] = $chartInfoYearly['By Year'];
// handle onclick event.
$chartData['by_year']['on_click_fun_name'] = 'byYearOnClick';
$chartData['by_year']['yname'] = ts('Total Amount');
}
$this->assign('hasContributions', $hasContributions);
// process the data.
$chartCnt = 1;
$monthlyChart = $yearlyChart = FALSE;
foreach ($chartData as $chartKey => & $values) {
$chartValues = CRM_Utils_Array::value('values', $values);
if (!is_array($chartValues) || empty($chartValues)) {
continue;
}
if ($chartKey == 'by_year') {
$yearlyChart = TRUE;
if (!empty($config->fiscalYearStart) && ($config->fiscalYearStart['M'] !== 1 || $config->fiscalYearStart['d'] !== 1)) {
$values['xLabelAngle'] = 45;
}
else {
$values['xLabelAngle'] = 0;
}
}
if ($chartKey == 'by_month') {
$monthlyChart = TRUE;
}
$values['divName'] = "open_flash_chart_{$chartKey}";
$funName = ($chartType == 'bvg') ? 'barChart' : 'pieChart';
// build the chart objects.
$values['object'] = CRM_Utils_OpenFlashChart::$funName($values);
//build the urls.
$urlCnt = 0;
foreach ($chartValues as $index => $val) {
$urlParams = NULL;
if ($chartKey == 'by_month') {
$monthPosition = array_search($index, $abbrMonthNames);
$startDate = CRM_Utils_Date::format(array('Y' => $selectedYear, 'M' => $monthPosition));
$endDate = date('Ymd', mktime(0, 0, 0, $monthPosition + 1, 0, $selectedYear));
$urlParams = "reset=1&force=1&status=1&start={$startDate}&end={$endDate}&test=0";
}
elseif ($chartKey == 'by_year') {
if (!empty($config->fiscalYearStart) && ($config->fiscalYearStart['M'] != 1 || $config->fiscalYearStart['d'] != 1)) {
$startDate = date('Ymd', mktime(0, 0, 0, $config->fiscalYearStart['M'], $config->fiscalYearStart['d'], substr($index, 0, 4)));
$endDate = date('Ymd', mktime(0, 0, 0, $config->fiscalYearStart['M'], $config->fiscalYearStart['d'], (substr($index, 0, 4)) + 1));
}
else {
$startDate = CRM_Utils_Date::format(array('Y' => substr($index, 0, 4)));
$endDate = date('Ymd', mktime(0, 0, 0, 13, 0, substr($index, 0, 4)));
}
$urlParams = "reset=1&force=1&status=1&start={$startDate}&end={$endDate}&test=0";
}
if ($urlParams) {
$values['on_click_urls']["url_" . $urlCnt++] = CRM_Utils_System::url('civicrm/contribute/search',
$urlParams, TRUE, FALSE, FALSE
);
}
}
// calculate chart size.
$xSize = 400;
$ySize = 300;
if ($chartType == 'bvg') {
$ySize = 250;
$xSize = 60 * count($chartValues);
// reduce x size by 100 for by_month
if ($chartKey == 'by_month') {
$xSize -= 100;
}
//hack to show tooltip.
if ($xSize < 150) {
$xSize = 150;
}
}
$values['size'] = array('xSize' => $xSize, 'ySize' => $ySize);
}
// finally assign this chart data to template.
$this->assign('hasYearlyChart', $yearlyChart);
$this->assign('hasByMonthChart', $monthlyChart);
$this->assign('hasOpenFlashChart', empty($chartData) ? FALSE : TRUE);
$this->assign('openFlashChartData', json_encode($chartData));
}
}

View file

@ -0,0 +1,480 @@
<?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
*/
/**
* Contribution Page form.
*/
class CRM_Contribute_Form_ContributionPage extends CRM_Core_Form {
/**
* The page id saved to the session for an update.
*
* @var int
*/
protected $_id;
/**
* The pledgeBlock id saved to the session for an update.
*
* @var int
*/
protected $_pledgeBlockID;
/**
* Are we in single form mode or wizard mode?
*
* @var boolean
*/
protected $_single;
/**
* Is this the first page?
*
* @var boolean
*/
protected $_first = FALSE;
/**
* Is this the last page?
*
* @var boolean
*/
protected $_last = FALSE;
/**
* Store price set id.
*
* @var int
*/
protected $_priceSetID = NULL;
protected $_values;
/**
* Explicitly declare the entity api name.
*/
public function getDefaultEntity() {
return 'Contribution';
}
/**
* Set variables up before form is built.
*/
public function preProcess() {
// current contribution page id
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive',
$this, FALSE, NULL, 'REQUEST'
);
$this->assign('contributionPageID', $this->_id);
// get the requested action
$this->_action = CRM_Utils_Request::retrieve('action', 'String',
// default to 'browse'
$this, FALSE, 'browse'
);
// setting title and 3rd level breadcrumb for html page if contrib page exists
if ($this->_id) {
$title = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $this->_id, 'title');
if ($this->_action == CRM_Core_Action::UPDATE) {
$this->_single = TRUE;
}
}
// CRM-16776 - show edit/copy/create buttons on Profiles Tab if user has required permission.
if (CRM_Core_Permission::check('administer CiviCRM')) {
$this->assign('perm', TRUE);
}
// set up tabs
CRM_Contribute_Form_ContributionPage_TabHeader::build($this);
if ($this->_action == CRM_Core_Action::UPDATE) {
CRM_Utils_System::setTitle(ts('Configure Page - %1', array(1 => $title)));
}
elseif ($this->_action == CRM_Core_Action::VIEW) {
CRM_Utils_System::setTitle(ts('Preview Page - %1', array(1 => $title)));
}
elseif ($this->_action == CRM_Core_Action::DELETE) {
CRM_Utils_System::setTitle(ts('Delete Page - %1', array(1 => $title)));
}
//cache values.
$this->_values = $this->get('values');
if (!is_array($this->_values)) {
$this->_values = array();
if (isset($this->_id) && $this->_id) {
$params = array('id' => $this->_id);
CRM_Core_DAO::commonRetrieve('CRM_Contribute_DAO_ContributionPage', $params, $this->_values);
CRM_Contribute_BAO_ContributionPage::setValues($this->_id, $this->_values);
}
$this->set('values', $this->_values);
}
// Check permission to edit contribution page
if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus() && $this->_action & CRM_Core_Action::UPDATE) {
$financialTypeID = CRM_Contribute_PseudoConstant::financialType($this->_values['financial_type_id']);
if (!CRM_Core_Permission::check('edit contributions of type ' . $financialTypeID)) {
CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
}
}
// Preload libraries required by the "Profiles" tab
$schemas = array('IndividualModel', 'OrganizationModel', 'ContributionModel');
if (in_array('CiviMember', CRM_Core_Config::singleton()->enableComponents)) {
$schemas[] = 'MembershipModel';
}
CRM_UF_Page_ProfileEditor::registerProfileScripts();
CRM_UF_Page_ProfileEditor::registerSchemas($schemas);
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->applyFilter('__ALL__', 'trim');
$session = CRM_Core_Session::singleton();
$this->_cancelURL = CRM_Utils_Array::value('cancelURL', $_POST);
if (!$this->_cancelURL) {
$this->_cancelURL = CRM_Utils_System::url('civicrm/admin/contribute', 'reset=1');
}
if ($this->_cancelURL) {
$this->addElement('hidden', 'cancelURL', $this->_cancelURL);
}
if ($this->_single) {
$buttons = array(
array(
'type' => 'next',
'name' => ts('Save'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
'isDefault' => TRUE,
),
array(
'type' => 'upload',
'name' => ts('Save and Done'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
'subName' => 'done',
),
);
if (!$this->_last) {
$buttons[] = array(
'type' => 'submit',
'name' => ts('Save and Next'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
'subName' => 'savenext',
);
}
$buttons[] = 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' => 'next',
'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);
// views are implemented as frozen form
if ($this->_action & CRM_Core_Action::VIEW) {
$this->freeze();
$this->addElement('button', 'done', ts('Done'), array('onclick' => "location.href='civicrm/admin/custom/group?reset=1&action=browse'"));
}
// don't show option for contribution amounts section if membership price set
// this flag is sent to template
$membershipBlock = new CRM_Member_DAO_MembershipBlock();
$membershipBlock->entity_table = 'civicrm_contribution_page';
$membershipBlock->entity_id = $this->_id;
$membershipBlock->is_active = 1;
$hasMembershipBlk = FALSE;
if ($membershipBlock->find(TRUE) &&
($setID = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $this->_id, NULL, 1))
) {
$extends = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $setID, 'extends');
if ($extends && $extends == CRM_Core_Component::getComponentID('CiviMember')) {
$hasMembershipBlk = TRUE;
}
}
// set value in DOM that membership price set exists
CRM_Core_Resources::singleton()->addSetting(array('memberPriceset' => $hasMembershipBlk));
}
/**
* Set default values for the form. Note that in edit/view mode
* the default values are retrieved from the database
*
*
* @return array
* defaults
*/
public function setDefaultValues() {
//some child classes calling setdefaults directly w/o preprocess.
$this->_values = $this->get('values');
if (!is_array($this->_values)) {
$this->_values = array();
if (isset($this->_id) && $this->_id) {
$params = array('id' => $this->_id);
CRM_Core_DAO::commonRetrieve('CRM_Contribute_DAO_ContributionPage', $params, $this->_values);
}
$this->set('values', $this->_values);
}
$defaults = $this->_values;
$config = CRM_Core_Config::singleton();
if (isset($this->_id)) {
//set defaults for pledgeBlock values.
$pledgeBlockParams = array(
'entity_id' => $this->_id,
'entity_table' => ts('civicrm_contribution_page'),
);
$pledgeBlockDefaults = array();
CRM_Pledge_BAO_PledgeBlock::retrieve($pledgeBlockParams, $pledgeBlockDefaults);
if ($this->_pledgeBlockID = CRM_Utils_Array::value('id', $pledgeBlockDefaults)) {
$defaults['is_pledge_active'] = TRUE;
}
$pledgeBlock = array(
'is_pledge_interval',
'max_reminders',
'initial_reminder_day',
'additional_reminder_day',
'pledge_start_date',
'is_pledge_start_date_visible',
'is_pledge_start_date_editable',
);
foreach ($pledgeBlock as $key) {
$defaults[$key] = CRM_Utils_Array::value($key, $pledgeBlockDefaults);
if ($key == 'pledge_start_date' && CRM_Utils_Array::value($key, $pledgeBlockDefaults)) {
$defaultPledgeDate = (array) json_decode($pledgeBlockDefaults['pledge_start_date']);
$pledgeDateFields = array(
'pledge_calendar_date' => 'calendar_date',
'pledge_calendar_month' => 'calendar_month',
);
$defaults['pledge_default_toggle'] = key($defaultPledgeDate);
foreach ($pledgeDateFields as $key => $value) {
if (array_key_exists($value, $defaultPledgeDate)) {
$defaults[$key] = reset($defaultPledgeDate);
$this->assign($key, reset($defaultPledgeDate));
}
}
}
}
if (!empty($pledgeBlockDefaults['pledge_frequency_unit'])) {
$defaults['pledge_frequency_unit'] = array_fill_keys(explode(CRM_Core_DAO::VALUE_SEPARATOR,
$pledgeBlockDefaults['pledge_frequency_unit']
), '1');
}
// fix the display of the monetary value, CRM-4038
if (isset($defaults['goal_amount'])) {
$defaults['goal_amount'] = CRM_Utils_Money::format($defaults['goal_amount'], NULL, '%a');
}
// get price set of type contributions
//this is the value for stored in db if price set extends contribution
$usedFor = 2;
$this->_priceSetID = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $this->_id, $usedFor, 1);
if ($this->_priceSetID) {
$defaults['price_set_id'] = $this->_priceSetID;
}
if (!empty($defaults['end_date'])) {
list($defaults['end_date'], $defaults['end_date_time']) = CRM_Utils_Date::setDateDefaults($defaults['end_date']);
}
if (!empty($defaults['start_date'])) {
list($defaults['start_date'], $defaults['start_date_time']) = CRM_Utils_Date::setDateDefaults($defaults['start_date']);
}
}
else {
$defaults['is_active'] = 1;
// set current date as start date
list($defaults['start_date'], $defaults['start_date_time']) = CRM_Utils_Date::setDateDefaults();
}
if (!empty($defaults['recur_frequency_unit'])) {
$defaults['recur_frequency_unit'] = array_fill_keys(explode(CRM_Core_DAO::VALUE_SEPARATOR,
$defaults['recur_frequency_unit']
), '1');
}
else {
# CRM 10860
$defaults['recur_frequency_unit'] = array('month' => 1);
}
// confirm page starts out enabled
if (!isset($defaults['is_confirm_enabled'])) {
$defaults['is_confirm_enabled'] = 1;
}
return $defaults;
}
/**
* Process the form.
*/
public function postProcess() {
$pageId = $this->get('id');
//page is newly created.
if ($pageId && !$this->_id) {
$session = CRM_Core_Session::singleton();
$session->pushUserContext(CRM_Utils_System::url('civicrm/admin/contribute', 'reset=1'));
}
}
public function endPostProcess() {
// make submit buttons keep the current working tab opened, or save and next tab
if ($this->_action & CRM_Core_Action::UPDATE) {
$className = CRM_Utils_String::getClassName($this->_name);
//retrieve list of pages from StateMachine and find next page
//this is quite painful because StateMachine is full of protected variables
//so we have to retrieve all pages, find current page, and then retrieve next
$stateMachine = new CRM_Contribute_StateMachine_ContributionPage($this);
$states = $stateMachine->getStates();
$statesList = array_keys($states);
$currKey = array_search($className, $statesList);
$nextPage = (array_key_exists($currKey + 1, $statesList)) ? $statesList[$currKey + 1] : '';
//unfortunately, some classes don't map to subpage names, so we alter the exceptions
switch ($className) {
case 'Contribute':
$attributes = $this->getVar('_attributes');
$subPage = strtolower(basename(CRM_Utils_Array::value('action', $attributes)));
$subPageName = ucfirst($subPage);
if ($subPage == 'friend') {
$nextPage = 'custom';
}
else {
$nextPage = 'settings';
}
break;
case 'MembershipBlock':
$subPage = 'membership';
$subPageName = 'MembershipBlock';
$nextPage = 'thankyou';
break;
default:
$subPage = strtolower($className);
$subPageName = $className;
$nextPage = strtolower($nextPage);
if ($subPage == 'amount') {
$nextPage = 'membership';
}
elseif ($subPage == 'thankyou') {
$nextPage = 'friend';
}
break;
}
CRM_Core_Session::setStatus(ts("'%1' information has been saved.",
array(1 => $subPageName)
), ts('Saved'), 'success');
$this->postProcessHook();
if ($this->controller->getButtonName('submit') == "_qf_{$className}_next") {
CRM_Utils_System::redirect(CRM_Utils_System::url("civicrm/admin/contribute/{$subPage}",
"action=update&reset=1&id={$this->_id}"
));
}
elseif ($this->controller->getButtonName('submit') == "_qf_{$className}_submit_savenext") {
if ($nextPage) {
CRM_Utils_System::redirect(CRM_Utils_System::url("civicrm/admin/contribute/{$nextPage}",
"action=update&reset=1&id={$this->_id}"
));
}
else {
CRM_Utils_System::redirect(CRM_Utils_System::url("civicrm/admin/contribute",
"reset=1"
));
}
}
else {
CRM_Utils_System::redirect(CRM_Utils_System::url("civicrm/admin/contribute", 'reset=1'));
}
}
}
/**
* Use the form name to create the tpl file name.
*
* @return string
*/
/**
* @return string
*/
public function getTemplateFileName() {
if ($this->controller->getPrint() || $this->getVar('_id') <= 0 ||
($this->_action & CRM_Core_Action::DELETE) ||
(CRM_Utils_String::getClassName($this->_name) == 'AddProduct')
) {
return parent::getTemplateFileName();
}
else {
// hack lets suppress the form rendering for now
self::$_template->assign('isForm', FALSE);
return 'CRM/Contribute/Form/ContributionPage/Tab.tpl';
}
}
}

View file

@ -0,0 +1,286 @@
<?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
*/
/**
* form to process actions fo adding product to contribution page
*/
class CRM_Contribute_Form_ContributionPage_AddProduct extends CRM_Contribute_Form_ContributionPage {
protected $_products;
protected $_pid;
/**
* Pre process the form.
*/
public function preProcess() {
parent::preProcess();
$this->_products = CRM_Contribute_PseudoConstant::products($this->_id);
$this->_pid = CRM_Utils_Request::retrieve('pid', 'Positive',
$this, FALSE, 0
);
if ($this->_pid) {
$dao = new CRM_Contribute_DAO_PremiumsProduct();
$dao->id = $this->_pid;
$dao->find(TRUE);
$temp = CRM_Contribute_PseudoConstant::products();
$this->_products[$dao->product_id] = $temp[$dao->product_id];
}
//$this->_products = array_merge(array('' => '-- Select Product --') , $this->_products );
}
/**
* Set default values for the form.
*
* Note that in edit/view mode the default values are retrieved from the database.
*/
public function setDefaultValues() {
$defaults = array();
if ($this->_pid) {
$dao = new CRM_Contribute_DAO_PremiumsProduct();
$dao->id = $this->_pid;
$dao->find(TRUE);
$defaults['product_id'] = $dao->product_id;
$defaults['financial_type_id'] = $dao->financial_type_id;
$defaults['weight'] = $dao->weight;
}
else {
$dao = new CRM_Contribute_DAO_Product();
$dao->id = key($this->_products);
$dao->find(TRUE);
$defaults['financial_type_id'] = $dao->financial_type_id;
}
if (!isset($defaults['weight']) || !($defaults['weight'])) {
$pageID = CRM_Utils_Request::retrieve('id', 'Positive',
$this, FALSE, 0
);
$dao = new CRM_Contribute_DAO_Premium();
$dao->entity_table = 'civicrm_contribution_page';
$dao->entity_id = $pageID;
$dao->find(TRUE);
$premiumID = $dao->id;
$sql = 'SELECT max( weight ) as max_weight FROM civicrm_premiums_product WHERE premiums_id = %1';
$params = array(1 => array($premiumID, 'Integer'));
$dao = CRM_Core_DAO::executeQuery($sql, $params);
$dao->fetch();
$defaults['weight'] = $dao->max_weight + 1;
}
RETURN $defaults;
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$urlParams = 'civicrm/admin/contribute/premium';
if ($this->_action & CRM_Core_Action::DELETE) {
$session = CRM_Core_Session::singleton();
$url = CRM_Utils_System::url($urlParams, 'reset=1&action=update&id=' . $this->_id);
$session->pushUserContext($url);
if (CRM_Utils_Request::retrieve('confirmed', 'Boolean',
CRM_Core_DAO::$_nullObject, '', '', 'GET'
)
) {
$dao = new CRM_Contribute_DAO_PremiumsProduct();
$dao->id = $this->_pid;
$dao->delete();
CRM_Core_Session::setStatus(ts('Selected Premium Product has been removed from this Contribution Page.'), ts('Saved'), 'success');
CRM_Utils_System::redirect($url);
}
$this->addButtons(array(
array(
'type' => 'next',
'name' => ts('Delete'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;',
'isDefault' => TRUE,
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
)
);
return;
}
if ($this->_action & CRM_Core_Action::PREVIEW) {
CRM_Contribute_BAO_Premium::buildPremiumPreviewBlock($this, NULL, $this->_pid);
$this->addButtons(array(
array(
'type' => 'next',
'name' => ts('Done with Preview'),
'isDefault' => TRUE,
),
)
);
return;
}
$session = CRM_Core_Session::singleton();
$url = CRM_Utils_System::url($urlParams, 'reset=1&action=update&id=' . $this->_id);
$session->pushUserContext($url);
$this->add('select', 'product_id', ts('Select the Product') . ' ', $this->_products, TRUE);
$this->addElement('text', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_PremiumsProduct', 'weight'));
$financialType = CRM_Contribute_PseudoConstant::financialType();
$premiumFinancialType = array();
CRM_Core_PseudoConstant::populate(
$premiumFinancialType,
'CRM_Financial_DAO_EntityFinancialAccount',
$all = TRUE,
$retrieve = 'entity_id',
$filter = NULL,
'account_relationship = 8'
);
$costFinancialType = array();
CRM_Core_PseudoConstant::populate(
$costFinancialType,
'CRM_Financial_DAO_EntityFinancialAccount',
$all = TRUE,
$retrieve = 'entity_id',
$filter = NULL,
'account_relationship = 7'
);
$productFinancialType = array_intersect($costFinancialType, $premiumFinancialType);
foreach ($financialType as $key => $financialTypeName) {
if (!in_array($key, $productFinancialType)) {
unset($financialType[$key]);
}
}
// Check permissioned financial types
CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialType, CRM_Core_Action::ADD);
if (count($financialType)) {
$this->assign('financialType', $financialType);
}
$this->add(
'select',
'financial_type_id',
ts('Financial Type'),
array('' => ts('- select -')) + $financialType
);
$this->addRule('weight', ts('Please enter integer value for weight'), 'integer');
$session->pushUserContext(CRM_Utils_System::url($urlParams, 'action=update&reset=1&id=' . $this->_id));
if ($this->_single) {
$this->addButtons(array(
array(
'type' => 'next',
'name' => ts('Save'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;',
'isDefault' => TRUE,
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
)
);
}
else {
parent::buildQuickForm();
}
}
/**
* Process the form.
*/
public function postProcess() {
// get the submitted form values.
$params = $this->controller->exportValues($this->_name);
$urlParams = 'civicrm/admin/contribute/premium';
if ($this->_action & CRM_Core_Action::PREVIEW) {
$session = CRM_Core_Session::singleton();
$url = CRM_Utils_System::url($urlParams, 'reset=1&action=update&id=' . $this->_id);
$single = $session->get('singleForm');
CRM_Utils_System::redirect($url);
return;
}
if ($this->_action & CRM_Core_Action::DELETE) {
$session = CRM_Core_Session::singleton();
$url = CRM_Utils_System::url($urlParams, 'reset=1&action=update&id=' . $this->_id);
$dao = new CRM_Contribute_DAO_PremiumsProduct();
$dao->id = $this->_pid;
$dao->delete();
CRM_Core_Session::setStatus(ts('Selected Premium Product has been removed from this Contribution Page.'), ts('Saved'), 'success');
CRM_Utils_System::redirect($url);
}
else {
$session = CRM_Core_Session::singleton();
$url = CRM_Utils_System::url($urlParams, 'reset=1&action=update&id=' . $this->_id);
if ($this->_pid) {
$params['id'] = $this->_pid;
}
$dao = new CRM_Contribute_DAO_Premium();
$dao->entity_table = 'civicrm_contribution_page';
$dao->entity_id = $this->_id;
$dao->find(TRUE);
$premiumID = $dao->id;
$params['premiums_id'] = $premiumID;
$oldWeight = NULL;
if ($this->_pid) {
$oldWeight = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_PremiumsProduct', $this->_pid, 'weight', 'id');
}
// updateOtherWeights needs to filter on premiums_id
$filter = array('premiums_id' => $params['premiums_id']);
$params['weight'] = CRM_Utils_Weight::updateOtherWeights('CRM_Contribute_DAO_PremiumsProduct', $oldWeight, $params['weight'], $filter);
$dao = new CRM_Contribute_DAO_PremiumsProduct();
$dao->copyValues($params);
$dao->save();
CRM_Utils_System::redirect($url);
}
}
/**
* Return a descriptive name for the page, used in wizard header
*
* @return string
*/
public function getTitle() {
return ts('Add Premium to Contribution Page');
}
}

View file

@ -0,0 +1,843 @@
<?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
*/
/**
* form to process actions on the group aspect of Custom Data
*/
class CRM_Contribute_Form_ContributionPage_Amount extends CRM_Contribute_Form_ContributionPage {
/**
* Contribution amount block.
*
* @var array
*/
protected $_amountBlock = array();
/**
* Constants for number of options for data types of multiple option.
*/
const NUM_OPTION = 11;
/**
* Build the form object.
*/
public function buildQuickForm() {
// do u want to allow a free form text field for amount
$this->addElement('checkbox', 'is_allow_other_amount', ts('Allow other amounts'), NULL, array('onclick' => "minMax(this);showHideAmountBlock( this, 'is_allow_other_amount' );"));
$this->add('text', 'min_amount', ts('Minimum Amount'), array('size' => 8, 'maxlength' => 8));
$this->addRule('min_amount', ts('Please enter a valid money value (e.g. %1).', array(1 => CRM_Utils_Money::format('9.99', ' '))), 'money');
$this->add('text', 'max_amount', ts('Maximum Amount'), array('size' => 8, 'maxlength' => 8));
$this->addRule('max_amount', ts('Please enter a valid money value (e.g. %1).', array(1 => CRM_Utils_Money::format('99.99', ' '))), 'money');
//CRM-12055
$this->add('text', 'amount_label', ts('Contribution Amounts Label'));
$default = array($this->createElement('radio', NULL, NULL, NULL, 0));
$this->add('hidden', "price_field_id", '', array('id' => "price_field_id"));
$this->add('hidden', "price_field_other", '', array('id' => "price_field_option"));
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 (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', 'amount_block_is_active', ts('Contribution Amounts section enabled'), NULL, array('onclick' => "showHideAmountBlock( this, 'amount_block_is_active' );"));
$this->addElement('checkbox', 'is_monetary', ts('Execute real-time monetary transactions'));
$paymentProcessors = CRM_Financial_BAO_PaymentProcessor::getAllPaymentProcessors('live');
$recurringPaymentProcessor = $futurePaymentProcessor = $paymentProcessor = array();
if (!empty($paymentProcessors)) {
foreach ($paymentProcessors as $id => $processor) {
if ($id != 0) {
$paymentProcessor[$id] = $processor['name'];
}
if (CRM_Utils_Array::value('is_recur', $processor)) {
$recurringPaymentProcessor[] = $id;
}
if (CRM_Utils_Array::value('object', $processor) && $processor['object']->supports('FutureRecurStartDate')) {
$futurePaymentProcessor[] = $id;
}
}
}
if (count($recurringPaymentProcessor)) {
$this->assign('recurringPaymentProcessor', $recurringPaymentProcessor);
}
if (count($futurePaymentProcessor)) {
$this->assign('futurePaymentProcessor', $futurePaymentProcessor);
}
if (count($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/>')
);
//check if selected payment processor supports recurring payment
if (!empty($recurringPaymentProcessor)) {
$this->addElement('checkbox', 'is_recur', ts('Recurring Contributions'), NULL,
array('onclick' => "showHideByValue('is_recur',true,'recurFields','table-row','radio',false);")
);
$this->addCheckBox('recur_frequency_unit', ts('Supported recurring units'),
CRM_Core_OptionGroup::values('recur_frequency_units', FALSE, FALSE, TRUE),
NULL, NULL, NULL, NULL,
array('&nbsp;&nbsp;', '&nbsp;&nbsp;', '&nbsp;&nbsp;', '<br/>'), TRUE
);
$this->addElement('checkbox', 'is_recur_interval', ts('Support recurring intervals'));
$this->addElement('checkbox', 'is_recur_installments', ts('Offer installments'));
}
// add pay later options
$this->addElement('checkbox', 'is_pay_later', ts('Pay later option'), NULL);
$this->addElement('textarea', 'pay_later_text', ts('Pay later label'),
CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionPage', 'pay_later_text'),
FALSE
);
$this->add('wysiwyg', 'pay_later_receipt', ts('Pay Later Instructions'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionPage', 'pay_later_receipt'));
$this->addElement('checkbox', 'is_billing_required', ts('Billing address required'));
//add partial payment options
// add price set fields
$price = CRM_Price_BAO_PriceSet::getAssoc(FALSE, 'CiviContribute');
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' => "showHideAmountBlock( this.value, 'price_set_id' );")
);
//CiviPledge fields.
$config = CRM_Core_Config::singleton();
if (in_array('CiviPledge', $config->enableComponents)) {
$this->assign('civiPledge', TRUE);
$this->addElement('checkbox', 'is_pledge_active', ts('Pledges'),
NULL, array('onclick' => "showHideAmountBlock( this, 'is_pledge_active' ); return showHideByValue('is_pledge_active',true,'pledgeFields','table-row','radio',false);")
);
$this->addCheckBox('pledge_frequency_unit', ts('Supported pledge frequencies'),
CRM_Core_OptionGroup::values('recur_frequency_units', FALSE, FALSE, TRUE),
NULL, NULL, NULL, NULL,
array('&nbsp;&nbsp;', '&nbsp;&nbsp;', '&nbsp;&nbsp;', '<br/>'), TRUE
);
$this->addElement('checkbox', 'is_pledge_interval', ts('Allow frequency intervals'));
$this->addElement('text', 'initial_reminder_day', ts('Send payment reminder'), array('size' => 3));
$this->addElement('text', 'max_reminders', ts('Send up to'), array('size' => 3));
$this->addElement('text', 'additional_reminder_day', ts('Send additional reminders'), array('size' => 3));
if (!empty($futurePaymentProcessor)) {
// CRM-18854
$this->addElement('checkbox', 'adjust_recur_start_date', ts('Adjust Recurring Start Date'), NULL,
array('onclick' => "showHideByValue('adjust_recur_start_date',true,'recurDefaults','table-row','radio',false);")
);
$this->addDate('pledge_calendar_date', ts('Specific Calendar Date'));
$month = CRM_Utils_Date::getCalendarDayOfMonth();
$this->add('select', 'pledge_calendar_month', ts('Specific day of Month'), $month);
$pledgeDefaults = array(
'contribution_date' => ts('Day of Contribution'),
'calendar_date' => ts('Specific Calendar Date'),
'calendar_month' => ts('Specific day of Month'),
);
$this->addRadio('pledge_default_toggle', ts('Recurring Contribution Start Date Default'), $pledgeDefaults, array('allowClear' => FALSE), '<br/><br/>');
$this->addElement('checkbox', 'is_pledge_start_date_visible', ts('Show Recurring Donation Start Date?'), NULL);
$this->addElement('checkbox', 'is_pledge_start_date_editable', ts('Allow Edits to Recurring Donation Start date?'), NULL);
}
}
//add currency element.
$this->addCurrency('currency', ts('Currency'));
$this->addFormRule(array('CRM_Contribute_Form_ContributionPage_Amount', 'formRule'), $this);
parent::buildQuickForm();
}
/**
* Set default values for the form. Note that in edit/view mode
* the default values are retrieved from the database
*
*
* @return array
*/
public function setDefaultValues() {
$defaults = parent::setDefaultValues();
if (empty($defaults['pay_later_text'])) {
$defaults['pay_later_text'] = ts('I will send payment by check');
}
if (!empty($defaults['amount_block_is_active'])) {
if ($priceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $this->_id, NULL)) {
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 = $pFIDs = array();
$priceFieldParams = array('price_set_id' => $priceSetId);
$priceFields = CRM_Core_DAO::commonRetrieveAll('CRM_Price_DAO_PriceField', 'price_set_id', $priceSetId, $pFIDs, $return = array(
'html_type',
'name',
'is_active',
'label',
));
foreach ($priceFields as $priceField) {
if ($priceField['id'] && $priceField['html_type'] == 'Radio' && $priceField['name'] == 'contribution_amount') {
$defaults['price_field_id'] = $priceField['id'];
$priceFieldOptions = CRM_Price_BAO_PriceFieldValue::getValues($priceField['id'], $options, 'id', 1);
if (empty($priceFieldOptions)) {
continue;
}
$countRow = 0;
$defaults['amount_label'] = $priceField['label'];
foreach ($options as $optionId => $optionValue) {
$countRow++;
$defaults['value'][$countRow] = $optionValue['amount'];
$defaults['label'][$countRow] = CRM_Utils_Array::value('label', $optionValue);
$defaults['name'][$countRow] = CRM_Utils_Array::value('name', $optionValue);
$defaults['weight'][$countRow] = $optionValue['weight'];
$defaults["price_field_value"][$countRow] = $optionValue['id'];
if ($optionValue['is_default']) {
$defaults['default'] = $countRow;
}
}
}
elseif ($priceField['id'] && $priceField['html_type'] == 'Text' && $priceField['name'] = 'other_amount' && $priceField['is_active']) {
$defaults['price_field_other'] = $priceField['id'];
if (!isset($defaults['amount_label'])) {
$defaults['amount_label'] = $priceField['label'];
}
}
}
}
}
if (empty($defaults['amount_label'])) {
$defaults['amount_label'] = ts('Contribution Amount');
}
if (!empty($defaults['value']) && is_array($defaults['value'])) {
// CRM-4038: fix value display
foreach ($defaults['value'] as & $amount) {
$amount = trim(CRM_Utils_Money::format($amount, ' '));
}
}
}
// fix the display of the monetary value, CRM-4038
if (isset($defaults['min_amount'])) {
$defaults['min_amount'] = CRM_Utils_Money::format($defaults['min_amount'], NULL, '%a');
}
if (isset($defaults['max_amount'])) {
$defaults['max_amount'] = CRM_Utils_Money::format($defaults['max_amount'], NULL, '%a');
}
if (!empty($defaults['payment_processor'])) {
$defaults['payment_processor'] = array_fill_keys(explode(CRM_Core_DAO::VALUE_SEPARATOR,
$defaults['payment_processor']
), '1');
}
return $defaults;
}
/**
* 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();
//as for separate membership payment we has to have
//contribution amount section enabled, hence to disable it need to
//check if separate membership payment enabled,
//if so disable first separate membership payment option
//then disable contribution amount section. CRM-3801,
$membershipBlock = new CRM_Member_DAO_MembershipBlock();
$membershipBlock->entity_table = 'civicrm_contribution_page';
$membershipBlock->entity_id = $self->_id;
$membershipBlock->is_active = 1;
$hasMembershipBlk = FALSE;
if ($membershipBlock->find(TRUE)) {
if (!empty($fields['amount_block_is_active']) &&
($setID = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $self->_id, NULL, 1))
) {
$extends = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $setID, 'extends');
if ($extends && $extends == CRM_Core_Component::getComponentID('CiviMember')) {
$errors['amount_block_is_active'] = ts('You cannot use a Membership Price Set when the Contribution Amounts section is enabled. Click the Memberships tab above, and select your Membership Price Set on that form. Membership Price Sets may include additional fields for non-membership options that require an additional fee (e.g. magazine subscription) or an additional voluntary contribution.');
return $errors;
}
}
$hasMembershipBlk = TRUE;
if ($membershipBlock->is_separate_payment && empty($fields['amount_block_is_active'])) {
$errors['amount_block_is_active'] = ts('To disable Contribution Amounts section you need to first disable Separate Membership Payment option from Membership Settings.');
}
//CRM-16165, Don't allow reccuring contribution if membership block contain any renewable membership option
$membershipTypes = unserialize($membershipBlock->membership_types);
if (!empty($fields['is_recur']) && !empty($membershipTypes)) {
if (!$membershipBlock->is_separate_payment) {
$errors['is_recur'] = ts('You need to enable Separate Membership Payment when online contribution page is configured for both Membership and Recurring Contribution.');
}
elseif (count(array_filter($membershipTypes)) != 0) {
$errors['is_recur'] = ts('You cannot enable both Recurring Contributions and Auto-renew memberships on the same online contribution page.');
}
}
}
// CRM-18854 Check if recurring start date is in the future.
if (CRM_Utils_Array::value('pledge_calendar_date', $fields)) {
if (date('Ymd') > date('Ymd', strtotime($fields['pledge_calendar_date']))) {
$errors['pledge_calendar_date'] = ts('The recurring start date cannot be prior to the current date.');
}
}
//check for the amount label (mandatory)
if (!empty($fields['amount_block_is_active']) && empty($fields['price_set_id']) && empty($fields['amount_label'])) {
$errors['amount_label'] = ts('Please enter the contribution amount label.');
}
$minAmount = CRM_Utils_Array::value('min_amount', $fields);
$maxAmount = CRM_Utils_Array::value('max_amount', $fields);
if (!empty($minAmount) && !empty($maxAmount)) {
$minAmount = CRM_Utils_Rule::cleanMoney($minAmount);
$maxAmount = CRM_Utils_Rule::cleanMoney($maxAmount);
if ((float ) $minAmount > (float ) $maxAmount) {
$errors['min_amount'] = ts('Minimum Amount should be less than Maximum Amount');
}
}
if (isset($fields['is_pay_later'])) {
if (empty($fields['pay_later_text'])) {
$errors['pay_later_text'] = ts('Please enter the text for the \'pay later\' checkbox displayed on the contribution form.');
}
if (empty($fields['pay_later_receipt'])) {
$errors['pay_later_receipt'] = ts('Please enter the instructions to be sent to the contributor when they choose to \'pay later\'.');
}
}
// don't allow price set w/ membership signup, CRM-5095
if ($priceSetId = CRM_Utils_Array::value('price_set_id', $fields)) {
// don't allow price set w/ membership.
if ($hasMembershipBlk) {
$errors['price_set_id'] = ts('You cannot enable both a Contribution Price Set and Membership Signup on the same online contribution page.');
}
}
else {
if (isset($fields['is_recur'])) {
if (empty($fields['recur_frequency_unit'])) {
$errors['recur_frequency_unit'] = ts('At least one recurring frequency option needs to be checked.');
}
}
// validation for pledge fields.
if (!empty($fields['is_pledge_active'])) {
if (empty($fields['pledge_frequency_unit'])) {
$errors['pledge_frequency_unit'] = ts('At least one pledge frequency option needs to be checked.');
}
if (!empty($fields['is_recur'])) {
$errors['is_recur'] = ts('You cannot enable both Recurring Contributions AND Pledges on the same online contribution page.');
}
}
// If Contribution amount section is enabled, then
// Allow other amounts must be enabled OR the Fixed Contribution
// Contribution options must contain at least one set of values.
if (!empty($fields['amount_block_is_active'])) {
if (empty($fields['is_allow_other_amount']) &&
!$priceSetId
) {
//get the values of amount block
$values = CRM_Utils_Array::value('value', $fields);
$isSetRow = FALSE;
for ($i = 1; $i < self::NUM_OPTION; $i++) {
if ((isset($values[$i]) && (strlen(trim($values[$i])) > 0))) {
$isSetRow = TRUE;
}
}
if (!$isSetRow) {
$errors['amount_block_is_active'] = ts('If you want to enable the \'Contribution Amounts section\', you need to either \'Allow Other Amounts\' and/or enter at least one row in the \'Fixed Contribution Amounts\' table.');
}
}
}
}
if (!empty($fields['payment_processor']) && $financialType = CRM_Contribute_BAO_Contribution::validateFinancialType($self->_defaultValues['financial_type_id'])) {
$errors['payment_processor'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
}
if (!empty($fields['is_recur_interval'])) {
foreach (array_keys($fields['payment_processor']) as $paymentProcessorID) {
$paymentProcessorTypeId = CRM_Core_DAO::getFieldValue(
'CRM_Financial_DAO_PaymentProcessor',
$paymentProcessorID,
'payment_processor_type_id'
);
$paymentProcessorType = CRM_Core_PseudoConstant::paymentProcessorType(FALSE, $paymentProcessorTypeId, 'name');
}
}
return $errors;
}
/**
* Process the form.
*/
public function postProcess() {
// get the submitted form values.
$params = $this->controller->exportValues($this->_name);
//update 'is_billing_required'
if (empty($params['is_pay_later'])) {
$params['is_billing_required'] = 0;
}
if (array_key_exists('payment_processor', $params)) {
if (array_key_exists(CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessor', 'AuthNet',
'id', 'payment_processor_type_id'
),
CRM_Utils_Array::value('payment_processor', $params)
)) {
CRM_Core_Session::setStatus(ts(' Please note that the Authorize.net payment processor only allows recurring contributions and auto-renew memberships with payment intervals from 7-365 days or 1-12 months (i.e. not greater than 1 year).'), '', 'alert');
}
}
// check for price set.
$priceSetID = CRM_Utils_Array::value('price_set_id', $params);
// get required fields.
$fields = array(
'id' => $this->_id,
'is_recur' => FALSE,
'min_amount' => "null",
'max_amount' => "null",
'is_monetary' => FALSE,
'is_pay_later' => FALSE,
'is_billing_required' => FALSE,
'is_recur_interval' => FALSE,
'is_recur_installments' => FALSE,
'recur_frequency_unit' => "null",
'default_amount_id' => "null",
'is_allow_other_amount' => FALSE,
'amount_block_is_active' => FALSE,
);
$resetFields = array();
if ($priceSetID) {
$resetFields = array('min_amount', 'max_amount', 'is_allow_other_amount');
}
if (empty($params['is_recur'])) {
$resetFields = array_merge($resetFields, array('is_recur_interval', 'recur_frequency_unit'));
}
foreach ($fields as $field => $defaultVal) {
$val = CRM_Utils_Array::value($field, $params, $defaultVal);
if (in_array($field, $resetFields)) {
$val = $defaultVal;
}
if (in_array($field, array(
'min_amount',
'max_amount',
))) {
$val = CRM_Utils_Rule::cleanMoney($val);
}
$params[$field] = $val;
}
if ($params['is_recur']) {
$params['recur_frequency_unit'] = implode(CRM_Core_DAO::VALUE_SEPARATOR,
array_keys($params['recur_frequency_unit'])
);
$params['is_recur_interval'] = CRM_Utils_Array::value('is_recur_interval', $params, FALSE);
$params['is_recur_installments'] = CRM_Utils_Array::value('is_recur_installments', $params, FALSE);
}
if (CRM_Utils_Array::value('adjust_recur_start_date', $params)) {
$fieldValue = '';
$pledgeDateFields = array(
'calendar_date' => 'pledge_calendar_date',
'calendar_month' => 'pledge_calendar_month',
);
if ($params['pledge_default_toggle'] == 'contribution_date') {
$fieldValue = json_encode(array('contribution_date' => date('m/d/Y')));
}
else {
foreach ($pledgeDateFields as $key => $pledgeDateField) {
if (CRM_Utils_Array::value($pledgeDateField, $params) && $params['pledge_default_toggle'] == $key) {
$fieldValue = json_encode(array($key => $params[$pledgeDateField]));
break;
}
}
}
$params['pledge_start_date'] = $fieldValue;
}
else {
$params['pledge_start_date'] = '';
$params['adjust_recur_start_date'] = 0;
$params['is_pledge_start_date_visible'] = 0;
$params['is_pledge_start_date_editable'] = 0;
}
if (!CRM_Utils_Array::value('is_pledge_start_date_visible', $params)) {
$params['is_pledge_start_date_visible'] = 0;
}
if (!CRM_Utils_Array::value('is_pledge_start_date_editable', $params)) {
$params['is_pledge_start_date_editable'] = 0;
}
if (array_key_exists('payment_processor', $params) &&
!CRM_Utils_System::isNull($params['payment_processor'])
) {
$params['payment_processor'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($params['payment_processor']));
}
else {
$params['payment_processor'] = 'null';
}
$contributionPage = CRM_Contribute_BAO_ContributionPage::create($params);
$contributionPageID = $contributionPage->id;
// prepare for data cleanup.
$deleteAmountBlk = $deletePledgeBlk = $deletePriceSet = FALSE;
if ($this->_priceSetID) {
$deletePriceSet = TRUE;
}
if ($this->_pledgeBlockID) {
$deletePledgeBlk = TRUE;
}
if (!empty($this->_amountBlock)) {
$deleteAmountBlk = TRUE;
}
if ($contributionPageID) {
if (!empty($params['amount_block_is_active'])) {
// handle price set.
if ($priceSetID) {
// add/update price set.
$deletePriceSet = FALSE;
if (!empty($params['price_field_id']) || !empty($params['price_field_other'])) {
$deleteAmountBlk = TRUE;
}
CRM_Price_BAO_PriceSet::addTo('civicrm_contribution_page', $contributionPageID, $priceSetID);
}
else {
$deletePriceSet = FALSE;
// process contribution amount block
$deleteAmountBlk = FALSE;
$labels = CRM_Utils_Array::value('label', $params);
$values = CRM_Utils_Array::value('value', $params);
$default = CRM_Utils_Array::value('default', $params);
$options = array();
for ($i = 1; $i < self::NUM_OPTION; $i++) {
if (isset($values[$i]) &&
(strlen(trim($values[$i])) > 0)
) {
$options[] = array(
'label' => trim($labels[$i]),
'value' => CRM_Utils_Rule::cleanMoney(trim($values[$i])),
'weight' => $i,
'is_active' => 1,
'is_default' => $default == $i,
);
}
}
/* || !empty($params['price_field_value']) || CRM_Utils_Array::value( 'price_field_other', $params )*/
if (!empty($options) || !empty($params['is_allow_other_amount'])) {
$fieldParams['is_quick_config'] = 1;
$noContriAmount = NULL;
$usedPriceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $this->_id, 3);
if (!(!empty($params['price_field_id']) || !empty($params['price_field_other'])) && !$usedPriceSetId) {
$pageTitle = strtolower(CRM_Utils_String::munge($this->_values['title'], '_', 245));
$setParams['title'] = $this->_values['title'];
if (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceSet', $pageTitle, 'id', 'name')) {
$setParams['name'] = $pageTitle;
}
elseif (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceSet', $pageTitle . '_' . $this->_id, 'id', 'name')) {
$setParams['name'] = $pageTitle . '_' . $this->_id;
}
else {
$timeSec = explode(".", microtime(TRUE));
$setParams['name'] = $pageTitle . '_' . date('is', $timeSec[0]) . $timeSec[1];
}
$setParams['is_quick_config'] = 1;
$setParams['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $this->_values);
$setParams['extends'] = CRM_Core_Component::getComponentID('CiviContribute');
$priceSet = CRM_Price_BAO_PriceSet::create($setParams);
$priceSetId = $priceSet->id;
}
elseif ($usedPriceSetId && empty($params['price_field_id'])) {
$priceSetId = $usedPriceSetId;
}
else {
if ($priceFieldId = CRM_Utils_Array::value('price_field_id', $params)) {
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]);
}
}
if (implode('', $params['price_field_value'])) {
$fieldParams['id'] = CRM_Utils_Array::value('price_field_id', $params);
$fieldParams['option_id'] = $params['price_field_value'];
}
else {
$noContriAmount = 0;
CRM_Price_BAO_PriceField::setIsActive($priceFieldId, '0');
}
}
else {
$priceFieldId = CRM_Utils_Array::value('price_field_other', $params);
}
$priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $priceFieldId, 'price_set_id');
}
CRM_Price_BAO_PriceSet::addTo('civicrm_contribution_page', $this->_id, $priceSetId);
if (!empty($options)) {
$editedFieldParams = array(
'price_set_id' => $priceSetId,
'name' => 'contribution_amount',
);
$editedResults = array();
$noContriAmount = 1;
CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
if (empty($editedResults['id'])) {
$fieldParams['name'] = strtolower(CRM_Utils_String::munge("Contribution Amount", '_', 245));
}
else {
$fieldParams['id'] = CRM_Utils_Array::value('id', $editedResults);
}
$fieldParams['price_set_id'] = $priceSetId;
$fieldParams['is_active'] = 1;
$fieldParams['weight'] = 2;
if (!empty($params['is_allow_other_amount'])) {
$fieldParams['is_required'] = 0;
}
else {
$fieldParams['is_required'] = 1;
}
$fieldParams['label'] = $params['amount_label'];
$fieldParams['html_type'] = 'Radio';
$fieldParams['option_label'] = $params['label'];
$fieldParams['option_amount'] = $params['value'];
$fieldParams['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $this->_values);
foreach ($options as $value) {
$fieldParams['option_weight'][$value['weight']] = $value['weight'];
}
$fieldParams['default_option'] = $params['default'];
$priceField = CRM_Price_BAO_PriceField::create($fieldParams);
}
if (!empty($params['is_allow_other_amount']) && empty($params['price_field_other'])) {
$editedFieldParams = array(
'price_set_id' => $priceSetId,
'name' => 'other_amount',
);
$editedResults = array();
CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
if (!$priceFieldID = CRM_Utils_Array::value('id', $editedResults)) {
$fieldParams = array(
'name' => 'other_amount',
'label' => ts('Other Amount'),
'price_set_id' => $priceSetId,
'html_type' => 'Text',
'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $this->_values),
'is_display_amounts' => 0,
'weight' => 3,
);
$fieldParams['option_weight'][1] = 1;
$fieldParams['option_amount'][1] = 1;
if (!$noContriAmount) {
$fieldParams['is_required'] = 1;
$fieldParams['option_label'][1] = $fieldParams['label'] = $params['amount_label'];
}
else {
$fieldParams['is_required'] = 0;
$fieldParams['option_label'][1] = $fieldParams['label'] = ts('Other Amount');
}
$priceField = CRM_Price_BAO_PriceField::create($fieldParams);
}
else {
if (empty($editedResults['is_active'])) {
$fieldParams = $editedResults;
if (!$noContriAmount) {
$priceFieldValueID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldID, 'id', 'price_field_id');
CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldValueID, 'label', $params['amount_label']);
$fieldParams = array(
'is_required' => 1,
'label' => $params['amount_label'],
'id' => $priceFieldID,
);
}
$fieldParams['is_active'] = 1;
$priceField = CRM_Price_BAO_PriceField::add($fieldParams);
}
}
}
elseif (empty($params['is_allow_other_amount']) && !empty($params['price_field_other'])) {
CRM_Price_BAO_PriceField::setIsActive($params['price_field_other'], '0');
}
elseif ($priceFieldID = CRM_Utils_Array::value('price_field_other', $params)) {
$priceFieldValueID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldID, 'id', 'price_field_id');
if (!$noContriAmount) {
$fieldParams = array(
'is_required' => 1,
'label' => $params['amount_label'],
'id' => $priceFieldID,
);
CRM_Price_BAO_PriceField::add($fieldParams);
CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldValueID, 'label', $params['amount_label']);
}
else {
CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceField', $priceFieldID, 'is_required', 0);
CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldValueID, 'label', ts('Other Amount'));
}
}
}
if (!empty($params['is_pledge_active'])) {
$deletePledgeBlk = FALSE;
$pledgeBlockParams = array(
'entity_id' => $contributionPageID,
'entity_table' => ts('civicrm_contribution_page'),
);
if ($this->_pledgeBlockID) {
$pledgeBlockParams['id'] = $this->_pledgeBlockID;
}
$pledgeBlock = array(
'pledge_frequency_unit',
'max_reminders',
'initial_reminder_day',
'additional_reminder_day',
'pledge_start_date',
'is_pledge_start_date_visible',
'is_pledge_start_date_editable',
);
foreach ($pledgeBlock as $key) {
$pledgeBlockParams[$key] = CRM_Utils_Array::value($key, $params);
}
$pledgeBlockParams['is_pledge_interval'] = CRM_Utils_Array::value('is_pledge_interval',
$params, FALSE
);
$pledgeBlockParams['pledge_start_date'] = CRM_Utils_Array::value('pledge_start_date',
$params, FALSE
);
// create pledge block.
CRM_Pledge_BAO_PledgeBlock::create($pledgeBlockParams);
}
}
}
else {
if (!empty($params['price_field_id']) || !empty($params['price_field_other'])) {
$usedPriceSetId = CRM_Price_BAO_PriceSet::getFor('civicrm_contribution_page', $this->_id, 3);
if ($usedPriceSetId) {
if (!empty($params['price_field_id'])) {
CRM_Price_BAO_PriceField::setIsActive($params['price_field_id'], '0');
}
if (!empty($params['price_field_other'])) {
CRM_Price_BAO_PriceField::setIsActive($params['price_field_other'], '0');
}
}
else {
$deleteAmountBlk = TRUE;
$deletePriceSet = TRUE;
}
}
}
// delete pledge block.
if ($deletePledgeBlk) {
CRM_Pledge_BAO_PledgeBlock::deletePledgeBlock($this->_pledgeBlockID);
}
// delete previous price set.
if ($deletePriceSet) {
CRM_Price_BAO_PriceSet::removeFrom('civicrm_contribution_page', $contributionPageID);
}
if ($deleteAmountBlk) {
$priceField = !empty($params['price_field_id']) ? $params['price_field_id'] : CRM_Utils_Array::value('price_field_other', $params);
if ($priceField) {
$priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $priceField, 'price_set_id');
CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
}
}
}
parent::endPostProcess();
}
/**
* Return a descriptive name for the page, used in wizard header
*
* @return string
*/
public function getTitle() {
return ts('Amounts');
}
}

View file

@ -0,0 +1,208 @@
<?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
*/
/**
* Form to process actions on the group aspect of Custom Data.
*/
class CRM_Contribute_Form_ContributionPage_Custom extends CRM_Contribute_Form_ContributionPage {
/**
* Build the form object.
*/
public function buildQuickForm() {
// Register 'contact_1' model
$entities = array();
$entities[] = array('entity_name' => 'contact_1', 'entity_type' => 'IndividualModel');
$allowCoreTypes = array_merge(array('Contact', 'Individual'), CRM_Contact_BAO_ContactType::subTypes('Individual'));
$allowSubTypes = array();
// Register 'contribution_1'
$financialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $this->_id, 'financial_type_id');
$allowCoreTypes[] = 'Contribution';
//CRM-15427
$allowSubTypes['ContributionType'] = array($financialTypeId);
$entities[] = array(
'entity_name' => 'contribution_1',
'entity_type' => 'ContributionModel',
'entity_sub_type' => '*',
);
// If applicable, register 'membership_1'
$member = CRM_Member_BAO_Membership::getMembershipBlock($this->_id);
if ($member && $member['is_active']) {
//CRM-15427
$entities[] = array(
'entity_name' => 'membership_1',
'entity_type' => 'MembershipModel',
'entity_sub_type' => '*',
);
$allowCoreTypes[] = 'Membership';
$allowSubTypes['MembershipType'] = explode(',', $member['membership_types']);
}
//CRM-15427
$this->addProfileSelector('custom_pre_id', ts('Include Profile') . '<br />' . ts('(top of page)'), $allowCoreTypes, $allowSubTypes, $entities, TRUE);
$this->addProfileSelector('custom_post_id', ts('Include Profile') . '<br />' . ts('(bottom of page)'), $allowCoreTypes, $allowSubTypes, $entities, TRUE);
$this->addFormRule(array('CRM_Contribute_Form_ContributionPage_Custom', 'formRule'), $this);
parent::buildQuickForm();
}
/**
* Set default values for the form.
*
* Note that in edit/view mode the default values are retrieved from the database.
*/
public function setDefaultValues() {
$defaults = parent::setDefaultValues();
$defaults['custom_pre_id'] = $this->_values['custom_pre_id'];
$defaults['custom_post_id'] = $this->_values['custom_post_id'];
return $defaults;
}
/**
* Process the form.
*/
public function postProcess() {
// get the submitted form values.
$params = $this->controller->exportValues($this->_name);
if ($this->_action & CRM_Core_Action::UPDATE) {
$params['id'] = $this->_id;
}
$transaction = new CRM_Core_Transaction();
// also update uf join table
$ufJoinParams = array(
'is_active' => 1,
'module' => 'CiviContribute',
'entity_table' => 'civicrm_contribution_page',
'entity_id' => $this->_id,
);
// first delete all past entries
CRM_Core_BAO_UFJoin::deleteAll($ufJoinParams);
if (!empty($params['custom_pre_id'])) {
$ufJoinParams['weight'] = 1;
$ufJoinParams['uf_group_id'] = $params['custom_pre_id'];
CRM_Core_BAO_UFJoin::create($ufJoinParams);
}
unset($ufJoinParams['id']);
if (!empty($params['custom_post_id'])) {
$ufJoinParams['weight'] = 2;
$ufJoinParams['uf_group_id'] = $params['custom_post_id'];
CRM_Core_BAO_UFJoin::create($ufJoinParams);
}
$transaction->commit();
parent::endPostProcess();
}
/**
* Return a descriptive name for the page, used in wizard header
*
* @return string
*/
public function getTitle() {
return ts('Include Profiles');
}
/**
* Global form rule.
*
* @param array $fields
* The input form values.
*
* @param $files
* @param object $form
*
* @return bool|array
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $form) {
$errors = array();
$preProfileType = $postProfileType = NULL;
// for membership profile make sure Membership section is enabled
// get membership section for this contribution page
$dao = new CRM_Member_DAO_MembershipBlock();
$dao->entity_table = 'civicrm_contribution_page';
$dao->entity_id = $form->_id;
$membershipEnable = FALSE;
if ($dao->find(TRUE) && $dao->is_active) {
$membershipEnable = TRUE;
}
if ($fields['custom_pre_id']) {
$preProfileType = CRM_Core_BAO_UFField::getProfileType($fields['custom_pre_id']);
}
if ($fields['custom_post_id']) {
$postProfileType = CRM_Core_BAO_UFField::getProfileType($fields['custom_post_id']);
}
$errorMsg = ts('You must enable the Membership Block for this Contribution Page if you want to include a Profile with Membership fields.');
if (($preProfileType == 'Membership') && !$membershipEnable) {
$errors['custom_pre_id'] = $errorMsg;
}
if (($postProfileType == 'Membership') && !$membershipEnable) {
$errors['custom_post_id'] = $errorMsg;
}
$behalf = (!empty($form->_values['onbehalf_profile_id'])) ? $form->_values['onbehalf_profile_id'] : NULL;
if ($fields['custom_pre_id']) {
$errorMsg = ts('You should move the membership related fields in the "On Behalf" profile for this Contribution Page');
if ($preProfileType == 'Membership' && $behalf) {
$errors['custom_pre_id'] = isset($errors['custom_pre_id']) ? $errors['custom_pre_id'] . $errorMsg : $errorMsg;
}
}
if ($fields['custom_post_id']) {
$errorMsg = ts('You should move the membership related fields in the "On Behalf" profile for this Contribution Page');
if ($postProfileType == 'Membership' && $behalf) {
$errors['custom_post_id'] = isset($errors['custom_post_id']) ? $errors['custom_post_id'] . $errorMsg : $errorMsg;
}
}
return empty($errors) ? TRUE : $errors;
}
}

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
*/
/**
* This class is to build the form for Deleting Group.
*/
class CRM_Contribute_Form_ContributionPage_Delete extends CRM_Contribute_Form_ContributionPage {
/**
* Page title.
*
* @var string
*/
protected $_title;
/**
* Check if there are any related contributions.
*/
protected $_relatedContributions;
/**
* Set variables up before form is built.
*/
public function preProcess() {
//Check if there are contributions related to Contribution Page
parent::preProcess();
//check for delete
if (!CRM_Core_Permission::checkActionPermission('CiviContribute', $this->_action)) {
CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
}
$dao = new CRM_Contribute_DAO_Contribution();
$dao->contribution_page_id = $this->_id;
if ($dao->find(TRUE)) {
$this->_relatedContributions = TRUE;
$this->assign('relatedContributions', TRUE);
}
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->_title = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $this->_id, 'title');
$this->assign('title', $this->_title);
//if there are contributions related to Contribution Page
//then onle cancel button is displayed
$buttons = array();
if (!$this->_relatedContributions) {
$buttons[] = array(
'type' => 'next',
'name' => ts('Delete Contribution Page'),
'isDefault' => TRUE,
);
}
$buttons[] = array(
'type' => 'cancel',
'name' => ts('Cancel'),
);
$this->addButtons($buttons);
}
/**
* Process the form when submitted.
*/
public function postProcess() {
$transaction = new CRM_Core_Transaction();
// first delete the join entries associated with this contribution page
$dao = new CRM_Core_DAO_UFJoin();
$params = array(
'entity_table' => 'civicrm_contribution_page',
'entity_id' => $this->_id,
);
$dao->copyValues($params);
$dao->delete();
//next delete the membership block fields
$dao = new CRM_Member_DAO_MembershipBlock();
$dao->entity_table = 'civicrm_contribution_page';
$dao->entity_id = $this->_id;
$dao->delete();
//next delete the pcp block fields
$dao = new CRM_PCP_DAO_PCPBlock();
$dao->entity_table = 'civicrm_contribution_page';
$dao->entity_id = $this->_id;
$dao->delete();
// need to delete premiums. CRM-4586
CRM_Contribute_BAO_Premium::deletePremium($this->_id);
// price set cleanup, CRM-5527
CRM_Price_BAO_PriceSet::removeFrom('civicrm_contribution_page', $this->_id);
// finally delete the contribution page
$dao = new CRM_Contribute_DAO_ContributionPage();
$dao->id = $this->_id;
$dao->delete();
$transaction->commit();
CRM_Core_Session::setStatus(ts("The contribution page '%1' has been deleted.", array(1 => $this->_title)), ts('Deleted'), 'success');
}
}

View file

@ -0,0 +1,158 @@
<?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
*/
/**
* Form to process actions on Premiums.
*/
class CRM_Contribute_Form_ContributionPage_Premium extends CRM_Contribute_Form_ContributionPage {
/**
* Set default values for the form.
*/
public function setDefaultValues() {
$defaults = array();
if (isset($this->_id)) {
$dao = new CRM_Contribute_DAO_Premium();
$dao->entity_table = 'civicrm_contribution_page';
$dao->entity_id = $this->_id;
$dao->find(TRUE);
CRM_Core_DAO::storeValues($dao, $defaults);
}
return $defaults;
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Premium');
$this->addElement('checkbox', 'premiums_active', ts('Premiums Section Enabled?'), NULL);
$this->addElement('text', 'premiums_intro_title', ts('Title'), $attributes['premiums_intro_title']);
$this->add('textarea', 'premiums_intro_text', ts('Introductory Message'), 'rows=5, cols=50');
$this->add('text', 'premiums_contact_email', ts('Contact Email') . ' ', $attributes['premiums_contact_email']);
$this->addRule('premiums_contact_email', ts('Please enter a valid email address.') . ' ', 'email');
$this->add('text', 'premiums_contact_phone', ts('Contact Phone'), $attributes['premiums_contact_phone']);
$this->addRule('premiums_contact_phone', ts('Please enter a valid phone number.'), 'phone');
$this->addElement('checkbox', 'premiums_display_min_contribution', ts('Display Minimum Contribution Amount?'));
// CRM-10999 Control label and position for No Thank-you radio button
$this->add('text', 'premiums_nothankyou_label', ts('No Thank-you Label'), $attributes['premiums_nothankyou_label']);
$positions = array(1 => ts('Before Premiums'), 2 => ts('After Premiums'));
$this->add('select', 'premiums_nothankyou_position', ts('No Thank-you Option'), $positions);
$showForm = TRUE;
if ($this->_single) {
if ($this->_id) {
$daoPremium = new CRM_Contribute_DAO_Premium();
$daoPremium->entity_id = $this->_id;
$daoPremium->entity_table = 'civicrm_contribution_page';
$daoPremium->premiums_active = 1;
if ($daoPremium->find(TRUE)) {
$showForm = FALSE;
}
}
}
$this->assign('showForm', $showForm);
parent::buildQuickForm();
$this->addFormRule(array('CRM_Contribute_Form_ContributionPage_Premium', 'formRule'), $this);
$premiumPage = new CRM_Contribute_Page_Premium();
$premiumPage->browse();
}
/**
* Validation.
*
* @param array $params
* (ref.) an assoc array of name/value pairs.
*
* @return bool|array
* mixed true or array of errors
*/
public static function formRule($params) {
$errors = array();
if (!empty($params['premiums_active'])) {
if (empty($params['premiums_nothankyou_label'])) {
$errors['premiums_nothankyou_label'] = ts('No Thank-you Label is a required field.');
}
}
return empty($errors) ? TRUE : $errors;
}
/**
* Process the form.
*/
public function postProcess() {
// get the submitted form values.
$params = $this->controller->exportValues($this->_name);
// we do this in case the user has hit the forward/back button
$dao = new CRM_Contribute_DAO_Premium();
$dao->entity_table = 'civicrm_contribution_page';
$dao->entity_id = $this->_id;
$dao->find(TRUE);
$premiumID = $dao->id;
if ($premiumID) {
$params['id'] = $premiumID;
}
$params['premiums_active'] = CRM_Utils_Array::value('premiums_active', $params, FALSE);
$params['premiums_display_min_contribution'] = CRM_Utils_Array::value('premiums_display_min_contribution', $params, FALSE);
$params['entity_table'] = 'civicrm_contribution_page';
$params['entity_id'] = $this->_id;
$dao = new CRM_Contribute_DAO_Premium();
$dao->copyValues($params);
$dao->save();
parent::endPostProcess();
}
/**
* Return a descriptive name for the page, used in wizard header
*
* @return string
*/
public function getTitle() {
return ts('Premiums');
}
}

View file

@ -0,0 +1,427 @@
<?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
*/
class CRM_Contribute_Form_ContributionPage_Settings extends CRM_Contribute_Form_ContributionPage {
/**
* Set variables up before form is built.
*/
public function preProcess() {
parent::preProcess();
}
/**
* Set default values for the form.
*/
public function setDefaultValues() {
$defaults = parent::setDefaultValues();
$soft_credit_types = CRM_Core_OptionGroup::values('soft_credit_type', TRUE, FALSE, FALSE, NULL, 'name');
if ($this->_id) {
$title = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage',
$this->_id,
'title'
);
CRM_Utils_System::setTitle(ts('Title and Settings') . " ($title)");
foreach (array('on_behalf', 'soft_credit') as $module) {
$ufJoinDAO = new CRM_Core_DAO_UFJoin();
$ufJoinDAO->module = $module;
$ufJoinDAO->entity_id = $this->_id;
$ufJoinDAO->entity_table = 'civicrm_contribution_page';
if ($ufJoinDAO->find(TRUE)) {
$jsonData = CRM_Contribute_BAO_ContributionPage::formatModuleData($ufJoinDAO->module_data, TRUE, $module);
if ($module == 'soft_credit') {
$defaults['honoree_profile'] = $ufJoinDAO->uf_group_id;
$defaults = array_merge($defaults, $jsonData);
$defaults['honor_block_is_active'] = $ufJoinDAO->is_active;
}
else {
$defaults['onbehalf_profile_id'] = $ufJoinDAO->uf_group_id;
$defaults = array_merge($defaults, $jsonData);
$defaults['is_organization'] = $ufJoinDAO->is_active;
}
}
else {
if ($module == 'soft_credit') {
$ufGroupDAO = new CRM_Core_DAO_UFGroup();
$ufGroupDAO->name = 'honoree_individual';
if ($ufGroupDAO->find(TRUE)) {
$defaults['honoree_profile'] = $ufGroupDAO->id;
}
$defaults['soft_credit_types'] = array(
CRM_Utils_Array::value('in_honor_of', $soft_credit_types),
CRM_Utils_Array::value('in_memory_of', $soft_credit_types),
);
}
else {
$ufGroupDAO = new CRM_Core_DAO_UFGroup();
$ufGroupDAO->name = 'on_behalf_organization';
if ($ufGroupDAO->find(TRUE)) {
$defaults['onbehalf_profile_id'] = $ufGroupDAO->id;
}
$defaults['for_organization'] = ts('I am contributing on behalf of an organization.');
$defaults['is_for_organization'] = 1;
}
}
}
}
else {
$ufGroupDAO = new CRM_Core_DAO_UFGroup();
$ufGroupDAO->name = 'honoree_individual';
if ($ufGroupDAO->find(TRUE)) {
$defaults['honoree_profile'] = $ufGroupDAO->id;
}
$defaults['soft_credit_types'] = array(
CRM_Utils_Array::value('in_honor_of', $soft_credit_types),
CRM_Utils_Array::value('in_memory_of', $soft_credit_types),
);
}
return $defaults;
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->_first = TRUE;
$attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionPage');
// financial Type
CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, CRM_Core_Action::ADD);
$financialOptions = array(
'options' => $financialTypes,
);
if (!CRM_Core_Permission::check('administer CiviCRM Financial Types')) {
$financialOptions['context'] = 'search';
}
$this->addSelect('financial_type_id', $financialOptions, TRUE);
// name
$this->add('text', 'title', ts('Title'), $attributes['title'], TRUE);
//CRM-7362 --add campaigns.
CRM_Campaign_BAO_Campaign::addCampaign($this, CRM_Utils_Array::value('campaign_id', $this->_values));
$this->add('wysiwyg', 'intro_text', ts('Introductory Message'), $attributes['intro_text']);
$this->add('wysiwyg', 'footer_text', ts('Footer Message'), $attributes['footer_text']);
//Register schema which will be used for OnBehalOf and HonorOf profile Selector
CRM_UF_Page_ProfileEditor::registerSchemas(array('OrganizationModel', 'HouseholdModel'));
// is on behalf of an organization ?
$this->addElement('checkbox', 'is_organization', ts('Allow individuals to contribute and / or signup for membership on behalf of an organization?'), NULL, array('onclick' => "showHideByValue('is_organization',true,'for_org_text','table-row','radio',false);showHideByValue('is_organization',true,'for_org_option','table-row','radio',false);"));
//CRM-15787 - If applicable, register 'membership_1'
$member = CRM_Member_BAO_Membership::getMembershipBlock($this->_id);
$coreTypes = array('Contact', 'Organization');
$entities[] = array(
'entity_name' => array('contact_1'),
'entity_type' => 'OrganizationModel',
);
if ($member && $member['is_active']) {
$coreTypes[] = 'Membership';
$entities[] = array(
'entity_name' => array('membership_1'),
'entity_type' => 'MembershipModel',
);
}
$allowCoreTypes = array_merge($coreTypes, CRM_Contact_BAO_ContactType::subTypes('Organization'));
$allowSubTypes = array();
$this->addProfileSelector('onbehalf_profile_id', ts('Organization Profile'), $allowCoreTypes, $allowSubTypes, $entities);
$options = array();
$options[] = $this->createElement('radio', NULL, NULL, ts('Optional'), 1);
$options[] = $this->createElement('radio', NULL, NULL, ts('Required'), 2);
$this->addGroup($options, 'is_for_organization', '');
$this->add('textarea', 'for_organization', ts('On behalf of Label'), array('rows' => 2, 'cols' => 50));
// collect goal amount
$this->add('text', 'goal_amount', ts('Goal Amount'), array('size' => 8, 'maxlength' => 12));
$this->addRule('goal_amount', ts('Please enter a valid money value (e.g. %1).', array(1 => CRM_Utils_Money::format('99.99', ' '))), 'money');
// is confirmation page enabled?
$this->addElement('checkbox', 'is_confirm_enabled', ts('Use a confirmation page?'));
// is this page shareable through social media ?
$this->addElement('checkbox', 'is_share', ts('Allow sharing through social media?'));
// is this page active ?
$this->addElement('checkbox', 'is_active', ts('Is this Online Contribution Page Active?'));
// should the honor be enabled
$this->addElement('checkbox', 'honor_block_is_active', ts('Honoree Section Enabled'), NULL, array('onclick' => "showHonor()"));
$this->add('text', 'honor_block_title', ts('Honoree Section Title'), array('maxlength' => 255, 'size' => 45));
$this->add('textarea', 'honor_block_text', ts('Honoree Introductory Message'), array('rows' => 2, 'cols' => 50));
$this->addSelect('soft_credit_types', array(
'label' => ts('Honor Types'),
'entity' => 'ContributionSoft',
'field' => 'soft_credit_type_id',
'multiple' => TRUE,
'class' => 'huge',
));
$entities = array(
array(
'entity_name' => 'contact_1',
'entity_type' => 'IndividualModel',
),
);
$allowCoreTypes = array_merge(array(
'Contact',
'Individual',
'Organization',
'Household',
), CRM_Contact_BAO_ContactType::subTypes('Individual'));
$allowSubTypes = array();
$this->addProfileSelector('honoree_profile', ts('Honoree Profile'), $allowCoreTypes, $allowSubTypes, $entities);
if (!empty($this->_submitValues['honor_block_is_active'])) {
$this->addRule('soft_credit_types', ts('At least one value must be selected if Honor Section is active'), 'required');
$this->addRule('honoree_profile', ts('Please select a profile used for honoree'), 'required');
}
// add optional start and end dates
$this->addDateTime('start_date', ts('Start Date'));
$this->addDateTime('end_date', ts('End Date'));
$this->addFormRule(array('CRM_Contribute_Form_ContributionPage_Settings', 'formRule'), $this);
parent::buildQuickForm();
}
/**
* Global validation rules for the form.
*
* @param array $values
* 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($values, $files, $self) {
$errors = array();
$contributionPageId = $self->_id;
//CRM-4286
if (strstr($values['title'], '/')) {
$errors['title'] = ts("Please do not use '/' in Title");
}
// ensure on-behalf-of profile meets minimum requirements
if (!empty($values['is_organization'])) {
if (empty($values['onbehalf_profile_id'])) {
$errors['onbehalf_profile_id'] = ts('Please select a profile to collect organization information on this contribution page.');
}
else {
$requiredProfileFields = array('organization_name', 'email');
if (!CRM_Core_BAO_UFGroup::checkValidProfile($values['onbehalf_profile_id'], $requiredProfileFields)) {
$errors['onbehalf_profile_id'] = ts('Profile does not contain the minimum required fields for an On Behalf Of Organization');
}
}
}
//CRM-11494
$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.');
}
if (!empty($self->_values['payment_processor']) && $financialType = CRM_Contribute_BAO_Contribution::validateFinancialType($values['financial_type_id'])) {
$errors['financial_type_id'] = ts("Financial Account of account relationship of 'Expense Account is' is not configured for Financial Type : ") . $financialType;
}
//dont allow on behalf of save when
//pre or post profile consists of membership fields
if ($contributionPageId && !empty($values['is_organization'])) {
$ufJoinParams = array(
'module' => 'CiviContribute',
'entity_table' => 'civicrm_contribution_page',
'entity_id' => $contributionPageId,
);
list($contributionProfiles['custom_pre_id'],
$contributionProfiles['custom_post_id']
) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
$conProfileType = NULL;
if ($contributionProfiles['custom_pre_id']) {
$preProfileType = CRM_Core_BAO_UFField::getProfileType($contributionProfiles['custom_pre_id']);
if ($preProfileType == 'Membership') {
$conProfileType = "'Includes Profile (top of page)'";
}
}
if ($contributionProfiles['custom_post_id']) {
$postProfileType = CRM_Core_BAO_UFField::getProfileType($contributionProfiles['custom_post_id']);
if ($postProfileType == 'Membership') {
$conProfileType = empty($conProfileType) ? "'Includes Profile (bottom of page)'" : "{$conProfileType} and 'Includes Profile (bottom of page)'";
}
}
if (!empty($conProfileType)) {
$errors['is_organization'] = ts("You should move the membership related fields configured in %1 to the 'On Behalf' profile for this Contribution Page", array(1 => $conProfileType));
}
}
return $errors;
}
/**
* Process the form.
*/
public function postProcess() {
// get the submitted form values.
$params = $this->controller->exportValues($this->_name);
// we do this in case the user has hit the forward/back button
if ($this->_id) {
$params['id'] = $this->_id;
}
else {
$session = CRM_Core_Session::singleton();
$params['created_id'] = $session->get('userID');
$params['created_date'] = date('YmdHis');
$config = CRM_Core_Config::singleton();
$params['currency'] = $config->defaultCurrency;
}
$params['is_confirm_enabled'] = CRM_Utils_Array::value('is_confirm_enabled', $params, FALSE);
$params['is_share'] = CRM_Utils_Array::value('is_share', $params, FALSE);
$params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
$params['is_credit_card_only'] = CRM_Utils_Array::value('is_credit_card_only', $params, FALSE);
$params['honor_block_is_active'] = CRM_Utils_Array::value('honor_block_is_active', $params, FALSE);
$params['is_for_organization'] = !empty($params['is_organization']) ? CRM_Utils_Array::value('is_for_organization', $params, FALSE) : 0;
$params['start_date'] = CRM_Utils_Date::processDate($params['start_date'], $params['start_date_time'], TRUE);
$params['end_date'] = CRM_Utils_Date::processDate($params['end_date'], $params['end_date_time'], TRUE);
$params['goal_amount'] = CRM_Utils_Rule::cleanMoney($params['goal_amount']);
if (!$params['honor_block_is_active']) {
$params['honor_block_title'] = NULL;
$params['honor_block_text'] = NULL;
}
$dao = CRM_Contribute_BAO_ContributionPage::create($params);
$ufJoinParams = array(
'is_organization' => array(
'module' => 'on_behalf',
'entity_table' => 'civicrm_contribution_page',
'entity_id' => $dao->id,
),
'honor_block_is_active' => array(
'module' => 'soft_credit',
'entity_table' => 'civicrm_contribution_page',
'entity_id' => $dao->id,
),
);
foreach ($ufJoinParams as $index => $ufJoinParam) {
if (!empty($params[$index])) {
// first delete all past entries
CRM_Core_BAO_UFJoin::deleteAll($ufJoinParam);
$ufJoinParam['uf_group_id'] = $params[$index];
$ufJoinParam['weight'] = 1;
$ufJoinParam['is_active'] = 1;
if ($index == 'honor_block_is_active') {
$ufJoinParam['uf_group_id'] = $params['honoree_profile'];
$ufJoinParam['module_data'] = CRM_Contribute_BAO_ContributionPage::formatModuleData($params, FALSE, 'soft_credit');
}
else {
$ufJoinParam['uf_group_id'] = $params['onbehalf_profile_id'];
$ufJoinParam['module_data'] = CRM_Contribute_BAO_ContributionPage::formatModuleData($params, FALSE, 'on_behalf');
}
CRM_Core_BAO_UFJoin::create($ufJoinParam);
}
else {
if ($index == 'honor_block_is_active') {
$params['honor_block_title'] = NULL;
$params['honor_block_text'] = NULL;
}
else {
$params['for_organization'] = NULL;
}
//On subsequent honor_block_is_active uncheck, disable(don't delete)
//that particular honoree profile entry in UFjoin table, CRM-13981
$ufId = CRM_Core_BAO_UFJoin::findJoinEntryId($ufJoinParam);
if ($ufId) {
$ufJoinParam['uf_group_id'] = CRM_Core_BAO_UFJoin::findUFGroupId($ufJoinParam);
$ufJoinParam['is_active'] = 0;
CRM_Core_BAO_UFJoin::create($ufJoinParam);
}
}
}
$this->set('id', $dao->id);
if ($this->_action & CRM_Core_Action::ADD) {
$url = 'civicrm/admin/contribute/amount';
$urlParams = "action=update&reset=1&id={$dao->id}";
// special case for 'Save and Done' consistency.
if ($this->controller->getButtonName('submit') == '_qf_Amount_upload_done') {
$url = 'civicrm/admin/contribute';
$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('Title and Settings');
}
}

View file

@ -0,0 +1,224 @@
<?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
*/
/**
* Helper class to build navigation links.
*/
class CRM_Contribute_Form_ContributionPage_TabHeader {
/**
* @param CRM_Core_Form $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),
),
));
return $tabs;
}
/**
* @param CRM_Core_Form $form
*
* @return array
*/
public static function process(&$form) {
if ($form->getVar('_id') <= 0) {
return NULL;
}
$tabs = array(
'settings' => array(
'title' => ts('Title'),
'link' => NULL,
'valid' => FALSE,
'active' => FALSE,
'current' => FALSE,
),
'amount' => array(
'title' => ts('Amounts'),
'link' => NULL,
'valid' => FALSE,
'active' => FALSE,
'current' => FALSE,
),
'membership' => array(
'title' => ts('Memberships'),
'link' => NULL,
'valid' => FALSE,
'active' => FALSE,
'current' => FALSE,
),
'thankyou' => array(
'title' => ts('Receipt'),
'link' => NULL,
'valid' => FALSE,
'active' => FALSE,
'current' => FALSE,
),
'friend' => array(
'title' => ts('Tell a Friend'),
'link' => NULL,
'valid' => FALSE,
'active' => FALSE,
'current' => FALSE,
),
'custom' => array(
'title' => ts('Profiles'),
'link' => NULL,
'valid' => FALSE,
'active' => FALSE,
'current' => FALSE,
),
'premium' => array(
'title' => ts('Premiums'),
'link' => NULL,
'valid' => FALSE,
'active' => FALSE,
'current' => FALSE,
),
'widget' => array(
'title' => ts('Widgets'),
'link' => NULL,
'valid' => FALSE,
'active' => FALSE,
'current' => FALSE,
),
'pcp' => array(
'title' => ts('Personal Campaigns'),
'link' => NULL,
'valid' => FALSE,
'active' => FALSE,
'current' => FALSE,
),
);
$contribPageId = $form->getVar('_id');
CRM_Utils_Hook::tabset('civicrm/admin/contribute', $tabs, array('contribution_page_id' => $contribPageId));
$fullName = $form->getVar('_name');
$className = CRM_Utils_String::getClassName($fullName);
// Hack for special cases.
switch ($className) {
case 'Contribute':
$attributes = $form->getVar('_attributes');
$class = strtolower(basename(CRM_Utils_Array::value('action', $attributes)));
break;
case 'MembershipBlock':
$class = 'membership';
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 ($contribPageId) {
$reset = !empty($_GET['reset']) ? 'reset=1&' : '';
foreach ($tabs as $key => $value) {
if (!isset($tabs[$key]['qfKey'])) {
$tabs[$key]['qfKey'] = NULL;
}
$tabs[$key]['link'] = CRM_Utils_System::url(
"civicrm/admin/contribute/{$key}",
"{$reset}action=update&id={$contribPageId}{$tabs[$key]['qfKey']}"
);
$tabs[$key]['active'] = $tabs[$key]['valid'] = TRUE;
}
//get all section info.
$contriPageInfo = CRM_Contribute_BAO_ContributionPage::getSectionInfo(array($contribPageId));
foreach ($contriPageInfo[$contribPageId] as $section => $info) {
if (!$info) {
$tabs[$section]['valid'] = FALSE;
}
}
}
return $tabs;
}
/**
* @param $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;
}
}

View file

@ -0,0 +1,133 @@
<?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
*/
/**
* Form to configure thank-you messages and receipting features for an online contribution page.
*/
class CRM_Contribute_Form_ContributionPage_ThankYou extends CRM_Contribute_Form_ContributionPage {
/**
* Set default values for the form.
*
* Note that in edit/view mode the default values are retrieved from the database.
*/
public function setDefaultValues() {
return parent::setDefaultValues();
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->registerRule('emailList', 'callback', 'emailList', 'CRM_Utils_Rule');
// thank you title and text (html allowed in text)
$this->add('text', 'thankyou_title', ts('Thank-you Page Title'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionPage', 'thankyou_title'), TRUE);
$attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionPage', 'thankyou_text') + array('class' => 'collapsed');
$this->add('wysiwyg', 'thankyou_text', ts('Thank-you Message'), $attributes);
$this->add('wysiwyg', 'thankyou_footer', ts('Thank-you Footer'), $attributes);
$this->addElement('checkbox', 'is_email_receipt', ts('Email Receipt to Contributor?'), NULL, array('onclick' => "showReceipt()"));
$this->add('text', 'receipt_from_name', ts('Receipt From Name'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionPage', 'receipt_from_name'));
$this->add('text', 'receipt_from_email', ts('Receipt From Email'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionPage', 'receipt_from_email'));
$this->add('textarea', 'receipt_text', ts('Receipt Message'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionPage', 'receipt_text'));
$this->add('text', 'cc_receipt', ts('CC Receipt To'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionPage', 'cc_receipt'));
$this->addRule('cc_receipt', ts('Please enter a valid list of comma delimited email addresses'), 'emailList');
$this->add('text', 'bcc_receipt', ts('BCC Receipt To'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionPage', 'bcc_receipt'));
$this->addRule('bcc_receipt', ts('Please enter a valid list of comma delimited email addresses'), 'emailList');
parent::buildQuickForm();
$this->addFormRule(array('CRM_Contribute_Form_ContributionPage_ThankYou', 'formRule'), $this);
}
/**
* Global form rule.
*
* @param array $fields
* The input form values.
* @param array $files
* The uploaded files if any.
* @param array $options
* Additional user data.
*
* @return bool|array
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $options) {
$errors = array();
// if is_email_receipt is set, the receipt message must be non-empty
if (!empty($fields['is_email_receipt'])) {
//added for CRM-1348
$email = trim(CRM_Utils_Array::value('receipt_from_email', $fields));
if (empty($email) || !CRM_Utils_Rule::email($email)) {
$errors['receipt_from_email'] = ts('A valid Receipt From Email address must be specified if Email Receipt to Contributor is enabled');
}
}
return $errors;
}
/**
* Process the form.
*/
public function postProcess() {
// get the submitted form values.
$params = $this->controller->exportValues($this->_name);
$params['id'] = $this->_id;
$params['is_email_receipt'] = CRM_Utils_Array::value('is_email_receipt', $params, FALSE);
if (!$params['is_email_receipt']) {
$params['receipt_from_name'] = NULL;
$params['receipt_from_email'] = NULL;
$params['receipt_text'] = NULL;
$params['cc_receipt'] = NULL;
$params['bcc_receipt'] = NULL;
}
$dao = CRM_Contribute_BAO_ContributionPage::create($params);
parent::endPostProcess();
}
/**
* Return a descriptive name for the page, used in wizard header
*
* @return string
*/
public function getTitle() {
return ts('Thanks and Receipt');
}
}

View file

@ -0,0 +1,279 @@
<?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
*/
class CRM_Contribute_Form_ContributionPage_Widget extends CRM_Contribute_Form_ContributionPage {
protected $_colors;
protected $_widget;
public function preProcess() {
parent::preProcess();
$this->_widget = new CRM_Contribute_DAO_Widget();
$this->_widget->contribution_page_id = $this->_id;
if (!$this->_widget->find(TRUE)) {
$this->_widget = NULL;
}
else {
$this->assign('widget_id', $this->_widget->id);
// check of home url is set, if set then it flash widget might be in use.
$this->assign('showStatus', FALSE);
if ($this->_widget->url_homepage) {
$this->assign('showStatus', TRUE);
}
}
$this->assign('cpageId', $this->_id);
$config = CRM_Core_Config::singleton();
$title = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage',
$this->_id,
'title'
);
$this->_fields = array(
'title' => array(
ts('Title'),
'text',
FALSE,
$title,
),
'url_logo' => array(
ts('URL to Logo Image'),
'text',
FALSE,
NULL,
),
'button_title' => array(
ts('Button Title'),
'text',
FALSE,
ts('Contribute!'),
),
);
$this->_colorFields = array(
'color_title' => array(
ts('Title Text Color'),
'text',
FALSE,
'#2786C2',
),
'color_bar' => array(
ts('Progress Bar Color'),
'text',
FALSE,
'#2786C2',
),
'color_main_text' => array(
ts('Additional Text Color'),
'text',
FALSE,
'#FFFFFF',
),
'color_main' => array(
ts('Background Color'),
'text',
FALSE,
'#96C0E7',
),
'color_main_bg' => array(
ts('Background Color Top Area'),
'text',
FALSE,
'#B7E2FF',
),
'color_bg' => array(
ts('Border Color'),
'text',
FALSE,
'#96C0E7',
),
'color_about_link' => array(
ts('Button Text Color'),
'text',
FALSE,
'#556C82',
),
'color_button' => array(
ts('Button Background Color'),
'text',
FALSE,
'#FFFFFF',
),
'color_homepage_link' => array(
ts('Homepage Link Color'),
'text',
FALSE,
'#FFFFFF',
),
);
}
/**
* Set default values for the form.
*/
public function setDefaultValues() {
$defaults = array();
// check if there is a widget already created
if ($this->_widget) {
CRM_Core_DAO::storeValues($this->_widget, $defaults);
}
else {
foreach ($this->_fields as $name => $val) {
$defaults[$name] = $val[3];
}
foreach ($this->_colorFields as $name => $val) {
$defaults[$name] = $val[3];
}
$defaults['about'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage',
$this->_id,
'intro_text'
);
}
$showHide = new CRM_Core_ShowHideBlocks();
$showHide->addHide('id-colors');
$showHide->addToTemplate();
return $defaults;
}
public function buildQuickForm() {
$attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Widget');
$this->addElement('checkbox',
'is_active',
ts('Enable Widget?'),
NULL,
array('onclick' => "widgetBlock(this)")
);
$this->add('wysiwyg', 'about', ts('About'), $attributes['about']);
foreach ($this->_fields as $name => $val) {
$this->add($val[1],
$name,
$val[0],
$attributes[$name],
$val[2]
);
}
foreach ($this->_colorFields as $name => $val) {
$this->add($val[1],
$name,
$val[0],
$attributes[$name],
$val[2]
);
}
$this->assign_by_ref('fields', $this->_fields);
$this->assign_by_ref('colorFields', $this->_colorFields);
$this->_refreshButtonName = $this->getButtonName('refresh');
$this->addElement('submit',
$this->_refreshButtonName,
ts('Save and Preview')
);
parent::buildQuickForm();
$this->addFormRule(array('CRM_Contribute_Form_ContributionPage_Widget', 'formRule'), $this);
}
/**
* Validation.
*
* @param array $params
* (ref.) an assoc array of name/value pairs.
*
* @param $files
* @param $self
*
* @return bool|array
* mixed true or array of errors
*/
public static function formRule($params, $files, $self) {
$errors = array();
if (!empty($params['is_active'])) {
if (empty($params['title'])) {
$errors['title'] = ts('Title is a required field.');
}
if (empty($params['about'])) {
$errors['about'] = ts('About is a required field.');
}
foreach ($params as $key => $val) {
if (substr($key, 0, 6) == 'color_' && empty($params[$key])) {
$errors[$key] = ts('%1 is a required field.', array(1 => $self->_colorFields[$key][0]));
}
}
}
return empty($errors) ? TRUE : $errors;
}
public function postProcess() {
//to reset quickform elements of next (pcp) page.
if ($this->controller->getNextName('Widget') == 'PCP') {
$this->controller->resetPage('PCP');
}
// get the submitted form values.
$params = $this->controller->exportValues($this->_name);
if ($this->_widget) {
$params['id'] = $this->_widget->id;
}
$params['contribution_page_id'] = $this->_id;
$params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
$params['url_homepage'] = 'null';
$widget = new CRM_Contribute_DAO_Widget();
$widget->copyValues($params);
$widget->save();
$buttonName = $this->controller->getButtonName();
if ($buttonName == $this->_refreshButtonName) {
return;
}
parent::endPostProcess();
}
/**
* Return a descriptive name for the page, used in wizard header
*
* @return string
*/
public function getTitle() {
return ts('Widget Settings');
}
}

View file

@ -0,0 +1,269 @@
<?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 Payment-Instrument.
*/
class CRM_Contribute_Form_ContributionView extends CRM_Core_Form {
/**
* Set variables up before form is built.
*/
public function preProcess() {
$id = $this->get('id');
$params = array('id' => $id);
$context = CRM_Utils_Request::retrieve('context', 'String', $this);
$this->assign('context', $context);
$values = CRM_Contribute_BAO_Contribution::getValuesWithMappings($params);
if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus() && $this->_action & CRM_Core_Action::VIEW) {
$financialTypeID = CRM_Contribute_PseudoConstant::financialType($values['financial_type_id']);
CRM_Financial_BAO_FinancialType::checkPermissionedLineItems($id, 'view');
if (CRM_Financial_BAO_FinancialType::checkPermissionedLineItems($id, 'edit', FALSE)) {
$this->assign('canEdit', TRUE);
}
if (CRM_Financial_BAO_FinancialType::checkPermissionedLineItems($id, 'delete', FALSE)) {
$this->assign('canDelete', TRUE);
}
if (!CRM_Core_Permission::check('view contributions of type ' . $financialTypeID)) {
CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
}
}
elseif ($this->_action & CRM_Core_Action::VIEW) {
$this->assign('noACL', TRUE);
}
CRM_Contribute_BAO_Contribution::resolveDefaults($values);
// @todo - I believe this cancelledStatus is unused - if someone reaches the same conclusion
// by grepping then the next few lines can go.
$cancelledStatus = TRUE;
$status = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
if (CRM_Utils_Array::value('contribution_status_id', $values) == array_search('Cancelled', $status)) {
$cancelledStatus = FALSE;
}
$this->assign('cancelledStatus', $cancelledStatus);
if (!empty($values['contribution_page_id'])) {
$contribPages = CRM_Contribute_PseudoConstant::contributionPage(NULL, TRUE);
$values['contribution_page_title'] = CRM_Utils_Array::value(CRM_Utils_Array::value('contribution_page_id', $values), $contribPages);
}
// get received into i.e to_financial_account_id from last trxn
$financialTrxnId = CRM_Core_BAO_FinancialTrxn::getFinancialTrxnId($values['contribution_id'], 'DESC');
$values['to_financial_account'] = '';
if (!empty($financialTrxnId['financialTrxnId'])) {
$values['to_financial_account_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $financialTrxnId['financialTrxnId'], 'to_financial_account_id');
if ($values['to_financial_account_id']) {
$values['to_financial_account'] = CRM_Contribute_PseudoConstant::financialAccount($values['to_financial_account_id']);
}
$values['payment_processor_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialTrxn', $financialTrxnId['financialTrxnId'], 'payment_processor_id');
if ($values['payment_processor_id']) {
$values['payment_processor_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessor', $values['payment_processor_id'], 'name');
}
}
if (!empty($values['contribution_recur_id'])) {
$sql = "SELECT installments, frequency_interval, frequency_unit FROM civicrm_contribution_recur WHERE id = %1";
$params = array(1 => array($values['contribution_recur_id'], 'Integer'));
$dao = CRM_Core_DAO::executeQuery($sql, $params);
if ($dao->fetch()) {
$values['recur_installments'] = $dao->installments;
$values['recur_frequency_unit'] = $dao->frequency_unit;
$values['recur_frequency_interval'] = $dao->frequency_interval;
}
}
$groupTree = CRM_Core_BAO_CustomGroup::getTree('Contribution', NULL, $id, 0, CRM_Utils_Array::value('financial_type_id', $values));
CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree, FALSE, NULL, NULL, NULL, $id);
$premiumId = NULL;
if ($id) {
$dao = new CRM_Contribute_DAO_ContributionProduct();
$dao->contribution_id = $id;
if ($dao->find(TRUE)) {
$premiumId = $dao->id;
$productID = $dao->product_id;
}
}
if ($premiumId) {
$productDAO = new CRM_Contribute_DAO_Product();
$productDAO->id = $productID;
$productDAO->find(TRUE);
$this->assign('premium', $productDAO->name);
$this->assign('option', $dao->product_option);
$this->assign('fulfilled', $dao->fulfilled_date);
}
// Get Note
$noteValue = CRM_Core_BAO_Note::getNote(CRM_Utils_Array::value('id', $values), 'civicrm_contribution');
$values['note'] = array_values($noteValue);
// show billing address location details, if exists
if (!empty($values['address_id'])) {
$addressParams = array('id' => CRM_Utils_Array::value('address_id', $values));
$addressDetails = CRM_Core_BAO_Address::getValues($addressParams, FALSE, 'id');
$addressDetails = array_values($addressDetails);
$values['billing_address'] = $addressDetails[0]['display'];
}
//assign soft credit record if exists.
$SCRecords = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($values['contribution_id'], TRUE);
if (!empty($SCRecords['soft_credit'])) {
$this->assign('softContributions', $SCRecords['soft_credit']);
unset($SCRecords['soft_credit']);
}
//assign pcp record if exists
foreach ($SCRecords as $name => $value) {
$this->assign($name, $value);
}
$lineItems = array();
$displayLineItems = FALSE;
if ($id) {
$lineItems = array(CRM_Price_BAO_LineItem::getLineItemsByContributionID(($id)));
$firstLineItem = reset($lineItems[0]);
if (empty($firstLineItem['price_set_id'])) {
// CRM-20297 All we care is that it's not QuickConfig, so no price set
// is no problem.
$displayLineItems = TRUE;
}
else {
try {
$priceSet = civicrm_api3('PriceSet', 'getsingle', array(
'id' => $firstLineItem['price_set_id'],
'return' => 'is_quick_config, id',
));
$displayLineItems = !$priceSet['is_quick_config'];
}
catch (CiviCRM_API3_Exception $e) {
throw new CRM_Core_Exception('Cannot find price set by ID');
}
}
}
$this->assign('lineItem', $lineItems);
$this->assign('displayLineItems', $displayLineItems);
$values['totalAmount'] = $values['total_amount'];
$this->assign('displayLineItemFinancialType', TRUE);
//do check for campaigns
if ($campaignId = CRM_Utils_Array::value('campaign_id', $values)) {
$campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId);
$values['campaign'] = $campaigns[$campaignId];
}
if ($values['contribution_status'] == 'Refunded') {
$this->assign('refund_trxn_id', CRM_Core_BAO_FinancialTrxn::getRefundTransactionTrxnID($id));
}
// assign values to the template
$this->assign($values);
$invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
$invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
$this->assign('invoicing', $invoicing);
$this->assign('isDeferred', CRM_Utils_Array::value('deferred_revenue_enabled', $invoiceSettings));
if ($invoicing && isset($values['tax_amount'])) {
$this->assign('totalTaxAmount', $values['tax_amount']);
}
$displayName = CRM_Contact_BAO_Contact::displayName($values['contact_id']);
$this->assign('displayName', $displayName);
// Check if this is default domain contact CRM-10482
if (CRM_Contact_BAO_Contact::checkDomainContact($values['contact_id'])) {
$displayName .= ' (' . ts('default organization') . ')';
}
// 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 Contribution from') . ' ' . $displayName);
// add viewed contribution to recent items list
$url = CRM_Utils_System::url('civicrm/contact/view/contribution',
"action=view&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"
);
$title = $displayName . ' - (' . CRM_Utils_Money::format($values['total_amount'], $values['currency']) . ' ' . ' - ' . $values['financial_type'] . ')';
$recentOther = array();
if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) {
$recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution',
"action=update&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"
);
}
if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) {
$recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution',
"action=delete&reset=1&id={$values['id']}&cid={$values['contact_id']}&context=home"
);
}
CRM_Utils_Recent::add($title,
$url,
$values['id'],
'Contribution',
$values['contact_id'],
NULL,
$recentOther
);
$contributionStatus = $status[$values['contribution_status_id']];
if (in_array($contributionStatus, array('Partially paid', 'Pending refund'))
|| ($contributionStatus == 'Pending' && $values['is_pay_later'])
) {
if ($contributionStatus == 'Pending refund') {
$this->assign('paymentButtonName', ts('Record Refund'));
}
else {
$this->assign('paymentButtonName', ts('Record Payment'));
}
$this->assign('addRecordPayment', TRUE);
$this->assign('contactId', $values['contact_id']);
$this->assign('componentId', $id);
$this->assign('component', 'contribution');
}
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->addButtons(array(
array(
'type' => 'cancel',
'name' => ts('Done'),
'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
'isDefault' => TRUE,
),
));
}
}

View file

@ -0,0 +1,368 @@
<?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 Premiums.
*/
class CRM_Contribute_Form_ManagePremiums extends CRM_Contribute_Form {
/**
* Pre process the form.
*/
public function preProcess() {
parent::preProcess();
}
/**
* Set default values for the form.
*/
public function setDefaultValues() {
$defaults = parent::setDefaultValues();
if ($this->_id) {
$params = array('id' => $this->_id);
CRM_Contribute_BAO_ManagePremiums::retrieve($params, $tempDefaults);
$imageUrl = (isset($tempDefaults['image'])) ? $tempDefaults['image'] : "";
if (isset($tempDefaults['image']) && isset($tempDefaults['thumbnail'])) {
$defaults['imageUrl'] = $tempDefaults['image'];
$defaults['thumbnailUrl'] = $tempDefaults['thumbnail'];
$defaults['imageOption'] = 'thumbnail';
// assign thumbnailUrl to template so we can display current image in update mode
$this->assign('thumbnailUrl', $defaults['thumbnailUrl']);
}
else {
$defaults['imageOption'] = 'noImage';
}
if (isset($tempDefaults['thumbnail']) && isset($tempDefaults['image'])) {
$this->assign('thumbURL', $tempDefaults['thumbnail']);
$this->assign('imageURL', $tempDefaults['image']);
}
if (isset($tempDefaults['period_type'])) {
$this->assign('showSubscriptions', TRUE);
}
}
return $defaults;
}
/**
* Build the form object.
*/
public function buildQuickForm() {
parent::buildQuickForm();
$this->setPageTitle(ts('Premium Product'));
if ($this->_action & CRM_Core_Action::PREVIEW) {
CRM_Contribute_BAO_Premium::buildPremiumPreviewBlock($this, $this->_id);
return;
}
if ($this->_action & CRM_Core_Action::DELETE) {
return;
}
$this->applyFilter('__ALL__', 'trim');
$this->add('text', 'name', ts('Name'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'name'), TRUE);
$this->addRule('name', ts('A product with this name already exists. Please select another name.'), 'objectExists', array(
'CRM_Contribute_DAO_Product',
$this->_id,
));
$this->add('text', 'sku', ts('SKU'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'sku'));
$this->add('textarea', 'description', ts('Description'), 'rows=3, cols=60');
$image['image'] = $this->createElement('radio', NULL, NULL, ts('Upload from my computer'), 'image', 'onclick="add_upload_file_block(\'image\');');
$image['thumbnail'] = $this->createElement('radio', NULL, NULL, ts('Display image and thumbnail from these locations on the web:'), 'thumbnail', 'onclick="add_upload_file_block(\'thumbnail\');');
$image['default_image'] = $this->createElement('radio', NULL, NULL, ts('Use default image'), 'default_image', 'onclick="add_upload_file_block(\'default\');');
$image['noImage'] = $this->createElement('radio', NULL, NULL, ts('Do not display an image'), 'noImage', 'onclick="add_upload_file_block(\'noImage\');');
$this->addGroup($image, 'imageOption', ts('Premium Image'));
$this->addRule('imageOption', ts('Please select an option for the premium image.'), 'required');
$this->addElement('text', 'imageUrl', ts('Image URL'));
$this->addElement('text', 'thumbnailUrl', ts('Thumbnail URL'));
$this->add('file', 'uploadFile', ts('Image File Name'), 'onChange="select_option();"');
$this->add('text', 'price', ts('Market Value'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'price'), TRUE);
$this->addRule('price', ts('Please enter the Market Value for this product.'), 'money');
$this->add('text', 'cost', ts('Actual Cost of Product'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'cost'));
$this->addRule('price', ts('Please enter the Actual Cost of Product.'), 'money');
$this->add('text', 'min_contribution', ts('Minimum Contribution Amount'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'min_contribution'), TRUE);
$this->addRule('min_contribution', ts('Please enter a monetary value for the Minimum Contribution Amount.'), 'money');
$this->add('textarea', 'options', ts('Options'), 'rows=3, cols=60');
$this->add('select', 'period_type', ts('Period Type'), array(
'' => '- select -',
'rolling' => 'Rolling',
'fixed' => 'Fixed',
));
$this->add('text', 'fixed_period_start_day', ts('Fixed Period Start Day'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'fixed_period_start_day'));
$this->add('Select', 'duration_unit', ts('Duration Unit'), array('' => '- select period -') + CRM_Core_SelectValues::getPremiumUnits());
$this->add('text', 'duration_interval', ts('Duration'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'duration_interval'));
$this->add('Select', 'frequency_unit', ts('Frequency Unit'), array('' => '- select period -') + CRM_Core_SelectValues::getPremiumUnits());
$this->add('text', 'frequency_interval', ts('Frequency'), CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Product', 'frequency_interval'));
//Financial Type CRM-11106
$financialType = CRM_Contribute_PseudoConstant::financialType();
$premiumFinancialType = array();
CRM_Core_PseudoConstant::populate(
$premiumFinancialType,
'CRM_Financial_DAO_EntityFinancialAccount',
$all = TRUE,
$retrieve = 'entity_id',
$filter = NULL,
'account_relationship = 8'
);
$costFinancialType = array();
CRM_Core_PseudoConstant::populate(
$costFinancialType,
'CRM_Financial_DAO_EntityFinancialAccount',
$all = TRUE,
$retrieve = 'entity_id',
$filter = NULL,
'account_relationship = 7'
);
$productFinancialType = array_intersect($costFinancialType, $premiumFinancialType);
foreach ($financialType as $key => $financialTypeName) {
if (!in_array($key, $productFinancialType)) {
unset($financialType[$key]);
}
}
if (count($financialType)) {
$this->assign('financialType', $financialType);
}
$this->add(
'select',
'financial_type_id',
ts('Financial Type'),
array('' => ts('- select -')) + $financialType
);
$this->add('checkbox', 'is_active', ts('Enabled?'));
$this->addFormRule(array('CRM_Contribute_Form_ManagePremiums', 'formRule'));
$this->addButtons(array(
array(
'type' => 'upload',
'name' => ts('Save'),
'isDefault' => TRUE,
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
)
);
$this->assign('productId', $this->_id);
}
/**
* Function for validation.
*
* @param array $params
* (ref.) an assoc array of name/value pairs.
* @param $files
*
* @return bool|array
* mixed true or array of errors
*/
public static function formRule($params, $files) {
// If choosing to upload an image, then an image must be provided
if (CRM_Utils_Array::value('imageOption', $params) == 'image'
&& empty($files['uploadFile']['name'])
) {
$errors['uploadFile'] = ts('A file must be selected');
}
// If choosing to use image URLs, then both URLs must be present
if (CRM_Utils_Array::value('imageOption', $params) == 'thumbnail') {
if (!$params['imageUrl']) {
$errors['imageUrl'] = ts('Image URL is Required');
}
if (!$params['thumbnailUrl']) {
$errors['thumbnailUrl'] = ts('Thumbnail URL is Required');
}
}
// CRM-13231 financial type required if product has cost
if (!empty($params['cost']) && empty($params['financial_type_id'])) {
$errors['financial_type_id'] = ts('Financial Type is required for product having cost.');
}
if (!$params['period_type']) {
if ($params['fixed_period_start_day'] || $params['duration_unit'] || $params['duration_interval'] ||
$params['frequency_unit'] || $params['frequency_interval']
) {
$errors['period_type'] = ts('Please select the Period Type for this subscription or service.');
}
}
if ($params['period_type'] == 'fixed' && !$params['fixed_period_start_day']) {
$errors['fixed_period_start_day'] = ts('Please enter a Fixed Period Start Day for this subscription or service.');
}
if ($params['duration_unit'] && !$params['duration_interval']) {
$errors['duration_interval'] = ts('Please enter the Duration Interval for this subscription or service.');
}
if ($params['duration_interval'] && !$params['duration_unit']) {
$errors['duration_unit'] = ts('Please enter the Duration Unit for this subscription or service.');
}
if ($params['frequency_interval'] && !$params['frequency_unit']) {
$errors['frequency_unit'] = ts('Please enter the Frequency Unit for this subscription or service.');
}
if ($params['frequency_unit'] && !$params['frequency_interval']) {
$errors['frequency_interval'] = ts('Please enter the Frequency Interval for this subscription or service.');
}
return empty($errors) ? TRUE : $errors;
}
/**
* Process the form submission.
*/
public function postProcess() {
// If previewing, don't do any post-processing
if ($this->_action & CRM_Core_Action::PREVIEW) {
return;
}
// If deleting, then only delete and skip the rest of the post-processing
if ($this->_action & CRM_Core_Action::DELETE) {
CRM_Contribute_BAO_ManagePremiums::del($this->_id);
CRM_Core_Session::setStatus(
ts('Selected Premium Product type has been deleted.'),
ts('Deleted'), 'info');
return;
}
$params = $this->controller->exportValues($this->_name);
// Clean the the money fields
$moneyFields = array('cost', 'price', 'min_contribution');
foreach ($moneyFields as $field) {
$params[$field] = CRM_Utils_Rule::cleanMoney($params[$field]);
}
$ids = array();
if ($this->_action & CRM_Core_Action::UPDATE) {
$ids['premium'] = $this->_id;
}
$this->_processImages($params);
// Save to database
$premium = CRM_Contribute_BAO_ManagePremiums::add($params, $ids);
CRM_Core_Session::setStatus(
ts("The Premium '%1' has been saved.", array(1 => $premium->name)),
ts('Saved'), 'success');
}
/**
* Look at $params to find form info about images. Manipulate images if
* necessary. Then alter $params to point to the newly manipulated images.
*
* @param array $params
*/
protected function _processImages(&$params) {
$defaults = array(
'imageOption' => 'noImage',
'uploadFile' => array('name' => ''),
'image' => '',
'thumbnail' => '',
'imageUrl' => '',
'thumbnailUrl' => '',
);
$params = array_merge($defaults, $params);
// User is uploading an image
if ($params['imageOption'] == 'image') {
$imageFile = $params['uploadFile']['name'];
try {
$params['image'] = CRM_Utils_File::resizeImage($imageFile, 200, 200, "_full");
$params['thumbnail'] = CRM_Utils_File::resizeImage($imageFile, 50, 50, "_thumb");
}
catch (CRM_Core_Exception $e) {
$params['image'] = self::_defaultImage();
$params['thumbnail'] = self::_defaultThumbnail();
$msg = ts('The product has been configured to use a default image.');
CRM_Core_Session::setStatus($e->getMessage() . " $msg", ts('Notice'), 'alert');
}
}
// User is specifying existing URLs for the images
elseif ($params['imageOption'] == 'thumbnail') {
$params['image'] = $params['imageUrl'];
$params['thumbnail'] = $params['thumbnailUrl'];
}
// User wants a default image
elseif ($params['imageOption'] == 'default_image') {
$params['image'] = self::_defaultImage();
$params['thumbnail'] = self::_defaultThumbnail();
}
}
/**
* Returns the path to the default premium image
* @return string
*/
protected static function _defaultImage() {
$config = CRM_Core_Config::singleton();
return $config->resourceBase . 'i/contribute/default_premium.jpg';
}
/**
* Returns the path to the default premium thumbnail
* @return string
*/
protected static function _defaultThumbnail() {
$config = CRM_Core_Config::singleton();
return $config->resourceBase . 'i/contribute/default_premium_thumb.jpg';
}
}

View file

@ -0,0 +1,470 @@
<?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
*/
/**
* Advanced search, extends basic search.
*/
class CRM_Contribute_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 = "contribute_";
/**
* Processing needed for buildForm and later.
*/
public function preProcess() {
$this->set('searchFormName', 'Search');
$this->_searchButtonName = $this->getButtonName('refresh');
$this->_actionButtonName = $this->getButtonName('next', 'action');
$this->_done = FALSE;
// @todo - is this an error - $this->_defaults is used.
$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->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->_formValues = $this->controller->exportValues($this->_name);
}
else {
$this->_formValues = $this->get('formValues');
}
//membership ID
$memberShipId = CRM_Utils_Request::retrieve('memberId', 'Positive', $this);
if (isset($memberShipId)) {
$this->_formValues['contribution_membership_id'] = $memberShipId;
}
$participantId = CRM_Utils_Request::retrieve('participantId', 'Positive', $this);
if (isset($participantId)) {
$this->_formValues['contribution_participant_id'] = $participantId;
}
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);
$selector = new CRM_Contribute_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('contributionSummary', $this->get('summary'));
}
/**
* Set defaults.
*
* @return array
*/
public function setDefaultValues() {
if (empty($this->_defaults['contribution_status'])) {
$this->_defaults['contribution_status'][1] = 1;
}
return $this->_defaults;
}
/**
* Build the form object.
*/
public function buildQuickForm() {
parent::buildQuickForm();
$this->addSortNameField();
$this->_group = CRM_Core_PseudoConstant::nestedGroup();
// multiselect for groups
if ($this->_group) {
$this->add('select', 'group', ts('Groups'), $this->_group, FALSE,
array('id' => 'group', 'multiple' => 'multiple', 'class' => 'crm-select2')
);
}
// multiselect for tags
$contactTags = CRM_Core_BAO_Tag::getTags();
if ($contactTags) {
$this->add('select', 'contact_tags', ts('Tags'), $contactTags, FALSE,
array('id' => 'contact_tags', 'multiple' => 'multiple', 'class' => 'crm-select2')
);
}
CRM_Contribute_BAO_Query::buildSearchForm($this);
$rows = $this->get('rows');
if (is_array($rows)) {
if (!$this->_single) {
$this->addRowSelectors($rows);
}
$permission = CRM_Core_Permission::getPermission();
$queryParams = $this->get('queryParams');
$softCreditFiltering = FALSE;
if (!empty($queryParams)) {
$softCreditFiltering = CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled($queryParams);
}
$tasks = CRM_Contribute_Task::permissionedTaskTitles($permission, $softCreditFiltering);
$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('Contributor 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('Contributor 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 processing.
* - 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 submission is
* done.
* The processing consists of using a Selector / Controller framework for getting the
* search results.
*/
public function postProcess() {
if ($this->_done) {
return;
}
$this->_done = TRUE;
if (!empty($_POST)) {
$this->_formValues = $this->controller->exportValues($this->_name);
}
$this->fixFormValues();
// We don't show test records in summaries or dashboards
if (empty($this->_formValues['contribution_test']) && $this->_force && !empty($this->_context) && $this->_context == 'dashboard') {
$this->_formValues["contribution_test"] = 0;
}
foreach (array(
'contribution_amount_low',
'contribution_amount_high',
) as $f) {
if (isset($this->_formValues[$f])) {
$this->_formValues[$f] = CRM_Utils_Rule::cleanMoney($this->_formValues[$f]);
}
}
$config = CRM_Core_Config::singleton();
if (!empty($_POST)) {
$specialParams = array(
'financial_type_id',
'contribution_soft_credit_type_id',
'contribution_status_id',
'contribution_source',
'contribution_trxn_id',
'contribution_page_id',
'contribution_product_id',
'invoice_id',
'payment_instrument_id',
'contribution_batch_id',
);
CRM_Contact_BAO_Query::processSpecialFormValue($this->_formValues, $specialParams);
$tags = CRM_Utils_Array::value('contact_tags', $this->_formValues);
if ($tags && !is_array($tags)) {
unset($this->_formValues['contact_tags']);
$this->_formValues['contact_tags'][$tags] = 1;
}
if ($tags && is_array($tags)) {
unset($this->_formValues['contact_tags']);
foreach ($tags as $notImportant => $tagID) {
$this->_formValues['contact_tags'][$tagID] = 1;
}
}
$group = CRM_Utils_Array::value('group', $this->_formValues);
if ($group && !is_array($group)) {
unset($this->_formValues['group']);
$this->_formValues['group'][$group] = 1;
}
if ($group && is_array($group)) {
unset($this->_formValues['group']);
foreach ($group as $groupID) {
$this->_formValues['group'][$groupID] = 1;
}
}
}
CRM_Core_BAO_CustomValue::fixCustomFieldValue($this->_formValues);
$this->_queryParams = CRM_Contact_BAO_Query::convertFormValues($this->_formValues);
$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);
$selector = new CRM_Contribute_Selector_Search($this->_queryParams,
$this->_action,
NULL,
$this->_single,
$this->_limit,
$this->_context
);
$selector->setKey($this->controller->_key);
$prefix = NULL;
if ($this->_context == 'basic' || $this->_context == 'user') {
$prefix = $this->_prefix;
}
$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);
}
$summary = &$query->summaryContribution($this->_context);
$this->set('summary', $summary);
$this->assign('contributionSummary', $summary);
$controller->run();
}
/**
* Use values from $_GET if force is set to TRUE.
*
* Note that this means that GET over-rides POST. This was a historical decision & the reasoning is not explained.
*/
public function fixFormValues() {
if (!$this->_force) {
return;
}
$status = CRM_Utils_Request::retrieve('status', 'String');
if ($status) {
$this->_formValues['contribution_status_id'] = array($status => 1);
$this->_defaults['contribution_status_id'] = array($status => 1);
}
$pcpid = (array) CRM_Utils_Request::retrieve('pcpid', 'String', $this);
if ($pcpid) {
// Add new pcpid to the tail of the array...
foreach ($pcpid as $pcpIdList) {
$this->_formValues['contribution_pcp_made_through_id'][] = $pcpIdList;
}
// and avoid any duplicate
$this->_formValues['contribution_pcp_made_through_id'] = array_unique($this->_formValues['contribution_pcp_made_through_id']);
}
$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;
// @todo - why do we retrieve these when they are not used?
list($display, $image) = CRM_Contact_BAO_Contact::getDisplayAndImage($cid);
$this->_defaults['sort_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $cid,
'sort_name'
);
// also assign individual mode to the template
$this->_single = TRUE;
}
}
$lowDate = CRM_Utils_Request::retrieve('start', 'Timestamp');
if ($lowDate) {
$lowDate = CRM_Utils_Type::escape($lowDate, 'Timestamp');
$date = CRM_Utils_Date::setDateDefaults($lowDate);
$this->_formValues['contribution_date_low'] = $this->_defaults['contribution_date_low'] = $date[0];
}
$highDate = CRM_Utils_Request::retrieve('end', 'Timestamp');
if ($highDate) {
$highDate = CRM_Utils_Type::escape($highDate, 'Timestamp');
$date = CRM_Utils_Date::setDateDefaults($highDate);
$this->_formValues['contribution_date_high'] = $this->_defaults['contribution_date_high'] = $date[0];
}
if ($highDate || $lowDate) {
//set the Choose Date Range value
$this->_formValues['contribution_date_relative'] = 0;
}
$this->_limit = CRM_Utils_Request::retrieve('limit', 'Positive',
$this
);
$test = CRM_Utils_Request::retrieve('test', 'Boolean');
if (isset($test)) {
$test = CRM_Utils_Type::escape($test, 'Boolean');
$this->_formValues['contribution_test'] = $test;
}
//Recurring id
$recur = CRM_Utils_Request::retrieve('recur', 'Positive', $this, FALSE);
if ($recur) {
$this->_formValues['contribution_recur_id'] = $recur;
$this->_formValues['contribution_recurring'] = 1;
}
//check for contribution page id.
$contribPageId = CRM_Utils_Request::retrieve('pid', 'Positive', $this);
if ($contribPageId) {
$this->_formValues['contribution_page_id'] = $contribPageId;
}
//give values to default.
$this->_defaults = $this->_formValues;
}
/**
* Return a descriptive name for the page, used in wizard header.
*
* @return string
*/
public function getTitle() {
return ts('Find Contributions');
}
}

View file

@ -0,0 +1,79 @@
<?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
*/
class CRM_Contribute_Form_SearchContribution extends CRM_Core_Form {
/**
* Build the form object.
*/
public function buildQuickForm() {
$attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_ContributionPage', 'title');
$attributes['style'] = 'width: 90%';
$this->add('text', 'title', ts('Find'), $attributes);
$financial_account = CRM_Contribute_PseudoConstant::financialType();
foreach ($financial_account as $contributionId => $contributionName) {
$this->addElement('checkbox', "financial_type_id[$contributionId]", 'Financial Type', $contributionName);
}
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', 'financial_type_id', 'campaign_id');
foreach ($fields as $field) {
if (isset($params[$field]) &&
!CRM_Utils_System::isNull($params[$field])
) {
$parent->set($field, $params[$field]);
}
else {
$parent->set($field, NULL);
}
}
}
}
}

View file

@ -0,0 +1,227 @@
<?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 build form elements for select existing or create new soft block.
*/
class CRM_Contribute_Form_SoftCredit {
/**
* Function used to build form element for soft credit block.
*
* @param CRM_Core_Form $form
*
* @return \CRM_Core_Form
*/
public static function buildQuickForm(&$form) {
if (!empty($form->_honor_block_is_active)) {
$ufJoinDAO = new CRM_Core_DAO_UFJoin();
$ufJoinDAO->module = 'soft_credit';
$ufJoinDAO->entity_id = $form->_id;
if ($ufJoinDAO->find(TRUE)) {
$jsonData = CRM_Contribute_BAO_ContributionPage::formatModuleData($ufJoinDAO->module_data, TRUE, 'soft_credit');
if ($jsonData) {
foreach (array('honor_block_title', 'honor_block_text') as $name) {
$form->assign($name, $jsonData[$name]);
}
$softCreditTypes = CRM_Core_OptionGroup::values("soft_credit_type", FALSE);
// radio button for Honor Type
foreach ($jsonData['soft_credit_types'] as $value) {
$honorTypes[$value] = $form->createElement('radio', NULL, NULL, $softCreditTypes[$value], $value);
}
$form->addGroup($honorTypes, 'soft_credit_type_id', NULL)->setAttribute('allowClear', TRUE);
}
}
return $form;
}
// by default generate 10 blocks
$item_count = 11;
$showSoftCreditRow = 2;
if ($form->getAction() & CRM_Core_Action::UPDATE) {
$form->_softCreditInfo = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($form->_id, TRUE);
}
elseif (!empty($form->_pledgeID)) {
//Check and select most recent completed contrubtion and use it to retrieve
//soft-credit information to use as default for current pledge payment, CRM-13981
$pledgePayments = CRM_Pledge_BAO_PledgePayment::getPledgePayments($form->_pledgeID);
foreach ($pledgePayments as $id => $record) {
if ($record['contribution_id']) {
$softCredits = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($record['contribution_id'], TRUE);
if ($record['status'] == 'Completed' && count($softCredits) > 0) {
$form->_softCreditInfo = $softCredits;
}
}
}
}
if (property_exists($form, "_softCreditInfo")) {
if (!empty($form->_softCreditInfo['soft_credit'])) {
$showSoftCreditRow = count($form->_softCreditInfo['soft_credit']);
$showSoftCreditRow++;
}
}
for ($rowNumber = 1; $rowNumber <= $item_count; $rowNumber++) {
$form->addEntityRef("soft_credit_contact_id[{$rowNumber}]", ts('Contact'), array('create' => TRUE));
$form->addMoney("soft_credit_amount[{$rowNumber}]", ts('Amount'), FALSE, NULL, FALSE);
$form->addSelect("soft_credit_type[{$rowNumber}]", array(
'entity' => 'contribution_soft',
'field' => 'soft_credit_type_id',
'label' => ts('Type'),
));
if (!empty($form->_softCreditInfo['soft_credit'][$rowNumber]['soft_credit_id'])) {
$form->add('hidden', "soft_credit_id[{$rowNumber}]",
$form->_softCreditInfo['soft_credit'][$rowNumber]['soft_credit_id']);
}
}
self::addPCPFields($form);
$form->assign('showSoftCreditRow', $showSoftCreditRow);
$form->assign('rowCount', $item_count);
$form->addElement('hidden', 'sct_default_id',
CRM_Core_OptionGroup::getDefaultValue("soft_credit_type"),
array('id' => 'sct_default_id')
);
}
/**
* Add PCP fields for the new contribution form and others.
*
* @param CRM_Core_Form &$form
* The form being built.
* @param string $suffix
* A suffix to add to field names.
*/
public static function addPCPFields(&$form, $suffix = '') {
// CRM-7368 allow user to set or edit PCP link for contributions
$siteHasPCPs = CRM_Contribute_PseudoConstant::pcPage();
if (!CRM_Utils_Array::crmIsEmptyArray($siteHasPCPs)) {
$form->assign('siteHasPCPs', 1);
// Fixme: Not a true entityRef field. Relies on PCP.js.tpl
$form->add('text', "pcp_made_through_id$suffix", ts('Credit to a Personal Campaign Page'), array('class' => 'twenty', 'placeholder' => ts('- select -')));
// stores the label
$form->add('hidden', "pcp_made_through$suffix");
$form->addElement('checkbox', "pcp_display_in_roll$suffix", ts('Display in Honor Roll?'), NULL);
$form->addElement('text', "pcp_roll_nickname$suffix", ts('Name (for Honor Roll)'));
$form->addElement('textarea', "pcp_personal_note$suffix", ts('Personal Note (for Honor Roll)'));
}
}
/**
* Function used to set defaults for soft credit block.
*
* @param $defaults
* @param $form
*/
public static function setDefaultValues(&$defaults, &$form) {
//Used to hide/unhide PCP and/or Soft-credit Panes
$noPCP = $noSoftCredit = TRUE;
if (!empty($form->_softCreditInfo['soft_credit'])) {
$noSoftCredit = FALSE;
foreach ($form->_softCreditInfo['soft_credit'] as $key => $value) {
$defaults["soft_credit_amount[$key]"] = CRM_Utils_Money::format($value['amount'], NULL, '%a');
$defaults["soft_credit_contact_id[$key]"] = $value['contact_id'];
$defaults["soft_credit_type[$key]"] = $value['soft_credit_type'];
}
}
if (!empty($form->_softCreditInfo['pcp_id'])) {
$noPCP = FALSE;
$pcpInfo = $form->_softCreditInfo;
$pcpId = CRM_Utils_Array::value('pcp_id', $pcpInfo);
$pcpTitle = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $pcpId, 'title');
$contributionPageTitle = CRM_PCP_BAO_PCP::getPcpPageTitle($pcpId, 'contribute');
$defaults['pcp_made_through'] = CRM_Utils_Array::value('sort_name', $pcpInfo) . " :: " . $pcpTitle . " :: " . $contributionPageTitle;
$defaults['pcp_made_through_id'] = CRM_Utils_Array::value('pcp_id', $pcpInfo);
$defaults['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $pcpInfo);
$defaults['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $pcpInfo);
$defaults['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $pcpInfo);
}
$form->assign('noSoftCredit', $noSoftCredit);
$form->assign('noPCP', $noPCP);
}
/**
* Global form rule.
*
* @param array $fields
* The input form values.
*
* @param $errors
* @param $self
*
* @return array
* Array of errors
*/
public static function formRule($fields, $errors, $self) {
$errors = array();
// if honor roll fields are populated but no PCP is selected
if (empty($fields['pcp_made_through_id'])) {
if (!empty($fields['pcp_display_in_roll']) || !empty($fields['pcp_roll_nickname']) ||
CRM_Utils_Array::value('pcp_personal_note', $fields)
) {
$errors['pcp_made_through_id'] = ts('Please select a Personal Campaign Page, OR uncheck Display in Honor Roll and clear both the Honor Roll Name and the Personal Note field.');
}
}
if (!empty($fields['soft_credit_amount'])) {
$repeat = array_count_values($fields['soft_credit_contact_id']);
foreach ($fields['soft_credit_amount'] as $key => $val) {
if (!empty($fields['soft_credit_contact_id'][$key])) {
if ($repeat[$fields['soft_credit_contact_id'][$key]] > 1) {
$errors["soft_credit_contact_id[$key]"] = ts('You cannot enter multiple soft credits for the same contact.');
}
if ($self->_action == CRM_Core_Action::ADD && $fields['soft_credit_amount'][$key]
&& (CRM_Utils_Rule::cleanMoney($fields['soft_credit_amount'][$key]) > CRM_Utils_Rule::cleanMoney($fields['total_amount']))
) {
$errors["soft_credit_amount[$key]"] = ts('Soft credit amount cannot be more than the total amount.');
}
if (empty($fields['soft_credit_amount'][$key])) {
$errors["soft_credit_amount[$key]"] = ts('Please enter the soft credit amount.');
}
}
}
}
return $errors;
}
}

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
*/
/**
* This class generates form components for relationship.
*/
class CRM_Contribute_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 contribution ids.
*
* @var array
*/
protected $_contributionIds;
/**
* The array that holds all the contact ids.
*
* @var array
*/
public $_contactIds;
/**
* The array that holds all the mapping contribution and contact ids.
*
* @var array
*/
protected $_contributionContactIds = array();
/**
* The flag to tell if there are soft credits included.
*
* @var boolean
*/
public $_includesSoftCredits = FALSE;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
self::preProcessCommon($this);
}
/**
* @param CRM_Core_Form $form
* @param bool $useTable
*/
public static function preProcessCommon(&$form, $useTable = FALSE) {
$form->_contributionIds = array();
$values = $form->controller->exportValues($form->get('searchFormName'));
$form->_task = CRM_Utils_Array::value('task', $values);
$contributeTasks = CRM_Contribute_Task::tasks();
$form->assign('taskName', CRM_Utils_Array::value($form->_task, $contributeTasks));
$ids = array();
if (isset($values['radio_ts']) && $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');
$isTest = FALSE;
foreach ($queryParams as $fields) {
if ($fields[0] == 'contribution_test') {
$isTest = TRUE;
break;
}
}
if (!$isTest) {
$queryParams[] = array(
'contribution_test',
'=',
0,
0,
0,
);
}
$returnProperties = array('contribution_id' => 1);
$sortOrder = $sortCol = NULL;
if ($form->get(CRM_Utils_Sort::SORT_ORDER)) {
$sortOrder = $form->get(CRM_Utils_Sort::SORT_ORDER);
//Include sort column in select clause.
$sortCol = trim(str_replace(array('`', 'asc', 'desc'), '', $sortOrder));
$returnProperties[$sortCol] = 1;
}
$form->_includesSoftCredits = CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled($queryParams);
$query = new CRM_Contact_BAO_Query($queryParams, $returnProperties, NULL, FALSE, FALSE,
CRM_Contact_BAO_Query::MODE_CONTRIBUTE
);
// @todo the function CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled should handle this
// can we remove? if not why not?
if ($form->_includesSoftCredits) {
$contactIds = $contributionContactIds = array();
$query->_rowCountClause = " count(civicrm_contribution.id)";
$query->_groupByComponentClause = " GROUP BY contribution_search_scredit_combined.id, contribution_search_scredit_combined.contact_id, contribution_search_scredit_combined.scredit_id ";
}
else {
$query->_distinctComponentClause = ' civicrm_contribution.id';
$query->_groupByComponentClause = ' GROUP BY civicrm_contribution.id ';
}
$result = $query->searchQuery(0, 0, $sortOrder);
while ($result->fetch()) {
$ids[] = $result->contribution_id;
if ($form->_includesSoftCredits) {
$contactIds[$result->contact_id] = $result->contact_id;
$contributionContactIds["{$result->contact_id}-{$result->contribution_id}"] = $result->contribution_id;
}
}
$result->free();
$form->assign('totalSelectedContributions', $form->get('rowCount'));
}
if (!empty($ids)) {
$form->_componentClause = ' civicrm_contribution.id IN ( ' . implode(',', $ids) . ' ) ';
$form->assign('totalSelectedContributions', count($ids));
}
if (!empty($form->_includesSoftCredits) && !empty($contactIds)) {
$form->_contactIds = $contactIds;
$form->_contributionContactIds = $contributionContactIds;
}
$form->_contributionIds = $form->_componentIds = $ids;
$form->set('contributionIds', $form->_contributionIds);
//set the context for redirection for any task actions
$session = CRM_Core_Session::singleton();
$qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $form);
$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/contribute/search', $urlParams));
}
else {
$session->replaceUserContext(CRM_Utils_System::url("civicrm/contact/search/$searchFormName",
$urlParams
));
}
}
/**
* Sets contribution Ids for unit test.
*
* @param array $contributionIds
*/
public function setContributionIds($contributionIds) {
$this->_contributionIds = $contributionIds;
}
/**
* Given the contribution id, compute the contact id
* since its used for things like send email
*/
public function setContactIDs() {
if (!$this->_includesSoftCredits) {
$this->_contactIds = &CRM_Core_DAO::getContactIDsFromComponent(
$this->_contributionIds,
'civicrm_contribution'
);
}
}
/**
* 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
* Button type for the form after processing.
* @param string $backType
* @param bool $submitOnce
*/
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,240 @@
<?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 provides the functionality for batch profile update for contributions.
*/
class CRM_Contribute_Form_Task_Batch extends CRM_Contribute_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;
/**
* Build all the data structures needed to build the form.
*/
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->_contributionIds,
'CiviContribute', $returnProperties
);
$this->assign('contactDetails', $contactDetails);
$this->assign('readOnlyFields', $readOnlyFields);
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$ufGroupId = $this->get('ufGroupId');
if (!$ufGroupId) {
CRM_Core_Error::fatal('ufGroupId is missing');
}
$this->_title = ts('Update multiple contributions') . ' - ' . 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);
// 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']) && !empty($this->_fields[$name]['attributes']['size']) && $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 Contribution(s)'),
'isDefault' => TRUE,
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
)
);
$this->assign('profileTitle', $this->_title);
$this->assign('componentIds', $this->_contributionIds);
//load all campaigns.
if (array_key_exists('contribution_campaign_id', $this->_fields)) {
$this->_componentCampaigns = array();
CRM_Core_PseudoConstant::populate($this->_componentCampaigns,
'CRM_Contribute_DAO_Contribution',
TRUE, 'campaign_id', 'id',
' id IN (' . implode(' , ', array_values($this->_contributionIds)) . ' ) '
);
}
// It is possible to have fields that are required in CiviCRM not be required in the
// profile. Overriding that here. Perhaps a better approach would be to
// make them required in the schema & read that up through getFields functionality.
$requiredFields = array('receive_date');
//fix for CRM-2752
$customFields = CRM_Core_BAO_CustomField::getFields('Contribution');
foreach ($this->_contributionIds as $contributionId) {
$typeId = CRM_Core_DAO::getFieldValue("CRM_Contribute_DAO_Contribution", $contributionId, 'financial_type_id');
foreach ($this->_fields as $name => $field) {
$entityColumnValue = array();
if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
$customValue = CRM_Utils_Array::value($customFieldID, $customFields);
if (!empty($customValue['extends_entity_column_value'])) {
$entityColumnValue = explode(CRM_Core_DAO::VALUE_SEPARATOR,
$customValue['extends_entity_column_value']
);
}
if (!empty($entityColumnValue[$typeId]) ||
CRM_Utils_System::isNull(CRM_Utils_Array::value($typeId, $entityColumnValue))
) {
CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $contributionId);
}
}
else {
// handle non custom fields
if (in_array($field['name'], $requiredFields)) {
$field['is_required'] = TRUE;
}
CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, $contributionId);
}
}
}
$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 contributions."), ts('Unsupported Field Type'), 'error');
}
$this->addDefaultButtons(ts('Update Contributions'));
}
/**
* Set default values for the form.
*/
public function setDefaultValues() {
if (empty($this->_fields)) {
return;
}
$defaults = array();
foreach ($this->_contributionIds as $contributionId) {
CRM_Core_BAO_UFGroup::setProfileDefaults(NULL, $this->_fields, $defaults, FALSE, $contributionId, 'Contribute');
}
return $defaults;
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
$params = $this->exportValues();
if (isset($params['field'])) {
foreach ($params['field'] as $contributionID => $value) {
$value['id'] = $contributionID;
if (!empty($value['financial_type'])) {
$value['financial_type_id'] = $value['financial_type'];
}
$value['options'] = array(
'reload' => 1,
);
$contribution = civicrm_api3('Contribution', 'create', $value);
$contribution = $contribution['values'][$contributionID];
// @todo add check as to whether the status is updated.
if (!empty($value['contribution_status_id'])) {
// @todo - use completeorder api or make api call do this.
CRM_Contribute_BAO_Contribution::transitionComponentWithReturnMessage($contribution['id'],
$value['contribution_status_id'],
CRM_Utils_Array::value("field[{$contributionID}][contribution_status_id]", $this->_defaultValues),
$contribution['receive_date']
);
}
}
CRM_Core_Session::setStatus(ts("Your updates have been saved."), ts('Saved'), 'success');
}
else {
CRM_Core_Session::setStatus(ts("No updates have been saved."), ts('Not Saved'), 'alert');
}
}
}

View file

@ -0,0 +1,127 @@
<?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 provides the functionality to delete a group of contributions.
*
* This class provides functionality for the actual deletion.
*/
class CRM_Contribute_Form_Task_Delete extends CRM_Contribute_Form_Task {
/**
* Are we operating in "single mode", i.e. deleting one
* specific contribution?
*
* @var boolean
*/
protected $_single = FALSE;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
//check for delete
if (!CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) {
CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
}
parent::preProcess();
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$count = 0;
if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
foreach ($this->_contributionIds as $key => $id) {
$finTypeID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $id, 'financial_type_id');
if (!CRM_Core_Permission::check('delete contributions of type ' . CRM_Contribute_PseudoConstant::financialType($finTypeID))) {
unset($this->_contributionIds[$key]);
$count++;
}
// Now check for lineItems
if ($lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($id)) {
foreach ($lineItems as $items) {
if (!CRM_Core_Permission::check('delete contributions of type ' . CRM_Contribute_PseudoConstant::financialType($items['financial_type_id']))) {
unset($this->_contributionIds[$key]);
$count++;
break;
}
}
}
}
}
if ($count && empty($this->_contributionIds)) {
CRM_Core_Session::setStatus(ts('1 contribution could not be deleted.', array('plural' => '%count contributions could not be deleted.', 'count' => $count)), ts('Error'), 'error');
$this->addButtons(array(
array(
'type' => 'back',
'name' => ts('Cancel'),
),
)
);
}
elseif ($count && !empty($this->_contributionIds)) {
CRM_Core_Session::setStatus(ts('1 contribution will not be deleted.', array('plural' => '%count contributions will not be deleted.', 'count' => $count)), ts('Warning'), 'warning');
$this->addDefaultButtons(ts('Delete Contributions'), 'done');
}
else {
$this->addDefaultButtons(ts('Delete Contributions'), 'done');
}
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
$deleted = $failed = 0;
foreach ($this->_contributionIds as $contributionId) {
if (CRM_Contribute_BAO_Contribution::deleteContribution($contributionId)) {
$deleted++;
}
else {
$failed++;
}
}
if ($deleted) {
$msg = ts('%count contribution deleted.', array('plural' => '%count contributions deleted.', 'count' => $deleted));
CRM_Core_Session::setStatus($msg, ts('Removed'), 'success');
}
if ($failed) {
CRM_Core_Session::setStatus(ts('1 could not be deleted.', array('plural' => '%count could not be deleted.', 'count' => $failed)), ts('Error'), 'error');
}
}
}

View file

@ -0,0 +1,97 @@
<?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 provides the functionality to email a group of contacts.
*/
class CRM_Contribute_Form_Task_Email extends CRM_Contribute_Form_Task {
/**
* Are we operating in "single mode", i.e. sending email to one
* specific contact?
*
* @var boolean
*/
public $_single = FALSE;
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 contribution 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();
$tokens = array_merge(CRM_Core_SelectValues::contributionTokens(), $tokens);
return $tokens;
}
}

View file

@ -0,0 +1,683 @@
<?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 Dompdf\Dompdf;
use Dompdf\Options;
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* This class provides the functionality to email a group of
* contacts.
*/
class CRM_Contribute_Form_Task_Invoice extends CRM_Contribute_Form_Task {
/**
* Are we operating in "single mode", i.e. updating the task of only
* one specific contribution?
*
* @var boolean
*/
public $_single = FALSE;
/**
* Gives all the statues for conribution.
*/
public $_contributionStatusId;
/**
* Gives the HTML template of PDF Invoice.
*/
public $_messageInvoice;
/**
* This variable is used to assign parameters for HTML template of PDF Invoice.
*/
public $_invoiceTemplate;
/**
* Selected output.
*/
public $_selectedOutput;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
$id = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE);
if ($id) {
$this->_contributionIds = array($id);
$this->_componentClause = " civicrm_contribution.id IN ( $id ) ";
$this->_single = TRUE;
$this->assign('totalSelectedContributions', 1);
// set the redirection after actions
$contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, FALSE);
$url = CRM_Utils_System::url('civicrm/contact/view/contribution',
"action=view&reset=1&id={$id}&cid={$contactId}&context=contribution&selectedChild=contribute"
);
CRM_Core_Session::singleton()->pushUserContext($url);
}
else {
parent::preProcess();
}
// check that all the contribution ids have status Completed, Pending, Refunded.
$this->_contributionStatusId = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
$status = array('Completed', 'Pending', 'Refunded');
$statusId = array();
foreach ($this->_contributionStatusId as $key => $value) {
if (in_array($value, $status)) {
$statusId[] = $key;
}
}
$Id = implode(",", $statusId);
$query = "SELECT count(*) FROM civicrm_contribution WHERE contribution_status_id NOT IN ($Id) AND {$this->_componentClause}";
$count = CRM_Core_DAO::singleValueQuery($query);
if ($count != 0) {
CRM_Core_Error::statusBounce(ts('Please select only contributions with Completed, Pending, Refunded status.'));
}
// we have all the contribution ids, so now we get the contact ids
parent::setContactIDs();
$this->assign('single', $this->_single);
$qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this);
$urlParams = 'force=1';
if (CRM_Utils_Rule::qfKey($qfKey)) {
$urlParams .= "&qfKey=$qfKey";
}
$url = CRM_Utils_System::url('civicrm/contribute/search', $urlParams);
$breadCrumb = array(
array(
'url' => $url,
'title' => ts('Search Results'),
),
);
CRM_Utils_System::appendBreadCrumb($breadCrumb);
$this->_selectedOutput = CRM_Utils_Request::retrieve('select', 'String', $this);
$this->assign('selectedOutput', $this->_selectedOutput);
if ($this->_selectedOutput == 'email') {
CRM_Utils_System::setTitle(ts('Email Invoice'));
}
else {
CRM_Utils_System::setTitle(ts('Print Contribution Invoice'));
}
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$session = CRM_Core_Session::singleton();
$this->preventAjaxSubmit();
if (CRM_Core_Permission::check('administer CiviCRM')) {
$this->assign('isAdmin', 1);
}
$contactID = $session->get('userID');
$contactEmails = CRM_Core_BAO_Email::allEmails($contactID);
$emails = array();
$fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
$contactID, 'display_name'
);
foreach ($contactEmails as $emailId => $item) {
$email = $item['email'];
if ($email) {
$emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
}
if (isset($emails[$emailId])) {
$emails[$emailId] .= $item['locationType'];
if ($item['is_primary']) {
$emails[$emailId] .= ' ' . ts('(preferred)');
}
$emails[$emailId] = htmlspecialchars($emails[$emailId]);
}
}
$fromEmailAddress = CRM_Core_OptionGroup::values('from_email_address');
foreach ($fromEmailAddress as $key => $email) {
$fromEmailAddress[$key] = htmlspecialchars($fromEmailAddress[$key]);
}
$fromEmail = CRM_Utils_Array::crmArrayMerge($emails, $fromEmailAddress);
$this->add('select', 'from_email_address', ts('From Email Address'), array('' => '- select -') + $fromEmail);
if ($this->_selectedOutput != 'email') {
$this->addElement('radio', 'output', NULL, ts('Email Invoice'), 'email_invoice');
$this->addElement('radio', 'output', NULL, ts('PDF Invoice'), 'pdf_invoice');
$this->addRule('output', ts('Selection required'), 'required');
$this->addFormRule(array('CRM_Contribute_Form_Task_Invoice', 'formRule'));
}
else {
$this->addRule('from_email_address', ts('From Email Address is required'), 'required');
}
$this->add('wysiwyg', 'email_comment', ts('If you would like to add personal message to email please add it here. (If sending to more then one receipient the same message will be sent to each contact.)'), array(
'rows' => 2,
'cols' => 40,
));
$this->addButtons(array(
array(
'type' => 'upload',
'name' => $this->_selectedOutput == 'email' ? ts('Send Email') : ts('Process Invoice(s)'),
'isDefault' => TRUE,
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
)
);
}
/**
* 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['output'] == 'email_invoice' && empty($values['from_email_address'])) {
$errors['from_email_address'] = ts("From Email Address is required");
}
return $errors;
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
$params = $this->controller->exportValues($this->_name);
self::printPDF($this->_contributionIds, $params, $this->_contactIds);
}
/**
* Process the PDf and email with activity and attachment on click of Print Invoices.
*
* @param array $contribIDs
* Contribution Id.
* @param array $params
* Associated array of submitted values.
* @param array $contactIds
* Contact Id.
*/
public static function printPDF($contribIDs, &$params, $contactIds) {
// get all the details needed to generate a invoice
$messageInvoice = array();
$invoiceTemplate = CRM_Core_Smarty::singleton();
$invoiceElements = CRM_Contribute_Form_Task_PDF::getElements($contribIDs, $params, $contactIds);
// gives the status id when contribution status is 'Refunded'
$contributionStatusID = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
$refundedStatusId = CRM_Utils_Array::key('Refunded', $contributionStatusID);
$cancelledStatusId = CRM_Utils_Array::key('Cancelled', $contributionStatusID);
$pendingStatusId = CRM_Utils_Array::key('Pending', $contributionStatusID);
// getting data from admin page
$prefixValue = Civi::settings()->get('contribution_invoice_settings');
foreach ($invoiceElements['details'] as $contribID => $detail) {
$input = $ids = $objects = array();
if (in_array($detail['contact'], $invoiceElements['excludeContactIds'])) {
continue;
}
$input['component'] = $detail['component'];
$ids['contact'] = $detail['contact'];
$ids['contribution'] = $contribID;
$ids['contributionRecur'] = NULL;
$ids['contributionPage'] = NULL;
$ids['membership'] = CRM_Utils_Array::value('membership', $detail);
$ids['participant'] = CRM_Utils_Array::value('participant', $detail);
$ids['event'] = CRM_Utils_Array::value('event', $detail);
if (!$invoiceElements['baseIPN']->validateData($input, $ids, $objects, FALSE)) {
CRM_Core_Error::fatal();
}
$contribution = &$objects['contribution'];
$input['amount'] = $contribution->total_amount;
$input['invoice_id'] = $contribution->invoice_id;
$input['receive_date'] = $contribution->receive_date;
$input['contribution_status_id'] = $contribution->contribution_status_id;
$input['organization_name'] = $contribution->_relatedObjects['contact']->organization_name;
$objects['contribution']->receive_date = CRM_Utils_Date::isoToMysql($objects['contribution']->receive_date);
$addressParams = array('contact_id' => $contribution->contact_id);
$addressDetails = CRM_Core_BAO_Address::getValues($addressParams);
// to get billing address if present
$billingAddress = array();
foreach ($addressDetails as $address) {
if (($address['is_billing'] == 1) && ($address['is_primary'] == 1) && ($address['contact_id'] == $contribution->contact_id)) {
$billingAddress[$address['contact_id']] = $address;
break;
}
elseif (($address['is_billing'] == 0 && $address['is_primary'] == 1) || ($address['is_billing'] == 1) && ($address['contact_id'] == $contribution->contact_id)) {
$billingAddress[$address['contact_id']] = $address;
}
}
if (!empty($billingAddress[$contribution->contact_id]['state_province_id'])) {
$stateProvinceAbbreviation = CRM_Core_PseudoConstant::stateProvinceAbbreviation($billingAddress[$contribution->contact_id]['state_province_id']);
}
else {
$stateProvinceAbbreviation = '';
}
if ($contribution->contribution_status_id == $refundedStatusId || $contribution->contribution_status_id == $cancelledStatusId) {
if (is_null($contribution->creditnote_id)) {
$creditNoteId = CRM_Contribute_BAO_Contribution::createCreditNoteId();
CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'creditnote_id', $creditNoteId);
}
else {
$creditNoteId = $contribution->creditnote_id;
}
}
if (!$contribution->invoice_number) {
$contribution->invoice_number = CRM_Contribute_BAO_Contribution::getInvoiceNumber($contribution->id);
}
//to obtain due date for PDF invoice
$contributionReceiveDate = date('F j,Y', strtotime(date($input['receive_date'])));
$invoiceDate = date("F j, Y");
$dueDate = date('F j, Y', strtotime($contributionReceiveDate . "+" . $prefixValue['due_date'] . "" . $prefixValue['due_date_period']));
if ($input['component'] == 'contribute') {
$lineItem = CRM_Price_BAO_LineItem::getLineItemsByContributionID($contribID);
}
else {
$eid = $contribution->_relatedObjects['participant']->id;
$lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, 'participant', NULL, TRUE, FALSE, TRUE);
}
$resultPayments = civicrm_api3('Payment', 'get', array(
'sequential' => 1,
'contribution_id' => $contribID,
));
$amountPaid = 0;
foreach ($resultPayments['values'] as $singlePayment) {
// Only count payments that have been (status =) completed.
if ($singlePayment['status_id'] == 1) {
$amountPaid += $singlePayment['total_amount'];
}
}
$amountDue = ($input['amount'] - $amountPaid);
// retrieving the subtotal and sum of same tax_rate
$dataArray = array();
$subTotal = 0;
foreach ($lineItem as $taxRate) {
if (isset($dataArray[(string) $taxRate['tax_rate']])) {
$dataArray[(string) $taxRate['tax_rate']] = $dataArray[(string) $taxRate['tax_rate']] + CRM_Utils_Array::value('tax_amount', $taxRate);
}
else {
$dataArray[(string) $taxRate['tax_rate']] = CRM_Utils_Array::value('tax_amount', $taxRate);
}
$subTotal += CRM_Utils_Array::value('subTotal', $taxRate);
}
// to email the invoice
$mailDetails = array();
$values = array();
if ($contribution->_component == 'event') {
$daoName = 'CRM_Event_DAO_Event';
$pageId = $contribution->_relatedObjects['event']->id;
$mailElements = array(
'title',
'confirm_from_name',
'confirm_from_email',
'cc_confirm',
'bcc_confirm',
);
CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
$values['title'] = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]);
$values['confirm_from_name'] = CRM_Utils_Array::value('confirm_from_name', $mailDetails[$contribution->_relatedObjects['event']->id]);
$values['confirm_from_email'] = CRM_Utils_Array::value('confirm_from_email', $mailDetails[$contribution->_relatedObjects['event']->id]);
$values['cc_confirm'] = CRM_Utils_Array::value('cc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]);
$values['bcc_confirm'] = CRM_Utils_Array::value('bcc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]);
$title = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]);
}
elseif ($contribution->_component == 'contribute') {
$daoName = 'CRM_Contribute_DAO_ContributionPage';
$pageId = $contribution->contribution_page_id;
$mailElements = array(
'title',
'receipt_from_name',
'receipt_from_email',
'cc_receipt',
'bcc_receipt',
);
CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
$values['title'] = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
$values['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
$values['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
$values['cc_receipt'] = CRM_Utils_Array::value('cc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
$values['bcc_receipt'] = CRM_Utils_Array::value('bcc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
$title = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
}
$source = $contribution->source;
$config = CRM_Core_Config::singleton();
if (!isset($params['forPage'])) {
$config->doNotAttachPDFReceipt = 1;
}
// get organization address
$domain = CRM_Core_BAO_Domain::getDomain();
$locParams = array('contact_id' => $domain->contact_id);
$locationDefaults = CRM_Core_BAO_Location::getValues($locParams);
if (isset($locationDefaults['address'][1]['state_province_id'])) {
$stateProvinceAbbreviationDomain = CRM_Core_PseudoConstant::stateProvinceAbbreviation($locationDefaults['address'][1]['state_province_id']);
}
else {
$stateProvinceAbbreviationDomain = '';
}
if (isset($locationDefaults['address'][1]['country_id'])) {
$countryDomain = CRM_Core_PseudoConstant::country($locationDefaults['address'][1]['country_id']);
}
else {
$countryDomain = '';
}
// parameters to be assign for template
$tplParams = array(
'title' => $title,
'component' => $input['component'],
'id' => $contribution->id,
'source' => $source,
'invoice_number' => $contribution->invoice_number,
'invoice_id' => $contribution->invoice_id,
'resourceBase' => $config->userFrameworkResourceURL,
'defaultCurrency' => $config->defaultCurrency,
'amount' => $contribution->total_amount,
'amountDue' => $amountDue,
'amountPaid' => $amountPaid,
'invoice_date' => $invoiceDate,
'dueDate' => $dueDate,
'notes' => CRM_Utils_Array::value('notes', $prefixValue),
'display_name' => $contribution->_relatedObjects['contact']->display_name,
'lineItem' => $lineItem,
'dataArray' => $dataArray,
'refundedStatusId' => $refundedStatusId,
'pendingStatusId' => $pendingStatusId,
'cancelledStatusId' => $cancelledStatusId,
'contribution_status_id' => $contribution->contribution_status_id,
'subTotal' => $subTotal,
'street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
'supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
'supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
'supplemental_address_3' => CRM_Utils_Array::value('supplemental_address_3', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
'city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
'stateProvinceAbbreviation' => $stateProvinceAbbreviation,
'postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
'is_pay_later' => $contribution->is_pay_later,
'organization_name' => $contribution->_relatedObjects['contact']->organization_name,
'domain_organization' => $domain->name,
'domain_street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value('1', $locationDefaults['address'])),
'domain_supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value('1', $locationDefaults['address'])),
'domain_supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value('1', $locationDefaults['address'])),
'domain_supplemental_address_3' => CRM_Utils_Array::value('supplemental_address_3', CRM_Utils_Array::value('1', $locationDefaults['address'])),
'domain_city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value('1', $locationDefaults['address'])),
'domain_postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value('1', $locationDefaults['address'])),
'domain_state' => $stateProvinceAbbreviationDomain,
'domain_country' => $countryDomain,
'domain_email' => CRM_Utils_Array::value('email', CRM_Utils_Array::value('1', $locationDefaults['email'])),
'domain_phone' => CRM_Utils_Array::value('phone', CRM_Utils_Array::value('1', $locationDefaults['phone'])),
);
if (isset($creditNoteId)) {
$tplParams['creditnote_id'] = $creditNoteId;
}
$pdfFileName = $contribution->invoice_number . ".pdf";
$sendTemplateParams = array(
'groupName' => 'msg_tpl_workflow_contribution',
'valueName' => 'contribution_invoice_receipt',
'contactId' => $contribution->contact_id,
'tplParams' => $tplParams,
'PDFFilename' => $pdfFileName,
);
$session = CRM_Core_Session::singleton();
$contactID = $session->get('userID');
//CRM-16319 - we dont store in userID in case the user is doing multiple
//transactions etc
if (empty($contactID)) {
$contactID = $session->get('transaction.userID');
}
// Fix Invoice email doesnot send out when completed payment using Paypal
if (empty($contactID)) {
$contactID = current($contactIds);
}
$contactEmails = CRM_Core_BAO_Email::allEmails($contactID);
$emails = array();
$fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
$contactID, 'display_name'
);
foreach ($contactEmails as $emailId => $item) {
$email = $item['email'];
if ($email) {
$emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
}
}
$fromEmail = CRM_Utils_Array::crmArrayMerge($emails, CRM_Core_OptionGroup::values('from_email_address'));
// from email address
if (isset($params['from_email_address'])) {
$fromEmailAddress = CRM_Utils_Array::value($params['from_email_address'], $fromEmail);
}
// condition to check for download PDF Invoice or email Invoice
if ($invoiceElements['createPdf']) {
list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
if (isset($params['forPage'])) {
return $html;
}
else {
$mail = array(
'subject' => $subject,
'body' => $message,
'html' => $html,
);
if ($mail['html']) {
$messageInvoice[] = $mail['html'];
}
else {
$messageInvoice[] = nl2br($mail['body']);
}
}
}
elseif ($contribution->_component == 'contribute') {
$email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
$sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
$sendTemplateParams['from'] = $fromEmailAddress;
$sendTemplateParams['toEmail'] = $email;
$sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_receipt', $values);
$sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $values);
list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
// functions call for adding activity with attachment
$pdfFileName = "{$invoiceNumber}.pdf";
$fileName = self::putFile($html, $pdfFileName);
self::addActivities($subject, $contribution->contact_id, $fileName, $params);
}
elseif ($contribution->_component == 'event') {
$email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
$sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
$sendTemplateParams['from'] = $fromEmailAddress;
$sendTemplateParams['toEmail'] = $email;
$sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_confirm', $values);
$sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_confirm', $values);
list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
// functions call for adding activity with attachment
$pdfFileName = "{$invoiceNumber}.pdf";
$fileName = self::putFile($html, $pdfFileName);
self::addActivities($subject, $contribution->contact_id, $fileName, $params);
}
$invoiceTemplate->clearTemplateVars();
}
if ($invoiceElements['createPdf']) {
if (isset($params['forPage'])) {
return $html;
}
else {
$pdfFileName = "{$invoiceNumber}.pdf";
CRM_Utils_PDF_Utils::html2pdf($messageInvoice, $pdfFileName, FALSE, array(
'margin_top' => 10,
'margin_left' => 65,
'metric' => 'px',
));
// functions call for adding activity with attachment
$fileName = self::putFile($html, $pdfFileName);
self::addActivities($subject, $contactIds, $fileName, $params);
CRM_Utils_System::civiExit();
}
}
else {
if ($invoiceElements['suppressedEmails']) {
$status = ts('Email was NOT sent to %1 contacts (no email address on file, or communication preferences specify DO NOT EMAIL, or contact is deceased).', array(1 => $invoiceElements['suppressedEmails']));
$msgTitle = ts('Email Error');
$msgType = 'error';
}
else {
$status = ts('Your mail has been sent.');
$msgTitle = ts('Sent');
$msgType = 'success';
}
CRM_Core_Session::setStatus($status, $msgTitle, $msgType);
}
}
/**
* Add activity for Email Invoice and the PDF Invoice.
*
* @param string $subject
* Activity subject.
* @param array $contactIds
* Contact Id.
* @param string $fileName
* Gives the location with name of the file.
* @param array $params
* For invoices.
*
*/
static public function addActivities($subject, $contactIds, $fileName, $params) {
$session = CRM_Core_Session::singleton();
$userID = $session->get('userID');
$config = CRM_Core_Config::singleton();
$config->doNotAttachPDFReceipt = 1;
if (!empty($params['output']) && $params['output'] == 'pdf_invoice') {
$activityTypeID = CRM_Core_PseudoConstant::getKey(
'CRM_Activity_DAO_Activity',
'activity_type_id',
'Downloaded Invoice'
);
}
else {
$activityTypeID = CRM_Core_PseudoConstant::getKey(
'CRM_Activity_DAO_Activity',
'activity_type_id',
'Emailed Invoice'
);
}
$activityParams = array(
'subject' => $subject,
'source_contact_id' => $userID,
'target_contact_id' => $contactIds,
'activity_type_id' => $activityTypeID,
'activity_date_time' => date('YmdHis'),
'attachFile_1' => array(
'uri' => $fileName,
'type' => 'application/pdf',
'location' => $fileName,
'upload_date' => date('YmdHis'),
),
);
CRM_Activity_BAO_Activity::create($activityParams);
}
/**
* Create the Invoice file in upload folder for attachment.
*
* @param string $html
* Content for pdf in html format.
*
* @param string $name
*
* @return string
* Name of file which is in pdf format
*/
static public function putFile($html, $name = 'Invoice.pdf') {
$options = new Options();
$options->set('isRemoteEnabled', TRUE);
$doc = new DOMPDF($options);
$doc->load_html($html);
$doc->render();
$html = $doc->output();
$config = CRM_Core_Config::singleton();
$fileName = $config->uploadDir . $name;
file_put_contents($fileName, $html);
return $fileName;
}
/**
* Callback to perform action on Print Invoice button.
*/
public static function getPrintPDF() {
$contributionId = CRM_Utils_Request::retrieve('id', 'Positive', CRM_Core_DAO::$_nullObject, FALSE);
$contributionIDs = array($contributionId);
$contactId = CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullObject, FALSE);
$params = array('output' => 'pdf_invoice');
CRM_Contribute_Form_Task_Invoice::printPDF($contributionIDs, $params, $contactId);
}
}

View file

@ -0,0 +1,308 @@
<?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 provides the functionality to email a group of
* contacts.
*/
class CRM_Contribute_Form_Task_PDF extends CRM_Contribute_Form_Task {
/**
* Are we operating in "single mode", i.e. updating the task of only
* one specific contribution?
*
* @var boolean
*/
public $_single = FALSE;
protected $_rows;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
$id = CRM_Utils_Request::retrieve('id', 'Positive',
$this, FALSE
);
if ($id) {
$this->_contributionIds = array($id);
$this->_componentClause = " civicrm_contribution.id IN ( $id ) ";
$this->_single = TRUE;
$this->assign('totalSelectedContributions', 1);
}
else {
parent::preProcess();
}
// check that all the contribution ids have pending status
$query = "
SELECT count(*)
FROM civicrm_contribution
WHERE contribution_status_id != 1
AND {$this->_componentClause}";
$count = CRM_Core_DAO::singleValueQuery($query);
if ($count != 0) {
CRM_Core_Error::statusBounce("Please select only online contributions with Completed status.");
}
$this->assign('single', $this->_single);
$qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this);
$urlParams = 'force=1';
if (CRM_Utils_Rule::qfKey($qfKey)) {
$urlParams .= "&qfKey=$qfKey";
}
$url = CRM_Utils_System::url('civicrm/contribute/search', $urlParams);
$breadCrumb = array(
array(
'url' => $url,
'title' => ts('Search Results'),
),
);
CRM_Contact_Form_Task_EmailCommon ::preProcessFromAddress($this, FALSE);
// we have all the contribution ids, so now we get the contact ids
parent::setContactIDs();
CRM_Utils_System::appendBreadCrumb($breadCrumb);
CRM_Utils_System::setTitle(ts('Print Contribution Receipts'));
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->addElement('radio', 'output', NULL, ts('Email Receipts'), 'email_receipt',
array(
'onClick' => "document.getElementById('selectPdfFormat').style.display = 'none';
document.getElementById('selectEmailFrom').style.display = 'block';")
);
$this->addElement('radio', 'output', NULL, ts('PDF Receipts'), 'pdf_receipt',
array('onClick' => "document.getElementById('selectPdfFormat').style.display = 'block';")
);
$this->addRule('output', ts('Selection required'), 'required');
$this->add('select', 'pdf_format_id', ts('Page Format'),
array(0 => ts('- default -')) + CRM_Core_BAO_PdfFormat::getList(TRUE)
);
$this->add('checkbox', 'receipt_update', ts('Update receipt dates for these contributions'), FALSE);
$this->add('checkbox', 'override_privacy', ts('Override privacy setting? (Do not email / Do not mail)'), FALSE);
$this->add('select', 'fromEmailAddress', ts('From Email'), $this->_fromEmails, FALSE, array('class' => 'crm-select2 huge'));
$this->addButtons(array(
array(
'type' => 'next',
'name' => ts('Process Receipt(s)'),
'isDefault' => TRUE,
),
array(
'type' => 'back',
'name' => ts('Cancel'),
),
)
);
}
/**
* Set default values.
*/
public function setDefaultValues() {
$defaultFormat = CRM_Core_BAO_PdfFormat::getDefaultValues();
return array('pdf_format_id' => $defaultFormat['id'], 'receipt_update' => 1, 'override_privacy' => 0);
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
// get all the details needed to generate a receipt
$message = array();
$template = CRM_Core_Smarty::singleton();
$params = $this->controller->exportValues($this->_name);
$elements = self::getElements($this->_contributionIds, $params, $this->_contactIds);
foreach ($elements['details'] as $contribID => $detail) {
$input = $ids = $objects = array();
if (in_array($detail['contact'], $elements['excludeContactIds'])) {
continue;
}
$input['component'] = $detail['component'];
$ids['contact'] = $detail['contact'];
$ids['contribution'] = $contribID;
$ids['contributionRecur'] = NULL;
$ids['contributionPage'] = NULL;
$ids['membership'] = CRM_Utils_Array::value('membership', $detail);
$ids['participant'] = CRM_Utils_Array::value('participant', $detail);
$ids['event'] = CRM_Utils_Array::value('event', $detail);
if (!$elements['baseIPN']->validateData($input, $ids, $objects, FALSE)) {
CRM_Core_Error::fatal();
}
$contribution = &$objects['contribution'];
// set some fake input values so we can reuse IPN code
$input['amount'] = $contribution->total_amount;
$input['is_test'] = $contribution->is_test;
$input['fee_amount'] = $contribution->fee_amount;
$input['net_amount'] = $contribution->net_amount;
$input['trxn_id'] = $contribution->trxn_id;
$input['trxn_date'] = isset($contribution->trxn_date) ? $contribution->trxn_date : NULL;
$input['receipt_update'] = $params['receipt_update'];
$input['contribution_status_id'] = $contribution->contribution_status_id;
$input['paymentProcessor'] = empty($contribution->trxn_id) ? NULL :
CRM_Core_DAO::singleValueQuery("SELECT payment_processor_id
FROM civicrm_financial_trxn
WHERE trxn_id = %1
LIMIT 1", array(
1 => array($contribution->trxn_id, 'String')));
// CRM_Contribute_BAO_Contribution::composeMessageArray expects mysql formatted date
$objects['contribution']->receive_date = CRM_Utils_Date::isoToMysql($objects['contribution']->receive_date);
$values = array();
if (isset($params['fromEmailAddress']) && !$elements['createPdf']) {
// CRM-19129 Allow useres the choice of From Email to send the receipt from.
$fromEmail = $params['fromEmailAddress'];
$from = CRM_Utils_Array::value($fromEmail, $this->_emails);
$fromDetails = explode(' <', $from);
$input['receipt_from_email'] = substr(trim($fromDetails[1]), 0, -1);
$input['receipt_from_name'] = str_replace('"', '', $fromDetails[0]);
}
$mail = CRM_Contribute_BAO_Contribution::sendMail($input, $ids, $objects['contribution']->id, $values,
$elements['createPdf']);
if ($mail['html']) {
$message[] = $mail['html'];
}
else {
$message[] = nl2br($mail['body']);
}
// reset template values before processing next transactions
$template->clearTemplateVars();
}
if ($elements['createPdf']) {
CRM_Utils_PDF_Utils::html2pdf($message,
'civicrmContributionReceipt.pdf',
FALSE,
$elements['params']['pdf_format_id']
);
CRM_Utils_System::civiExit();
}
else {
if ($elements['suppressedEmails']) {
$status = ts('Email was NOT sent to %1 contacts (no email address on file, or communication preferences specify DO NOT EMAIL, or contact is deceased).', array(1 => $elements['suppressedEmails']));
$msgTitle = ts('Email Error');
$msgType = 'error';
}
else {
$status = ts('Your mail has been sent.');
$msgTitle = ts('Sent');
$msgType = 'success';
}
CRM_Core_Session::setStatus($status, $msgTitle, $msgType);
}
}
/**
* Declaration of common variables for Invoice and PDF.
*
*
* @param array $contribIds
* Contribution Id.
* @param array $params
* Parameter for pdf or email invoices.
* @param array $contactIds
* Contact Id.
*
* @return array
* array of common elements
*
*/
static public function getElements($contribIds, $params, $contactIds) {
$pdfElements = array();
$pdfElements['contribIDs'] = implode(',', $contribIds);
$pdfElements['details'] = CRM_Contribute_Form_Task_Status::getDetails($pdfElements['contribIDs']);
$pdfElements['baseIPN'] = new CRM_Core_Payment_BaseIPN();
$pdfElements['params'] = $params;
$pdfElements['createPdf'] = FALSE;
if (!empty($pdfElements['params']['output']) &&
($pdfElements['params']['output'] == "pdf_invoice" || $pdfElements['params']['output'] == "pdf_receipt")
) {
$pdfElements['createPdf'] = TRUE;
}
$excludeContactIds = array();
if (!$pdfElements['createPdf']) {
$returnProperties = array(
'email' => 1,
'do_not_email' => 1,
'is_deceased' => 1,
'on_hold' => 1,
);
list($contactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, $returnProperties, FALSE, FALSE);
$pdfElements['suppressedEmails'] = 0;
$suppressedEmails = 0;
foreach ($contactDetails as $id => $values) {
if (empty($values['email']) ||
(empty($params['override_privacy']) && !empty($values['do_not_email']))
|| CRM_Utils_Array::value('is_deceased', $values)
|| !empty($values['on_hold'])
) {
$suppressedEmails++;
$pdfElements['suppressedEmails'] = $suppressedEmails;
$excludeContactIds[] = $values['contact_id'];
}
}
}
$pdfElements['excludeContactIds'] = $excludeContactIds;
return $pdfElements;
}
}

View file

@ -0,0 +1,174 @@
<?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 provides the functionality to create PDF letter for a group of contacts or a single contact.
*/
class CRM_Contribute_Form_Task_PDFLetter extends CRM_Contribute_Form_Task {
/**
* All the existing templates in the system.
*
* @var array
*/
public $_templates = NULL;
public $_single = NULL;
public $_cid = NULL;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
$this->skipOnHold = $this->skipDeceased = FALSE;
CRM_Contact_Form_Task_PDFLetterCommon::preProcess($this);
// store case id if present
$this->_caseId = CRM_Utils_Request::retrieve('caseid', 'Positive', $this, FALSE);
// retrieve contact ID if this is 'single' mode
$cid = CRM_Utils_Request::retrieve('cid', 'Positive', $this, FALSE);
$this->_activityId = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE);
if ($cid) {
CRM_Contact_Form_Task_PDFLetterCommon::preProcessSingle($this, $cid);
$this->_single = TRUE;
$this->_cid = $cid;
}
else {
parent::preProcess();
}
$this->assign('single', $this->_single);
}
/**
* This virtual function is used to set the default values of
* various form elements
*
* access public
*
* @return array
* reference to the array of default values
*/
/**
* @return array
*/
public function setDefaultValues() {
$defaults = array();
if (isset($this->_activityId)) {
$params = array('id' => $this->_activityId);
CRM_Activity_BAO_Activity::retrieve($params, $defaults);
$defaults['html_message'] = CRM_Utils_Array::value('details', $defaults);
}
else {
$defaults['thankyou_update'] = 1;
}
$defaults = $defaults + CRM_Contact_Form_Task_PDFLetterCommon::setDefaultValues();
return $defaults;
}
/**
* Build the form object.
*/
public function buildQuickForm() {
//enable form element
$this->assign('suppressForm', FALSE);
// use contact form as a base
CRM_Contact_Form_Task_PDFLetterCommon::buildQuickForm($this);
// specific need for contributions
$this->add('static', 'more_options_header', NULL, ts('Thank-you Letter Options'));
$this->add('checkbox', 'receipt_update', ts('Update receipt dates for these contributions'), FALSE);
$this->add('checkbox', 'thankyou_update', ts('Update thank-you dates for these contributions'), FALSE);
// Group options for tokens are not yet implemented. dgg
$options = array(
'' => ts('- no grouping -'),
'contact_id' => ts('Contact'),
'contribution_recur_id' => ts('Contact and Recurring'),
'financial_type_id' => ts('Contact and Financial Type'),
'campaign_id' => ts('Contact and Campaign'),
'payment_instrument_id' => ts('Contact and Payment Method'),
);
$this->addElement('select', 'group_by', ts('Group contributions by'), $options, array(), "<br/>", FALSE);
// this was going to be free-text but I opted for radio options in case there was a script injection risk
$separatorOptions = array('comma' => 'Comma', 'td' => 'Horizontal Table Cell', 'tr' => 'Vertical Table Cell', 'br' => 'Line Break');
$this->addElement('select', 'group_by_separator', ts('Separator (grouped contributions)'), $separatorOptions);
$emailOptions = array(
'' => ts('Generate PDFs for printing (only)'),
'email' => ts('Send emails where possible. Generate printable PDFs for contacts who cannot receive email.'),
'both' => ts('Send emails where possible. Generate printable PDFs for all contacts.'),
);
if (CRM_Core_Config::singleton()->doNotAttachPDFReceipt) {
$emailOptions['pdfemail'] = ts('Send emails with an attached PDF where possible. Generate printable PDFs for contacts who cannot receive email.');
$emailOptions['pdfemail_both'] = ts('Send emails with an attached PDF where possible. Generate printable PDFs for all contacts.');
}
$this->addElement('select', 'email_options', ts('Print and email options'), $emailOptions, array(), "<br/>", FALSE);
$this->addButtons(array(
array(
'type' => 'upload',
'name' => ts('Make Thank-you Letters'),
'isDefault' => TRUE,
),
array(
'type' => 'cancel',
'name' => ts('Done'),
),
)
);
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
CRM_Contribute_Form_Task_PDFLetterCommon::postProcess($this);
}
/**
* List available tokens for this form.
*
* @return array
*/
public function listTokens() {
$tokens = CRM_Core_SelectValues::contactTokens();
$tokens = array_merge(CRM_Core_SelectValues::contributionTokens(), $tokens);
return $tokens;
}
}

View file

@ -0,0 +1,428 @@
<?php
/**
* This class provides the common functionality for creating PDF letter for
* one or a group of contact ids.
*/
class CRM_Contribute_Form_Task_PDFLetterCommon extends CRM_Contact_Form_Task_PDFLetterCommon {
/**
* Process the form after the input has been submitted and validated.
*
* @param CRM_Contribute_Form_Task $form
* @param array $formValues
*/
public static function postProcess(&$form, $formValues = NULL) {
if (empty($formValues)) {
$formValues = $form->controller->exportValues($form->getName());
}
list($formValues, $categories, $html_message, $messageToken, $returnProperties) = self::processMessageTemplate($formValues);
$isPDF = FALSE;
$emailParams = array();
if (!empty($formValues['email_options'])) {
$returnProperties['email'] = $returnProperties['on_hold'] = $returnProperties['is_deceased'] = $returnProperties['do_not_email'] = 1;
$emailParams = array(
'subject' => $formValues['subject'],
);
// We need display_name for emailLetter() so add to returnProperties here
$returnProperties['display_name'] = 1;
if (stristr($formValues['email_options'], 'pdfemail')) {
$isPDF = TRUE;
}
}
// update dates ?
$receipt_update = isset($formValues['receipt_update']) ? $formValues['receipt_update'] : FALSE;
$thankyou_update = isset($formValues['thankyou_update']) ? $formValues['thankyou_update'] : FALSE;
$nowDate = date('YmdHis');
$receipts = $thanks = $emailed = 0;
$updateStatus = '';
$task = 'CRM_Contribution_Form_Task_PDFLetterCommon';
$realSeparator = ', ';
$tableSeparators = array(
'td' => '</td><td>',
'tr' => '</td></tr><tr><td>',
);
//the original thinking was mutliple options - but we are going with only 2 (comma & td) for now in case
// there are security (& UI) issues we need to think through
if (isset($formValues['group_by_separator'])) {
if (in_array($formValues['group_by_separator'], array('td', 'tr'))) {
$realSeparator = $tableSeparators[$formValues['group_by_separator']];
}
elseif ($formValues['group_by_separator'] == 'br') {
$realSeparator = "<br />";
}
}
$separator = '****~~~~';// a placeholder in case the separator is common in the string - e.g ', '
$groupBy = $formValues['group_by'];
// skip some contacts ?
$skipOnHold = isset($form->skipOnHold) ? $form->skipOnHold : FALSE;
$skipDeceased = isset($form->skipDeceased) ? $form->skipDeceased : TRUE;
$contributionIDs = $form->getVar('_contributionIds');
if ($form->_includesSoftCredits) {
//@todo - comment on what is stored there
$contributionIDs = $form->getVar('_contributionContactIds');
}
list($contributions, $contacts) = self::buildContributionArray($groupBy, $contributionIDs, $returnProperties, $skipOnHold, $skipDeceased, $messageToken, $task, $separator, $form->_includesSoftCredits);
$html = array();
$contactHtml = $emailedHtml = array();
foreach ($contributions as $contributionId => $contribution) {
$contact = &$contacts[$contribution['contact_id']];
$grouped = FALSE;
$groupByID = 0;
if ($groupBy) {
$groupByID = empty($contribution[$groupBy]) ? 0 : $contribution[$groupBy];
$contribution = $contact['combined'][$groupBy][$groupByID];
$grouped = TRUE;
}
if (empty($groupBy) || empty($contact['is_sent'][$groupBy][$groupByID])) {
$html[$contributionId] = self::generateHtml($contact, $contribution, $groupBy, $contributions, $realSeparator, $tableSeparators, $messageToken, $html_message, $separator, $grouped, $groupByID);
$contactHtml[$contact['contact_id']][] = $html[$contributionId];
if (!empty($formValues['email_options'])) {
if (self::emailLetter($contact, $html[$contributionId], $isPDF, $formValues, $emailParams)) {
$emailed++;
if (!stristr($formValues['email_options'], 'both')) {
$emailedHtml[$contributionId] = TRUE;
}
}
}
$contact['is_sent'][$groupBy][$groupByID] = TRUE;
}
// update dates (do it for each contribution including grouped recurring contribution)
//@todo - the 2 calls below bypass all hooks. Using the api would possibly be slower than one call but not than 2
if ($receipt_update) {
$result = CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'receipt_date', $nowDate);
if ($result) {
$receipts++;
}
}
if ($thankyou_update) {
$result = CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'thankyou_date', $nowDate);
if ($result) {
$thanks++;
}
}
}
// This seems silly, but the old behavior was to first check `_cid`
// and then use the provided `$contactIds`. Probably not even necessary,
// but difficult to audit.
$contactIds = $form->_cid ? array($form->_cid) : array_keys($contacts);
self::createActivities($form, $html_message, $contactIds, CRM_Utils_Array::value('subject', $formValues, ts('Thank you letter')), CRM_Utils_Array::value('campaign_id', $formValues), $contactHtml);
$html = array_diff_key($html, $emailedHtml);
if (!empty($formValues['is_unit_test'])) {
return $html;
}
//CRM-19761
if (!empty($html)) {
$type = $formValues['document_type'];
if ($type == 'pdf') {
CRM_Utils_PDF_Utils::html2pdf($html, "CiviLetter.pdf", FALSE, $formValues);
}
else {
CRM_Utils_PDF_Document::html2doc($html, "CiviLetter.$type", $formValues);
}
}
$form->postProcessHook();
if ($emailed) {
$updateStatus = ts('Receipts have been emailed to %1 contributions.', array(1 => $emailed));
}
if ($receipts) {
$updateStatus = ts('Receipt date has been updated for %1 contributions.', array(1 => $receipts));
}
if ($thanks) {
$updateStatus .= ' ' . ts('Thank-you date has been updated for %1 contributions.', array(1 => $thanks));
}
if ($updateStatus) {
CRM_Core_Session::setStatus($updateStatus);
}
if (!empty($html)) {
// ie. we have only sent emails - lets no show a white screen
CRM_Utils_System::civiExit(1);
}
}
/**
* Check whether any of the tokens exist in the html outside a table cell.
* If they do the table cell separator is not supported (return false)
* At this stage we are only anticipating contributions passed in this way but
* it would be easy to add others
* @param $tokens
* @param $html
*
* @return bool
*/
public static function isValidHTMLWithTableSeparator($tokens, $html) {
$relevantEntities = array('contribution');
foreach ($relevantEntities as $entity) {
if (isset($tokens[$entity]) && is_array($tokens[$entity])) {
foreach ($tokens[$entity] as $token) {
if (!self::isHtmlTokenInTableCell($token, $entity, $html)) {
return FALSE;
}
}
}
}
return TRUE;
}
/**
* Check that the token only appears in a table cell. The '</td><td>' separator cannot otherwise work
* Calculate the number of times it appears IN the cell & the number of times it appears - should be the same!
*
* @param $token
* @param $entity
* @param $textToSearch
*
* @return bool
*/
public static function isHtmlTokenInTableCell($token, $entity, $textToSearch) {
$tokenToMatch = $entity . '.' . $token;
$dontCare = array();
$within = preg_match_all("|<td.+?{" . $tokenToMatch . "}.+?</td|si", $textToSearch, $dontCare);
$total = preg_match_all("|{" . $tokenToMatch . "}|", $textToSearch, $dontCare);
return ($within == $total);
}
/**
*
* @param string $html_message
* @param array $contact
* @param array $contribution
* @param array $messageToken
* @param bool $grouped
* Does this letter represent more than one contribution.
* @param string $separator
* What is the preferred letter separator.
* @return string
*/
private static function resolveTokens($html_message, $contact, $contribution, $messageToken, $grouped, $separator) {
$categories = self::getTokenCategories();
$tokenHtml = CRM_Utils_Token::replaceContactTokens($html_message, $contact, TRUE, $messageToken);
if ($grouped) {
$tokenHtml = CRM_Utils_Token::replaceMultipleContributionTokens($separator, $tokenHtml, $contribution, TRUE, $messageToken);
}
else {
// no change to normal behaviour to avoid risk of breakage
$tokenHtml = CRM_Utils_Token::replaceContributionTokens($tokenHtml, $contribution, TRUE, $messageToken);
}
$tokenHtml = CRM_Utils_Token::replaceHookTokens($tokenHtml, $contact, $categories, TRUE);
if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
$smarty = CRM_Core_Smarty::singleton();
// also add the tokens to the template
$smarty->assign_by_ref('contact', $contact);
$tokenHtml = $smarty->fetch("string:$tokenHtml");
}
return $tokenHtml;
}
/**
* Generate the contribution array from the form, we fill in the contact details and determine any aggregation
* around contact_id of contribution_recur_id
*
* @param string $groupBy
* @param array $contributionIDs
* @param array $returnProperties
* @param bool $skipOnHold
* @param bool $skipDeceased
* @param array $messageToken
* @param string $task
* @param string $separator
* @param bool $isIncludeSoftCredits
*
* @return array
*/
public static function buildContributionArray($groupBy, $contributionIDs, $returnProperties, $skipOnHold, $skipDeceased, $messageToken, $task, $separator, $isIncludeSoftCredits) {
$contributions = $contacts = array();
foreach ($contributionIDs as $item => $contributionId) {
// Basic return attributes available to the template.
$returnValues = array('contact_id', 'total_amount', 'financial_type', 'receive_date', 'contribution_campaign_title');
if (!empty($messageToken['contribution'])) {
$returnValues = array_merge($messageToken['contribution'], $returnValues);
}
// retrieve contribution tokens listed in $returnProperties using Contribution.Get API
$contribution = civicrm_api3('Contribution', 'getsingle', array(
'id' => $contributionId,
'return' => $returnValues,
));
$contribution['campaign'] = CRM_Utils_Array::value('contribution_campaign_title', $contribution);
$contributions[$contributionId] = $contribution;
if ($isIncludeSoftCredits) {
//@todo find out why this happens & add comments
list($contactID) = explode('-', $item);
$contactID = (int) $contactID;
}
else {
$contactID = $contribution['contact_id'];
}
if (!isset($contacts[$contactID])) {
$contacts[$contactID] = array();
$contacts[$contactID]['contact_aggregate'] = 0;
$contacts[$contactID]['combined'] = $contacts[$contactID]['contribution_ids'] = array();
}
$contacts[$contactID]['contact_aggregate'] += $contribution['total_amount'];
$groupByID = empty($contribution[$groupBy]) ? 0 : $contribution[$groupBy];
$contacts[$contactID]['contribution_ids'][$groupBy][$groupByID][$contributionId] = TRUE;
if (!isset($contacts[$contactID]['combined'][$groupBy]) || !isset($contacts[$contactID]['combined'][$groupBy][$groupByID])) {
$contacts[$contactID]['combined'][$groupBy][$groupByID] = $contribution;
$contacts[$contactID]['aggregates'][$groupBy][$groupByID] = $contribution['total_amount'];
}
else {
$contacts[$contactID]['combined'][$groupBy][$groupByID] = self::combineContributions($contacts[$contactID]['combined'][$groupBy][$groupByID], $contribution, $separator);
$contacts[$contactID]['aggregates'][$groupBy][$groupByID] += $contribution['total_amount'];
}
}
// Assign the available contributions before calling tokens so hooks parsing smarty can access it.
// Note that in core code you can only use smarty here if enable if for the whole site, incl
// CiviMail, with a big performance impact.
// Hooks allow more nuanced smarty usage here.
CRM_Core_Smarty::singleton()->assign('contributions', $contributions);
foreach ($contacts as $contactID => $contact) {
$tokenResolvedContacts = CRM_Utils_Token::getTokenDetails(array('contact_id' => $contactID),
$returnProperties,
$skipOnHold,
$skipDeceased,
NULL,
$messageToken,
$task
);
$contacts[$contactID] = array_merge($tokenResolvedContacts[0][$contactID], $contact);
}
return array($contributions, $contacts);
}
/**
* We combine the contributions by adding the contribution to each field with the separator in
* between the existing value and the new one. We put the separator there even if empty so it is clear what the
* value for previous contributions was
*
* @param array $existing
* @param array $contribution
* @param string $separator
*
* @return array
*/
public static function combineContributions($existing, $contribution, $separator) {
foreach ($contribution as $field => $value) {
$existing[$field] = isset($existing[$field]) ? $existing[$field] . $separator : '';
$existing[$field] .= $value;
}
return $existing;
}
/**
* We are going to retrieve the combined contribution and if smarty mail is enabled we
* will also assign an array of contributions for this contact to the smarty template
*
* @param array $contact
* @param array $contributions
* @param $groupBy
* @param int $groupByID
*/
public static function assignCombinedContributionValues($contact, $contributions, $groupBy, $groupByID) {
CRM_Core_Smarty::singleton()->assign('contact_aggregate', $contact['contact_aggregate']);
CRM_Core_Smarty::singleton()
->assign('contributions', array_intersect_key($contributions, $contact['contribution_ids'][$groupBy][$groupByID]));
CRM_Core_Smarty::singleton()->assign('contribution_aggregate', $contact['aggregates'][$groupBy][$groupByID]);
}
/**
* Send pdf by email.
*
* @param array $contact
* @param string $html
*
* @param $is_pdf
* @param array $format
* @param array $params
*
* @return bool
*/
public static function emailLetter($contact, $html, $is_pdf, $format = array(), $params = array()) {
try {
if (empty($contact['email'])) {
return FALSE;
}
$mustBeEmpty = array('do_not_email', 'is_deceased', 'on_hold');
foreach ($mustBeEmpty as $emptyField) {
if (!empty($contact[$emptyField])) {
return FALSE;
}
}
$defaults = array(
'toName' => $contact['display_name'],
'toEmail' => $contact['email'],
'text' => '',
'html' => $html,
);
if (empty($params['from'])) {
$emails = CRM_Core_BAO_Email::getFromEmail();
$emails = array_keys($emails);
$defaults['from'] = array_pop($emails);
}
if (!empty($params['subject'])) {
$defaults['subject'] = $params['subject'];
}
else {
$defaults['subject'] = ts('Thank you for your contribution/s');
}
if ($is_pdf) {
$defaults['html'] = ts('Please see attached');
$defaults['attachments'] = array(CRM_Utils_Mail::appendPDF('ThankYou.pdf', $html, $format));
}
$params = array_merge($defaults);
return CRM_Utils_Mail::send($params);
}
catch (CRM_Core_Exception $e) {
return FALSE;
}
}
/**
* @param $contact
* @param $formValues
* @param $contribution
* @param $groupBy
* @param $contributions
* @param $realSeparator
* @param $tableSeparators
* @param $messageToken
* @param $html_message
* @param $separator
* @param $categories
* @param bool $grouped
* @param int $groupByID
*
* @return string
*/
protected static function generateHtml(&$contact, $contribution, $groupBy, $contributions, $realSeparator, $tableSeparators, $messageToken, $html_message, $separator, $grouped, $groupByID) {
static $validated = FALSE;
$html = NULL;
self::assignCombinedContributionValues($contact, $contributions, $groupBy, $groupByID);
if (empty($groupBy) || empty($contact['is_sent'][$groupBy][$groupByID])) {
if (!$validated && in_array($realSeparator, $tableSeparators) && !self::isValidHTMLWithTableSeparator($messageToken, $html_message)) {
$realSeparator = ', ';
CRM_Core_Session::setStatus(ts('You have selected the table cell separator, but one or more token fields are not placed inside a table cell. This would result in invalid HTML, so comma separators have been used instead.'));
}
$validated = TRUE;
$html = str_replace($separator, $realSeparator, self::resolveTokens($html_message, $contact, $contribution, $messageToken, $grouped, $separator));
}
return $html;
}
}

View file

@ -0,0 +1,136 @@
<?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 provides the functionality for batch profile update for contributions.
*/
class CRM_Contribute_Form_Task_PickProfile extends CRM_Contribute_Form_Task {
/**
* The title of the group
*
* @var string
*/
protected $_title;
/**
* Maximum contributions that should be allowed to update
*/
protected $_maxContributions = 100;
/**
* Variable to store redirect path
*/
protected $_userContext;
/**
* Build all the data structures needed to build the form.
*/
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 contributions'));
$validate = FALSE;
//validations
if (count($this->_contributionIds) > $this->_maxContributions) {
CRM_Core_Session::setStatus(ts("The maximum number of contributions you can select for Update multiple contributions is %1. You have selected %2. Please select fewer contributions from your search results and try again.", array(
1 => $this->_maxContributions,
2 => count($this->_contributionIds),
)), ts('Update multiple records error'), 'error');
$validate = TRUE;
}
// than redirect
if ($validate) {
CRM_Utils_System::redirect($this->_userContext);
}
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$types = array('Contribution');
$profiles = CRM_Core_BAO_UFGroup::getProfiles($types, TRUE);
if (empty($profiles)) {
CRM_Core_Session::setStatus(ts("You will need to create a Profile containing the %1 fields you want to edit before you can use Update multiple contributions. Navigate to Administer CiviCRM > Customize Data and Screens > CiviCRM Profile to configure a Profile. Consult the online Administrator documentation for more information.", array(1 => $types[0])), ts('Profile Required'), 'error');
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.
*/
public function addRules() {
$this->addFormRule(array('CRM_Contribute_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.
*/
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,97 @@
<?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 provides the functionality to print contribution records.
*/
class CRM_Contribute_Form_Task_Print extends CRM_Contribute_Form_Task {
/**
* Build all the data structures needed to build the form.
*/
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_Contribute_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
*/
public function buildQuickForm() {
//
// just need to add a javascript to popup the window for printing
//
$this->addButtons(array(
array(
'type' => 'next',
'name' => ts('Print Contributions'),
'js' => array('onclick' => 'window.print()'),
'isDefault' => TRUE,
),
array(
'type' => 'back',
'name' => ts('Done'),
),
)
);
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
// redirect to the main search page after printing is over
}
}

View file

@ -0,0 +1,59 @@
<?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
*/
/**
* Used for displaying results
*/
class CRM_Contribute_Form_Task_Result extends CRM_Contribute_Form_Task {
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->addButtons(array(
array(
'type' => 'done',
'name' => ts('Done'),
'isDefault' => TRUE,
),
)
);
}
}

View file

@ -0,0 +1,87 @@
<?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 provides the functionality to save a search
* Saved Searches are used for saving frequently used queries
*/
class CRM_Contribute_Form_Task_SearchTaskHookSample extends CRM_Contribute_Form_Task {
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
parent::preProcess();
$rows = array();
// display name and contribution details of all selected contacts
$contribIDs = implode(',', $this->_contributionIds);
$query = "
SELECT co.total_amount as amount,
co.receive_date as receive_date,
co.source as source,
ct.display_name as display_name
FROM civicrm_contribution co
INNER JOIN civicrm_contact ct ON ( co.contact_id = ct.id )
WHERE co.id IN ( $contribIDs )";
$dao = CRM_Core_DAO::executeQuery($query,
CRM_Core_DAO::$_nullArray
);
while ($dao->fetch()) {
$rows[] = array(
'display_name' => $dao->display_name,
'amount' => $dao->amount,
'source' => $dao->source,
'receive_date' => $dao->receive_date,
);
}
$this->assign('rows', $rows);
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$this->addButtons(array(
array(
'type' => 'done',
'name' => ts('Done'),
'isDefault' => TRUE,
),
)
);
}
}

View file

@ -0,0 +1,350 @@
<?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 provides the functionality to email a group of contacts.
*/
class CRM_Contribute_Form_Task_Status extends CRM_Contribute_Form_Task {
/**
* Are we operating in "single mode", i.e. updating the task of only
* one specific contribution?
*
* @var boolean
*/
public $_single = FALSE;
protected $_rows;
/**
* Build all the data structures needed to build the form.
*/
public function preProcess() {
$id = CRM_Utils_Request::retrieve('id', 'Positive',
$this, FALSE
);
if ($id) {
$this->_contributionIds = array($id);
$this->_componentClause = " civicrm_contribution.id IN ( $id ) ";
$this->_single = TRUE;
$this->assign('totalSelectedContributions', 1);
}
else {
parent::preProcess();
}
// check that all the contribution ids have pending status
$query = "
SELECT count(*)
FROM civicrm_contribution
WHERE contribution_status_id != 2
AND {$this->_componentClause}";
$count = CRM_Core_DAO::singleValueQuery($query,
CRM_Core_DAO::$_nullArray
);
if ($count != 0) {
CRM_Core_Error::statusBounce(ts('Please select only online contributions with Pending status.'));
}
// we have all the contribution ids, so now we get the contact ids
parent::setContactIDs();
$this->assign('single', $this->_single);
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$status = CRM_Contribute_PseudoConstant::contributionStatus();
unset($status[2]);
unset($status[5]);
unset($status[6]);
$this->add('select', 'contribution_status_id',
ts('Contribution Status'),
$status,
TRUE
);
$contribIDs = implode(',', $this->_contributionIds);
$query = "
SELECT c.id as contact_id,
co.id as contribution_id,
c.display_name as display_name,
co.total_amount as amount,
co.receive_date as receive_date,
co.source as source,
co.payment_instrument_id as paid_by,
co.check_number as check_no
FROM civicrm_contact c,
civicrm_contribution co
WHERE co.contact_id = c.id
AND co.id IN ( $contribIDs )";
$dao = CRM_Core_DAO::executeQuery($query,
CRM_Core_DAO::$_nullArray
);
// build a row for each contribution id
$this->_rows = array();
$attributes = CRM_Core_DAO::getAttribute('CRM_Contribute_DAO_Contribution');
$defaults = array();
$now = date("m/d/Y");
$paidByOptions = array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument();
while ($dao->fetch()) {
$row['contact_id'] = $dao->contact_id;
$row['contribution_id'] = $dao->contribution_id;
$row['display_name'] = $dao->display_name;
$row['amount'] = $dao->amount;
$row['source'] = $dao->source;
$row['trxn_id'] = &$this->addElement('text', "trxn_id_{$row['contribution_id']}", ts('Transaction ID'));
$this->addRule("trxn_id_{$row['contribution_id']}",
ts('This Transaction ID already exists in the database. Include the account number for checks.'),
'objectExists',
array('CRM_Contribute_DAO_Contribution', $dao->contribution_id, 'trxn_id')
);
$row['fee_amount'] = &$this->add('text', "fee_amount_{$row['contribution_id']}", ts('Fee Amount'),
$attributes['fee_amount']
);
$this->addRule("fee_amount_{$row['contribution_id']}", ts('Please enter a valid amount.'), 'money');
$defaults["fee_amount_{$row['contribution_id']}"] = 0.0;
$row['trxn_date'] = $this->addDate("trxn_date_{$row['contribution_id']}", FALSE,
ts('Receipt Date'), array('formatType' => 'activityDate')
);
$defaults["trxn_date_{$row['contribution_id']}"] = $now;
$this->add("text", "check_number_{$row['contribution_id']}", ts('Check Number'));
$defaults["check_number_{$row['contribution_id']}"] = $dao->check_no;
$this->add("select", "payment_instrument_id_{$row['contribution_id']}", ts('Payment Method'), $paidByOptions);
$defaults["payment_instrument_id_{$row['contribution_id']}"] = $dao->paid_by;
$this->_rows[] = $row;
}
$this->assign_by_ref('rows', $this->_rows);
$this->setDefaults($defaults);
$this->addButtons(array(
array(
'type' => 'next',
'name' => ts('Update Pending Status'),
'isDefault' => TRUE,
),
array(
'type' => 'back',
'name' => ts('Cancel'),
),
)
);
$this->addFormRule(array('CRM_Contribute_Form_Task_Status', '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) {
$seen = $errors = array();
foreach ($fields as $name => $value) {
if (strpos($name, 'trxn_id_') !== FALSE) {
if ($fields[$name]) {
if (array_key_exists($value, $seen)) {
$errors[$name] = ts('Transaction ID\'s must be unique. Include the account number for checks.');
}
$seen[$value] = 1;
}
}
if ((strpos($name, 'check_number_') !== FALSE) && $value) {
$contribID = substr($name, 13);
if ($fields["payment_instrument_id_{$contribID}"] != CRM_Core_OptionGroup::getValue('payment_instrument', 'Check', 'name')) {
$errors["payment_instrument_id_{$contribID}"] = ts("Payment Method should be Check when a check number is entered for a contribution.");
}
}
}
return empty($errors) ? TRUE : $errors;
}
/**
* Process the form after the input has been submitted and validated.
*/
public function postProcess() {
$params = $this->controller->exportValues($this->_name);
// submit the form with values.
self::processForm($this, $params);
CRM_Core_Session::setStatus(ts('Contribution status has been updated for selected record(s).'), ts('Status Updated'), 'success');
}
/**
* Process the form with submitted params.
*
* Also supports unit test.
*
* @param CRM_Core_Form $form
* @param array $params
*
* @throws \Exception
*/
public static function processForm($form, $params) {
$statusID = CRM_Utils_Array::value('contribution_status_id', $params);
$baseIPN = new CRM_Core_Payment_BaseIPN();
$transaction = new CRM_Core_Transaction();
// get the missing pieces for each contribution
$contribIDs = implode(',', $form->_contributionIds);
$details = self::getDetails($contribIDs);
$template = CRM_Core_Smarty::singleton();
// for each contribution id, we just call the baseIPN stuff
foreach ($form->_rows as $row) {
$input = $ids = $objects = array();
$input['component'] = $details[$row['contribution_id']]['component'];
$ids['contact'] = $row['contact_id'];
$ids['contribution'] = $row['contribution_id'];
$ids['contributionRecur'] = NULL;
$ids['contributionPage'] = NULL;
$ids['membership'] = CRM_Utils_Array::value('membership', $details[$row['contribution_id']]);
$ids['participant'] = CRM_Utils_Array::value('participant', $details[$row['contribution_id']]);
$ids['event'] = CRM_Utils_Array::value('event', $details[$row['contribution_id']]);
if (!$baseIPN->validateData($input, $ids, $objects, FALSE)) {
CRM_Core_Error::fatal();
}
$contribution = &$objects['contribution'];
$contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL,
'name'
);
if ($statusID == array_search('Cancelled', $contributionStatuses)) {
$baseIPN->cancelled($objects, $transaction);
$transaction->commit();
continue;
}
elseif ($statusID == array_search('Failed', $contributionStatuses)) {
$baseIPN->failed($objects, $transaction);
$transaction->commit();
continue;
}
// status is not pending
if ($contribution->contribution_status_id != array_search('Pending',
$contributionStatuses
)
) {
$transaction->commit();
continue;
}
// set some fake input values so we can reuse IPN code
$input['amount'] = $contribution->total_amount;
$input['is_test'] = $contribution->is_test;
$input['fee_amount'] = $params["fee_amount_{$row['contribution_id']}"];
$input['check_number'] = $params["check_number_{$row['contribution_id']}"];
$input['payment_instrument_id'] = $params["payment_instrument_id_{$row['contribution_id']}"];
$input['net_amount'] = $contribution->total_amount - $input['fee_amount'];
if (!empty($params["trxn_id_{$row['contribution_id']}"])) {
$input['trxn_id'] = trim($params["trxn_id_{$row['contribution_id']}"]);
}
else {
$input['trxn_id'] = $contribution->invoice_id;
}
$input['trxn_date'] = CRM_Utils_Date::processDate($params["trxn_date_{$row['contribution_id']}"], date('H:i:s'));
// @todo calling baseIPN like this is a pattern in it's last gasps. Call contribute.completetransaction api.
$baseIPN->completeTransaction($input, $ids, $objects, $transaction, FALSE);
// reset template values before processing next transactions
$template->clearTemplateVars();
}
}
/**
* @param $contributionIDs
*
* @return array
*/
public static function &getDetails($contributionIDs) {
$query = "
SELECT c.id as contribution_id,
c.contact_id as contact_id ,
mp.membership_id as membership_id ,
pp.participant_id as participant_id ,
p.event_id as event_id
FROM civicrm_contribution c
LEFT JOIN civicrm_membership_payment mp ON mp.contribution_id = c.id
LEFT JOIN civicrm_participant_payment pp ON pp.contribution_id = c.id
LEFT JOIN civicrm_participant p ON pp.participant_id = p.id
WHERE c.id IN ( $contributionIDs )";
$rows = array();
$dao = CRM_Core_DAO::executeQuery($query,
CRM_Core_DAO::$_nullArray
);
$rows = array();
while ($dao->fetch()) {
$rows[$dao->contribution_id]['component'] = $dao->participant_id ? 'event' : 'contribute';
$rows[$dao->contribution_id]['contact'] = $dao->contact_id;
if ($dao->membership_id) {
if (!array_key_exists('membership', $rows[$dao->contribution_id])) {
$rows[$dao->contribution_id]['membership'] = array();
}
$rows[$dao->contribution_id]['membership'][] = $dao->membership_id;
}
if ($dao->participant_id) {
$rows[$dao->contribution_id]['participant'] = $dao->participant_id;
}
if ($dao->event_id) {
$rows[$dao->contribution_id]['event'] = $dao->event_id;
}
}
return $rows;
}
}

View file

@ -0,0 +1,418 @@
<?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 a contribution.
*/
class CRM_Contribute_Form_UpdateBilling extends CRM_Core_Form {
protected $_crid = NULL;
protected $_coid = NULL;
protected $_mode = NULL;
protected $_subscriptionDetails = NULL;
protected $_selfService = FALSE;
public $_bltID = NULL;
/**
* @var array current payment processor including a copy of the object in 'object' key
*/
public $_paymentProcessor = array();
/**
* Set variables up before form is built.
*/
public function preProcess() {
$this->_mid = CRM_Utils_Request::retrieve('mid', 'Integer', $this, FALSE);
$this->_crid = CRM_Utils_Request::retrieve('crid', 'Integer', $this, FALSE);
if ($this->_crid) {
$this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_crid, 'recur', 'info');
$this->_paymentProcessor['object'] = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_crid, 'recur', 'obj');
$this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_crid);
// Are we cancelling a recurring contribution that is linked to an auto-renew membership?
if ($this->_subscriptionDetails->membership_id) {
$this->_mid = $this->_subscriptionDetails->membership_id;
}
}
$this->_coid = CRM_Utils_Request::retrieve('coid', 'Integer', $this, FALSE);
if ($this->_coid) {
$this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'info');
$this->_paymentProcessor['object'] = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'obj');
$this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_coid, 'contribution');
}
if ($this->_mid) {
$this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_mid, 'membership', 'info');
$this->_paymentProcessor['object'] = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_mid, 'membership', 'obj');
$this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_mid, 'membership');
$membershipTypes = CRM_Member_PseudoConstant::membershipType();
$membershipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_mid, 'membership_type_id');
$this->assign('membershipType', CRM_Utils_Array::value($membershipTypeId, $membershipTypes));
$this->_mode = 'auto_renew';
}
if ((!$this->_crid && !$this->_coid && !$this->_mid) || (!$this->_subscriptionDetails)) {
CRM_Core_Error::fatal('Required information missing.');
}
if (!CRM_Core_Permission::check('edit contributions')) {
$userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this, FALSE);
if (!CRM_Contact_BAO_Contact_Utils::validChecksum($this->_subscriptionDetails->contact_id, $userChecksum)) {
CRM_Core_Error::fatal(ts('You do not have permission to cancel subscription.'));
}
$this->_selfService = TRUE;
}
if (!$this->_paymentProcessor['object']->isSupported('updateSubscriptionBillingInfo')) {
CRM_Core_Error::fatal(ts("%1 processor doesn't support updating subscription billing details.",
array(1 => $this->_paymentProcessor['object']->_processorName)
));
}
$this->assign('paymentProcessor', $this->_paymentProcessor);
$this->assignBillingType();
$this->assign('frequency_unit', $this->_subscriptionDetails->frequency_unit);
$this->assign('frequency_interval', $this->_subscriptionDetails->frequency_interval);
$this->assign('amount', $this->_subscriptionDetails->amount);
$this->assign('installments', $this->_subscriptionDetails->installments);
$this->assign('mode', $this->_mode);
// handle context redirection
CRM_Contribute_BAO_ContributionRecur::setSubscriptionContext();
}
/**
* Set the default values of various form elements.
*
* @return array
* Default values
*/
public function setDefaultValues() {
$this->_defaults = array();
if ($this->_subscriptionDetails->contact_id) {
$fields = array();
$names = array(
'first_name',
'middle_name',
'last_name',
"street_address-{$this->_bltID}",
"city-{$this->_bltID}",
"postal_code-{$this->_bltID}",
"country_id-{$this->_bltID}",
"state_province_id-{$this->_bltID}",
);
foreach ($names as $name) {
$fields[$name] = 1;
}
$fields["state_province-{$this->_bltID}"] = 1;
$fields["country-{$this->_bltID}"] = 1;
$fields["email-{$this->_bltID}"] = 1;
$fields['email-Primary'] = 1;
CRM_Core_BAO_UFGroup::setProfileDefaults($this->_subscriptionDetails->contact_id, $fields, $this->_defaults);
// use primary email address if billing email address is empty
if (empty($this->_defaults["email-{$this->_bltID}"]) &&
!empty($this->_defaults['email-Primary'])
) {
$this->_defaults["email-{$this->_bltID}"] = $this->_defaults['email-Primary'];
}
foreach ($names as $name) {
if (!empty($this->_defaults[$name])) {
$this->_defaults['billing_' . $name] = $this->_defaults[$name];
}
}
}
$config = CRM_Core_Config::singleton();
// set default country from config if no country set
if (empty($this->_defaults["billing_country_id-{$this->_bltID}"])) {
$this->_defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
}
return $this->_defaults;
}
/**
* Build the form object.
*/
public function buildQuickForm() {
$type = 'next';
if ($this->_selfService) {
$type = 'submit';
}
$this->addButtons(array(
array(
'type' => $type,
'name' => ts('Save'),
'isDefault' => TRUE,
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
)
);
CRM_Core_Payment_Form::buildPaymentForm($this, $this->_paymentProcessor, TRUE, TRUE);
$this->addFormRule(array('CRM_Contribute_Form_UpdateBilling', 'formRule'), $this);
}
/**
* Global form rule.
*
* @param array $fields
* The input form values.
* @param array $files
* The uploaded files if any.
* @param CRM_Core_Form $self
*
*
* @return bool|array
* true if no errors, else array of errors
*/
public static function formRule($fields, $files, $self) {
$errors = array();
CRM_Core_Form::validateMandatoryFields($self->_fields, $fields, $errors);
// validate the payment instrument values (e.g. credit card number)
CRM_Core_Payment_Form::validatePaymentInstrument($self->_paymentProcessor['id'], $fields, $errors, NULL);
return empty($errors) ? TRUE : $errors;
}
/**
* Process the form.
*/
public function postProcess() {
$params = $this->controller->exportValues($this->_name);
$status = NULL;
// now set the values for the billing location.
foreach ($this->_fields as $name => $value) {
$fields[$name] = 1;
}
$fields["email-{$this->_bltID}"] = 1;
$processorParams = array();
foreach ($params as $key => $val) {
$key = str_replace('billing_', '', $key);
list($key) = explode('-', $key);
$processorParams[$key] = $val;
}
$processorParams['state_province'] = CRM_Core_PseudoConstant::stateProvince($params["billing_state_province_id-{$this->_bltID}"], FALSE);
$processorParams['country'] = CRM_Core_PseudoConstant::country($params["billing_country_id-{$this->_bltID}"], FALSE);
$processorParams['month'] = $processorParams['credit_card_exp_date']['M'];
$processorParams['year'] = $processorParams['credit_card_exp_date']['Y'];
$processorParams['subscriptionId'] = $this->_subscriptionDetails->subscription_id;
$processorParams['amount'] = $this->_subscriptionDetails->amount;
$updateSubscription = $this->_paymentProcessor['object']->updateSubscriptionBillingInfo($message, $processorParams);
if (is_a($updateSubscription, 'CRM_Core_Error')) {
CRM_Core_Error::displaySessionError($updateSubscription);
}
elseif ($updateSubscription) {
$ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_subscriptionDetails->contact_id, 'contact_type');
$contact = &CRM_Contact_BAO_Contact::createProfileContact($params,
$fields,
$this->_subscriptionDetails->contact_id,
NULL,
NULL,
$ctype
);
// build tpl params
if ($this->_subscriptionDetails->membership_id) {
$inputParams = array('id' => $this->_subscriptionDetails->membership_id);
CRM_Member_BAO_Membership::getValues($inputParams, $tplParams);
$tplParams = $tplParams[$this->_subscriptionDetails->membership_id];
$tplParams['membership_status'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $tplParams['status_id']);
$tplParams['membershipType'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $tplParams['membership_type_id']);
$status = ts('Billing details for your automatically renewed %1 membership have been updated.',
array(1 => $tplParams['membershipType'])
);
$msgTitle = ts('Details Updated');
$msgType = 'success';
}
else {
$status = ts('Billing details for the recurring contribution of %1, every %2 %3 have been updated.',
array(
1 => $this->_subscriptionDetails->amount,
2 => $this->_subscriptionDetails->frequency_interval,
3 => $this->_subscriptionDetails->frequency_unit,
)
);
$msgTitle = ts('Details Updated');
$msgType = 'success';
$tplParams = array(
'recur_frequency_interval' => $this->_subscriptionDetails->frequency_interval,
'recur_frequency_unit' => $this->_subscriptionDetails->frequency_unit,
'amount' => $this->_subscriptionDetails->amount,
);
}
// format new address for display
$addressParts = array("street_address", "city", "postal_code", "state_province", "country");
foreach ($addressParts as $part) {
$addressParts[$part] = CRM_Utils_Array::value($part, $processorParams);
}
$tplParams['address'] = CRM_Utils_Address::format($addressParts);
// format old address to store in activity details
$this->_defaults["state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvince($this->_defaults["state_province-{$this->_bltID}"], FALSE);
$this->_defaults["country-{$this->_bltID}"] = CRM_Core_PseudoConstant::country($this->_defaults["country-{$this->_bltID}"], FALSE);
$addressParts = array("street_address", "city", "postal_code", "state_province", "country");
foreach ($addressParts as $part) {
$key = "{$part}-{$this->_bltID}";
$addressParts[$part] = CRM_Utils_Array::value($key, $this->_defaults);
}
$this->_defaults['address'] = CRM_Utils_Address::format($addressParts);
// format new billing name
$name = $processorParams['first_name'];
if (!empty($processorParams['middle_name'])) {
$name .= " {$processorParams['middle_name']}";
}
$name .= ' ' . $processorParams['last_name'];
$name = trim($name);
$tplParams['billingName'] = $name;
// format old billing name
$name = $this->_defaults['first_name'];
if (!empty($this->_defaults['middle_name'])) {
$name .= " {$this->_defaults['middle_name']}";
}
$name .= ' ' . $this->_defaults['last_name'];
$name = trim($name);
$this->_defaults['billingName'] = $name;
$message .= "
<br/><br/>New Billing Name and Address
<br/>==============================
<br/>{$tplParams['billingName']}
<br/>{$tplParams['address']}
<br/><br/>Previous Billing Name and Address
<br/>==================================
<br/>{$this->_defaults['billingName']}
<br/>{$this->_defaults['address']}";
$activityParams = array(
'source_contact_id' => $this->_subscriptionDetails->contact_id,
'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
'Update Recurring Contribution Billing Details',
'name'
),
'subject' => ts('Recurring Contribution Billing Details Updated'),
'details' => $message,
'activity_date_time' => date('YmdHis'),
'status_id' => CRM_Core_OptionGroup::getValue('activity_status',
'Completed',
'name'
),
);
$session = CRM_Core_Session::singleton();
$cid = $session->get('userID');
if ($cid) {
$activityParams['target_contact_id'][] = $activityParams['source_contact_id'];
$activityParams['source_contact_id'] = $cid;
}
CRM_Activity_BAO_Activity::create($activityParams);
// send notification
if ($this->_subscriptionDetails->contribution_page_id) {
CRM_Core_DAO::commonRetrieveAll('CRM_Contribute_DAO_ContributionPage', 'id',
$this->_subscriptionDetails->contribution_page_id, $value, array(
'title',
'receipt_from_name',
'receipt_from_email',
)
);
$receiptFrom = '"' . CRM_Utils_Array::value('receipt_from_name', $value[$this->_subscriptionDetails->contribution_page_id]) . '" <' . $value[$this->_subscriptionDetails->contribution_page_id]['receipt_from_email'] . '>';
}
else {
$domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
$receiptFrom = "$domainValues[0] <$domainValues[1]>";
}
list($donorDisplayName, $donorEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_subscriptionDetails->contact_id);
$tplParams['contact'] = array('display_name' => $donorDisplayName);
$date = CRM_Utils_Date::format($processorParams['credit_card_exp_date']);
$tplParams['credit_card_exp_date'] = CRM_Utils_Date::mysqlToIso($date);
$tplParams['credit_card_number'] = CRM_Utils_System::mungeCreditCard($processorParams['credit_card_number']);
$tplParams['credit_card_type'] = $processorParams['credit_card_type'];
$sendTemplateParams = array(
'groupName' => $this->_subscriptionDetails->membership_id ? 'msg_tpl_workflow_membership' : 'msg_tpl_workflow_contribution',
'valueName' => $this->_subscriptionDetails->membership_id ? 'membership_autorenew_billing' : 'contribution_recurring_billing',
'contactId' => $this->_subscriptionDetails->contact_id,
'tplParams' => $tplParams,
'isTest' => $this->_subscriptionDetails->is_test,
'PDFFilename' => 'receipt.pdf',
'from' => $receiptFrom,
'toName' => $donorDisplayName,
'toEmail' => $donorEmail,
);
list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
}
else {
$status = ts('There was some problem updating the billing details.');
$msgTitle = ts('Update Error');
$msgType = 'error';
}
$session = CRM_Core_Session::singleton();
$userID = $session->get('userID');
if ($userID && $status) {
$session->setStatus($status, $msgTitle, $msgType);
}
elseif (!$userID) {
if ($status) {
CRM_Utils_System::setUFMessage($status);
}
$result = (int) ($updateSubscription && isset($ctype));
if (isset($tplParams)) {
$session->set('resultParams', $tplParams);
}
return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/subscriptionstatus',
"reset=1&task=billing&result={$result}"));
}
}
}

View file

@ -0,0 +1,373 @@
<?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 generic to recurring contributions.
*
* It delegates the work to lower level subclasses and integrates the changes
* back in. It also uses a lot of functionality with the CRM API's, so any change
* made here could potentially affect the API etc. Be careful, be aware, use unit tests.
*/
class CRM_Contribute_Form_UpdateSubscription extends CRM_Core_Form {
/**
* The recurring contribution id, used when editing the recurring contribution.
*
* @var int
*/
protected $contributionRecurID = NULL;
protected $_coid = NULL;
protected $_subscriptionDetails = NULL;
protected $_selfService = FALSE;
public $_paymentProcessor = NULL;
public $_paymentProcessorObj = NULL;
/**
* Fields that affect the schedule and are defined as editable by the processor.
*
* @var array
*/
protected $editableScheduleFields = array();
/**
* The id of the contact associated with this recurring contribution.
*
* @var int
*/
public $_contactID;
/**
* Pre-processing for the form.
*
* @throws \Exception
*/
public function preProcess() {
$this->setAction(CRM_Core_Action::UPDATE);
$this->contributionRecurID = CRM_Utils_Request::retrieve('crid', 'Integer', $this, FALSE);
if ($this->contributionRecurID) {
$this->_paymentProcessor = CRM_Contribute_BAO_ContributionRecur::getPaymentProcessor($this->contributionRecurID);
if (!$this->_paymentProcessor) {
CRM_Core_Error::statusBounce(ts('There is no valid processor for this subscription so it cannot be edited.'));
}
$this->_paymentProcessorObj = $this->_paymentProcessor['object'];
$this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->contributionRecurID);
}
$this->_coid = CRM_Utils_Request::retrieve('coid', 'Integer', $this, FALSE);
if ($this->_coid) {
$this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'info');
$this->_paymentProcessorObj = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'obj');
$this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_coid, 'contribution');
$this->contributionRecurID = $this->_subscriptionDetails->recur_id;
}
elseif ($this->contributionRecurID) {
$this->_coid = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $this->contributionRecurID, 'id', 'contribution_recur_id');
}
if (!$this->contributionRecurID || !$this->_subscriptionDetails) {
CRM_Core_Error::statusBounce(ts('Required information missing.'));
}
if ($this->_subscriptionDetails->membership_id && $this->_subscriptionDetails->auto_renew) {
CRM_Core_Error::statusBounce(ts('You cannot update the subscription.'));
}
if (!CRM_Core_Permission::check('edit contributions')) {
$userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this, FALSE);
if (!CRM_Contact_BAO_Contact_Utils::validChecksum($this->_subscriptionDetails->contact_id, $userChecksum)) {
CRM_Core_Error::statusBounce(ts('You do not have permission to update subscription.'));
}
$this->_selfService = TRUE;
}
$this->assign('self_service', $this->_selfService);
$this->editableScheduleFields = $this->_paymentProcessorObj->getEditableRecurringScheduleFields();
$changeHelpText = $this->_paymentProcessorObj->getRecurringScheduleUpdateHelpText();
if (!in_array('amount', $this->editableScheduleFields)) {
// Not sure if this is good behaviour - maintaining this existing behaviour for now.
CRM_Core_Session::setStatus($changeHelpText, ts('Warning'), 'alert');
}
else {
$this->assign('changeHelpText', $changeHelpText);
}
$alreadyHardCodedFields = array('amount', 'installments');
foreach ($this->editableScheduleFields as $editableScheduleField) {
if (!in_array($editableScheduleField, $alreadyHardCodedFields)) {
$this->addField($editableScheduleField, array('entity' => 'ContributionRecur'));
}
}
$this->assign('editableScheduleFields', array_diff($this->editableScheduleFields, $alreadyHardCodedFields));
$this->assign('paymentProcessor', $this->_paymentProcessor);
$this->assign('frequency_unit', $this->_subscriptionDetails->frequency_unit);
$this->assign('frequency_interval', $this->_subscriptionDetails->frequency_interval);
if ($this->_subscriptionDetails->contact_id) {
list($this->_donorDisplayName, $this->_donorEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_subscriptionDetails->contact_id);
}
CRM_Utils_System::setTitle(ts('Update Recurring Contribution'));
// Handle context redirection.
CRM_Contribute_BAO_ContributionRecur::setSubscriptionContext();
}
/**
* Set default values for the form.
*
* Note that in edit/view mode the default values are retrieved from the database.
*/
public function setDefaultValues() {
$this->_defaults = array();
$this->_defaults['amount'] = $this->_subscriptionDetails->amount;
$this->_defaults['installments'] = $this->_subscriptionDetails->installments;
$this->_defaults['campaign_id'] = $this->_subscriptionDetails->campaign_id;
$this->_defaults['financial_type_id'] = $this->_subscriptionDetails->financial_type_id;
$this->_defaults['is_notify'] = 1;
foreach ($this->editableScheduleFields as $field) {
$this->_defaults[$field] = $this->_subscriptionDetails->$field;
}
return $this->_defaults;
}
/**
* Actually build the components of the form.
*/
public function buildQuickForm() {
// CRM-16398: If current recurring contribution got > 1 lineitems then make amount field readonly
$amtAttr = array('size' => 20);
$lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($this->_coid);
if (count($lineItems) > 1) {
$amtAttr += array('readonly' => TRUE);
}
$this->addMoney('amount', ts('Recurring Contribution Amount'), TRUE, $amtAttr,
TRUE, 'currency', $this->_subscriptionDetails->currency, TRUE
);
$this->add('text', 'installments', ts('Number of Installments'), array('size' => 20), FALSE);
if ($this->_donorEmail) {
$this->add('checkbox', 'is_notify', ts('Notify Contributor?'));
}
if (CRM_Core_Permission::check('edit contributions')) {
CRM_Campaign_BAO_Campaign::addCampaign($this, $this->_subscriptionDetails->campaign_id);
}
if (CRM_Contribute_BAO_ContributionRecur::supportsFinancialTypeChange($this->contributionRecurID)) {
$this->addEntityRef('financial_type_id', ts('Financial Type'), array('entity' => 'FinancialType'), !$this->_selfService);
}
$type = 'next';
if ($this->_selfService) {
$type = 'submit';
}
// define the buttons
$this->addButtons(array(
array(
'type' => $type,
'name' => ts('Save'),
'isDefault' => TRUE,
),
array(
'type' => 'cancel',
'name' => ts('Cancel'),
),
)
);
}
/**
* Called after the user submits the form.
*/
public function postProcess() {
// store the submitted values in an array
$params = $this->exportValues();
if ($this->_selfService && $this->_donorEmail) {
// for self service force notify
$params['is_notify'] = 1;
}
// if this is an update of an existing recurring contribution, pass the ID
$params['id'] = $this->_subscriptionDetails->recur_id;
$message = '';
$params['subscriptionId'] = $this->_subscriptionDetails->subscription_id;
$updateSubscription = TRUE;
if ($this->_paymentProcessorObj->isSupported('changeSubscriptionAmount')) {
$updateSubscription = $this->_paymentProcessorObj->changeSubscriptionAmount($message, $params);
}
if (is_a($updateSubscription, 'CRM_Core_Error')) {
CRM_Core_Error::displaySessionError($updateSubscription);
$status = ts('Could not update the Recurring contribution details');
$msgTitle = ts('Update Error');
$msgType = 'error';
}
elseif ($updateSubscription) {
// save the changes
$result = CRM_Contribute_BAO_ContributionRecur::add($params);
$status = ts('Recurring contribution has been updated to: %1, every %2 %3(s) for %4 installments.',
array(
1 => CRM_Utils_Money::format($params['amount'], $this->_subscriptionDetails->currency),
2 => $this->_subscriptionDetails->frequency_interval,
3 => $this->_subscriptionDetails->frequency_unit,
4 => $params['installments'],
)
);
$msgTitle = ts('Update Success');
$msgType = 'success';
$msg = ts('Recurring Contribution Updated');
$contactID = $this->_subscriptionDetails->contact_id;
if ($this->_subscriptionDetails->amount != $params['amount']) {
$message .= "<br /> " . ts("Recurring contribution amount has been updated from %1 to %2 for this subscription.",
array(
1 => CRM_Utils_Money::format($this->_subscriptionDetails->amount, $this->_subscriptionDetails->currency),
2 => CRM_Utils_Money::format($params['amount'], $this->_subscriptionDetails->currency),
)) . ' ';
if ($this->_subscriptionDetails->amount < $params['amount']) {
$msg = ts('Recurring Contribution Updated - increased installment amount');
}
else {
$msg = ts('Recurring Contribution Updated - decreased installment amount');
}
}
if ($this->_subscriptionDetails->installments != $params['installments']) {
$message .= "<br /> " . ts("Recurring contribution installments have been updated from %1 to %2 for this subscription.", array(
1 => $this->_subscriptionDetails->installments,
2 => $params['installments'],
)) . ' ';
}
$activityParams = array(
'source_contact_id' => $contactID,
'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type',
'Update Recurring Contribution',
'name'
),
'subject' => $msg,
'details' => $message,
'activity_date_time' => date('YmdHis'),
'status_id' => CRM_Core_OptionGroup::getValue('activity_status',
'Completed',
'name'
),
);
$session = CRM_Core_Session::singleton();
$cid = $session->get('userID');
if ($cid) {
$activityParams['target_contact_id'][] = $activityParams['source_contact_id'];
$activityParams['source_contact_id'] = $cid;
}
CRM_Activity_BAO_Activity::create($activityParams);
if (!empty($params['is_notify'])) {
// send notification
if ($this->_subscriptionDetails->contribution_page_id) {
CRM_Core_DAO::commonRetrieveAll('CRM_Contribute_DAO_ContributionPage', 'id',
$this->_subscriptionDetails->contribution_page_id, $value, array(
'title',
'receipt_from_name',
'receipt_from_email',
)
);
$receiptFrom = '"' . CRM_Utils_Array::value('receipt_from_name', $value[$this->_subscriptionDetails->contribution_page_id]) . '" <' . $value[$this->_subscriptionDetails->contribution_page_id]['receipt_from_email'] . '>';
}
else {
$domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
$receiptFrom = "$domainValues[0] <$domainValues[1]>";
}
list($donorDisplayName, $donorEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
$tplParams = array(
'recur_frequency_interval' => $this->_subscriptionDetails->frequency_interval,
'recur_frequency_unit' => $this->_subscriptionDetails->frequency_unit,
'amount' => CRM_Utils_Money::format($params['amount']),
'installments' => $params['installments'],
);
$tplParams['contact'] = array('display_name' => $donorDisplayName);
$tplParams['receipt_from_email'] = $receiptFrom;
$sendTemplateParams = array(
'groupName' => 'msg_tpl_workflow_contribution',
'valueName' => 'contribution_recurring_edit',
'contactId' => $contactID,
'tplParams' => $tplParams,
'isTest' => $this->_subscriptionDetails->is_test,
'PDFFilename' => 'receipt.pdf',
'from' => $receiptFrom,
'toName' => $donorDisplayName,
'toEmail' => $donorEmail,
);
list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
}
}
$session = CRM_Core_Session::singleton();
$userID = $session->get('userID');
if ($userID && $status) {
CRM_Core_Session::setStatus($status, $msgTitle, $msgType);
}
elseif (!$userID) {
if ($status) {
CRM_Utils_System::setUFMessage($status);
}
// keep result as 1, since we not displaying anything on the redirected page anyway
return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/subscriptionstatus',
"reset=1&task=update&result=1"));
}
}
/**
* Explicitly declare the form context.
*/
public function getDefaultContext() {
return 'create';
}
}

View file

@ -0,0 +1,60 @@
<?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
*/
class CRM_Contribute_Import_Controller 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);
// 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,218 @@
<?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
*/
class CRM_Contribute_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;
/**
* Is this field required
* @var boolean
*/
public $_required;
/**
* Data to be carried for use by a derived class
* @var object
*/
public $_payload;
/**
* 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;
/**
* This is soft credit field
* @var string
*/
public $_softCreditField;
/**
* @param string $name
* @param $title
* @param int $type
* @param string $headerPattern
* @param string $dataPattern
* @param null $softCreditField
*/
public function __construct($name, $title, $type = CRM_Utils_Type::T_INT, $headerPattern = '//', $dataPattern = '//', $softCreditField = NULL) {
$this->_name = $name;
$this->_title = $title;
$this->_type = $type;
$this->_headerPattern = $headerPattern;
$this->_dataPattern = $dataPattern;
$this->_softCreditField = $softCreditField;
$this->_value = NULL;
}
public function resetValue() {
$this->_value = NULL;
}
/**
* Set a value.
*
* The value is in string format. Convert the value to the type of this field
* and set the field value with the appropriate type
*
* @param $value
*/
public function setValue($value) {
$this->_value = $value;
}
/**
* Validate a field.
*
* @return bool
*/
public function validate() {
if (CRM_Utils_System::isNull($this->_value)) {
return TRUE;
}
switch ($this->_name) {
case 'contact_id':
// note: we validate existence of the contact in API, upon
// insert (it would be too costly to do a db call here)
return CRM_Utils_Rule::integer($this->_value);
case 'receive_date':
case 'cancel_date':
case 'receipt_date':
case 'thankyou_date':
return CRM_Utils_Rule::date($this->_value);
case 'non_deductible_amount':
case 'total_amount':
case 'fee_amount':
case 'net_amount':
return CRM_Utils_Rule::money($this->_value);
case 'trxn_id':
static $seenTrxnIds = array();
if (in_array($this->_value, $seenTrxnIds)) {
return FALSE;
}
elseif ($this->_value) {
$seenTrxnIds[] = $this->_value;
return TRUE;
}
else {
$this->_value = NULL;
return TRUE;
}
break;
case 'currency':
return CRM_Utils_Rule::currencyCode($this->_value);
case 'financial_type':
static $contributionTypes = NULL;
if (!$contributionTypes) {
$contributionTypes = CRM_Contribute_PseudoConstant::financialType();
}
if (in_array($this->_value, $contributionTypes)) {
return TRUE;
}
else {
return FALSE;
}
break;
case 'payment_instrument':
static $paymentInstruments = NULL;
if (!$paymentInstruments) {
$paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument();
}
if (in_array($this->_value, $paymentInstruments)) {
return TRUE;
}
else {
return FALSE;
}
break;
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('Contribution');
}
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,81 @@
<?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 gets the name of the file to upload
*/
class CRM_Contribute_Import_Form_DataSource extends CRM_Import_Form_DataSource {
const PATH = 'civicrm/contribute/import';
const IMPORT_ENTITY = 'Contribution';
/**
* Build the form object.
*/
public function buildQuickForm() {
parent::buildQuickForm();
$duplicateOptions = array();
$duplicateOptions[] = $this->createElement('radio',
NULL, NULL, ts('Insert new contributions'), CRM_Import_Parser::DUPLICATE_SKIP
);
$duplicateOptions[] = $this->createElement('radio',
NULL, NULL, ts('Update existing contributions'), CRM_Import_Parser::DUPLICATE_UPDATE
);
$this->addGroup($duplicateOptions, 'onDuplicate',
ts('Import mode')
);
$this->setDefaults(array('onDuplicate' => CRM_Import_Parser::DUPLICATE_SKIP));
$this->addElement('submit', 'loadMapping', ts('Load Mapping'), NULL, array('onclick' => 'checkSelect()'));
$this->addContactTypeSelector();
}
/**
* Process the uploaded file.
*/
public function postProcess() {
$this->storeFormValues(array(
'onDuplicate',
'contactType',
'dateFormats',
'savedMapping',
));
$this->submitFileForMapping('CRM_Contribute_Import_Parser_Contribution');
}
}

View file

@ -0,0 +1,558 @@
<?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 gets the name of the file to upload.
*/
class CRM_Contribute_Import_Form_MapField extends CRM_Import_Form_MapField {
/**
* Set variables up before form is built.
*/
public function preProcess() {
$this->_mapperFields = $this->get('fields');
asort($this->_mapperFields);
$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', isset($onDuplicate) ? $onDuplicate : "");
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);
}
$highlightedFields = array('financial_type', 'total_amount');
//CRM-2219 removing other required fields since for updation only
//invoice id or trxn id or contribution id is required.
if ($this->_onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE) {
$remove = array('contribution_contact_id', 'email', 'first_name', 'last_name', 'external_identifier');
foreach ($remove as $value) {
unset($this->_mapperFields[$value]);
}
//modify field title only for update mode. CRM-3245
foreach (array(
'contribution_id',
'invoice_id',
'trxn_id',
) as $key) {
$this->_mapperFields[$key] .= ' (match to contribution record)';
$highlightedFields[] = $key;
}
}
elseif ($this->_onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) {
unset($this->_mapperFields['contribution_id']);
$highlightedFieldsArray = array(
'contribution_contact_id',
'email',
'first_name',
'last_name',
'external_identifier',
);
foreach ($highlightedFieldsArray as $name) {
$highlightedFields[] = $name;
}
}
// modify field title for contribution status
$this->_mapperFields['contribution_status_id'] = ts('Contribution Status');
$this->assign('highlightedFields', $highlightedFields);
}
/**
* Build the form object.
*/
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', CRM_Utils_Array::value(1, $mappingLocation));
$mappingPhoneType = CRM_Utils_Array::value('1', CRM_Utils_Array::value(1, $mappingPhoneType));
$mappingRelation = CRM_Utils_Array::value('1', 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 Contributions';
$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_Contribute_Import_Form_MapField', 'formRule'), $this);
//-------- end of saved mapping stuff ---------
$defaults = array();
$mapperKeys = array_keys($this->_mapperFields);
$hasHeaders = !empty($this->_columnHeaders);
$headerPatterns = $this->get('headerPatterns');
$dataPatterns = $this->get('dataPatterns');
$mapperKeysValues = $this->controller->exportValue($this->_name, 'mapper');
/* 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;
if (!$this->get('onDuplicate')) {
unset($sel1['id']);
unset($sel1['contribution_id']);
}
$softCreditFields['contact_id'] = ts('Contact ID');
$softCreditFields['external_identifier'] = ts('External ID');
$softCreditFields['email'] = ts('Email');
$sel2['soft_credit'] = $softCreditFields;
$sel3['soft_credit']['contact_id'] = $sel3['soft_credit']['external_identifier'] = $sel3['soft_credit']['email'] = CRM_Core_OptionGroup::values('soft_credit_type');
$sel4 = NULL;
// end of soft credit section
$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]);
// reusing contact_type field array for soft credit
$softField = isset($mappingContactType[$i]) ? $mappingContactType[$i] : 0;
if (!$softField) {
$js .= "{$formName}['mapper[$i][1]'].style.display = 'none';\n";
}
$js .= "{$formName}['mapper[$i][2]'].style.display = 'none';\n";
$js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
$defaults["mapper[$i]"] = array(
CRM_Utils_Array::value(0, $mappingHeader),
($softField) ? $softField : "",
(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_0_');\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_0_');\n";
if ($hasHeaders) {
// do array search first to see if has mapped key
$columnKey = array_search($this->_columnHeaders[$i], $this->_mapperFields);
if (isset($this->_fieldUsed[$columnKey])) {
$defaults["mapper[$i]"] = $columnKey;
$this->_fieldUsed[$key] = TRUE;
}
else {
// Infer the default from the column names if we have them
$defaults["mapper[$i]"] = array(
$this->defaultFromHeader($this->_columnHeaders[$i],
$headerPatterns
),
0,
);
}
}
else {
// Otherwise guess the default from the form of the data
$defaults["mapper[$i]"] = array(
$this->defaultFromData($dataPatterns, $i),
// $defaultLocationType->id
0,
);
}
if (!empty($mapperKeysValues) && $mapperKeysValues[$i][0] == 'soft_credit') {
$js .= "cj('#mapper_" . $i . "_1').val($mapperKeysValues[$i][1]);\n";
$js .= "cj('#mapper_" . $i . "_2').val($mapperKeysValues[$i][2]);\n";
}
}
$sel->setOptions(array($sel1, $sel2, $sel3, $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();
$fieldMessage = NULL;
$contactORContributionId = $self->_onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE ? 'contribution_id' : 'contribution_contact_id';
if (!array_key_exists('savedMapping', $fields)) {
$importKeys = array();
foreach ($fields['mapper'] as $mapperPart) {
$importKeys[] = $mapperPart[0];
}
$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' => isset($contactTypes[$contactTypeId]) ? $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];
}
if ($val == "soft_credit") {
$mapperKey = CRM_Utils_Array::key('soft_credit', $importKeys);
if (empty($fields['mapper'][$mapperKey][1])) {
if (empty($errors['_qf_default'])) {
$errors['_qf_default'] = '';
}
$errors['_qf_default'] .= ts('Missing required fields: Soft Credit') . '<br />';
}
}
}
foreach ($ruleFields as $field => $weight) {
$fieldMessage .= ' ' . $field . '(weight ' . $weight . ')';
}
// FIXME: should use the schema titles, not redeclare them
$requiredFields = array(
$contactORContributionId == 'contribution_id' ? 'contribution_id' : 'contribution_contact_id' => $contactORContributionId == 'contribution_id' ? ts('Contribution ID') : ts('Contact ID'),
'total_amount' => ts('Total Amount'),
'financial_type' => ts('Financial Type'),
);
foreach ($requiredFields as $field => $title) {
if (!in_array($field, $importKeys)) {
if (empty($errors['_qf_default'])) {
$errors['_qf_default'] = '';
}
if ($field == $contactORContributionId) {
if (!($weightSum >= $threshold || in_array('external_identifier', $importKeys)) &&
$self->_onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE
) {
$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,
)) . '<br />';
}
elseif ($self->_onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE &&
!(in_array('invoice_id', $importKeys) || in_array('trxn_id', $importKeys) ||
in_array('contribution_id', $importKeys)
)
) {
$errors['_qf_default'] .= ts('Invoice ID or Transaction ID or Contribution ID are required to match to the existing contribution records in Update mode.') . '<br />';
}
}
else {
$errors['_qf_default'] .= ts('Missing required field: %1', array(
1 => $title,
)) . '<br />';
}
}
}
//at least one field should be mapped during update.
if ($self->_onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE) {
$atleastOne = FALSE;
foreach ($self->_mapperFields as $key => $field) {
if (in_array($key, $importKeys) &&
!in_array($key, array('doNotImport', 'contribution_id', 'invoice_id', 'trxn_id'))
) {
$atleastOne = TRUE;
break;
}
}
if (!$atleastOne) {
$errors['_qf_default'] .= ts('At least one contribution field needs to be mapped for update during update mode.') . '<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 Contribution', 'name');
if (CRM_Core_BAO_Mapping::checkMapping($nameField, $mappingTypeId)) {
$errors['saveMappingName'] = ts('Duplicate Import Contribution Mapping Name');
}
}
}
if (!empty($errors)) {
if (!empty($errors['saveMappingName'])) {
$_flag = 1;
$assignError = new CRM_Core_Page();
$assignError->assign('mappingDetailsError', $_flag);
}
if (!empty($errors['_qf_default'])) {
CRM_Core_Session::setStatus($errors['_qf_default'], ts("Error"), "error");
return $errors;
}
}
return TRUE;
}
/**
* Process the mapped fields and map it into the uploaded file preview the file and extract some summary statistics.
*/
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');
$mapper = $mapperKeys = $mapperKeysMain = $mapperSoftCredit = $softCreditFields = $mapperPhoneType = $mapperSoftCreditType = array();
$mapperKeys = $this->controller->exportValue($this->_name, 'mapper');
$softCreditTypes = CRM_Core_OptionGroup::values('soft_credit_type');
for ($i = 0; $i < $this->_columnCount; $i++) {
$mapper[$i] = $this->_mapperFields[$mapperKeys[$i][0]];
$mapperKeysMain[$i] = $mapperKeys[$i][0];
if (isset($mapperKeys[$i][0]) && $mapperKeys[$i][0] == 'soft_credit') {
$mapperSoftCredit[$i] = $mapperKeys[$i][1];
if (strpos($mapperSoftCredit[$i], '_') !== FALSE) {
list($first, $second) = explode('_', $mapperSoftCredit[$i]);
$softCreditFields[$i] = ucwords($first . " " . $second);
}
else {
$softCreditFields[$i] = $mapperSoftCredit[$i];
}
$mapperSoftCreditType[$i] = array(
'value' => isset($mapperKeys[$i][2]) ? $mapperKeys[$i][2] : '',
'label' => isset($softCreditTypes[$mapperKeys[$i][2]]) ? $softCreditTypes[$mapperKeys[$i][2]] : '',
);
}
else {
$mapperSoftCredit[$i] = $softCreditFields[$i] = $mapperSoftCreditType[$i] = NULL;
}
}
$this->set('mapper', $mapper);
$this->set('softCreditFields', $softCreditFields);
$this->set('mapperSoftCreditType', $mapperSoftCreditType);
// 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;
$updateMappingFields->name = $mapper[$i];
//reuse contact_type field in db to store fields associated with soft credit
$updateMappingFields->contact_type = isset($mapperSoftCredit[$i]) ? $mapperSoftCredit[$i] : NULL;
$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 Contribution',
'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;
$saveMappingFields->name = $mapper[$i];
//reuse contact_type field in db to store fields associated with soft credit
$saveMappingFields->contact_type = isset($mapperSoftCredit[$i]) ? $mapperSoftCredit[$i] : NULL;
$saveMappingFields->save();
}
$this->set('savedMapping', $saveMappingFields->mapping_id);
}
$parser = new CRM_Contribute_Import_Parser_Contribution($mapperKeysMain, $mapperSoftCredit, $mapperPhoneType);
$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,185 @@
<?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 previews the uploaded file and returns summary statistics.
*/
class CRM_Contribute_Import_Form_Preview extends CRM_Import_Form_Preview {
/**
* Set variables up before form is built.
*/
public function preProcess() {
$skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
//get the data from the session
$dataValues = $this->get('dataValues');
$mapper = $this->get('mapper');
$softCreditFields = $this->get('softCreditFields');
$mapperSoftCreditType = $this->get('mapperSoftCreditType');
$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_Contribute_Import_Parser';
$this->set('downloadErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
if ($conflictRowCount) {
$urlParams = 'type=' . CRM_Import_Parser::CONFLICT . '&parser=CRM_Contribute_Import_Parser';
$this->set('downloadConflictRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
if ($mismatchCount) {
$urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . '&parser=CRM_Contribute_Import_Parser';
$this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
$properties = array(
'mapper',
'softCreditFields',
'mapperSoftCreditType',
'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.
*/
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');
$mapperSoftCreditType = $this->get('mapperSoftCreditType');
$mapper = $this->controller->exportValue('MapField', 'mapper');
$mapperKeys = array();
$mapperSoftCredit = array();
$mapperPhoneType = array();
foreach ($mapper as $key => $value) {
$mapperKeys[$key] = $mapper[$key][0];
if (isset($mapper[$key][0]) && $mapper[$key][0] == 'soft_credit' && isset($mapper[$key])) {
$mapperSoftCredit[$key] = isset($mapper[$key][1]) ? $mapper[$key][1] : '';
$mapperSoftCreditType[$key] = $mapperSoftCreditType[$key]['value'];
}
else {
$mapperSoftCredit[$key] = $mapperSoftCreditType[$key] = NULL;
}
}
$parser = new CRM_Contribute_Import_Parser_Contribution($mapperKeys, $mapperSoftCredit, $mapperPhoneType, $mapperSoftCreditType);
$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_Contribute_Import_Parser';
$this->set('downloadErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
$urlParams = 'type=' . CRM_Import_Parser::CONFLICT . '&parser=CRM_Contribute_Import_Parser';
$this->set('downloadConflictRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
$urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . '&parser=CRM_Contribute_Import_Parser';
$this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
}
}

View file

@ -0,0 +1,128 @@
<?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 summarizes the import results.
*/
class CRM_Contribute_Import_Form_Summary extends CRM_Import_Form_Summary {
/**
* Set variables up before form is built.
*/
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');
$invalidSoftCreditRowCount = $this->get('invalidSoftCreditRowCount');
if ($invalidSoftCreditRowCount) {
$urlParams = 'type=' . CRM_Contribute_Import_Parser::SOFT_CREDIT_ERROR . '&parser=CRM_Contribute_Import_Parser';
$this->set('downloadSoftCreditErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
$validSoftCreditRowCount = $this->get('validSoftCreditRowCount');
$invalidPledgePaymentRowCount = $this->get('invalidPledgePaymentRowCount');
if ($invalidPledgePaymentRowCount) {
$urlParams = 'type=' . CRM_Contribute_Import_Parser::PLEDGE_PAYMENT_ERROR . '&parser=CRM_Contribute_Import_Parser';
$this->set('downloadPledgePaymentErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
$validPledgePaymentRowCount = $this->get('validPledgePaymentRowCount');
$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_Contribute_Import_Parser';
$this->set('downloadDuplicateRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
}
elseif ($mismatchCount) {
$urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . '&parser=CRM_Contribute_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 - $invalidSoftCreditRowCount - $invalidPledgePaymentRowCount
);
}
$this->assign('dupeActionString', $dupeActionString);
$properties = array(
'totalRowCount',
'validRowCount',
'invalidRowCount',
'validSoftCreditRowCount',
'invalidSoftCreditRowCount',
'conflictRowCount',
'downloadConflictRecordsUrl',
'downloadErrorRecordsUrl',
'duplicateRowCount',
'downloadDuplicateRecordsUrl',
'downloadMismatchRecordsUrl',
'groupAdditions',
'unMatchCount',
'validPledgePaymentRowCount',
'invalidPledgePaymentRowCount',
'downloadPledgePaymentErrorRecordsUrl',
'downloadSoftCreditErrorRecordsUrl',
);
foreach ($properties as $property) {
$this->assign($property, $this->get($property));
}
}
}

View file

@ -0,0 +1,662 @@
<?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
*/
abstract class CRM_Contribute_Import_Parser extends CRM_Import_Parser {
/**
* Contribution-specific result codes
* @see CRM_Import_Parser result code constants
*/
const SOFT_CREDIT = 512, SOFT_CREDIT_ERROR = 1024, PLEDGE_PAYMENT = 2048, PLEDGE_PAYMENT_ERROR = 4096;
protected $_fileName;
/**
* Imported file size
*/
protected $_fileSize;
/**
* Seperator being used
*/
protected $_seperator;
/**
* Total number of lines in file
*/
protected $_lineCount;
/**
* Running total number of valid soft credit rows
*/
protected $_validSoftCreditRowCount;
/**
* Running total number of invalid soft credit rows
*/
protected $_invalidSoftCreditRowCount;
/**
* Running total number of valid pledge payment rows
*/
protected $_validPledgePaymentRowCount;
/**
* Running total number of invalid pledge payment rows
*/
protected $_invalidPledgePaymentRowCount;
/**
* Array of pledge payment error lines, bounded by MAX_ERROR
*/
protected $_pledgePaymentErrors;
/**
* Array of pledge payment error lines, bounded by MAX_ERROR
*/
protected $_softCreditErrors;
/**
* Filename of pledge payment error data
*
* @var string
*/
protected $_pledgePaymentErrorsFileName;
/**
* Filename of soft credit error data
*
* @var string
*/
protected $_softCreditErrorsFileName;
/**
* 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 = $this->_validSoftCreditRowCount = $this->_validPledgePaymentRowCount = 0;
$this->_invalidRowCount = $this->_validCount = $this->_invalidSoftCreditRowCount = $this->_invalidPledgePaymentRowCount = 0;
$this->_totalCount = $this->_conflictCount = 0;
$this->_errors = array();
$this->_warnings = array();
$this->_conflicts = array();
$this->_pledgePaymentErrors = array();
$this->_softCreditErrors = 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::SOFT_CREDIT) {
$this->_validSoftCreditRowCount++;
$this->_validCount++;
if ($mode == self::MODE_MAPFIELD) {
$this->_rows[] = $values;
$this->_activeFieldCount = max($this->_activeFieldCount, count($values));
}
}
if ($returnCode == self::PLEDGE_PAYMENT) {
$this->_validPledgePaymentRowCount++;
$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::PLEDGE_PAYMENT_ERROR) {
$this->_invalidPledgePaymentRowCount++;
if ($this->_invalidPledgePaymentRowCount < $this->_maxErrorCount) {
$recordNumber = $this->_lineCount;
if ($this->_haveColumnHeader) {
$recordNumber--;
}
array_unshift($values, $recordNumber);
$this->_pledgePaymentErrors[] = $values;
}
}
if ($returnCode == self::SOFT_CREDIT_ERROR) {
$this->_invalidSoftCreditRowCount++;
if ($this->_invalidSoftCreditRowCount < $this->_maxErrorCount) {
$recordNumber = $this->_lineCount;
if ($this->_haveColumnHeader) {
$recordNumber--;
}
array_unshift($values, $recordNumber);
$this->_softCreditErrors[] = $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('Contribution');
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->_invalidPledgePaymentRowCount) {
// removed view url for invlaid contacts
$headers = array_merge(array(
ts('Line Number'),
ts('Reason'),
),
$customHeaders
);
$this->_pledgePaymentErrorsFileName = self::errorFileName(self::PLEDGE_PAYMENT_ERROR);
self::exportCSV($this->_pledgePaymentErrorsFileName, $headers, $this->_pledgePaymentErrors);
}
if ($this->_invalidSoftCreditRowCount) {
// removed view url for invlaid contacts
$headers = array_merge(array(
ts('Line Number'),
ts('Reason'),
),
$customHeaders
);
$this->_softCreditErrorsFileName = self::errorFileName(self::SOFT_CREDIT_ERROR);
self::exportCSV($this->_softCreditErrorsFileName, $headers, $this->_softCreditErrors);
}
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 Contribution 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 array $fieldKeys mapped array of values
*/
public function setActiveFields($fieldKeys) {
$this->_activeFieldCount = count($fieldKeys);
foreach ($fieldKeys as $key) {
if (empty($this->_fields[$key])) {
$this->_activeFields[] = new CRM_Contribute_Import_Field('', ts('- do not import -'));
}
else {
$this->_activeFields[] = clone($this->_fields[$key]);
}
}
}
/**
* @param array $elements
*/
public function setActiveFieldSoftCredit($elements) {
for ($i = 0; $i < count($elements); $i++) {
$this->_activeFields[$i]->_softCreditField = $elements[$i];
}
}
/**
* @param array $elements
*/
public function setActiveFieldSoftCreditType($elements) {
for ($i = 0; $i < count($elements); $i++) {
$this->_activeFields[$i]->_softCreditType = $elements[$i];
}
}
/**
* 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)) {
if (isset($this->_activeFields[$i]->_softCreditField)) {
if (!isset($params[$this->_activeFields[$i]->_name])) {
$params[$this->_activeFields[$i]->_name] = array();
}
$params[$this->_activeFields[$i]->_name][$i][$this->_activeFields[$i]->_softCreditField] = $this->_activeFields[$i]->_value;
if (isset($this->_activeFields[$i]->_softCreditType)) {
$params[$this->_activeFields[$i]->_name][$i]['soft_credit_type_id'] = $this->_activeFields[$i]->_softCreditType;
}
}
if (!isset($params[$this->_activeFields[$i]->_name])) {
if (!isset($this->_activeFields[$i]->_softCreditField)) {
$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_Contribute_Import_Field($name, $title, $type, $headerPattern, $dataPattern);
}
else {
$tempField = CRM_Contact_BAO_Contact::importableFields('All', NULL);
if (!array_key_exists($name, $tempField)) {
$this->_fields[$name] = new CRM_Contribute_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
*/
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('invalidSoftCreditRowCount', $this->_invalidSoftCreditRowCount);
$store->set('validSoftCreditRowCount', $this->_validSoftCreditRowCount);
$store->set('invalidPledgePaymentRowCount', $this->_invalidPledgePaymentRowCount);
$store->set('validPledgePaymentRowCount', $this->_validPledgePaymentRowCount);
$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 ($this->_invalidPledgePaymentRowCount) {
$store->set('pledgePaymentErrorsFileName', $this->_pledgePaymentErrorsFileName);
}
if ($this->_invalidSoftCreditRowCount) {
$store->set('softCreditErrorsFileName', $this->_softCreditErrorsFileName);
}
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
*/
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 (isset($value[0]) && 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);
}
/**
* Determines the file extension based on error code.
*
* @param int $type
* Error code constant.
*
* @return string
*/
public static function errorFileName($type) {
$fileName = NULL;
if (empty($type)) {
return $fileName;
}
$config = CRM_Core_Config::singleton();
$fileName = $config->uploadDir . "sqlImport";
switch ($type) {
case CRM_Contribute_Import_Parser::SOFT_CREDIT_ERROR:
$fileName .= '.softCreditErrors';
break;
case CRM_Contribute_Import_Parser::PLEDGE_PAYMENT_ERROR:
$fileName .= '.pledgePaymentErrors';
break;
default:
$fileName = parent::errorFileName($type);
break;
}
return $fileName;
}
/**
* Determines the file name based on error code.
*
* @param int $type
* Error code constant.
*
* @return string
*/
public static function saveFileName($type) {
$fileName = NULL;
if (empty($type)) {
return $fileName;
}
switch ($type) {
case CRM_Contribute_Import_Parser::SOFT_CREDIT_ERROR:
$fileName = 'Import_Soft_Credit_Errors.csv';
break;
case CRM_Contribute_Import_Parser::PLEDGE_PAYMENT_ERROR:
$fileName = 'Import_Pledge_Payment_Errors.csv';
break;
default:
$fileName = parent::saveFileName($type);
break;
}
return $fileName;
}
}

View file

@ -0,0 +1,611 @@
<?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
*/
/**
* Class to parse contribution csv files.
*/
class CRM_Contribute_Import_Parser_Contribution extends CRM_Contribute_Import_Parser {
protected $_mapperKeys;
private $_contactIdIndex;
private $_totalAmountIndex;
private $_contributionTypeIndex;
protected $_mapperSoftCredit;
//protected $_mapperPhoneType;
/**
* Array of successfully imported contribution id's
*
* @array
*/
protected $_newContributions;
/**
* Class constructor.
*
* @param $mapperKeys
* @param null $mapperSoftCredit
* @param null $mapperPhoneType
* @param null $mapperSoftCreditType
*/
public function __construct(&$mapperKeys, $mapperSoftCredit = NULL, $mapperPhoneType = NULL, $mapperSoftCreditType = NULL) {
parent::__construct();
$this->_mapperKeys = &$mapperKeys;
$this->_mapperSoftCredit = &$mapperSoftCredit;
$this->_mapperSoftCreditType = &$mapperSoftCreditType;
}
/**
* The initializer code, called before the processing
*/
public function init() {
$fields = CRM_Contribute_BAO_Contribution::importableFields($this->_contactType, FALSE);
$fields = array_merge($fields,
array(
'soft_credit' => array(
'title' => ts('Soft Credit'),
'softCredit' => TRUE,
'headerPattern' => '/Soft Credit/i',
),
)
);
// add pledge fields only if its is enabled
if (CRM_Core_Permission::access('CiviPledge')) {
$pledgeFields = array(
'pledge_payment' => array(
'title' => ts('Pledge Payment'),
'headerPattern' => '/Pledge Payment/i',
),
'pledge_id' => array(
'title' => ts('Pledge ID'),
'headerPattern' => '/Pledge ID/i',
),
);
$fields = array_merge($fields, $pledgeFields);
}
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->_newContributions = array();
$this->setActiveFields($this->_mapperKeys);
$this->setActiveFieldSoftCredit($this->_mapperSoftCredit);
$this->setActiveFieldSoftCreditType($this->_mapperSoftCreditType);
// FIXME: we should do this in one place together with Form/MapField.php
$this->_contactIdIndex = -1;
$this->_totalAmountIndex = -1;
$this->_contributionTypeIndex = -1;
$index = 0;
foreach ($this->_mapperKeys as $key) {
switch ($key) {
case 'contribution_contact_id':
$this->_contactIdIndex = $index;
break;
case 'total_amount':
$this->_totalAmountIndex = $index;
break;
case 'financial_type':
$this->_contributionTypeIndex = $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);
$params = &$this->getActiveFieldParams();
$errorMessage = NULL;
//for date-Formats
$session = CRM_Core_Session::singleton();
$dateType = $session->get('dateTypes');
foreach ($params as $key => $val) {
if ($val) {
switch ($key) {
case 'receive_date':
if ($dateValue = CRM_Utils_Date::formatDate($params[$key], $dateType)) {
$params[$key] = $dateValue;
}
else {
CRM_Contact_Import_Parser_Contact::addToErrorMsg('Receive Date', $errorMessage);
}
break;
case 'cancel_date':
if ($dateValue = CRM_Utils_Date::formatDate($params[$key], $dateType)) {
$params[$key] = $dateValue;
}
else {
CRM_Contact_Import_Parser_Contact::addToErrorMsg('Cancel Date', $errorMessage);
}
break;
case 'receipt_date':
if ($dateValue = CRM_Utils_Date::formatDate($params[$key], $dateType)) {
$params[$key] = $dateValue;
}
else {
CRM_Contact_Import_Parser_Contact::addToErrorMsg('Receipt date', $errorMessage);
}
break;
case 'thankyou_date':
if ($dateValue = CRM_Utils_Date::formatDate($params[$key], $dateType)) {
$params[$key] = $dateValue;
}
else {
CRM_Contact_Import_Parser_Contact::addToErrorMsg('Thankyou Date', $errorMessage);
}
break;
}
}
}
//date-Format part ends
$params['contact_type'] = 'Contribution';
//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();
$formatted = array('version' => 3);
// don't add to recent items, CRM-4399
$formatted['skipRecentView'] = TRUE;
//for date-Formats
$session = CRM_Core_Session::singleton();
$dateType = $session->get('dateTypes');
$customDataType = !empty($params['contact_type']) ? $params['contact_type'] : 'Contribution';
$customFields = CRM_Core_BAO_CustomField::getFields($customDataType);
//CRM-10994
if (isset($params['total_amount']) && $params['total_amount'] == 0) {
$params['total_amount'] = '0.00';
}
foreach ($params as $key => $val) {
if ($val) {
switch ($key) {
case 'receive_date':
case 'cancel_date':
case 'receipt_date':
case 'thankyou_date':
$params[$key] = CRM_Utils_Date::formatDate($params[$key], $dateType);
break;
case 'pledge_payment':
$params[$key] = CRM_Utils_String::strtobool($val);
break;
}
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);
}
}
}
}
//date-Format part ends
static $indieFields = NULL;
if ($indieFields == NULL) {
$tempIndieFields = CRM_Contribute_DAO_Contribution::import();
$indieFields = $tempIndieFields;
}
$paramValues = array();
foreach ($params as $key => $field) {
if ($field == NULL || $field === '') {
continue;
}
$paramValues[$key] = $field;
}
//import contribution record according to select contact type
if ($onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP &&
(!empty($paramValues['contribution_contact_id']) || !empty($paramValues['external_identifier']))
) {
$paramValues['contact_type'] = $this->_contactType;
}
elseif ($onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE &&
(!empty($paramValues['contribution_id']) || !empty($values['trxn_id']) || !empty($paramValues['invoice_id']))
) {
$paramValues['contact_type'] = $this->_contactType;
}
elseif (!empty($params['soft_credit'])) {
$paramValues['contact_type'] = $this->_contactType;
}
elseif (!empty($paramValues['pledge_payment'])) {
$paramValues['contact_type'] = $this->_contactType;
}
//need to pass $onDuplicate to check import mode.
if (!empty($paramValues['pledge_payment'])) {
$paramValues['onDuplicate'] = $onDuplicate;
}
require_once 'CRM/Utils/DeprecatedUtils.php';
$formatError = _civicrm_api3_deprecated_formatted_param($paramValues, $formatted, TRUE, $onDuplicate);
if ($formatError) {
array_unshift($values, $formatError['error_message']);
if (CRM_Utils_Array::value('error_data', $formatError) == 'soft_credit') {
return CRM_Contribute_Import_Parser::SOFT_CREDIT_ERROR;
}
elseif (CRM_Utils_Array::value('error_data', $formatError) == 'pledge_payment') {
return CRM_Contribute_Import_Parser::PLEDGE_PAYMENT_ERROR;
}
return CRM_Import_Parser::ERROR;
}
if ($onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE) {
$formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted,
NULL,
'Contribution'
);
}
else {
//fix for CRM-2219 - Update Contribution
// onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE
if (!empty($paramValues['invoice_id']) || !empty($paramValues['trxn_id']) || !empty($paramValues['contribution_id'])) {
$dupeIds = array(
'id' => CRM_Utils_Array::value('contribution_id', $paramValues),
'trxn_id' => CRM_Utils_Array::value('trxn_id', $paramValues),
'invoice_id' => CRM_Utils_Array::value('invoice_id', $paramValues),
);
$ids['contribution'] = CRM_Contribute_BAO_Contribution::checkDuplicateIds($dupeIds);
if ($ids['contribution']) {
$formatted['id'] = $ids['contribution'];
$formatted['custom'] = CRM_Core_BAO_CustomField::postProcess($formatted,
$formatted['id'],
'Contribution'
);
//process note
if (!empty($paramValues['note'])) {
$noteID = array();
$contactID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $ids['contribution'], 'contact_id');
$daoNote = new CRM_Core_BAO_Note();
$daoNote->entity_table = 'civicrm_contribution';
$daoNote->entity_id = $ids['contribution'];
if ($daoNote->find(TRUE)) {
$noteID['id'] = $daoNote->id;
}
$noteParams = array(
'entity_table' => 'civicrm_contribution',
'note' => $paramValues['note'],
'entity_id' => $ids['contribution'],
'contact_id' => $contactID,
);
CRM_Core_BAO_Note::add($noteParams, $noteID);
unset($formatted['note']);
}
//need to check existing soft credit contribution, CRM-3968
if (!empty($formatted['soft_credit'])) {
$dupeSoftCredit = array(
'contact_id' => $formatted['soft_credit'],
'contribution_id' => $ids['contribution'],
);
//Delete all existing soft Contribution from contribution_soft table for pcp_id is_null
$existingSoftCredit = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($dupeSoftCredit['contribution_id']);
if (isset($existingSoftCredit['soft_credit']) && !empty($existingSoftCredit['soft_credit'])) {
foreach ($existingSoftCredit['soft_credit'] as $key => $existingSoftCreditValues) {
if (!empty($existingSoftCreditValues['soft_credit_id'])) {
civicrm_api3('ContributionSoft', 'delete', array(
'id' => $existingSoftCreditValues['soft_credit_id'],
'pcp_id' => NULL,
));
}
}
}
}
$newContribution = CRM_Contribute_BAO_Contribution::create($formatted, $ids);
$this->_newContributions[] = $newContribution->id;
//return soft valid since we need to show how soft credits were added
if (!empty($formatted['soft_credit'])) {
return CRM_Contribute_Import_Parser::SOFT_CREDIT;
}
// process pledge payment assoc w/ the contribution
return self::processPledgePayments($formatted);
return CRM_Import_Parser::VALID;
}
else {
$labels = array(
'id' => 'Contribution ID',
'trxn_id' => 'Transaction ID',
'invoice_id' => 'Invoice ID',
);
foreach ($dupeIds as $k => $v) {
if ($v) {
$errorMsg[] = "$labels[$k] $v";
}
}
$errorMsg = implode(' AND ', $errorMsg);
array_unshift($values, 'Matching Contribution record not found for ' . $errorMsg . '. Row was skipped.');
return CRM_Import_Parser::ERROR;
}
}
}
if ($this->_contactIdIndex < 0) {
// set the contact type if its not set
if (!isset($paramValues['contact_type'])) {
$paramValues['contact_type'] = $this->_contactType;
}
$error = $this->checkContactDuplicate($paramValues);
if (CRM_Core_Error::isAPIError($error, CRM_Core_ERROR::DUPLICATE_CONTACT)) {
$matchedIDs = explode(',', $error['error_message']['params'][0]);
if (count($matchedIDs) > 1) {
array_unshift($values, 'Multiple matching contact records detected for this row. The contribution was not imported');
return CRM_Import_Parser::ERROR;
}
else {
$cid = $matchedIDs[0];
$formatted['contact_id'] = $cid;
$newContribution = civicrm_api('contribution', 'create', $formatted);
if (civicrm_error($newContribution)) {
if (is_array($newContribution['error_message'])) {
array_unshift($values, $newContribution['error_message']['message']);
if ($newContribution['error_message']['params'][0]) {
return CRM_Import_Parser::DUPLICATE;
}
}
else {
array_unshift($values, $newContribution['error_message']);
return CRM_Import_Parser::ERROR;
}
}
$this->_newContributions[] = $newContribution['id'];
$formatted['contribution_id'] = $newContribution['id'];
//return soft valid since we need to show how soft credits were added
if (!empty($formatted['soft_credit'])) {
return CRM_Contribute_Import_Parser::SOFT_CREDIT;
}
// process pledge payment assoc w/ the contribution
return self::processPledgePayments($formatted);
return CRM_Import_Parser::VALID;
}
}
else {
// Using new Dedupe rule.
$ruleParams = array(
'contact_type' => $this->_contactType,
'used' => 'Unsupervised',
);
$fieldsArray = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
$disp = NULL;
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($paramValues['external_identifier'])) {
$checkCid = new CRM_Contact_DAO_Contact();
$checkCid->external_identifier = $paramValues['external_identifier'];
$checkCid->find(TRUE);
if ($checkCid->id != $formatted['contact_id']) {
array_unshift($values, 'Mismatch of External ID:' . $paramValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']);
return CRM_Import_Parser::ERROR;
}
}
$newContribution = civicrm_api('contribution', 'create', $formatted);
if (civicrm_error($newContribution)) {
if (is_array($newContribution['error_message'])) {
array_unshift($values, $newContribution['error_message']['message']);
if ($newContribution['error_message']['params'][0]) {
return CRM_Import_Parser::DUPLICATE;
}
}
else {
array_unshift($values, $newContribution['error_message']);
return CRM_Import_Parser::ERROR;
}
}
$this->_newContributions[] = $newContribution['id'];
$formatted['contribution_id'] = $newContribution['id'];
//return soft valid since we need to show how soft credits were added
if (!empty($formatted['soft_credit'])) {
return CRM_Contribute_Import_Parser::SOFT_CREDIT;
}
// process pledge payment assoc w/ the contribution
return self::processPledgePayments($formatted);
return CRM_Import_Parser::VALID;
}
}
/**
* Process pledge payments.
*
* @param array $formatted
*
* @return int
*/
public function processPledgePayments(&$formatted) {
if (!empty($formatted['pledge_payment_id']) && !empty($formatted['pledge_id'])) {
//get completed status
$completeStatusID = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
//need to update payment record to map contribution_id
CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $formatted['pledge_payment_id'],
'contribution_id', $formatted['contribution_id']
);
CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($formatted['pledge_id'],
array($formatted['pledge_payment_id']),
$completeStatusID,
NULL,
$formatted['total_amount']
);
return CRM_Contribute_Import_Parser::PLEDGE_PAYMENT;
}
}
/**
* Get the array of successfully imported contribution id's
*
* @return array
*/
public function &getImportedContributions() {
return $this->_newContributions;
}
/**
* The initializer code, called before the processing.
*/
public function fini() {
}
}

View file

@ -0,0 +1,231 @@
<?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
*/
class CRM_Contribute_Info extends CRM_Core_Component_Info {
/**
* @inheritDoc
*/
protected $keyword = 'contribute';
/**
* @inheritDoc
* Provides base information about the component.
* Needs to be implemented in component's information
* class.
*
* @return array
* collection of required component settings
*/
/**
* @return array
*/
public function getInfo() {
return array(
'name' => 'CiviContribute',
'translatedName' => ts('CiviContribute'),
'title' => ts('CiviCRM Contribution Engine'),
'search' => 1,
'showActivitiesInCore' => 1,
);
}
/**
* @inheritDoc
* Provides permissions that are used by component.
* Needs to be implemented in component's information
* class.
*
* NOTE: if using conditionally permission return,
* implementation of $getAllUnconditionally is required.
*
* @param bool $getAllUnconditionally
* @param bool $descriptions
* Whether to return permission descriptions
*
* @return array|null
* collection of permissions, null if none
*/
public function getPermissions($getAllUnconditionally = FALSE, $descriptions = FALSE) {
$permissions = array(
'access CiviContribute' => array(
ts('access CiviContribute'),
ts('Record backend contributions (with edit contributions) and view all contributions (for visible contacts)'),
),
'edit contributions' => array(
ts('edit contributions'),
ts('Record and update contributions'),
),
'make online contributions' => array(
ts('make online contributions'),
),
'delete in CiviContribute' => array(
ts('delete in CiviContribute'),
ts('Delete contributions'),
),
);
if (!$descriptions) {
foreach ($permissions as $name => $attr) {
$permissions[$name] = array_shift($attr);
}
}
return $permissions;
}
/**
* Provides permissions that are unwise for Anonymous Roles to have.
*
* @return array
* list of permissions
* @see CRM_Component_Info::getPermissions
*/
/**
* @return array
*/
public function getAnonymousPermissionWarnings() {
return array(
'access CiviContribute',
);
}
/**
* @inheritDoc
* Provides information about user dashboard element
* offered by this component.
*
* @return array|null
* collection of required dashboard settings,
* null if no element offered
*/
/**
* @return array|null
*/
public function getUserDashboardElement() {
return array(
'name' => ts('Contributions'),
'title' => ts('Your Contribution(s)'),
'perm' => array('make online contributions'),
'weight' => 10,
);
}
/**
* @inheritDoc
* Provides information about user dashboard element
* offered by this component.
*
* @return array|null
* collection of required dashboard settings,
* null if no element offered
*/
/**
* @return array|null
*/
public function registerTab() {
return array(
'title' => ts('Contributions'),
'url' => 'contribution',
'weight' => 20,
);
}
/**
* @inheritDoc
* Provides information about advanced search pane
* offered by this component.
*
* @return array|null
* collection of required pane settings,
* null if no element offered
*/
/**
* @return array|null
*/
public function registerAdvancedSearchPane() {
return array(
'title' => ts('Contributions'),
'weight' => 20,
);
}
/**
* @inheritDoc
* Provides potential activity types that this
* component might want to register in activity history.
* Needs to be implemented in component's information
* class.
*
* @return array|null
* collection of activity types
*/
/**
* @return array|null
*/
public function getActivityTypes() {
return NULL;
}
/**
* add shortcut to Create New.
* @param $shortCuts
* @param $newCredit
*/
public function creatNewShortcut(&$shortCuts, $newCredit) {
if (CRM_Core_Permission::check('access CiviContribute') &&
CRM_Core_Permission::check('edit contributions')
) {
$shortCut[] = array(
'path' => 'civicrm/contribute/add',
'query' => "reset=1&action=add&context=standalone",
'ref' => 'new-contribution',
'title' => ts('Contribution'),
);
if ($newCredit) {
$title = ts('Contribution') . '<br />&nbsp;&nbsp;(' . ts('credit card') . ')';
$shortCut[0]['shortCuts'][] = array(
'path' => 'civicrm/contribute/add',
'query' => "reset=1&action=add&context=standalone&mode=live",
'ref' => 'new-contribution-cc',
'title' => $title,
);
}
$shortCuts = array_merge($shortCuts, $shortCut);
}
}
}

View file

@ -0,0 +1,64 @@
<?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 contains all the function that are called using AJAX (jQuery)
*/
class CRM_Contribute_Page_AJAX {
/**
* Get Soft credit to list in DT
*/
public static function getSoftContributionRows() {
$requiredParameters = array(
'cid' => 'Integer',
'context' => 'String',
);
$optionalParameters = array(
'entityID' => 'Integer',
'isTest' => 'Integer',
);
$params = CRM_Core_Page_AJAX::defaultSortAndPagerParams();
$params += CRM_Core_Page_AJAX::validateParams($requiredParameters, $optionalParameters);
$softCreditList = CRM_Contribute_BAO_ContributionSoft::getSoftContributionSelector($params);
if (!empty($_GET['is_unit_test'])) {
return $softCreditList;
}
CRM_Utils_JSON::output($softCreditList);
}
}

View file

@ -0,0 +1,712 @@
<?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
*/
/**
* Create a page for displaying Contribute Pages
* Contribute Pages are pages that are used to display
* contributions of different types. Pages consist
* of many customizable sections which can be
* accessed.
*
* This page provides a top level browse view
* of all the contribution pages in the system.
*
*/
class CRM_Contribute_Page_ContributionPage extends CRM_Core_Page {
/**
* The action links that we need to display for the browse screen.
*
* @var array
*/
private static $_actionLinks;
private static $_contributionLinks;
private static $_configureActionLinks;
private static $_onlineContributionLinks;
/**
* @var CRM_Utils_Pager
*/
protected $_pager = NULL;
/**
* @var string
*/
protected $_sortByCharacter;
/**
* Get the action links for this page.
*
* @return array
*/
public static function &actionLinks() {
// check if variable _actionsLinks is populated
if (!isset(self::$_actionLinks)) {
// helper variable for nicer formatting
$deleteExtra = ts('Are you sure you want to delete this Contribution page?');
$copyExtra = ts('Are you sure you want to make a copy of this Contribution page?');
self::$_actionLinks = array(
CRM_Core_Action::COPY => array(
'name' => ts('Make a Copy'),
'url' => CRM_Utils_System::currentPath(),
'qs' => 'action=copy&gid=%%id%%',
'title' => ts('Make a Copy of CiviCRM Contribution Page'),
'extra' => 'onclick = "return confirm(\'' . $copyExtra . '\');"',
),
CRM_Core_Action::DISABLE => array(
'name' => ts('Disable'),
'title' => ts('Disable'),
'ref' => 'crm-enable-disable',
),
CRM_Core_Action::ENABLE => array(
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable'),
),
CRM_Core_Action::DELETE => array(
'name' => ts('Delete'),
'url' => CRM_Utils_System::currentPath(),
'qs' => 'action=delete&reset=1&id=%%id%%',
'title' => ts('Delete Custom Field'),
'extra' => 'onclick = "return confirm(\'' . $deleteExtra . '\');"',
),
);
}
return self::$_actionLinks;
}
/**
* Get the configure action links for this page.
*
* @return array
*/
public function &configureActionLinks() {
// check if variable _actionsLinks is populated
if (!isset(self::$_configureActionLinks)) {
$urlString = 'civicrm/admin/contribute/';
$urlParams = 'reset=1&action=update&id=%%id%%';
self::$_configureActionLinks = array(
CRM_Core_Action::ADD => array(
'name' => ts('Title and Settings'),
'title' => ts('Title and Settings'),
'url' => $urlString . 'settings',
'qs' => $urlParams,
'uniqueName' => 'settings',
),
CRM_Core_Action::UPDATE => array(
'name' => ts('Contribution Amounts'),
'title' => ts('Contribution Amounts'),
'url' => $urlString . 'amount',
'qs' => $urlParams,
'uniqueName' => 'amount',
),
CRM_Core_Action::VIEW => array(
'name' => ts('Membership Settings'),
'title' => ts('Membership Settings'),
'url' => $urlString . 'membership',
'qs' => $urlParams,
'uniqueName' => 'membership',
),
CRM_Core_Action::EXPORT => array(
'name' => ts('Thank-you and Receipting'),
'title' => ts('Thank-you and Receipting'),
'url' => $urlString . 'thankyou',
'qs' => $urlParams,
'uniqueName' => 'thankyou',
),
CRM_Core_Action::BASIC => array(
'name' => ts('Tell a Friend'),
'title' => ts('Tell a Friend'),
'url' => $urlString . 'friend',
'qs' => $urlParams,
'uniqueName' => 'friend',
),
CRM_Core_Action::PROFILE => array(
'name' => ts('Include Profiles'),
'title' => ts('Include Profiles'),
'url' => $urlString . 'custom',
'qs' => $urlParams,
'uniqueName' => 'custom',
),
CRM_Core_Action::MAP => array(
'name' => ts('Contribution Widget'),
'title' => ts('Contribution Widget'),
'url' => $urlString . 'widget',
'qs' => $urlParams,
'uniqueName' => 'widget',
),
CRM_Core_Action::FOLLOWUP => array(
'name' => ts('Premiums'),
'title' => ts('Premiums'),
'url' => $urlString . 'premium',
'qs' => $urlParams,
'uniqueName' => 'premium',
),
CRM_Core_Action::ADVANCED => array(
'name' => ts('Personal Campaign Pages'),
'title' => ts('Personal Campaign Pages'),
'url' => $urlString . 'pcp',
'qs' => $urlParams,
'uniqueName' => 'pcp',
),
);
$context = array(
'urlString' => $urlString,
'urlParams' => $urlParams,
);
CRM_Utils_Hook::tabset('civicrm/admin/contribute', self::$_configureActionLinks, $context);
}
return self::$_configureActionLinks;
}
/**
* Get the online contribution links.
*
* @return array
*/
public function &onlineContributionLinks() {
if (!isset(self::$_onlineContributionLinks)) {
$urlString = 'civicrm/contribute/transact';
$urlParams = 'reset=1&id=%%id%%';
self::$_onlineContributionLinks = array(
CRM_Core_Action::RENEW => array(
'name' => ts('Live Page'),
'title' => ts('Live Page'),
'url' => $urlString,
'qs' => $urlParams,
'fe' => TRUE,
'uniqueName' => 'live_page',
),
CRM_Core_Action::PREVIEW => array(
'name' => ts('Test-drive'),
'title' => ts('Test-drive'),
'url' => $urlString,
'qs' => $urlParams . '&action=preview',
'uniqueName' => 'test_drive',
),
);
}
return self::$_onlineContributionLinks;
}
/**
* Get the contributions links.
*
* @return array
*/
public function &contributionLinks() {
if (!isset(self::$_contributionLinks)) {
//get contribution dates.
$dates = CRM_Contribute_BAO_Contribution::getContributionDates();
$now = $dates['now'];
$yearDate = $dates['yearDate'];
$monthDate = $dates['monthDate'];
$yearNow = $yearDate + 10000;
$urlString = 'civicrm/contribute/search';
$urlParams = 'reset=1&pid=%%id%%&force=1&test=0';
self::$_contributionLinks = array(
CRM_Core_Action::DETACH => array(
'name' => ts('Current Month-To-Date'),
'title' => ts('Current Month-To-Date'),
'url' => $urlString,
'qs' => "{$urlParams}&start={$monthDate}&end={$now}",
'uniqueName' => 'current_month_to_date',
),
CRM_Core_Action::REVERT => array(
'name' => ts('Fiscal Year-To-Date'),
'title' => ts('Fiscal Year-To-Date'),
'url' => $urlString,
'qs' => "{$urlParams}&start={$yearDate}&end={$yearNow}",
'uniqueName' => 'fiscal_year_to_date',
),
CRM_Core_Action::BROWSE => array(
'name' => ts('Cumulative'),
'title' => ts('Cumulative'),
'url' => $urlString,
'qs' => "{$urlParams}&start=&end=$now",
'uniqueName' => 'cumulative',
),
);
}
return self::$_contributionLinks;
}
/**
* 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 mixed
*/
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
);
// set breadcrumb to append to 2nd layer pages
$breadCrumb = array(
array(
'title' => ts('Manage Contribution Pages'),
'url' => CRM_Utils_System::url(CRM_Utils_System::currentPath(),
'reset=1'
),
),
);
// what action to take ?
if ($action & CRM_Core_Action::ADD) {
$session = CRM_Core_Session::singleton();
$session->pushUserContext(CRM_Utils_System::url(CRM_Utils_System::currentPath(),
'action=browse&reset=1'
));
$controller = new CRM_Contribute_Controller_ContributionPage(NULL, $action);
CRM_Utils_System::setTitle(ts('Manage Contribution Page'));
CRM_Utils_System::appendBreadCrumb($breadCrumb);
return $controller->run();
}
elseif ($action & CRM_Core_Action::UPDATE) {
$config = CRM_Core_Config::singleton();
// assign vars to templates
$this->assign('id', $id);
$this->assign('title', CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $id, 'title'));
$this->assign('is_active', CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $id, 'is_active'));
if (in_array('CiviMember', $config->enableComponents)) {
$this->assign('CiviMember', TRUE);
}
}
elseif ($action & CRM_Core_Action::COPY) {
// @todo Unused local variable can be safely removed.
// But are there any side effects of CRM_Core_Session::singleton() that we
// need to preserve?
$session = CRM_Core_Session::singleton();
CRM_Core_Session::setStatus(ts('A copy of the contribution page has been created'), ts('Successfully Copied'), 'success');
$this->copy();
}
elseif ($action & CRM_Core_Action::DELETE) {
CRM_Utils_System::appendBreadCrumb($breadCrumb);
$session = CRM_Core_Session::singleton();
$session->pushUserContext(CRM_Utils_System::url(CRM_Utils_System::currentPath(),
'reset=1&action=browse'
));
$id = CRM_Utils_Request::retrieve('id', 'Positive',
$this, FALSE, 0
);
$query = "
SELECT ccp.title
FROM civicrm_contribution_page ccp
JOIN civicrm_pcp cp ON ccp.id = cp.page_id
WHERE cp.page_id = {$id}
AND cp.page_type = 'contribute'
";
if ($pageTitle = CRM_Core_DAO::singleValueQuery($query)) {
CRM_Core_Session::setStatus(ts('The \'%1\' cannot be deleted! You must Delete all Personal Campaign Page(s) related with this contribution page prior to deleting the page.', array(1 => $pageTitle)), ts('Deletion Error'), 'error');
CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/admin/contribute', 'reset=1'));
}
$controller = new CRM_Core_Controller_Simple('CRM_Contribute_Form_ContributionPage_Delete',
'Delete Contribution Page',
CRM_Core_Action::DELETE
);
$controller->set('id', $id);
$controller->process();
return $controller->run();
}
else {
// finally browse the contribution pages
$this->browse();
CRM_Utils_System::setTitle(ts('Manage Contribution Pages'));
}
return parent::run();
}
/**
* Make a copy of a contribution page, including all the fields in the page.
*/
public function copy() {
$gid = CRM_Utils_Request::retrieve('gid', 'Positive',
$this, TRUE, 0, 'GET'
);
CRM_Contribute_BAO_ContributionPage::copy($gid);
CRM_Utils_System::redirect(CRM_Utils_System::url(CRM_Utils_System::currentPath(), 'reset=1'));
}
/**
* Browse all contribution pages.
*
* @param mixed $action
* Unused parameter.
*/
public function browse($action = NULL) {
Civi::resources()->addStyleFile('civicrm', 'css/searchForm.css', 1, 'html-header');
$this->_sortByCharacter = CRM_Utils_Request::retrieve('sortByCharacter',
'String',
$this
);
// @todo Unused local variable can be safely removed.
// But are there any side effects of CRM_Utils_Request::retrieve() that we
// need to preserve?
$createdId = CRM_Utils_Request::retrieve('cid', 'Positive',
$this, FALSE, 0
);
if ($this->_sortByCharacter == 'all' ||
!empty($_POST)
) {
$this->_sortByCharacter = '';
$this->set('sortByCharacter', '');
}
$this->search();
$params = array();
$whereClause = $this->whereClause($params, FALSE);
$this->pagerAToZ($whereClause, $params);
$params = array();
$whereClause = $this->whereClause($params, TRUE);
$this->pager($whereClause, $params);
list($offset, $rowCount) = $this->_pager->getOffsetAndRowCount();
//check for delete CRM-4418
$allowToDelete = CRM_Core_Permission::check('delete in CiviContribute');
$query = "
SELECT id
FROM civicrm_contribution_page
WHERE $whereClause
ORDER BY is_active desc, title asc
LIMIT $offset, $rowCount";
$contribPage = CRM_Core_DAO::executeQuery($query, $params, TRUE, 'CRM_Contribute_DAO_ContributionPage');
$contribPageIds = array();
while ($contribPage->fetch()) {
$contribPageIds[$contribPage->id] = $contribPage->id;
}
//get all section info.
$contriPageSectionInfo = CRM_Contribute_BAO_ContributionPage::getSectionInfo($contribPageIds);
$query = "
SELECT *
FROM civicrm_contribution_page
WHERE $whereClause
ORDER BY is_active desc, title asc
LIMIT $offset, $rowCount";
$dao = CRM_Core_DAO::executeQuery($query, $params, TRUE, 'CRM_Contribute_DAO_ContributionPage');
//get all campaigns.
$allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
//get configure actions links.
$configureActionLinks = self::configureActionLinks();
while ($dao->fetch()) {
$contribution[$dao->id] = array();
CRM_Core_DAO::storeValues($dao, $contribution[$dao->id]);
// form all action links
$action = array_sum(array_keys(self::actionLinks()));
//add configure actions links.
$action += array_sum(array_keys($configureActionLinks));
//add online contribution links.
$action += array_sum(array_keys(self::onlineContributionLinks()));
//add contribution search links.
$action += array_sum(array_keys(self::contributionLinks()));
if ($dao->is_active) {
$action -= (int) CRM_Core_Action::ENABLE;
}
else {
$action -= (int) CRM_Core_Action::DISABLE;
}
//CRM-4418
if (!$allowToDelete) {
$action -= (int) CRM_Core_Action::DELETE;
}
//build the configure links.
$sectionsInfo = CRM_Utils_Array::value($dao->id, $contriPageSectionInfo, array());
$contribution[$dao->id]['configureActionLinks'] = CRM_Core_Action::formLink(self::formatConfigureLinks($sectionsInfo),
$action,
array('id' => $dao->id),
ts('Configure'),
TRUE,
'contributionpage.configure.actions',
'ContributionPage',
$dao->id
);
//build the contributions links.
$contribution[$dao->id]['contributionLinks'] = CRM_Core_Action::formLink(self::contributionLinks(),
$action,
array('id' => $dao->id),
ts('Contributions'),
TRUE,
'contributionpage.contributions.search',
'ContributionPage',
$dao->id
);
//build the online contribution links.
$contribution[$dao->id]['onlineContributionLinks'] = CRM_Core_Action::formLink(self::onlineContributionLinks(),
$action,
array('id' => $dao->id),
ts('Links'),
TRUE,
'contributionpage.online.links',
'ContributionPage',
$dao->id
);
//build the normal action links.
$contribution[$dao->id]['action'] = CRM_Core_Action::formLink(self::actionLinks(),
$action,
array('id' => $dao->id),
ts('more'),
TRUE,
'contributionpage.action.links',
'ContributionPage',
$dao->id
);
//show campaigns on selector.
$contribution[$dao->id]['campaign'] = CRM_Utils_Array::value($dao->campaign_id, $allCampaigns);
}
if (isset($contribution)) {
$this->assign('rows', $contribution);
}
}
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_Contribute_Form_SearchContribution',
ts('Search Contribution'),
CRM_Core_Action::ADD
);
$form->setEmbedded(TRUE);
$form->setParent($this);
$form->process();
$form->run();
}
/**
* @param array $params
* @param bool $sortBy
*
* @return int|string
*/
public function whereClause(&$params, $sortBy = TRUE) {
// @todo Unused local variable can be safely removed.
$values = $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('financial_type_id');
$val = array();
if ($value) {
if (is_array($value)) {
foreach ($value as $k => $v) {
if ($v) {
$val[$k] = $k;
}
}
$type = implode(',', $val);
}
// @todo Variable 'type' might not have been defined.
$clauses[] = "financial_type_id IN ({$type})";
}
if ($sortBy && $this->_sortByCharacter !== NULL) {
$clauses[] = "title LIKE '" . strtolower(CRM_Core_DAO::escapeWildCardString($this->_sortByCharacter)) . "%'";
}
$campaignIds = $this->getCampaignIds();
if (count($campaignIds) >= 1) {
$clauses[] = '( campaign_id IN ( ' . implode(' , ', $campaignIds) . ' ) )';
}
if (empty($clauses)) {
// Let template know if user has run a search or not
$this->assign('isSearch', 0);
return 1;
}
else {
$this->assign('isSearch', 1);
}
return implode(' AND ', $clauses);
}
/**
* Gets the campaign ids from the session.
*
* @return int[]
*/
public function getCampaignIds() {
// The unfiltered value from the session cannot be trusted, it needs to be
// processed to get a clean array of positive integers.
$ids = array();
foreach ((array) $this->get('campaign_id') as $id) {
if ((string) (int) $id === (string) $id && $id > 0) {
$ids[] = $id;
}
}
return $ids;
}
/**
* @param $whereClause
* @param array $whereParams
*/
public function pager($whereClause, $whereParams) {
$params['status'] = ts('Contribution %%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_contribution_page
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_contribution_page
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);
}
/**
* @param array $sectionsInfo
*
* @return array
*/
public function formatConfigureLinks($sectionsInfo) {
// build the formatted configure links.
$formattedConfLinks = self::configureActionLinks();
foreach ($formattedConfLinks as $act => & $link) {
$sectionName = CRM_Utils_Array::value('uniqueName', $link);
if (!$sectionName) {
continue;
}
if (empty($sectionsInfo[$sectionName])) {
$classes = array();
if (isset($link['class'])) {
$classes = $link['class'];
}
$link['class'] = array_merge($classes, array('disabled'));
}
}
return $formattedConfLinks;
}
}

View file

@ -0,0 +1,109 @@
<?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
*/
/**
* Main page for viewing Recurring Contributions.
*/
class CRM_Contribute_Page_ContributionRecur extends CRM_Core_Page {
static $_links = NULL;
public $_permission = NULL;
public $_contactId = NULL;
/**
* View details of a recurring contribution.
*/
public function view() {
$recur = new CRM_Contribute_DAO_ContributionRecur();
$recur->id = $this->_id;
if ($recur->find(TRUE)) {
$values = array();
CRM_Core_DAO::storeValues($recur, $values);
// if there is a payment processor ID, get the name of the payment processor
if (!empty($values['payment_processor_id'])) {
$values['payment_processor'] = CRM_Core_DAO::getFieldValue(
'CRM_Financial_DAO_PaymentProcessor',
$values['payment_processor_id'],
'name'
);
}
$idFields = array('contribution_status_id', 'campaign_id');
if (CRM_Contribute_BAO_ContributionRecur::supportsFinancialTypeChange($values['id'])) {
$idFields[] = 'financial_type_id';
}
foreach ($idFields as $idField) {
if (!empty($values[$idField])) {
$values[substr($idField, 0, -3)] = CRM_Core_PseudoConstant::getLabel('CRM_Contribute_BAO_ContributionRecur', $idField, $values[$idField]);
}
}
$this->assign('recur', $values);
}
}
public function preProcess() {
$context = CRM_Utils_Request::retrieve('context', 'String', $this);
$this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'view');
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
$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 contributions')) {
// demote to view since user does not have edit contrib 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();
if ($this->_action & CRM_Core_Action::VIEW) {
$this->view();
}
return parent::run();
}
}

View file

@ -0,0 +1,133 @@
<?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
*/
/**
* Page for displaying list of Payment-Instrument.
*/
class CRM_Contribute_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.
*/
public function preProcess() {
CRM_Utils_System::setTitle(ts('CiviContribute'));
$status = array('Valid', 'Cancelled');
$prefixes = array('start', 'month', 'year');
$startDate = NULL;
$startToDate = $monthToDate = $yearToDate = array();
//get contribution dates.
$dates = CRM_Contribute_BAO_Contribution::getContributionDates();
foreach (array(
'now',
'yearDate',
'monthDate',
) as $date) {
$$date = $dates[$date];
}
// fiscal years end date
$yearNow = date('Ymd', strtotime('+1 year -1 day', strtotime($yearDate)));
foreach ($prefixes as $prefix) {
$aName = $prefix . 'ToDate';
$dName = $prefix . 'Date';
if ($prefix == 'year') {
$now = $yearNow;
}
// appending end date i.e $now with time
// to also calculate records of end date till mid-night
$nowWithTime = $now . '235959';
foreach ($status as $s) {
${$aName}[$s] = CRM_Contribute_BAO_Contribution::getTotalAmountAndCount($s, $$dName, $nowWithTime);
${$aName}[$s]['url'] = CRM_Utils_System::url('civicrm/contribute/search',
"reset=1&force=1&status=1&start={$$dName}&end=$now&test=0"
);
}
$this->assign($aName, $$aName);
}
//for contribution tabular View
$buildTabularView = CRM_Utils_Array::value('showtable', $_GET, FALSE);
$this->assign('buildTabularView', $buildTabularView);
if ($buildTabularView) {
return;
}
// Check for admin permission to see if we should include the Manage Contribution Pages action link
$isAdmin = 0;
if (CRM_Core_Permission::check('administer CiviCRM')) {
$isAdmin = 1;
}
$this->assign('isAdmin', $isAdmin);
}
/**
* 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_Contribute_Form_Search',
ts('Contributions'), NULL
);
$controller->setEmbedded(TRUE);
$controller->set('limit', 10);
$controller->set('force', 1);
$controller->set('context', 'dashboard');
$controller->process();
$controller->run();
$chartForm = new CRM_Core_Controller_Simple('CRM_Contribute_Form_ContributionCharts',
ts('Contributions Charts'), NULL
);
$chartForm->setEmbedded(TRUE);
$chartForm->process();
$chartForm->run();
CRM_Core_Resources::singleton()
->addScriptFile('civicrm', 'templates/CRM/Contribute/Page/DashBoard.js', 1, 'html-header');
return parent::run();
}
}

View file

@ -0,0 +1,194 @@
<?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
*/
/**
* Page for displaying list of Premiums.
*/
class CRM_Contribute_Page_ManagePremiums extends CRM_Core_Page_Basic {
public $useLivePageJS = TRUE;
/**
* The action links that we need to display for the browse screen.
*
* @var array
*/
static $_links = NULL;
/**
* Get BAO Name.
*
* @return string
* Classname of BAO.
*/
public function getBAOName() {
return 'CRM_Contribute_BAO_ManagePremiums';
}
/**
* Get action Links.
*
* @return array
* (reference) of action links
*/
public function &links() {
if (!(self::$_links)) {
self::$_links = array(
CRM_Core_Action::UPDATE => array(
'name' => ts('Edit'),
'url' => 'civicrm/admin/contribute/managePremiums',
'qs' => 'action=update&id=%%id%%&reset=1',
'title' => ts('Edit Premium'),
),
CRM_Core_Action::PREVIEW => array(
'name' => ts('Preview'),
'url' => 'civicrm/admin/contribute/managePremiums',
'qs' => 'action=preview&id=%%id%%',
'title' => ts('Preview Premium'),
),
CRM_Core_Action::DISABLE => array(
'name' => ts('Disable'),
'ref' => 'crm-enable-disable',
'title' => ts('Disable Premium'),
),
CRM_Core_Action::ENABLE => array(
'name' => ts('Enable'),
'ref' => 'crm-enable-disable',
'title' => ts('Enable Premium'),
),
CRM_Core_Action::DELETE => array(
'name' => ts('Delete'),
'url' => 'civicrm/admin/contribute/managePremiums',
'qs' => 'action=delete&id=%%id%%',
'title' => ts('Delete Premium'),
),
);
}
return self::$_links;
}
/**
* 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.
*/
public function run() {
$id = $this->getIdAndAction();
// what action to take ?
if ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD | CRM_Core_Action::PREVIEW)) {
$this->edit($this->_action, $id, TRUE);
}
// finally browse the custom groups
$this->browse();
// parent run
return CRM_Core_Page::run();
}
/**
* Browse all custom data groups.
*/
public function browse() {
// get all custom groups sorted by weight
$premiums = array();
$dao = new CRM_Contribute_DAO_Product();
$dao->orderBy('name');
$dao->find();
while ($dao->fetch()) {
$premiums[$dao->id] = array();
CRM_Core_DAO::storeValues($dao, $premiums[$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;
}
$premiums[$dao->id]['action'] = CRM_Core_Action::formLink(self::links(),
$action,
array('id' => $dao->id),
ts('more'),
FALSE,
'premium.manage.row',
'Premium',
$dao->id
);
//Financial Type
if (!empty($dao->financial_type_id)) {
require_once 'CRM/Core/DAO.php';
$premiums[$dao->id]['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $dao->financial_type_id, 'name');
}
}
$this->assign('rows', $premiums);
}
/**
* Get name of edit form.
*
* @return string
* Classname of edit form.
*/
public function editForm() {
return 'CRM_Contribute_Form_ManagePremiums';
}
/**
* Get edit form name.
*
* @return string
* name of this page.
*/
public function editName() {
return 'Manage Premiums';
}
/**
* Get user context.
*
* @param null $mode
*
* @return string
* user context.
*/
public function userContext($mode = NULL) {
return 'civicrm/admin/contribute/managePremiums';
}
}

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
*/
class CRM_Contribute_Page_PaymentInfo extends CRM_Core_Page {
public function preProcess() {
$this->_component = CRM_Utils_Request::retrieve('component', 'String', $this, TRUE);
$this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
$this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
$this->_context = CRM_Utils_Request::retrieve('context', 'String', $this, TRUE);
$this->_cid = CRM_Utils_Request::retrieve('cid', 'String', $this, TRUE);
$this->assign('cid', $this->_cid);
$this->assign('id', $this->_id);
$this->assign('context', $this->_context);
$this->assign('component', $this->_component);
if ($this->_component != 'event') {
$this->assign('hideButtonLinks', TRUE);
}
}
public function browse() {
$getTrxnInfo = $this->_context == 'transaction' ? TRUE : FALSE;
$paymentInfo = CRM_Contribute_BAO_Contribution::getPaymentInfo($this->_id, $this->_component, $getTrxnInfo, TRUE);
if ($this->_context == 'payment_info') {
$this->assign('paymentInfo', $paymentInfo);
}
}
/**
* Run page.
*
* This typically involves assigning the appropriate
* smarty variable :)
*
* @return string
* The content generated by running this page
*/
public function run() {
$this->preProcess();
if ($this->_action) {
$this->browse();
}
return parent::run();
}
}

View file

@ -0,0 +1,224 @@
<?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
*/
/**
* Page for displaying list of Premiums.
*/
class CRM_Contribute_Page_Premium extends CRM_Core_Page_Basic {
/**
* The action links that we need to display for the browse screen.
*
* @var array
*/
static $_links = NULL;
/**
* Get BAO Name.
*
* @return string
* Classname of BAO.
*/
public function getBAOName() {
return 'CRM_Contribute_BAO_Premium';
}
/**
* Get action Links.
*
* @return array
* (reference) of action links
*/
public function &links() {
if (!(self::$_links)) {
// helper variable for nicer formatting
$deleteExtra = ts('Are you sure you want to remove this product form this page?');
self::$_links = array(
CRM_Core_Action::UPDATE => array(
'name' => ts('Edit'),
'url' => 'civicrm/admin/contribute/addProductToPage',
'qs' => 'action=update&id=%%id%%&pid=%%pid%%&reset=1',
'title' => ts('Edit Premium'),
),
CRM_Core_Action::PREVIEW => array(
'name' => ts('Preview'),
'url' => 'civicrm/admin/contribute/addProductToPage',
'qs' => 'action=preview&id=%%id%%&pid=%%pid%%',
'title' => ts('Preview Premium'),
),
CRM_Core_Action::DELETE => array(
'name' => ts('Remove'),
'url' => 'civicrm/admin/contribute/addProductToPage',
'qs' => 'action=delete&id=%%id%%&pid=%%pid%%',
'extra' => 'onclick = "if (confirm(\'' . $deleteExtra . '\') ) this.href+=\'&amp;confirmed=1\'; else return false;"',
'title' => ts('Disable Premium'),
),
);
}
return self::$_links;
}
/**
* 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.
*/
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
);
$this->assign('id', $id);
$this->edit($action, $id, FALSE, FALSE);
// this is special case where we need to call browse to list premium
if ($action == CRM_Core_Action::UPDATE) {
$this->browse();
}
// parent run
return parent::run();
}
/**
* Browse function.
*/
public function browse() {
// get all custom groups sorted by weight
$premiums = array();
$pageID = CRM_Utils_Request::retrieve('id', 'Positive',
$this, FALSE, 0
);
$dao = new CRM_Contribute_DAO_Premium();
$dao->entity_table = 'civicrm_contribution_page';
$dao->entity_id = $pageID;
$dao->find(TRUE);
$premiumID = $dao->id;
$this->assign('products', FALSE);
$this->assign('id', $pageID);
if (!$premiumID) {
return;
}
$dao = new CRM_Contribute_DAO_PremiumsProduct();
$dao->premiums_id = $premiumID;
$dao->orderBy('weight');
$dao->find();
while ($dao->fetch()) {
$productDAO = new CRM_Contribute_DAO_Product();
$productDAO->id = $dao->product_id;
$productDAO->is_active = 1;
if ($productDAO->find(TRUE)) {
$premiums[$productDAO->id] = array();
$premiums[$productDAO->id]['weight'] = $dao->weight;
CRM_Core_DAO::storeValues($productDAO, $premiums[$productDAO->id]);
$action = array_sum(array_keys($this->links()));
$premiums[$dao->product_id]['action'] = CRM_Core_Action::formLink(self::links(), $action,
array('id' => $pageID, 'pid' => $dao->id),
ts('more'),
FALSE,
'premium.contributionpage.row',
'Premium',
$dao->id
);
//Financial Type
if (!empty($dao->financial_type_id)) {
$premiums[$productDAO->id]['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $dao->financial_type_id, 'name');
}
}
}
if (count(CRM_Contribute_PseudoConstant::products($pageID)) == 0) {
$this->assign('products', FALSE);
}
else {
$this->assign('products', TRUE);
}
// Add order changing widget to selector
$returnURL = CRM_Utils_System::url('civicrm/admin/contribute/premium', "reset=1&action=update&id={$pageID}");
$filter = "premiums_id = {$premiumID}";
CRM_Utils_Weight::addOrder($premiums, 'CRM_Contribute_DAO_PremiumsProduct',
'id', $returnURL, $filter
);
$this->assign('rows', $premiums);
}
/**
* Get name of edit form.
*
* @return string
* Classname of edit form.
*/
public function editForm() {
return 'CRM_Contribute_Form_ContributionPage_Premium';
}
/**
* Get edit form name.
*
* @return string
* name of this page.
*/
public function editName() {
return 'Configure Premiums';
}
/**
* Get user context.
*
* @param null $mode
*
* @return string
* user context.
*/
public function userContext($mode = NULL) {
return CRM_Utils_System::currentPath();
}
}

View file

@ -0,0 +1,59 @@
<?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
*/
class CRM_Contribute_Page_SubscriptionStatus extends CRM_Core_Page {
/**
* 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() {
$task = CRM_Utils_Request::retrieve('task', 'String');
$result = CRM_Utils_Request::retrieve('result', 'Integer');
$this->assign('task', $task);
$this->assign('result', $result);
if ($task == 'billing') {
$session = CRM_Core_Session::singleton();
$tplParams = $session->get('resultParams');
foreach ($tplParams as $key => $val) {
$this->assign($key, $val);
}
}
return parent::run();
}
}

View file

@ -0,0 +1,470 @@
<?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
*/
class CRM_Contribute_Page_Tab extends CRM_Core_Page {
/**
* The action links that we need to display for the browse screen.
*
* @var array
*/
static $_links = NULL;
static $_recurLinks = NULL;
public $_permission = NULL;
public $_contactId = NULL;
public $_crid = NULL;
/**
* This method returns the links that are given for recur search row.
* currently the links added for each row are:
* - View
* - Edit
* - Cancel
*
* @param bool $recurID
* @param string $context
*
* @return array
*/
public static function &recurLinks($recurID = FALSE, $context = 'contribution') {
if (!(self::$_links)) {
self::$_links = array(
CRM_Core_Action::VIEW => array(
'name' => ts('View'),
'title' => ts('View Recurring Payment'),
'url' => 'civicrm/contact/view/contributionrecur',
'qs' => "reset=1&id=%%crid%%&cid=%%cid%%&context={$context}",
),
CRM_Core_Action::UPDATE => array(
'name' => ts('Edit'),
'title' => ts('Edit Recurring Payment'),
'url' => 'civicrm/contribute/updaterecur',
'qs' => "reset=1&action=update&crid=%%crid%%&cid=%%cid%%&context={$context}",
),
CRM_Core_Action::DISABLE => array(
'name' => ts('Cancel'),
'title' => ts('Cancel'),
'ref' => 'crm-enable-disable',
),
);
}
if ($recurID) {
$links = self::$_links;
$paymentProcessorObj = CRM_Financial_BAO_PaymentProcessor::getProcessorForEntity($recurID, 'recur', 'obj');
if (is_object($paymentProcessorObj) && $paymentProcessorObj->supports('cancelRecurring')) {
unset($links[CRM_Core_Action::DISABLE]['extra'], $links[CRM_Core_Action::DISABLE]['ref']);
$links[CRM_Core_Action::DISABLE]['url'] = "civicrm/contribute/unsubscribe";
$links[CRM_Core_Action::DISABLE]['qs'] = "reset=1&crid=%%crid%%&cid=%%cid%%&context={$context}";
}
if (is_object($paymentProcessorObj) && $paymentProcessorObj->isSupported('updateSubscriptionBillingInfo')) {
$links[CRM_Core_Action::RENEW] = array(
'name' => ts('Change Billing Details'),
'title' => ts('Change Billing Details'),
'url' => 'civicrm/contribute/updatebilling',
'qs' => "reset=1&crid=%%crid%%&cid=%%cid%%&context={$context}",
);
}
return $links;
}
return self::$_links;
}
// end function
/**
* called when action is browse.
*
*/
public function browse() {
// add annual contribution
$annual = array();
list($annual['count'],
$annual['amount'],
$annual['avg']
) = CRM_Contribute_BAO_Contribution::annual($this->_contactId);
$this->assign('annual', $annual);
$controller = new CRM_Core_Controller_Simple(
'CRM_Contribute_Form_Search',
ts('Contributions'),
$this->_action,
FALSE, FALSE, TRUE
);
$controller->setEmbedded(TRUE);
$controller->reset();
$controller->set('cid', $this->_contactId);
$controller->set('crid', $this->_crid);
$controller->set('context', 'contribution');
$controller->set('limit', 50);
$controller->process();
$controller->run();
// add recurring block
$action = array_sum(array_keys($this->recurLinks()));
$params = CRM_Contribute_BAO_ContributionRecur::getRecurContributions($this->_contactId);
if (!empty($params)) {
foreach ($params as $ids => $recur) {
$action = array_sum(array_keys($this->recurLinks($ids)));
// no action allowed if it's not active
$params[$ids]['is_active'] = ($recur['contribution_status_id'] != 3);
if ($params[$ids]['is_active']) {
$details = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($params[$ids]['id'], 'recur');
$hideUpdate = $details->membership_id & $details->auto_renew;
if ($hideUpdate) {
$action -= CRM_Core_Action::UPDATE;
}
$params[$ids]['action'] = CRM_Core_Action::formLink(self::recurLinks($ids), $action,
array(
'cid' => $this->_contactId,
'crid' => $ids,
'cxt' => 'contribution',
),
ts('more'),
FALSE,
'contribution.selector.recurring',
'Contribution',
$ids
);
}
}
// assign vars to templates
$this->assign('action', $this->_action);
$this->assign('recurRows', $params);
$this->assign('recur', TRUE);
}
//enable/disable soft credit records for test contribution
$isTest = 0;
if (CRM_Utils_Request::retrieve('isTest', 'Positive', $this)) {
$isTest = 1;
}
$this->assign('isTest', $isTest);
$softCreditList = CRM_Contribute_BAO_ContributionSoft::getSoftContributionList($this->_contactId, NULL, $isTest);
if (!empty($softCreditList)) {
$softCreditTotals = array();
list($softCreditTotals['amount'],
$softCreditTotals['avg'],
$softCreditTotals['currency'],
$softCreditTotals['cancelAmount'] //to get cancel amount
) = CRM_Contribute_BAO_ContributionSoft::getSoftContributionTotals($this->_contactId, $isTest);
$this->assign('softCredit', TRUE);
$this->assign('softCreditRows', $softCreditList);
$this->assign('softCreditTotals', $softCreditTotals);
}
if ($this->_contactId) {
$displayName = CRM_Contact_BAO_Contact::displayName($this->_contactId);
$this->assign('displayName', $displayName);
$this->ajaxResponse['tabCount'] = CRM_Contact_BAO_Contact::getCountComponent('contribution', $this->_contactId);
}
}
/**
* called when action is view.
*
* @return null
*/
public function view() {
$controller = new CRM_Core_Controller_Simple(
'CRM_Contribute_Form_ContributionView',
ts('View Contribution'),
$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();
}
$controller = new CRM_Core_Controller_Simple(
'CRM_Contribute_Form_Contribution',
'Create Contribution',
$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, empty($this->_id));
if (empty($this->_contactId)) {
$this->_contactId = civicrm_api3('contribution', 'getvalue', array(
'id' => $this->_id,
'return' => 'contact_id',
));
}
$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 contributions')) {
// demote to view since user does not have edit contrib 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 contribs
$this->assign('newCredit', CRM_Core_Config::isEnabledBackOfficeCreditCardPayments());
$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() {
$qfKey = CRM_Utils_Request::retrieve('key', 'String', $this);
$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);
//swap the context.
if ($context == 'search' && $compContext) {
$context = $compContext;
}
else {
$compContext = NULL;
}
// make sure we dont get tricked with a bad key
// so check format
if (!CRM_Core_Key::valid($qfKey)) {
$qfKey = NULL;
}
$session = CRM_Core_Session::singleton();
switch ($context) {
case 'user':
$url = CRM_Utils_System::url('civicrm/user', 'reset=1');
break;
case 'dashboard':
$url = CRM_Utils_System::url('civicrm/contribute',
'reset=1'
);
break;
case 'pledgeDashboard':
$url = CRM_Utils_System::url('civicrm/pledge',
'reset=1'
);
break;
case 'contribution':
$url = CRM_Utils_System::url('civicrm/contact/view',
"reset=1&force=1&cid={$this->_contactId}&selectedChild=contribute"
);
break;
case 'search':
case 'advanced':
$extraParams = "force=1";
if ($qfKey) {
$extraParams .= "&qfKey=$qfKey";
}
$this->assign('searchKey', $qfKey);
if ($context == 'advanced') {
$url = CRM_Utils_System::url('civicrm/contact/search/advanced', $extraParams);
}
elseif ($searchContext) {
$url = CRM_Utils_System::url("civicrm/$searchContext/search", $extraParams);
}
else {
$url = CRM_Utils_System::url('civicrm/contribute/search', $extraParams);
}
break;
case 'home':
$url = CRM_Utils_System::url('civicrm/dashboard', 'reset=1');
break;
case 'activity':
$url = CRM_Utils_System::url('civicrm/contact/view',
"reset=1&force=1&cid={$this->_contactId}&selectedChild=activity"
);
break;
case 'member':
case 'membership':
$componentId = CRM_Utils_Request::retrieve('compId', 'Positive', $this);
$componentAction = CRM_Utils_Request::retrieve('compAction', 'Integer', $this);
$context = 'membership';
$searchKey = NULL;
if ($compContext) {
$context = 'search';
if ($qfKey) {
$searchKey = "&key=$qfKey";
}
$compContext = "&compContext={$compContext}";
}
if ($componentAction & CRM_Core_Action::VIEW) {
$action = 'view';
}
else {
$action = 'update';
}
$url = CRM_Utils_System::url('civicrm/contact/view/membership',
"reset=1&action={$action}&id={$componentId}&cid={$this->_contactId}&context={$context}&selectedChild=member{$searchKey}{$compContext}"
);
break;
case 'participant':
$componentId = CRM_Utils_Request::retrieve('compId', 'Positive', $this);
$componentAction = CRM_Utils_Request::retrieve('compAction', 'Integer', $this);
$context = 'participant';
$searchKey = NULL;
if ($compContext) {
$context = 'search';
if ($qfKey) {
$searchKey = "&key=$qfKey";
}
$compContext = "&compContext={$compContext}";
}
if ($componentAction == CRM_Core_Action::VIEW) {
$action = 'view';
}
else {
$action = 'update';
}
$url = CRM_Utils_System::url('civicrm/contact/view/participant',
"reset=1&action={$action}&id={$componentId}&cid={$this->_contactId}&context={$context}&selectedChild=event{$searchKey}{$compContext}"
);
break;
case 'pledge':
$url = CRM_Utils_System::url('civicrm/contact/view',
"reset=1&force=1&cid={$this->_contactId}&selectedChild=pledge"
);
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/contribution';
}
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/contribute/search',
'reset=1&force=1' . $cid
);
break;
}
$session = CRM_Core_Session::singleton();
$session->pushUserContext($url);
}
}

View file

@ -0,0 +1,151 @@
<?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
*/
class CRM_Contribute_Page_UserDashboard extends CRM_Contact_Page_View_UserDashBoard {
/**
* called when action is browse.
*/
public function listContribution() {
$controller = new CRM_Core_Controller_Simple(
'CRM_Contribute_Form_Search',
ts('Contributions'),
NULL,
FALSE, FALSE, TRUE, FALSE
);
$controller->setEmbedded(TRUE);
$controller->reset();
$controller->set('limit', 12);
$controller->set('cid', $this->_contactId);
$controller->set('context', 'user');
$controller->set('force', 1);
$controller->process();
$controller->run();
//add honor block
$params = CRM_Contribute_BAO_Contribution::getHonorContacts($this->_contactId);
if (!empty($params)) {
// assign vars to templates
$this->assign('honorRows', $params);
$this->assign('honor', TRUE);
}
$recur = new CRM_Contribute_DAO_ContributionRecur();
$recur->contact_id = $this->_contactId;
$recur->is_test = 0;
$recur->find();
$config = CRM_Core_Config::singleton();
$recurStatus = CRM_Contribute_PseudoConstant::contributionStatus();
$recurRow = array();
$recurIDs = array();
while ($recur->fetch()) {
$mode = $recur->is_test ? 'test' : 'live';
$paymentProcessor = CRM_Contribute_BAO_ContributionRecur::getPaymentProcessor($recur->id,
$mode
);
if (!$paymentProcessor) {
continue;
}
require_once 'api/v3/utils.php';
//@todo calling api functions directly is not supported
_civicrm_api3_object_to_array($recur, $values);
$values['recur_status'] = $recurStatus[$values['contribution_status_id']];
$recurRow[$values['id']] = $values;
$action = array_sum(array_keys(CRM_Contribute_Page_Tab::recurLinks($recur->id, 'dashboard')));
$details = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($recur->id, 'recur');
$hideUpdate = $details->membership_id & $details->auto_renew;
if ($hideUpdate) {
$action -= CRM_Core_Action::UPDATE;
}
$recurRow[$values['id']]['action'] = CRM_Core_Action::formLink(CRM_Contribute_Page_Tab::recurLinks($recur->id, 'dashboard'),
$action, array(
'cid' => $this->_contactId,
'crid' => $values['id'],
'cxt' => 'contribution',
),
ts('more'),
FALSE,
'contribution.dashboard.recurring',
'Contribution',
$values['id']
);
$recurIDs[] = $values['id'];
//reset $paymentObject for checking other paymenet processor
//recurring url
$paymentObject = NULL;
}
if (is_array($recurIDs) && !empty($recurIDs)) {
$getCount = CRM_Contribute_BAO_ContributionRecur::getCount($recurIDs);
foreach ($getCount as $key => $val) {
$recurRow[$key]['completed'] = $val;
$recurRow[$key]['link'] = CRM_Utils_System::url('civicrm/contribute/search',
"reset=1&force=1&recur=$key"
);
}
}
$this->assign('recurRows', $recurRow);
if (!empty($recurRow)) {
$this->assign('recur', TRUE);
}
else {
$this->assign('recur', FALSE);
}
}
/**
* 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() {
$invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
$invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
$defaultInvoicePage = CRM_Utils_Array::value('default_invoice_page', $invoiceSettings);
$this->assign('invoicing', $invoicing);
$this->assign('defaultInvoicePage', $defaultInvoicePage);
parent::preProcess();
$this->listContribution();
}
}

View file

@ -0,0 +1,434 @@
<?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 holds all the Pseudo constants that are specific to Contributions.
*
* This avoids polluting the core class and isolates the mass mailer class.
*/
class CRM_Contribute_PseudoConstant extends CRM_Core_PseudoConstant {
/**
* Financial types
* @var array
*/
private static $financialType;
/**
* Financial types
* @var array
*/
private static $financialAccount;
/**
* Contribution pages
* @var array
*/
private static $contributionPageActive = NULL;
/**
* Contribution pages
* @var array
*/
private static $contributionPageAll = NULL;
/**
* Payment instruments
*
* @var array
*/
private static $paymentInstrument;
/**
* Contribution status
*
* @var array
*/
private static $contributionStatus;
/**
* Personal campaign pages
* @var array
*/
private static $pcPage;
/**
* Status of personal campaign page
* @var array
*/
private static $pcpStatus;
/**
* Contribution / financial batches
* @var array
*/
private static $batch;
/**
* @deprecated. Please use the buildOptions() method in the appropriate BAO object.
*
*
* Get all the financial types
*
*
* @param int $id
* @param bool $includeDisabled
*
* @return array
* array reference of all financial types if any
*/
public static function &financialType($id = NULL, $includeDisabled = FALSE) {
if (!self::$financialType) {
$condition = "";
if (!$includeDisabled) {
$condition = " is_active = 1 ";
}
CRM_Core_PseudoConstant::populate(
self::$financialType,
'CRM_Financial_DAO_FinancialType',
TRUE,
'name',
NULL,
$condition
);
}
if ($id) {
$result = CRM_Utils_Array::value($id, self::$financialType);
return $result;
}
return self::$financialType;
}
/**
* @deprecated. Please use the buildOptions() method in the appropriate BAO object.
*
* Get all the financial Accounts
*
*
* @param int $id
* @param int $financialAccountTypeId
* @param string $retrieveColumn
* @param string $key
*
* @return array
* array reference of all financial accounts if any
*/
public static function &financialAccount($id = NULL, $financialAccountTypeId = NULL, $retrieveColumn = 'name', $key = 'id') {
$condition = NULL;
if ($financialAccountTypeId) {
$condition = " financial_account_type_id = " . $financialAccountTypeId;
}
$cacheKey = "{$id}_{$financialAccountTypeId}_{$retrieveColumn}_{$key}";
if (!isset(self::$financialAccount[$cacheKey])) {
CRM_Core_PseudoConstant::populate(
self::$financialAccount[$cacheKey],
'CRM_Financial_DAO_FinancialAccount',
TRUE,
$retrieveColumn,
'is_active',
$condition,
NULL,
$key
);
}
if ($id) {
$result = CRM_Utils_Array::value($id, self::$financialAccount[$cacheKey]);
return $result;
}
return self::$financialAccount[$cacheKey];
}
/**
* 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;
}
}
/**
* @deprecated. Please use the buildOptions() method in the appropriate BAO object.
*
* Get all the contribution pages
*
* @param int $id
* Id of the contribution page.
* @param bool $all
* Do we want all pages or only active pages.
*
*
* @return array
* array reference of all contribution pages if any
*/
public static function &contributionPage($id = NULL, $all = FALSE) {
if ($all) {
$cacheVarToUse = &self::$contributionPageAll;
}
else {
$cacheVarToUse = &self::$contributionPageActive;
}
if (!$cacheVarToUse) {
CRM_Core_PseudoConstant::populate($cacheVarToUse,
'CRM_Contribute_DAO_ContributionPage',
$all, 'title'
);
}
if ($id) {
$pageTitle = CRM_Utils_Array::value($id, $cacheVarToUse);
return $pageTitle;
}
return $cacheVarToUse;
}
/**
* @deprecated. Please use the buildOptions() method in the appropriate BAO object.
*
* Get all the payment instruments
*
*
* @param string $columnName
*
* @return array
* array reference of all payment instruments if any
*/
public static function &paymentInstrument($columnName = 'label') {
if (!isset(self::$paymentInstrument[$columnName])) {
self::$paymentInstrument[$columnName] = CRM_Core_OptionGroup::values('payment_instrument',
FALSE, FALSE, FALSE, NULL, $columnName
);
}
return self::$paymentInstrument[$columnName];
}
/**
* Get all the valid accepted credit cards.
*
*
* @return array
* array reference of all payment instruments if any
*/
public static function &creditCard() {
return CRM_Core_OptionGroup::values('accept_creditcard', FALSE, FALSE, FALSE, NULL, 'label', TRUE, FALSE, 'name');
}
/**
* Get all premiums.
*
*
* @param int $pageID
* @return array
* array of all Premiums if any
*/
public static function products($pageID = NULL) {
$products = array();
$dao = new CRM_Contribute_DAO_Product();
$dao->is_active = 1;
$dao->orderBy('id');
$dao->find();
while ($dao->fetch()) {
$products[$dao->id] = $dao->name;
}
if ($pageID) {
$dao = new CRM_Contribute_DAO_Premium();
$dao->entity_table = 'civicrm_contribution_page';
$dao->entity_id = $pageID;
$dao->find(TRUE);
$premiumID = $dao->id;
$productID = array();
$dao = new CRM_Contribute_DAO_PremiumsProduct();
$dao->premiums_id = $premiumID;
$dao->find();
while ($dao->fetch()) {
$productID[$dao->product_id] = $dao->product_id;
}
$tempProduct = array();
foreach ($products as $key => $value) {
if (!array_key_exists($key, $productID)) {
$tempProduct[$key] = $value;
}
}
return $tempProduct;
}
return $products;
}
/**
* Get all the contribution statuses.
*
*
* @param int $id
* @param string $columnName
* @return array
* array reference of all contribution statuses
*/
public static function &contributionStatus($id = NULL, $columnName = 'label') {
$cacheKey = $columnName;
if (!isset(self::$contributionStatus[$cacheKey])) {
self::$contributionStatus[$cacheKey] = CRM_Core_OptionGroup::values('contribution_status',
FALSE, FALSE, FALSE, NULL, $columnName
);
}
$result = self::$contributionStatus[$cacheKey];
if ($id) {
$result = CRM_Utils_Array::value($id, $result);
}
return $result;
}
/**
* Get all the Personal campaign pages.
*
*
* @param null $pageType
* @param int $id
*
* @return array
* array reference of all pcp if any
*/
public static function &pcPage($pageType = NULL, $id = NULL) {
if (!isset(self::$pcPage[$pageType])) {
if ($pageType) {
$params = "page_type='{$pageType}'";
}
else {
$params = '';
}
CRM_Core_PseudoConstant::populate(self::$pcPage[$pageType],
'CRM_PCP_DAO_PCP',
FALSE, 'title', 'is_active', $params
);
}
$result = self::$pcPage[$pageType];
if ($id) {
return $result = CRM_Utils_Array::value($id, $result);
}
return $result;
}
/**
* Get all PCP Statuses.
*
* The static array pcpStatus is returned
*
*
* @param string $column
* @return array
* array reference of all PCP activity statuses
*/
public static function &pcpStatus($column = 'label') {
if (NULL === self::$pcpStatus) {
self::$pcpStatus = array();
}
if (!array_key_exists($column, self::$pcpStatus)) {
self::$pcpStatus[$column] = array();
self::$pcpStatus[$column] = CRM_Core_OptionGroup::values('pcp_status', FALSE,
FALSE, FALSE, NULL, $column
);
}
return self::$pcpStatus[$column];
}
/**
* Get financial account for a Financial type.
*
*
* @param int $entityId
* @param string $accountRelationType
* @param string $entityTable
* @param string $returnField
* @return int
*/
public static function getRelationalFinancialAccount($entityId, $accountRelationType, $entityTable = 'civicrm_financial_type', $returnField = 'financial_account_id') {
$params = array(
'return' => array($returnField),
'entity_table' => $entityTable,
'entity_id' => $entityId,
);
if ($accountRelationType) {
$params['account_relationship.name'] = $accountRelationType;
}
$result = civicrm_api3('EntityFinancialAccount', 'get', $params);
if (!$result['count']) {
return NULL;
}
return $result['values'][$result['id']][$returnField];
}
/**
* Get all batches.
*
*
* @param int $id
* @return array
* array reference of all batches if any
*/
public static function &batch($id = NULL) {
if (!self::$batch) {
$orderBy = " id DESC ";
CRM_Core_PseudoConstant::populate(
self::$batch,
'CRM_Batch_DAO_Batch',
TRUE,
'title',
NULL,
NULL,
$orderBy
);
}
if ($id) {
$result = CRM_Utils_Array::value($id, self::$batch);
return $result;
}
return self::$batch;
}
}

View file

@ -0,0 +1,650 @@
<?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
*/
/**
* Class to render contribution search results.
*/
class CRM_Contribute_Selector_Search extends CRM_Core_Selector_Base implements CRM_Core_Selector_API {
/**
* Array of action links.
*
* @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',
'contribution_id',
'contact_type',
'sort_name',
'amount_level',
'total_amount',
'financial_type',
'contribution_source',
'receive_date',
'thankyou_date',
'contribution_status_id',
'contribution_status',
'cancel_date',
'product_name',
'is_test',
'contribution_recur_id',
'receipt_date',
'membership_id',
'currency',
'contribution_campaign_id',
'contribution_soft_credit_name',
'contribution_soft_credit_contact_id',
'contribution_soft_credit_amount',
'contribution_soft_credit_type',
);
/**
* 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 $_contributionClause = NULL;
/**
* The query object
*
* @var string
*/
protected $_query;
protected $_includeSoftCredits = FALSE;
/**
* Class constructor.
*
* @param array $queryParams
* Array of parameters for query.
* @param \const|int $action - action of search basic or advanced.
* @param string $contributionClause
* If the caller wants to further restrict the search (used in contributions).
* @param bool $single
* Are we dealing only with one contact?.
* @param int $limit
* How many contributions do we want returned.
*
* @param string $context
* @param null $compContext
*
* @return \CRM_Contribute_Selector_Search
*/
public function __construct(
&$queryParams,
$action = CRM_Core_Action::NONE,
$contributionClause = 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->_contributionClause = $contributionClause;
// type of selector
$this->_action = $action;
$returnProperties = CRM_Contribute_BAO_Query::selectorReturnProperties();
$this->_includeSoftCredits = CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled($this->_queryParams);
$this->_query = new CRM_Contact_BAO_Query(
$this->_queryParams,
$returnProperties,
NULL, FALSE, FALSE,
CRM_Contact_BAO_Query::MODE_CONTRIBUTE
);
// @todo the function CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled should handle this
// can we remove? if not why not?
if ($this->_includeSoftCredits) {
$this->_query->_rowCountClause = " count(civicrm_contribution.id)";
$this->_query->_groupByComponentClause = " GROUP BY contribution_search_scredit_combined.id, contribution_search_scredit_combined.contact_id, contribution_search_scredit_combined.scredit_id ";
}
else {
$this->_query->_distinctComponentClause = " civicrm_contribution.id";
$this->_query->_groupByComponentClause = " GROUP BY civicrm_contribution.id ";
}
}
/**
* This method returns the links that are given for each search row.
* currently the links added for each row are
*
* - View
* - Edit
*
* @param int $componentId
* @param null $componentAction
* @param null $key
* @param null $compContext
*
* @return array
*/
public static function &links($componentId = NULL, $componentAction = NULL, $key = NULL, $compContext = NULL) {
$extraParams = NULL;
if ($componentId) {
$extraParams = "&compId={$componentId}&compAction={$componentAction}";
}
if ($compContext) {
$extraParams .= "&compContext={$compContext}";
}
if ($key) {
$extraParams .= "&key={$key}";
}
if (!(self::$_links)) {
self::$_links = array(
CRM_Core_Action::VIEW => array(
'name' => ts('View'),
'url' => 'civicrm/contact/view/contribution',
'qs' => "reset=1&id=%%id%%&cid=%%cid%%&action=view&context=%%cxt%%&selectedChild=contribute{$extraParams}",
'title' => ts('View Contribution'),
),
CRM_Core_Action::UPDATE => array(
'name' => ts('Edit'),
'url' => 'civicrm/contact/view/contribution',
'qs' => "reset=1&action=update&id=%%id%%&cid=%%cid%%&context=%%cxt%%{$extraParams}",
'title' => ts('Edit Contribution'),
),
CRM_Core_Action::DELETE => array(
'name' => ts('Delete'),
'url' => 'civicrm/contact/view/contribution',
'qs' => "reset=1&action=delete&id=%%id%%&cid=%%cid%%&context=%%cxt%%{$extraParams}",
'title' => ts('Delete Contribution'),
),
);
}
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('Contribution') . ' %%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 string $action
*
* @return int
* Total number of rows
*/
public function getTotalCount($action) {
return $this->_query->searchQuery(0, 0, NULL,
TRUE, FALSE,
FALSE, FALSE,
FALSE,
$this->_contributionClause
);
}
/**
* 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 int
* the total number of rows for this action
*/
public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
if ($this->_includeSoftCredits) {
// especial sort order when rows include soft credits
$sort = $sort->orderBy() . ", civicrm_contribution.id, civicrm_contribution_soft.id";
}
$result = $this->_query->searchQuery($offset, $rowCount, $sort,
FALSE, FALSE,
FALSE, FALSE,
FALSE,
$this->_contributionClause
);
// process the result of the query
$rows = array();
//CRM-4418 check for view/edit/delete
$permissions = array(CRM_Core_Permission::VIEW);
if (CRM_Core_Permission::check('edit contributions')) {
$permissions[] = CRM_Core_Permission::EDIT;
}
if (CRM_Core_Permission::check('delete in CiviContribute')) {
$permissions[] = CRM_Core_Permission::DELETE;
}
$mask = CRM_Core_Action::mask($permissions);
$qfKey = $this->_key;
$componentId = $componentContext = NULL;
if ($this->_context != 'contribute') {
// @todo explain the significance of context & why we do not get these i that context.
$qfKey = CRM_Utils_Request::retrieve('key', 'String');
$componentId = CRM_Utils_Request::retrieve('id', 'Positive');
$componentAction = CRM_Utils_Request::retrieve('action', 'String');
$componentContext = CRM_Utils_Request::retrieve('compContext', 'String');
if (!$componentContext &&
$this->_compContext
) {
// @todo explain when this condition might occur.
$componentContext = $this->_compContext;
$qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', CRM_Core_DAO::$_nullObject, NULL, FALSE, 'REQUEST');
}
// CRM-17628 for some reason qfKey is not always set when searching from contribution search.
// as a result if the edit link is opened using right-click + open in new tab
// then the browser is not returned to the search results on save.
// This is an effort to getting the qfKey without, sadly, understanding the intent of those who came before me.
if (empty($qfKey)) {
$qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', CRM_Core_DAO::$_nullObject, NULL, FALSE, 'REQUEST');
}
}
// get all contribution status
$contributionStatuses = CRM_Core_OptionGroup::values('contribution_status',
FALSE, FALSE, FALSE, NULL, 'name', FALSE
);
//get all campaigns.
$allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
while ($result->fetch()) {
$this->_query->convertToPseudoNames($result);
$links = self::links($componentId,
$componentAction,
$qfKey,
$componentContext
);
$checkLineItem = FALSE;
$row = array();
// Now check for lineItems
if (CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
$lineItems = CRM_Price_BAO_LineItem::getLineItemsByContributionID($result->id);
foreach ($lineItems as $items) {
if (!CRM_Core_Permission::check('view contributions of type ' . CRM_Contribute_PseudoConstant::financialType($items['financial_type_id']))) {
$checkLineItem = TRUE;
break;
}
if (!CRM_Core_Permission::check('edit contributions of type ' . CRM_Contribute_PseudoConstant::financialType($items['financial_type_id']))) {
unset($links[CRM_Core_Action::UPDATE]);
}
if (!CRM_Core_Permission::check('delete contributions of type ' . CRM_Contribute_PseudoConstant::financialType($items['financial_type_id']))) {
unset($links[CRM_Core_Action::DELETE]);
}
}
if ($checkLineItem) {
continue;
}
if (!CRM_Core_Permission::check('edit contributions of type ' . CRM_Contribute_PseudoConstant::financialType($result->financial_type_id))) {
unset($links[CRM_Core_Action::UPDATE]);
}
if (!CRM_Core_Permission::check('delete contributions of type ' . CRM_Contribute_PseudoConstant::financialType($result->financial_type_id))) {
unset($links[CRM_Core_Action::DELETE]);
}
}
// the columns we are interested in
foreach (self::$_properties as $property) {
if (property_exists($result, $property)) {
$row[$property] = $result->$property;
}
}
//carry campaign on selectors.
// @todo - I can't find any evidence that 'carrying' the campaign on selectors actually
// results in it being displayed anywhere so why do we do this???
$row['campaign'] = CRM_Utils_Array::value($result->contribution_campaign_id, $allCampaigns);
$row['campaign_id'] = $result->contribution_campaign_id;
// add contribution status name
$row['contribution_status_name'] = CRM_Utils_Array::value($row['contribution_status_id'],
$contributionStatuses
);
$isPayLater = FALSE;
if ($result->is_pay_later && CRM_Utils_Array::value('contribution_status_name', $row) == 'Pending') {
$isPayLater = TRUE;
$row['contribution_status'] .= ' (' . ts('Pay Later') . ')';
$links[CRM_Core_Action::ADD] = array(
'name' => ts('Pay with Credit Card'),
'url' => 'civicrm/contact/view/contribution',
'qs' => 'reset=1&action=update&id=%%id%%&cid=%%cid%%&context=%%cxt%%&mode=live',
'title' => ts('Pay with Credit Card'),
);
}
elseif (CRM_Utils_Array::value('contribution_status_name', $row) == 'Pending') {
$row['contribution_status'] .= ' (' . ts('Incomplete Transaction') . ')';
}
if ($row['is_test']) {
$row['financial_type'] = $row['financial_type'] . ' (' . ts('test') . ')';
}
$row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->contribution_id;
$actions = array(
'id' => $result->contribution_id,
'cid' => $result->contact_id,
'cxt' => $this->_context,
);
if (in_array($row['contribution_status_name'], array('Partially paid', 'Pending refund')) || $isPayLater) {
$buttonName = ts('Record Payment');
if ($row['contribution_status_name'] == 'Pending refund') {
$buttonName = ts('Record Refund');
}
elseif (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=contribution&mode=live',
'title' => ts('Submit Credit Card payment'),
);
}
$links[CRM_Core_Action::ADD] = array(
'name' => $buttonName,
'url' => 'civicrm/payment',
'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=add&component=contribution',
'title' => $buttonName,
);
}
$row['action'] = CRM_Core_Action::formLink(
$links,
$mask, $actions,
ts('more'),
FALSE,
'contribution.selector.row',
'Contribution',
$result->contribution_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
);
if (!empty($row['amount_level'])) {
CRM_Event_BAO_Participant::fixEventLevel($row['amount_level']);
}
$rows[] = $row;
}
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) {
$pre = array();
self::$_columnHeaders = array(
array(
'name' => $this->_includeSoftCredits ? ts('Contribution Amount') : ts('Amount'),
'sort' => 'total_amount',
'direction' => CRM_Utils_Sort::DONTCARE,
'field_name' => 'total_amount',
),
);
if ($this->_includeSoftCredits) {
self::$_columnHeaders
= array_merge(
self::$_columnHeaders,
array(
array(
'name' => ts('Soft Credit Amount'),
'sort' => 'contribution_soft_credit_amount',
'field_name' => 'contribution_soft_credit_amount',
'direction' => CRM_Utils_Sort::DONTCARE,
),
)
);
}
self::$_columnHeaders
= array_merge(
self::$_columnHeaders,
array(
array(
'name' => ts('Type'),
'sort' => 'financial_type',
'field_name' => 'financial_type',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Source'),
'sort' => 'contribution_source',
'field_name' => 'contribution_source',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Received'),
'sort' => 'receive_date',
'field_name' => 'receive_date',
'type' => 'date',
'direction' => CRM_Utils_Sort::DESCENDING,
),
array(
'name' => ts('Thank-you Sent'),
'sort' => 'thankyou_date',
'field_name' => 'thankyou_date',
'type' => 'date',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Status'),
'sort' => 'contribution_status',
'field_name' => 'contribution_status',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Premium'),
'sort' => 'product_name',
'field_name' => 'product_name',
'direction' => CRM_Utils_Sort::DONTCARE,
),
)
);
if (!$this->_single) {
$pre = array(
array(
'name' => ts('Name'),
'sort' => 'sort_name',
'direction' => CRM_Utils_Sort::DONTCARE,
),
);
}
self::$_columnHeaders = array_merge($pre, self::$_columnHeaders);
if ($this->_includeSoftCredits) {
self::$_columnHeaders = array_merge(
self::$_columnHeaders,
array(
array(
'name' => ts('Soft Credit For'),
'sort' => 'contribution_soft_credit_name',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Soft Credit Type'),
'sort' => 'contribution_soft_credit_type',
'direction' => CRM_Utils_Sort::ASCENDING,
),
)
);
}
self::$_columnHeaders
= array_merge(
self::$_columnHeaders, array(
array('desc' => ts('Actions'), 'type' => 'actions'),
)
);
foreach (array_keys(self::$_columnHeaders) as $index) {
// Add weight & space it out a bit to allow headers to be inserted.
self::$_columnHeaders[$index]['weight'] = $index * 10;
}
CRM_Core_Smarty::singleton()->assign('softCreditColumns', $this->_includeSoftCredits);
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 Contribution Search');
}
/**
* @return mixed
*/
public function getSummary() {
return $this->_query->summaryContribution($this->_context);
}
}

View file

@ -0,0 +1,60 @@
<?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
*/
/**
* State machine for managing different states of the Import process.
*
*/
class CRM_Contribute_StateMachine_Contribution extends CRM_Core_StateMachine {
/**
* Class constructor.
*
* @param CRM_Core_Controller $controller
* @param \const|int $action
*
* @return CRM_Contribute_StateMachine_Contribution
*/
public function __construct($controller, $action = CRM_Core_Action::NONE) {
parent::__construct($controller, $action);
$this->_pages = array(
'CRM_Contribute_Form_Contribution_Main' => NULL,
'CRM_Contribute_Form_Contribution_Confirm' => NULL,
'CRM_Contribute_Form_Contribution_ThankYou' => NULL,
);
$this->addSequentialPages($this->_pages, $action);
}
}

View file

@ -0,0 +1,74 @@
<?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
*/
/**
* State machine for managing different states of the Import process.
*/
class CRM_Contribute_StateMachine_ContributionPage extends CRM_Core_StateMachine {
/**
* Class constructor.
*
* @param CRM_Contribute_Controller_ContributionPage $controller
* @param const|int $action
*
* @return CRM_Contribute_StateMachine_ContributionPage
*/
public function __construct($controller, $action = CRM_Core_Action::NONE) {
parent::__construct($controller, $action);
$session = CRM_Core_Session::singleton();
$session->set('singleForm', FALSE);
$config = CRM_Core_Config::singleton();
$this->_pages = array(
'CRM_Contribute_Form_ContributionPage_Settings' => NULL,
'CRM_Contribute_Form_ContributionPage_Amount' => NULL,
'CRM_Member_Form_MembershipBlock' => NULL,
'CRM_Contribute_Form_ContributionPage_ThankYou' => NULL,
'CRM_Friend_Form_Contribute' => NULL,
'CRM_PCP_Form_Contribute' => NULL,
'CRM_Contribute_Form_ContributionPage_Custom' => NULL,
'CRM_Contribute_Form_ContributionPage_Premium' => NULL,
'CRM_Contribute_Form_ContributionPage_Widget' => NULL,
);
if (!in_array("CiviMember", $config->enableComponents)) {
unset($this->_pages['CRM_Member_Form_MembershipBlock']);
}
$this->addSequentialPages($this->_pages, $action);
}
}

View file

@ -0,0 +1,111 @@
<?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
*/
class CRM_Contribute_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_Contribute_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_Contribute_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_Contribute_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,220 @@
<?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
*/
/**
* Class to represent the actions that can be performed on a group of contacts.
*
* Used by the search forms.
*/
class CRM_Contribute_Task {
const DELETE_CONTRIBUTIONS = 1, PRINT_CONTRIBUTIONS = 2, EXPORT_CONTRIBUTIONS = 3, BATCH_CONTRIBUTIONS = 4, EMAIL_CONTACTS = 5, UPDATE_STATUS = 6, PDF_RECEIPT = 7;
/**
* 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 contributions'),
'class' => 'CRM_Contribute_Form_Task_Delete',
'result' => FALSE,
),
2 => array(
'title' => ts('Print selected rows'),
'class' => 'CRM_Contribute_Form_Task_Print',
'result' => FALSE,
),
3 => array(
'title' => ts('Export contributions'),
'class' => array(
'CRM_Export_Form_Select',
'CRM_Export_Form_Map',
),
'result' => FALSE,
),
4 => array(
'title' => ts('Update multiple contributions'),
'class' => array(
'CRM_Contribute_Form_Task_PickProfile',
'CRM_Contribute_Form_Task_Batch',
),
'result' => TRUE,
),
5 => array(
'title' => ts('Email - send now'),
'class' => 'CRM_Contribute_Form_Task_Email',
'result' => TRUE,
),
6 => array(
'title' => ts('Update pending contribution status'),
'class' => 'CRM_Contribute_Form_Task_Status',
'result' => TRUE,
),
7 => array(
'title' => ts('Receipts - print or email'),
'class' => 'CRM_Contribute_Form_Task_PDF',
'result' => FALSE,
),
8 => array(
'title' => ts('Thank-you letters - print or email'),
'class' => 'CRM_Contribute_Form_Task_PDFLetter',
'result' => FALSE,
),
9 => array(
'title' => ts('Invoices - print or email'),
'class' => 'CRM_Contribute_Form_Task_Invoice',
'result' => FALSE,
),
);
//CRM-4418, check for delete
if (!CRM_Core_Permission::check('delete in CiviContribute')) {
unset(self::$_tasks[1]);
}
//CRM-12920 - check for edit permission
if (!CRM_Core_Permission::check('edit contributions')) {
unset(self::$_tasks[4], self::$_tasks[6]);
}
// remove action "Invoices - print or email"
$invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
$invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
if (!$invoicing) {
unset(self::$_tasks[9]);
}
CRM_Utils_Hook::searchTasks('contribution', self::$_tasks);
asort(self::$_tasks);
}
return self::$_tasks;
}
/**
* These tasks are the core set of task titles
* on contributors
*
* @return array
* the set of task titles
*/
public static function &taskTitles() {
self::tasks();
$titles = array();
foreach (self::$_tasks as $id => $value) {
$titles[$id] = $value['title'];
}
return $titles;
}
/**
* Show tasks selectively based on the permission level
* of the user
*
* @param int $permission
*
* @param bool $softCreditFiltering
*
* @return array
* set of tasks that are valid for the user
*/
public static function &permissionedTaskTitles($permission, $softCreditFiltering = FALSE) {
$tasks = array();
if (($permission == CRM_Core_Permission::EDIT)
|| CRM_Core_Permission::check('edit contributions')
) {
$tasks = self::taskTitles();
}
else {
$tasks = array(
3 => self::$_tasks[3]['title'],
5 => self::$_tasks[5]['title'],
7 => self::$_tasks[7]['title'],
);
//CRM-4418,
if (CRM_Core_Permission::check('delete in CiviContribute')) {
$tasks[1] = self::$_tasks[1]['title'];
}
}
if ($softCreditFiltering) {
unset($tasks[4], $tasks[7]);
}
return $tasks;
}
/**
* These tasks are the core set of tasks that the user can perform
* on contributors
*
* @param int $value
*
* @return array
* the set of tasks for a group of contributors
*/
public static function getTask($value) {
self::tasks();
if (!$value || !CRM_Utils_Array::value($value, self::$_tasks)) {
// make the print task by default
$value = 2;
}
// this is possible since hooks can inject a task
// CRM-13697
if (!isset(self::$_tasks[$value]['result'])) {
self::$_tasks[$value]['result'] = NULL;
}
return array(
self::$_tasks[$value]['class'],
self::$_tasks[$value]['result'],
);
}
}

View file

@ -0,0 +1,147 @@
<?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_Contribute_Tokens
*
* Generate "contribution.*" tokens.
*
* At time of writing, we don't have any particularly special tokens -- we just
* do some basic formatting based on the corresponding DB field.
*/
class CRM_Contribute_Tokens extends \Civi\Token\AbstractTokenSubscriber {
/**
* Get a list of tokens whose name and title match the DB fields.
* @return array
*/
protected function getPassthruTokens() {
return array(
'contribution_page_id',
'receive_date',
'total_amount',
'fee_amount',
'net_amount',
'trxn_id',
'invoice_id',
'currency',
'cancel_date',
'receipt_date',
'thankyou_date',
'tax_amount',
);
}
/**
* Get alias tokens.
*
* @return array
*/
protected function getAliasTokens() {
return array(
'id' => 'contribution_id',
'payment_instrument' => 'payment_instrument_id',
'source' => 'contribution_source',
'status' => 'contribution_status_id',
'type' => 'financial_type_id',
);
}
/**
* Class constructor.
*/
public function __construct() {
$tokens = CRM_Utils_Array::subset(
CRM_Utils_Array::collect('title', CRM_Contribute_DAO_Contribution::fields()),
$this->getPassthruTokens()
);
$tokens['id'] = ts('Contribution ID');
$tokens['payment_instrument'] = ts('Payment Instrument');
$tokens['source'] = ts('Contribution Source');
$tokens['status'] = ts('Contribution Status');
$tokens['type'] = ts('Financial Type');
$tokens = array_merge($tokens, CRM_Utils_Token::getCustomFieldTokens('Contribution'));
parent::__construct('contribution', $tokens);
}
/**
* Check if the token processor is active.
*
* @param \Civi\Token\TokenProcessor $processor
*
* @return bool
*/
public function checkActive(\Civi\Token\TokenProcessor $processor) {
return
!empty($processor->context['actionMapping'])
&& $processor->context['actionMapping']->getEntity() === 'civicrm_contribution';
}
/**
* Alter action schedule query.
*
* @param \Civi\ActionSchedule\Event\MailingQueryEvent $e
*/
public function alterActionScheduleQuery(\Civi\ActionSchedule\Event\MailingQueryEvent $e) {
if ($e->mapping->getEntity() !== 'civicrm_contribution') {
return;
}
$fields = CRM_Contribute_DAO_Contribution::fields();
foreach ($this->getPassthruTokens() as $token) {
$e->query->select("e." . $fields[$token]['name'] . " AS contrib_{$token}");
}
foreach ($this->getAliasTokens() as $alias => $orig) {
$e->query->select("e." . $fields[$orig]['name'] . " AS contrib_{$alias}");
}
}
/**
* @inheritDoc
*/
public function evaluateToken(\Civi\Token\TokenRow $row, $entity, $field, $prefetch = NULL) {
$actionSearchResult = $row->context['actionSearchResult'];
$fieldValue = isset($actionSearchResult->{"contrib_$field"}) ? $actionSearchResult->{"contrib_$field"} : NULL;
$aliasTokens = $this->getAliasTokens();
if (in_array($field, array('total_amount', 'fee_amount', 'net_amount'))) {
return $row->format('text/plain')->tokens($entity, $field,
\CRM_Utils_Money::format($fieldValue, $actionSearchResult->contrib_currency));
}
elseif (isset($aliasTokens[$field])) {
$row->dbToken($entity, $field, 'CRM_Contribute_BAO_Contribution', $aliasTokens[$field], $fieldValue);
}
elseif ($cfID = \CRM_Core_BAO_CustomField::getKeyID($field)) {
$row->customToken($entity, $cfID, $actionSearchResult->entity_id);
}
else {
$row->dbToken($entity, $field, 'CRM_Contribute_BAO_Contribution', $field, $fieldValue);
}
}
}

View file

@ -0,0 +1,326 @@
<?xml version="1.0" encoding="iso-8859-1" ?>
<menu>
<item>
<path>civicrm/contribute</path>
<title>CiviContribute Dashboard</title>
<page_callback>CRM_Contribute_Page_DashBoard</page_callback>
<access_arguments>access CiviContribute</access_arguments>
<page_type>1</page_type>
<weight>500</weight>
<component>CiviContribute</component>
</item>
<item>
<path>civicrm/contribute/add</path>
<title>New Contribution</title>
<page_callback>CRM_Contribute_Page_Tab</page_callback>
<path_arguments>action=add</path_arguments>
<access_arguments>access CiviContribute</access_arguments>
<page_type>1</page_type>
<component>CiviContribute</component>
</item>
<item>
<path>civicrm/contribute/chart</path>
<title>Contribution Summary - Chart View</title>
<page_callback>CRM_Contribute_Form_ContributionCharts</page_callback>
<access_arguments>access CiviContribute</access_arguments>
<component>CiviContribute</component>
</item>
<item>
<path>civicrm/contribute/transact</path>
<title>CiviContribute</title>
<page_callback>CRM_Contribute_Controller_Contribution</page_callback>
<access_arguments>make online contributions</access_arguments>
<weight>0</weight>
<is_ssl>true</is_ssl>
<is_public>true</is_public>
</item>
<item>
<path>civicrm/admin/contribute</path>
<title>Manage Contribution Pages</title>
<page_callback>CRM_Contribute_Page_ContributionPage</page_callback>
<desc>CiviContribute allows you to create and maintain any number of Online Contribution Pages. You can create different pages for different programs or campaigns - and customize text, amounts, types of information collected from contributors, etc.</desc>
<adminGroup>CiviContribute</adminGroup>
<icon>admin/small/online_contribution_pages.png</icon>
<weight>360</weight>
</item>
<item>
<path>civicrm/admin/contribute/settings</path>
<title>Title and Settings</title>
<page_callback>CRM_Contribute_Form_ContributionPage_Settings</page_callback>
<weight>400</weight>
</item>
<item>
<path>civicrm/admin/contribute/amount</path>
<title>Contribution Amounts</title>
<page_callback>CRM_Contribute_Form_ContributionPage_Amount</page_callback>
<weight>410</weight>
</item>
<item>
<path>civicrm/admin/contribute/membership</path>
<title>Membership Section</title>
<page_callback>CRM_Member_Form_MembershipBlock</page_callback>
<weight>420</weight>
</item>
<item>
<path>civicrm/admin/contribute/custom</path>
<title>Include Profiles</title>
<page_callback>CRM_Contribute_Form_ContributionPage_Custom</page_callback>
<weight>430</weight>
</item>
<item>
<path>civicrm/admin/contribute/thankyou</path>
<title>Thank-you and Receipting</title>
<page_callback>CRM_Contribute_Form_ContributionPage_ThankYou</page_callback>
<weight>430</weight>
</item>
<item>
<path>civicrm/admin/contribute/friend</path>
<title>Tell a Friend</title>
<page_callback>CRM_Friend_Form_Contribute</page_callback>
<weight>440</weight>
</item>
<item>
<path>civicrm/admin/contribute/widget</path>
<title>Configure Widget</title>
<page_callback>CRM_Contribute_Form_ContributionPage_Widget</page_callback>
<weight>460</weight>
</item>
<item>
<path>civicrm/admin/contribute/premium</path>
<title>Premiums</title>
<page_callback>CRM_Contribute_Form_ContributionPage_Premium</page_callback>
<weight>470</weight>
</item>
<item>
<path>civicrm/admin/contribute/addProductToPage</path>
<title>Add Products to This Page</title>
<page_callback>CRM_Contribute_Form_ContributionPage_AddProduct</page_callback>
<weight>480</weight>
</item>
<item>
<path>civicrm/admin/contribute/add</path>
<title>New Contribution Page</title>
<page_callback>CRM_Contribute_Controller_ContributionPage</page_callback>
<path_arguments>action=add</path_arguments>
</item>
<item>
<path>civicrm/admin/contribute/managePremiums</path>
<title>Manage Premiums</title>
<page_callback>CRM_Contribute_Page_ManagePremiums</page_callback>
<desc>CiviContribute allows you to configure any number of Premiums which can be offered to contributors as incentives / thank-you gifts. Define the premiums you want to offer here.</desc>
<adminGroup>CiviContribute</adminGroup>
<icon>admin/small/Premiums.png</icon>
<weight>365</weight>
</item>
<item>
<path>civicrm/admin/financial/financialType</path>
<title>Financial Types</title>
<page_callback>CRM_Financial_Page_FinancialType</page_callback>
<desc>Formerly civicrm_contribution_type merged into this table in 4.1</desc>
<adminGroup>CiviContribute</adminGroup>
<weight>580</weight>
</item>
<item>
<path>civicrm/payment</path>
<title>New Payment</title>
<page_callback>CRM_Contribute_Form_AdditionalPayment</page_callback>
<path_arguments>action=add</path_arguments>
<access_arguments>access CiviContribute</access_arguments>
<page_type>1</page_type>
<component>CiviContribute</component>
</item>
<item>
<path>civicrm/admin/financial/financialAccount</path>
<title>Financial Accounts</title>
<page_callback>CRM_Financial_Page_FinancialAccount</page_callback>
<desc>Financial types are used to categorize contributions for reporting and accounting purposes. These are also referred to as Funds.</desc>
<adminGroup>CiviContribute</adminGroup>
<icon>admin/small/contribution_types.png</icon>
<weight>370</weight>
</item>
<item>
<path>civicrm/admin/options/payment_instrument</path>
<title>Payment Methods</title>
<page_callback>CRM_Admin_Page_Options</page_callback>
<desc>You may choose to record the payment instrument used for each contribution. Common payment methods are installed by default (e.g. Check, Cash, Credit Card...). If your site requires additional payment methods, add them here.</desc>
<adminGroup>CiviContribute</adminGroup>
<icon>admin/small/payment_instruments.png</icon>
<weight>380</weight>
</item>
<item>
<path>civicrm/admin/options/accept_creditcard</path>
<title>Accepted Credit Cards</title>
<page_callback>CRM_Admin_Page_Options</page_callback>
<desc>Credit card options that will be offered to contributors using your Online Contribution pages.</desc>
<adminGroup>CiviContribute</adminGroup>
<icon>admin/small/accepted_creditcards.png</icon>
<weight>395</weight>
</item>
<item>
<path>civicrm/admin/options/soft_credit_type</path>
<title>Soft Credit Types</title>
<page_callback>CRM_Admin_Page_Options</page_callback>
<desc>Soft Credit Types that will be offered to contributors during soft credit contribution</desc>
<adminGroup>CiviContribute</adminGroup>
<icon>admin/small/soft_credit_type.png</icon>
</item>
<item>
<path>civicrm/contact/view/contribution</path>
<title>Contributions</title>
<page_callback>CRM_Contribute_Page_Tab</page_callback>
<weight>1</weight>
</item>
<item>
<path>civicrm/contact/view/contributionrecur</path>
<title>Recurring Contributions</title>
<page_callback>CRM_Contribute_Page_ContributionRecur</page_callback>
</item>
<item>
<path>civicrm/contact/view/contribution/additionalinfo</path>
<title>Additional Info</title>
<page_callback>CRM_Contribute_Form_AdditionalInfo</page_callback>
</item>
<item>
<path>civicrm/contribute/search</path>
<title>Find Contributions</title>
<page_callback>CRM_Contribute_Controller_Search</page_callback>
<access_arguments>access CiviContribute</access_arguments>
<page_type>1</page_type>
<weight>510</weight>
</item>
<item>
<path>civicrm/contribute/searchBatch</path>
<page_callback>CRM_Contribute_Controller_SearchBatch</page_callback>
<access_arguments>access CiviContribute</access_arguments>
<page_type>1</page_type>
<weight>588</weight>
</item>
<item>
<path>civicrm/contribute/import</path>
<title>Import Contributions</title>
<page_callback>CRM_Contribute_Import_Controller</page_callback>
<access_arguments>access CiviContribute,edit contributions</access_arguments>
<page_type>1</page_type>
<weight>520</weight>
</item>
<item>
<path>civicrm/contribute/manage</path>
<title>Manage Contribution Pages</title>
<page_callback>CRM_Contribute_Page_ContributionPage</page_callback>
<access_arguments>administer CiviCRM,access CiviContribute</access_arguments>
<page_type>1</page_type>
<weight>530</weight>
</item>
<item>
<path>civicrm/contribute/additionalinfo</path>
<title>AdditionalInfo Form</title>
<page_callback>CRM_Contribute_Form_AdditionalInfo</page_callback>
<access_arguments>access CiviContribute</access_arguments>
<weight>0</weight>
</item>
<item>
<path>civicrm/ajax/permlocation</path>
<page_callback>CRM_Core_Page_AJAX_Location::getPermissionedLocation</page_callback>
<access_arguments>make online contributions</access_arguments>
</item>
<item>
<path>civicrm/contribute/unsubscribe</path>
<title>Cancel Subscription</title>
<page_callback>CRM_Contribute_Form_CancelSubscription</page_callback>
<access_arguments>make online contributions</access_arguments>
</item>
<item>
<path>civicrm/contribute/onbehalf</path>
<page_callback>CRM_Contribute_Form_Contribution_OnBehalfOf</page_callback>
<access_arguments>make online contributions</access_arguments>
</item>
<item>
<path>civicrm/contribute/updatebilling</path>
<title>Update Billing Details</title>
<page_callback>CRM_Contribute_Form_UpdateBilling</page_callback>
<access_arguments>make online contributions</access_arguments>
</item>
<item>
<path>civicrm/contribute/updaterecur</path>
<title>Update Subscription</title>
<page_callback>CRM_Contribute_Form_UpdateSubscription</page_callback>
<access_arguments>make online contributions</access_arguments>
</item>
<item>
<path>civicrm/contribute/subscriptionstatus</path>
<page_callback>CRM_Contribute_Page_SubscriptionStatus</page_callback>
<access_arguments>make online contributions</access_arguments>
</item>
<item>
<path>civicrm/admin/financial/financialType/accounts</path>
<title>Financial Type Accounts</title>
<page_callback>CRM_Financial_Page_FinancialTypeAccount</page_callback>
<weight>581</weight>
</item>
<item>
<path>civicrm/financial/batch</path>
<title>Accounting Batch</title>
<page_callback>CRM_Financial_Page_FinancialBatch</page_callback>
<access_arguments>create manual batch</access_arguments>
<weight>585</weight>
</item>
<item>
<path>civicrm/financial/financialbatches</path>
<title>Accounting Batches</title>
<page_callback>CRM_Financial_Page_Batch</page_callback>
<weight>586</weight>
</item>
<item>
<path>civicrm/batchtransaction</path>
<title>Accounting Batch</title>
<page_callback>CRM_Financial_Page_BatchTransaction</page_callback>
<weight>600</weight>
</item>
<item>
<path>civicrm/financial/batch/export</path>
<title>Accounting Batch Export</title>
<page_callback>CRM_Financial_Form_Export</page_callback>
<weight>610</weight>
</item>
<item>
<path>civicrm/payment/view</path>
<title>View Payment</title>
<page_callback>CRM_Contribute_Page_PaymentInfo</page_callback>
<path_arguments>action=view</path_arguments>
<access_arguments>access CiviContribute</access_arguments>
<page_type>1</page_type>
<component>CiviContribute</component>
</item>
<item>
<path>civicrm/admin/setting/preferences/contribute</path>
<title>CiviContribute Component Settings</title>
<page_callback>CRM_Admin_Form_Preferences_Contribute</page_callback>
<desc>Configure global CiviContribute behaviors.</desc>
<access_arguments>access CiviContribute,administer CiviCRM</access_arguments>
<adminGroup>CiviContribute</adminGroup>
</item>
<item>
<path>civicrm/contribute/invoice</path>
<title>PDF Invoice</title>
<page_callback>CRM_Contribute_Form_Task_Invoice::getPrintPDF</page_callback>
<access_callback>CRM_Core_Permission::checkDownloadInvoice</access_callback>
<page_type>1</page_type>
<weight>620</weight>
<component>CiviContribute</component>
</item>
<item>
<path>civicrm/contribute/invoice/email</path>
<title>Email Invoice</title>
<page_callback>CRM_Contribute_Form_Task_Invoice</page_callback>
<access_arguments>access CiviContribute</access_arguments>
<page_type>1</page_type>
<weight>630</weight>
<component>CiviContribute</component>
</item>
<item>
<path>civicrm/ajax/softcontributionlist</path>
<page_callback>CRM_Contribute_Page_AJAX::getSoftContributionRows</page_callback>
<access_arguments>access CiviCRM</access_arguments>
</item>
</menu>

View file

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="iso-8859-1" ?>
<menu>
<item>
<path>civicrm/admin/pcp</path>
<title>Personal Campaign Pages</title>
<page_callback>CRM_PCP_Page_PCP</page_callback>
<path_arguments>context=contribute</path_arguments>
<desc>View and manage existing personal campaign pages.</desc>
<adminGroup>CiviContribute</adminGroup>
<icon>admin/small/contribution_types.png</icon>
<weight>362</weight>
</item>
<item>
<path>civicrm/admin/contribute/pcp</path>
<title>Personal Campaign Pages</title>
<page_callback>CRM_PCP_Form_Contribute</page_callback>
<weight>450</weight>
</item>
<item>
<path>civicrm/contribute/campaign</path>
<title>Setup a Personal Campaign Page - Account Information</title>
<page_callback>CRM_PCP_Controller_PCP</page_callback>
<access_arguments>make online contributions</access_arguments>
<is_public>true</is_public>
<weight>0</weight>
</item>
</menu>