/**
  * Function to set variables up before form is built
  *
  * @return void
  * @access public
  */
 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_Core_BAO_PaymentProcessor::getProcessorForEntity($this->_crid, 'recur', 'info');
         $this->_paymentProcessorObj = CRM_Core_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_Core_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'info');
         $this->_paymentProcessorObj = CRM_Core_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'obj');
         $this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_coid, 'contribution');
     }
     if ($this->_mid) {
         $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getProcessorForEntity($this->_mid, 'membership', 'info');
         $this->_paymentProcessorObj = CRM_Core_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_DAO::$_nullObject) {
         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->_paymentProcessorObj->isSupported('updateSubscriptionBillingInfo')) {
         CRM_Core_Error::fatal(ts("%1 processor doesn't support updating subscription billing details.", array(1 => $this->_paymentProcessorObj->_processorName)));
     }
     $this->assign('paymentProcessor', $this->_paymentProcessor);
     // get the billing location type
     $locationTypes = CRM_Core_PseudoConstant::locationType();
     $this->_bltID = array_search('Billing', $locationTypes);
     $this->assign('bltID', $this->_bltID);
     if (!$this->_bltID) {
         CRM_Core_Error::fatal(ts('Please set a location type of %1', array(1 => 'Billing')));
     }
     $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();
 }
 /**
  * Function to set variables up before form is built
  *
  * @return void
  * @access public
  */
 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_Core_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) {
         if (CRM_Member_BAO_Membership::isSubscriptionCancelled($this->_mid)) {
             CRM_Core_Error::fatal(ts('The auto renewal option for this membership looks to have been cancelled already.'));
         }
         $this->_mode = 'auto_renew';
         $this->_paymentProcessorObj = CRM_Core_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_Core_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'obj');
         $this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_coid, 'contribution');
     }
     if (!$this->_crid && !$this->_coid && !$this->_mid || $this->_subscriptionDetails == CRM_Core_DAO::$_nullObject) {
         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);
     }
 }
/**
 * create a contribution page
 *
 * @param  array   $params           (reference ) input parameters - need id and contribution_type_id
 *
 * @return array (reference )        contributionType id and other fields
 * @static void
 * @access public
 */
function &civicrm_paymentprocessor_getpayment( &$params ) {
    _civicrm_initialize( );

    if( ! is_array($params) ) {
        return civicrm_create_error( 'Params need to be of type array!' );
    }	
	
	civicrm_verify_mandatory ($params,null,array ('id', 'mode'));
	$id		= CRM_Utils_Array::value( 'id', $params );
	$mode	= CRM_Utils_Array::value( 'mode', $params );

	$paymentProcessor =& CRM_Core_BAO_PaymentProcessor::getPayment($id, $mode);

    return $paymentProcessor;
}
 static function preProcess(&$form, $type = NULL, $mode = NULL)
 {
     if ($type) {
         $form->_type = $type;
     } else {
         $form->_type = CRM_Utils_Request::retrieve('type', 'String', $form);
     }
     if ($form->_type) {
         $form->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($form->_type, $form->_mode);
     }
     //$form->_paymentProcessor['processorName'] = $form->_paymentObject->_processorName;
     $form->set('paymentProcessor', $form->_paymentProcessor);
     // also set cancel subscription url
     if (CRM_Utils_Array::value('is_recur', $form->_paymentProcessor) && CRM_Utils_Array::value('is_recur', $form->_values)) {
         $form->_paymentObject =& CRM_Core_Payment::singleton($mode, $form->_paymentProcessor, $form);
         $form->_values['cancelSubscriptionUrl'] = $form->_paymentObject->subscriptionURL();
     }
     //checks after setting $form->_paymentProcessor
     // we do this outside of the above conditional to avoid
     // saving the country/state list in the session (which could be huge)
     if ($form->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM && CRM_Utils_Array::value('is_monetary', $form->_values)) {
         if ($form->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_DIRECT_DEBIT) {
             CRM_Core_Payment_Form::setDirectDebitFields($form);
         } else {
             CRM_Core_Payment_Form::setCreditCardFields($form);
         }
     }
     $form->assign_by_ref('paymentProcessor', $form->_paymentProcessor);
     // check if this is a paypal auto return and redirect accordingly
     if (CRM_Core_Payment::paypalRedirect($form->_paymentProcessor)) {
         $url = CRM_Utils_System::url('civicrm/contribute/transact', "_qf_ThankYou_display=1&qfKey={$form->controller->_key}");
         CRM_Utils_System::redirect($url);
     }
     // make sure we have a valid payment class, else abort
     if (CRM_Utils_Array::value('is_monetary', $form->_values) && !$form->_paymentProcessor['class_name'] && !CRM_Utils_Array::value('is_pay_later', $form->_values)) {
         CRM_Core_Error::fatal(ts('Payment processor is not set for this page'));
     }
     if (!empty($form->_membershipBlock) && CRM_Utils_Array::value('is_separate_payment', $form->_membershipBlock) && (CRM_Utils_Array::value('class_name', $form->_paymentProcessor) && !(CRM_Utils_Array::value('billing_mode', $form->_paymentProcessor) & CRM_Core_Payment::BILLING_MODE_FORM))) {
         CRM_Core_Error::fatal(ts('This contribution page is configured to support separate contribution and membership payments. This %1 plugin does not currently support multiple simultaneous payments, or the option to "Execute real-time monetary transactions" is disabled. Please contact the site administrator and notify them of this error', array(1 => $form->_paymentProcessor['payment_processor_type'])));
     }
     $profileAddressFields = $form->get('profileAddressFields');
     if (!empty($profileAddressFields)) {
         $form->assign('profileAddressFields', $profileAddressFields);
     }
 }
 /**
  * This method returns the links that are given for recur search row.
  * currently the links added for each row are:
  * - View
  * - Edit
  * - Cancel
  *
  * @return array
  * @access 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'), 'extra' => 'onclick = "enableDisable( %%crid%%,\'' . 'CRM_Contribute_BAO_ContributionRecur' . '\',\'' . 'enable-disable' . '\' );"', 'ref' => 'disable-action'));
     }
     if ($recurID) {
         $paymentProcessorObj = CRM_Core_BAO_PaymentProcessor::getProcessorForEntity($recurID, 'recur', 'obj');
         if (is_object($paymentProcessorObj) && $paymentProcessorObj->isSupported('cancelSubscription')) {
             unset(self::$_links[CRM_Core_Action::DISABLE]['extra'], self::$_links[CRM_Core_Action::DISABLE]['ref']);
             self::$_links[CRM_Core_Action::DISABLE]['url'] = "civicrm/contribute/unsubscribe";
             self::$_links[CRM_Core_Action::DISABLE]['qs'] = "reset=1&crid=%%crid%%&cid=%%cid%%&context={$context}";
         }
         if (is_object($paymentProcessorObj) && $paymentProcessorObj->isSupported('updateSubscriptionBillingInfo')) {
             self::$_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 self::$_links;
 }
 function preProcess()
 {
     $this->_crid = CRM_Utils_Request::retrieve('crid', 'Integer', $this, FALSE);
     if ($this->_crid) {
         $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getProcessorForEntity($this->_crid, 'recur', 'info');
         $this->_paymentProcessorObj = CRM_Core_BAO_PaymentProcessor::getProcessorForEntity($this->_crid, 'recur', 'obj');
         $this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_crid);
     }
     $this->_coid = CRM_Utils_Request::retrieve('coid', 'Integer', $this, FALSE);
     if ($this->_coid) {
         $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'info');
         $this->_paymentProcessorObj = CRM_Core_BAO_PaymentProcessor::getProcessorForEntity($this->_coid, 'contribute', 'obj');
         $this->_subscriptionDetails = CRM_Contribute_BAO_ContributionRecur::getSubscriptionDetails($this->_coid, 'contribution');
     }
     if (!$this->_crid && !$this->_coid || $this->_subscriptionDetails == CRM_Core_DAO::$_nullObject) {
         CRM_Core_Error::fatal('Required information missing.');
     }
     if ($this->_subscriptionDetails->membership_id && $this->_subscriptionDetails->auto_renew) {
         CRM_Core_Error::fatal(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::fatal(ts('You do not have permission to update subscription.'));
         }
         $this->_selfService = TRUE;
     }
     $this->assign('self_service', $this->_selfService);
     if (!$this->_paymentProcessorObj->isSupported('changeSubscriptionAmount')) {
         $userAlert = "<span class='font-red'>" . ts('WARNING: Updates made using this form will change the recurring contribution information stored in your CiviCRM database, but will NOT be sent to the payment processor. You must enter the same changes using the payment processor web site.', array(1 => $this->_paymentProcessorObj->_processorName)) . '</span>';
         CRM_Core_Session::setStatus($userAlert);
     }
     $this->assign('isChangeSupported', $this->_paymentProcessorObj->isSupported('changeSubscriptionAmount'));
     $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();
 }
Beispiel #7
0
 /**
  * Function to process the renewal form
  *
  * @access public
  * @return None
  */
 public function postProcess()
 {
     require_once 'CRM/Member/BAO/Membership.php';
     require_once 'CRM/Member/BAO/MembershipType.php';
     require_once 'CRM/Member/BAO/MembershipStatus.php';
     // get the submitted form values.
     $this->_params = $formValues = $this->controller->exportValues($this->_name);
     $params = array();
     $ids = array();
     $config =& CRM_Core_Config::singleton();
     $params['contact_id'] = $this->_contactID;
     if ($this->_mode) {
         $formValues['total_amount'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'minimum_fee');
         $formValues['contribution_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'contribution_type_id');
         require_once 'CRM/Core/BAO/PaymentProcessor.php';
         $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($formValues['payment_processor_id'], $this->_mode);
         require_once "CRM/Contact/BAO/Contact.php";
         $now = CRM_Utils_Date::getToday($now, 'YmdHis');
         $fields = array();
         // set email for primary location.
         $fields["email-Primary"] = 1;
         $formValues["email-5"] = $formValues["email-Primary"] = $this->_contributorEmail;
         $formValues['register_date'] = $now;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $formValues["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_middle_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_last_name', $formValues);
         $formValues["address_name-{$this->_bltID}"] = trim($formValues["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         $fields["email-{$this->_bltID}"] = 1;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $formValues)) {
                 $formValues[$name] = $formValues["billing_{$name}"];
                 $formValues['preserveDBName'] = true;
             }
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($formValues, $fields, $this->_contactID, null, null, $ctype);
         // add all the additioanl payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = $this->_params['credit_card_exp_date']['Y'];
         $this->_params['month'] = $this->_params['credit_card_exp_date']['M'];
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $formValues['total_amount'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['payment_action'] = 'Sale';
         $this->_params['invoiceID'] = md5(uniqid(rand(), true));
         // 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;
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         require_once 'CRM/Core/Payment/Form.php';
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, true);
         $payment =& CRM_Core_Payment::singleton($this->_mode, 'Contribute', $this->_paymentProcessor, $this);
         $result =& $payment->doDirectPayment($paymentParams);
         if (is_a($result, 'CRM_Core_Error')) {
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=renew&cid={$this->_contactID}&id={$this->_id}&context=membership&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $formValues['contribution_status_id'] = 1;
         $formValues['receive_date'] = $now;
         $formValues['invoice_id'] = $this->_params['invoiceID'];
         $formValues['trxn_id'] = $result['trxn_id'];
         $formValues['payment_instrument_id'] = 1;
         $formValues['is_test'] = $this->_mode == 'live' ? 0 : 1;
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $formValues['receipt_date'] = $now;
         } else {
             $formValues['receipt_date'] = null;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
         $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($formValues['receive_date']));
     }
     $renewalDate = null;
     if ($formValues['renewal_date']) {
         $this->set('renewDate', CRM_Utils_Date::processDate($formValues['renewal_date']));
     }
     $this->_membershipId = $this->_id;
     // check for test membership.
     $isTestMembership = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_membershipId, 'is_test');
     $renewMembership = CRM_Member_BAO_Membership::renewMembership($this->_contactID, $this->_memType, $isTestMembership, $this, null);
     $endDate = CRM_Utils_Date::processDate($renewMembership->end_date);
     require_once 'CRM/Contact/BAO/Contact/Location.php';
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     $session =& CRM_Core_Session::singleton();
     $userID = $session->get('userID');
     list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
     $memType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $renewMembership->membership_type_id, 'name');
     if (CRM_Utils_Array::value('record_contribution', $formValues) || $this->_mode) {
         //building contribution params
         $contributionParams = array();
         $config =& CRM_Core_Config::singleton();
         $contributionParams['currency'] = $config->defaultCurrency;
         $contributionParams['contact_id'] = $params['contact_id'];
         $contributionParams['source'] = "{$memType} Membership: Offline membership renewal (by {$userName})";
         $contributionParams['non_deductible_amount'] = 'null';
         $contributionParams['receive_date'] = date('Y-m-d H:i:s');
         $contributionParams['receipt_date'] = CRM_Utils_Array::value('send_receipt', $formValues) ? $contributionParams['receive_date'] : 'null';
         $recordContribution = array('total_amount', 'contribution_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'invoice_id', 'check_number', 'is_test');
         foreach ($recordContribution as $f) {
             $contributionParams[$f] = CRM_Utils_Array::value($f, $formValues);
         }
         require_once 'CRM/Contribute/BAO/Contribution.php';
         $contribution =& CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
         require_once 'CRM/Member/DAO/MembershipPayment.php';
         $mpDAO =& new CRM_Member_DAO_MembershipPayment();
         $mpDAO->membership_id = $renewMembership->id;
         $mpDAO->contribution_id = $contribution->id;
         $mpDAO->save();
         if ($this->_mode) {
             $trxnParams = array('contribution_id' => $contribution->id, 'trxn_date' => $now, 'trxn_type' => 'Debit', 'total_amount' => $formValues['total_amount'], 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $formValues['total_amount']), 'currency' => $config->defaultCurrency, 'payment_processor' => $this->_paymentProcessor['payment_processor_type'], 'trxn_id' => $result['trxn_id']);
             require_once 'CRM/Contribute/BAO/FinancialTrxn.php';
             $trxn =& CRM_Contribute_BAO_FinancialTrxn::create($trxnParams);
         }
     }
     if (CRM_Utils_Array::value('send_receipt', $formValues)) {
         require_once 'CRM/Core/DAO.php';
         CRM_Core_DAO::setFieldValue('CRM_Member_DAO_MembershipType', CRM_Utils_Array::value('membership_type_id', $params), 'receipt_text_renewal', $formValues['receipt_text_renewal']);
     }
     $receiptSend = false;
     if (CRM_Utils_Array::value('send_receipt', $formValues)) {
         $receiptSend = true;
         // Retrieve the name and email of the contact - this will be the TO for receipt email
         list($this->_contributorDisplayName, $this->_contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
         $receiptFrom = '"' . $userName . '" <' . $userEmail . '>';
         $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
         $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
         //get the group Tree
         $this->_groupTree =& CRM_Core_BAO_CustomGroup::getTree('Membership', $this, $this->_id, false, $this->_memType);
         // retrieve custom data
         require_once "CRM/Core/BAO/UFGroup.php";
         $customFields = $customValues = $fo = array();
         foreach ($this->_groupTree as $groupID => $group) {
             if ($groupID == 'info') {
                 continue;
             }
             foreach ($group['fields'] as $k => $field) {
                 $field['title'] = $field['label'];
                 $customFields["custom_{$k}"] = $field;
             }
         }
         CRM_Core_BAO_UFGroup::getValues($this->_contactID, $customFields, $customValues, false, array(array('member_id', '=', $renewMembership->id, 0, 0)));
         $this->assign_by_ref('formValues', $formValues);
         $this->assign('receive_date', $renewalDate);
         $this->assign('module', 'Membership');
         $this->assign('receiptType', 'membership renewal');
         $this->assign('mem_start_date', CRM_Utils_Date::customFormat($renewMembership->start_date));
         $this->assign('mem_end_date', CRM_Utils_Date::customFormat($renewMembership->end_date));
         $this->assign('membership_name', CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $renewMembership->membership_type_id));
         $this->assign('customValues', $customValues);
         if ($this->_mode) {
             if (CRM_Utils_Array::value('billing_first_name', $this->_params)) {
                 $name = $this->_params['billing_first_name'];
             }
             if (CRM_Utils_Array::value('billing_middle_name', $this->_params)) {
                 $name .= " {$this->_params['billing_middle_name']}";
             }
             if (CRM_Utils_Array::value('billing_last_name', $this->_params)) {
                 $name .= " {$this->_params['billing_last_name']}";
             }
             $this->assign('billingName', $name);
             // assign the address formatted up for display
             $addressParts = array("street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "state_province-{$this->_bltID}", "country-{$this->_bltID}");
             $addressFields = array();
             foreach ($addressParts as $part) {
                 list($n, $id) = explode('-', $part);
                 if (isset($this->_params['billing_' . $part])) {
                     $addressFields[$n] = $this->_params['billing_' . $part];
                 }
             }
             require_once 'CRM/Utils/Address.php';
             $this->assign('address', CRM_Utils_Address::format($addressFields));
             $date = CRM_Utils_Date::format($this->_params['credit_card_exp_date']);
             $date = CRM_Utils_Date::mysqlToIso($date);
             $this->assign('credit_card_exp_date', $date);
             $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($this->_params['credit_card_number']));
             $this->assign('credit_card_type', $this->_params['credit_card_type']);
             $this->assign('contributeMode', 'direct');
             $this->assign('isAmountzero', 0);
             $this->assign('is_pay_later', 0);
             $this->assign('isPrimary', 1);
             if ($this->_mode == 'test') {
                 $this->assign('action', '1024');
             }
         }
         require_once 'CRM/Core/BAO/MessageTemplates.php';
         list($mailSend, $subject, $message, $html) = CRM_Core_BAO_MessageTemplates::sendTemplate(array('groupName' => 'msg_tpl_workflow_membership', 'valueName' => 'membership_offline_receipt', 'contactId' => $this->_contactID, 'from' => $receiptFrom, 'toName' => $this->_contributorDisplayName, 'toEmail' => $this->_contributorEmail, 'isTest' => $this->_mode == 'test'));
     }
     $statusMsg = ts('%1 membership for %2 has been renewed.', array(1 => $memType, 2 => $this->_contributorDisplayName));
     $endDate = CRM_Utils_Date::customFormat(CRM_Core_DAO::getFieldValue("CRM_Member_DAO_Membership", $this->_id, "end_date"));
     if ($endDate) {
         $statusMsg .= ' ' . ts('The new membership End Date is %1.', array(1 => $endDate));
     }
     if ($receiptSend && $mailSend) {
         $statusMsg .= ' ' . ts('A renewal confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
     }
     CRM_Core_Session::setStatus($statusMsg);
 }
 static function getPaymentProcessor($id, $mode)
 {
     $sql = "\nSELECT p.payment_processor_id\n  FROM civicrm_contribution c,\n       civicrm_contribution_recur r,\n       civicrm_contribution_page  p\n WHERE c.contribution_recur_id = %1\n   AND c.contribution_page_id  = p.id\n   AND p.payment_processor_id is not null\n LIMIT 1";
     $params = array(1 => array($id, 'Integer'));
     $paymentProcessorID =& CRM_Core_DAO::singleValueQuery($sql, $params);
     if (!$paymentProcessorID) {
         return null;
     }
     require_once 'CRM/Core/BAO/PaymentProcessor.php';
     return CRM_Core_BAO_PaymentProcessor::getPayment($paymentProcessorID, $mode);
 }
 /**
  * Function to check whether payment processor supports 
  * cancellation of membership subscription
  *
  * @param int $mid membership id
  * 
  * @return boolean
  * @access public
  * @static
  */
 static function isCancelSubscriptionSupported($mid, $isNotCancelled = true)
 {
     $cacheKeyString = "{$mid}";
     $cacheKeyString .= $isNotCancelled ? "_1" : "_0";
     static $supportsCancel = array();
     if (!array_key_exists($cacheKeyString, $supportsCancel)) {
         $supportsCancel[$cacheKeyString] = false;
         $isCancelled = false;
         if ($isNotCancelled) {
             $isCancelled = self::isSubscriptionCancelled($mid);
         }
         require_once 'CRM/Core/BAO/PaymentProcessor.php';
         require_once 'CRM/Core/Payment.php';
         $paymentObject = CRM_Core_BAO_PaymentProcessor::getProcessorForEntity($mid, 'membership', 'obj');
         if (!empty($paymentObject)) {
             $supportsCancel[$cacheKeyString] = CRM_Core_Payment::isCancelSupported($paymentObject) && !$isCancelled;
         }
     }
     return $supportsCancel[$cacheKeyString];
 }
 /**
  * Function to process the form
  *
  * @access public
  *
  * @return None
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         CRM_Member_BAO_Membership::deleteRelatedMemberships($this->_id);
         CRM_Member_BAO_Membership::deleteMembership($this->_id);
         return;
     }
     $config = CRM_Core_Config::singleton();
     // get the submitted form values.
     $this->_params = $formValues = $this->controller->exportValues($this->_name);
     $params = $ids = array();
     $membershipTypeValues = array();
     foreach ($this->_memTypeSelected as $memType) {
         $membershipTypeValues[$memType]['membership_type_id'] = $memType;
     }
     //take the required membership recur values.
     if ($this->_mode && CRM_Utils_Array::value('auto_renew', $this->_params)) {
         $params['is_recur'] = $this->_params['is_recur'] = $formValues['is_recur'] = TRUE;
         $mapping = array('frequency_interval' => 'duration_interval', 'frequency_unit' => 'duration_unit');
         $count = 0;
         foreach ($this->_memTypeSelected as $memType) {
             $recurMembershipTypeValues = CRM_Utils_Array::value($memType, $this->_recurMembershipTypes, array());
             foreach ($mapping as $mapVal => $mapParam) {
                 $membershipTypeValues[$memType][$mapVal] = CRM_Utils_Array::value($mapParam, $recurMembershipTypeValues);
                 if (!$count) {
                     $this->_params[$mapVal] = $formValues[$mapVal] = CRM_Utils_Array::value($mapParam, $recurMembershipTypeValues);
                 }
             }
             $count++;
         }
         // unset send-receipt option, since receipt will be sent when ipn is received.
         unset($this->_params['send_receipt'], $formValues['send_receipt']);
     }
     // process price set and get total amount and line items.
     $lineItem = array();
     $priceSetId = NULL;
     if (!($priceSetId = CRM_Utils_Array::value('price_set_id', $formValues))) {
         CRM_Member_BAO_Membership::createLineItems($this, $formValues['membership_type_id'], $priceSetId);
     }
     if ($priceSetId) {
         CRM_Price_BAO_Set::processAmount($this->_priceSet['fields'], $this->_params, $lineItem[$priceSetId]);
         $params['total_amount'] = CRM_Utils_Array::value('amount', $this->_params);
     }
     $this->storeContactFields($formValues);
     $params['contact_id'] = $this->_contactID;
     $fields = array('status_id', 'source', 'is_override', 'campaign_id');
     foreach ($fields as $f) {
         $params[$f] = CRM_Utils_Array::value($f, $formValues);
     }
     // fix for CRM-3724
     // when is_override false ignore is_admin statuses during membership
     // status calculation. similarly we did fix for import in CRM-3570.
     if (!CRM_Utils_Array::value('is_override', $params)) {
         $params['exclude_is_admin'] = TRUE;
     }
     // process date params to mysql date format.
     $dateTypes = array('join_date' => 'joinDate', 'start_date' => 'startDate', 'end_date' => 'endDate');
     foreach ($dateTypes as $dateField => $dateVariable) {
         ${$dateVariable} = CRM_Utils_Date::processDate($formValues[$dateField]);
     }
     $dates = array('join_date', 'start_date', 'end_date', 'reminder_date');
     $calcDates = array();
     foreach ($this->_memTypeSelected as $memType) {
         $calcDates[$memType] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($memType, $joinDate, $startDate, $endDate);
     }
     foreach ($calcDates as $memType => $calcDate) {
         foreach ($dates as $d) {
             //first give priority to form values then calDates.
             $date = CRM_Utils_Array::value($d, $formValues);
             if (!$date) {
                 $date = CRM_Utils_Array::value($d, $calcDate);
             }
             $membershipTypeValues[$memType][$d] = CRM_Utils_Date::processDate($date);
             //$params[$d] = CRM_Utils_Date::processDate( $date );
         }
     }
     if ($this->_id) {
         $ids['membership'] = $params['id'] = $this->_id;
     }
     $session = CRM_Core_Session::singleton();
     $ids['userId'] = $session->get('userID');
     // membership type custom data
     foreach ($this->_memTypeSelected as $memType) {
         $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $memType);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, NULL, NULL, TRUE));
         $membershipTypeValues[$memType]['custom'] = CRM_Core_BAO_CustomField::postProcess($formValues, $customFields, $this->_id, 'Membership');
     }
     foreach ($this->_memTypeSelected as $memType) {
         $membershipTypes[$memType] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $memType);
     }
     $membershipType = implode(', ', $membershipTypes);
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($ids['userId']);
     //CRM-10223 - allow contribution to be recorded against different contact
     if ($this->_contributorContactID != $this->_contactID) {
         $params['contribution_contact_id'] = $this->_contributorContactID;
         if (CRM_Utils_Array::value('honor_type_id', $this->_params)) {
             $params['honor_type_id'] = $this->_params['honor_type_id'];
             $params['honor_contact_id'] = $params['contact_id'];
         }
     }
     if (CRM_Utils_Array::value('record_contribution', $formValues)) {
         $recordContribution = array('total_amount', 'honor_type_id', 'contribution_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'check_number', 'campaign_id', 'receive_date');
         foreach ($recordContribution as $f) {
             $params[$f] = CRM_Utils_Array::value($f, $formValues);
         }
         if (!$this->_onlinePendingContributionId) {
             $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)', array(1 => $membershipType, 2 => $userName));
         }
         if (!CRM_Utils_Array::value('is_override', $params) && CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'))) {
             $allStatus = CRM_Member_PseudoConstant::membershipStatus();
             $params['status_id'] = array_search('Pending', $allStatus);
             $params['skipStatusCal'] = TRUE;
             $params['is_pay_later'] = 1;
             $this->assign('is_pay_later', 1);
         }
         if (CRM_Utils_Array::value('receive_date', $params)) {
             $formValues['receive_date'] = $params['receive_date'] = CRM_Utils_Date::processDate($params['receive_date']);
         }
         if (CRM_Utils_Array::value('send_receipt', $formValues)) {
             $params['receipt_date'] = CRM_Utils_Array::value('receive_date', $params);
         }
         //insert contribution type name in receipt.
         $formValues['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionType', $formValues['contribution_type_id']);
     }
     // process line items, until no previous line items.
     if (!empty($lineItem)) {
         $params['lineItems'] = $lineItem;
         $params['processPriceSet'] = TRUE;
     }
     //crm_core_error::debug('params', $params );
     //crm_core_error::debug('formValue', $formValues );
     //exit;
     $createdMemberships = array();
     if ($this->_mode) {
         if (empty($formValues['total_amount']) && !$priceSetId) {
             // if total amount not provided minimum for membership type is used
             $params['total_amount'] = $formValues['total_amount'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $formValues['membership_type_id'][1], 'minimum_fee');
         } else {
             $params['total_amount'] = CRM_Utils_Array::value('total_amount', $formValues, 0);
         }
         if ($priceSetId) {
             $params['contribution_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', $priceSetId, 'contribution_type_id');
         } else {
             $params['contribution_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', end($this->_memTypeSelected), 'contribution_type_id');
         }
         $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($formValues['payment_processor_id'], $this->_mode);
         //get the payment processor id as per mode.
         $params['payment_processor_id'] = $this->_params['payment_processor_id'] = $formValues['payment_processor_id'] = $this->_paymentProcessor['id'];
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields["email-Primary"] = 1;
         $formValues["email-5"] = $formValues["email-Primary"] = $this->_memberEmail;
         $params['register_date'] = $now;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $formValues["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_middle_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_last_name', $formValues);
         $formValues["address_name-{$this->_bltID}"] = trim($formValues["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         $fields["email-{$this->_bltID}"] = 1;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $formValues)) {
                 $formValues[$name] = $formValues["billing_{$name}"];
                 $formValues['preserveDBName'] = TRUE;
             }
         }
         //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($formValues, $fields, $this->_contributorContactID, NULL, NULL, $ctype);
         // add all the additioanl payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
         $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $params['total_amount'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['payment_action'] = 'Sale';
         $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
         $this->_params['contribution_type_id'] = $params['contribution_type_id'];
         // 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->_contributorContactID;
         //CRM-10377 if payment is by an alternate contact then we need to set that person
         // as the contact in the payment params
         if ($this->_contributorContactID != $this->_contactID) {
             if (CRM_Utils_Array::value('honor_type_id', $this->_params)) {
                 $paymentParams['honor_contact_id'] = $this->_contactID;
                 $paymentParams['honor_type_id'] = $this->_params['honor_type_id'];
             }
         }
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
         // CRM-7137 -for recurring membership,
         // we do need contribution and recuring records.
         $result = NULL;
         if (CRM_Utils_Array::value('is_recur', $paymentParams)) {
             $allStatus = CRM_Member_PseudoConstant::membershipStatus();
             $contributionType = new CRM_Contribute_DAO_ContributionType();
             $contributionType->id = $params['contribution_type_id'];
             if (!$contributionType->find(TRUE)) {
                 CRM_Core_Error::fatal('Could not find a system table');
             }
             $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $paymentParams, $result, $this->_contributorContactID, $contributionType, FALSE, TRUE, FALSE);
             $paymentParams['contributionID'] = $contribution->id;
             $paymentParams['contributionTypeID'] = $contribution->contribution_type_id;
             $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
             $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
             $ids['contribution'] = $contribution->id;
             $params['contribution_recur_id'] = $paymentParams['contributionRecurID'];
             $params['status_id'] = array_search('Pending', $allStatus);
             $params['skipStatusCal'] = TRUE;
             //as membership is pending set dates to null.
             $memberDates = array('join_date' => 'joinDate', 'start_date' => 'startDate', 'end_date' => 'endDate');
             foreach ($memberDates as $dp => $dv) {
                 ${$dv} = NULL;
                 foreach ($this->_memTypeSelected as $memType) {
                     $membershipTypeValues[$memType][$dv] = NULL;
                 }
             }
         }
         if ($params['total_amount'] > 0.0) {
             $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
             $result =& $payment->doDirectPayment($paymentParams);
         }
         if (is_a($result, 'CRM_Core_Error')) {
             //make sure to cleanup db for recurring case.
             if (CRM_Utils_Array::value('contributionID', $paymentParams)) {
                 CRM_Contribute_BAO_Contribution::deleteContribution($paymentParams['contributionID']);
             }
             if (CRM_Utils_Array::value('contributionRecurID', $paymentParams)) {
                 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
             }
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=add&cid={$this->_contactID}&context=&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
             //assign amount to template if payment was successful
             $this->assign('amount', $params['total_amount']);
         }
         $params['contribution_status_id'] = CRM_Utils_Array::value('is_recur', $paymentParams) ? 2 : 1;
         $params['receive_date'] = $now;
         $params['invoice_id'] = $this->_params['invoiceID'];
         $params['contribution_source'] = ts('%1 Membership Signup: Credit card or direct debit (by %2)', array(1 => $membershipType, 2 => $userName));
         $params['source'] = $formValues['source'] ? $formValues['source'] : $params['contribution_source'];
         $params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
         $params['payment_instrument_id'] = 1;
         $params['is_test'] = $this->_mode == 'live' ? 0 : 1;
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $params['receipt_date'] = $now;
         } else {
             $params['receipt_date'] = NULL;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $result));
         $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($params['receive_date']));
         // required for creating membership for related contacts
         $params['action'] = $this->_action;
         //create membership record.
         $count = 0;
         foreach ($this->_memTypeSelected as $memType) {
             if ($count && ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))) {
                 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
             }
             $membershipParams = array_merge($membershipTypeValues[$memType], $params);
             $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
             $this->_membershipIDs[] = $membership->id;
             $createdMemberships[$memType] = $membership;
             $count++;
         }
         if (!CRM_Utils_Array::value('is_recur', $params) && $params['total_amount'] > 0.0) {
             $contribution = new CRM_Contribute_BAO_Contribution();
             $contribution->trxn_id = CRM_Utils_Array::value('trxn_id', $result);
             if ($contribution->find(TRUE)) {
                 // next create the transaction record
                 $trxnParams = array('contribution_id' => $contribution->id, 'trxn_date' => $now, 'trxn_type' => 'Debit', 'total_amount' => $params['total_amount'], 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['total_amount']), 'currency' => $config->defaultCurrency, 'payment_processor' => $this->_paymentProcessor['payment_processor_type'], 'trxn_id' => CRM_Utils_Array::value('trxn_id', $result));
                 $trxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
             }
         }
     } else {
         $params['action'] = $this->_action;
         if ($this->_onlinePendingContributionId && CRM_Utils_Array::value('record_contribution', $formValues)) {
             // update membership as well as contribution object, CRM-4395
             $params['contribution_id'] = $this->_onlinePendingContributionId;
             $params['componentId'] = $params['id'];
             $params['componentName'] = 'contribute';
             $result = CRM_Contribute_BAO_Contribution::transitionComponents($params, TRUE);
             if (!empty($result) && CRM_Utils_Array::value('contribution_id', $params)) {
                 $lineItem = array();
                 $lineItems = CRM_Price_BAO_LineItem::getLineItems($params['contribution_id'], 'contribution');
                 $itemId = key($lineItems);
                 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Field', $lineItems[$itemId]['price_field_id'], 'price_set_id');
                 $fieldType = NULL;
                 if ($itemId && CRM_Utils_Array::value('price_field_id', $lineItems[$itemId])) {
                     $fieldType = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Field', $lineItems[$itemId]['price_field_id'], 'html_type');
                 }
                 $lineItems[$itemId]['unit_price'] = $params['total_amount'];
                 $lineItems[$itemId]['line_total'] = $params['total_amount'];
                 $lineItems[$itemId]['id'] = $itemId;
                 $lineItem[$priceSetId] = $lineItems;
                 CRM_Contribute_Form_AdditionalInfo::processPriceSet($params['contribution_id'], $lineItem);
             }
             //carry updated membership object.
             $membership = new CRM_Member_DAO_Membership();
             $membership->id = $this->_id;
             $membership->find(TRUE);
             $cancelled = TRUE;
             if ($membership->end_date) {
                 //display end date w/ status message.
                 $endDate = $membership->end_date;
                 $membershipStatues = CRM_Member_PseudoConstant::membershipStatus();
                 if (!in_array($membership->status_id, array(array_search('Cancelled', $membershipStatues), array_search('Expired', $membershipStatues)))) {
                     $cancelled = FALSE;
                 }
             }
             // suppress form values in template.
             $this->assign('cancelled', $cancelled);
             // FIX ME: need to recheck this
             // here we might updated dates, so get from object.
             foreach ($calcDates[$membership->membership_type_id] as $date => &$val) {
                 if ($membership->{$date}) {
                     $val = $membership->{$date};
                 }
             }
             $createdMemberships[] = $membership;
         } else {
             $count = 0;
             foreach ($this->_memTypeSelected as $memType) {
                 if ($count && CRM_Utils_Array::value('record_contribution', $formValues) && ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))) {
                     $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
                 }
                 $membershipParams = array_merge($params, $membershipTypeValues[$memType]);
                 $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
                 $this->_membershipIDs[] = $membership->id;
                 $createdMemberships[$memType] = $membership;
                 $count++;
             }
         }
     }
     if (!empty($lineItem)) {
         foreach ($lineItem[$priceSetId] as &$priceFieldOp) {
             if (CRM_Utils_Array::value('membership_type_id', $priceFieldOp)) {
                 $priceFieldOp['start_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'], '%d%f %b, %Y') : '-';
                 $priceFieldOp['end_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'], '%d%f %b, %Y') : '-';
             } else {
                 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
             }
         }
     }
     $isQuickConfig = 0;
     if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', $this->_priceSetId, 'is_quick_config')) {
         $isQuickConfig = 1;
     }
     $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
     $receiptSend = FALSE;
     if (CRM_Utils_Array::value('send_receipt', $formValues)) {
         $receiptSend = TRUE;
         $formValues['contact_id'] = $this->_contactID;
         // send email receipt
         $mailSend = self::emailReceipt($this, $formValues, $membership);
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         //end date can be modified by hooks, so if end date is set then use it.
         $endDate = $membership->end_date ? $membership->end_date : $endDate;
         $statusMsg = ts('Membership for %1 has been updated.', array(1 => $this->_memberDisplayName));
         if ($endDate && $endDate !== 'null') {
             $endDate = CRM_Utils_Date::customFormat($endDate);
             $statusMsg .= ' ' . ts('The membership End Date is %1.', array(1 => $endDate));
         }
         if ($receiptSend) {
             $statusMsg .= ' ' . ts('A confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
         }
     } elseif ($this->_action & CRM_Core_Action::ADD) {
         // FIX ME: fix status messages
         $statusMsg = array();
         foreach ($membershipTypes as $memType => $membershipType) {
             $statusMsg[$memType] = ts('%1 membership for %2 has been added.', array(1 => $membershipType, 2 => $this->_memberDisplayName));
             $membership = $createdMemberships[$memType];
             $memEndDate = $membership->end_date ? $membership->end_date : $endDate;
             //get the end date from calculated dates.
             if (!$memEndDate && !CRM_Utils_Array::value('is_recur', $params)) {
                 $memEndDate = CRM_Utils_Array::value('end_date', $calcDates[$memType]);
             }
             if ($memEndDate && $memEndDate !== 'null') {
                 $memEndDate = CRM_Utils_Date::customFormat($memEndDate);
                 $statusMsg[$memType] .= ' ' . ts('The new membership End Date is %1.', array(1 => $memEndDate));
             }
         }
         $statusMsg = implode('<br/>', $statusMsg);
         if ($receiptSend && $mailSend) {
             $statusMsg .= '<br/>' . ts('A membership confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
         }
     }
     // finally set membership id if already not set
     if (!$this->_id) {
         $this->_id = $membership->id;
     }
     CRM_Core_Session::setStatus($statusMsg);
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/member/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=member"));
         }
     } elseif ($buttonName == $this->getButtonName('upload', 'new')) {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=add&context=membership&cid={$this->_contactID}"));
     }
 }
 /**
  * Payment callback handler
  * Load requested payment processor and call that processor's handle<$method> method
  *
  * @public
  */
 static function handlePaymentMethod($method, $params = array())
 {
     if (!isset($params['processor_name'])) {
         CRM_Core_Error::fatal("Missing 'processor_name' param for payment callback");
     }
     // Query db for processor ..
     $mode = @$params['mode'];
     $dao = CRM_Core_DAO::executeQuery("\n             SELECT ppt.class_name, ppt.name as processor_name, pp.id AS processor_id\n               FROM civicrm_payment_processor_type ppt\n         INNER JOIN civicrm_payment_processor pp\n                 ON pp.payment_processor_type = ppt.name\n                AND pp.is_active\n                AND pp.is_test = %1\n              WHERE ppt.name = %2 \n        ", array(1 => array($mode == 'test' ? 1 : 0, 'Integer'), 2 => array($params['processor_name'], 'String')));
     // Check whether we found anything at all ..
     if (!$dao->N) {
         CRM_Core_Error::fatal("No active instances of the '{$params['processor_name']}' payment processor were found.");
     }
     $method = 'handle' . $method;
     $extension_instance_found = FALSE;
     // In all likelihood, we'll just end up with the one instance returned here. But it's
     // possible we may get more. Hence, iterate through all instances ..
     while ($dao->fetch()) {
         // Check pp is extension
         $ext = new CRM_Core_Extensions();
         if ($ext->isExtensionKey($dao->class_name)) {
             $extension_instance_found = TRUE;
             $paymentClass = $ext->keyToClass($dao->class_name, 'payment');
             require_once $ext->classToPath($paymentClass);
         } else {
             // Legacy instance - but there may also be an extension instance, so
             // continue on to the next instance and check that one. We'll raise an
             // error later on if none are found.
             continue;
         }
         $paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($dao->processor_id, $mode);
         // Should never be empty - we already established this processor_id exists and is active.
         if (empty($paymentProcessor)) {
             continue;
         }
         // Instantiate PP
         eval('$processorInstance = ' . $paymentClass . '::singleton( $mode, $paymentProcessor );');
         // Does PP implement this method, and can we call it?
         if (!method_exists($processorInstance, $method) || !is_callable(array($processorInstance, $method))) {
             // No? This will be the case in all instances, so let's just die now
             // and not prolong the agony.
             CRM_Core_Error::fatal("Payment processor does not implement a '{$method}' method");
         }
         // Everything, it seems, is ok - execute pp callback handler
         $processorInstance->{$method}();
     }
     if (!$extension_instance_found) {
         CRM_Core_Error::fatal("No extension instances of the '{$params['processor_name']}' payment processor were found.<br />" . "{$method} method is unsupported in legacy payment processors.");
     }
     // Exit here on web requests, allowing just the plain text response to be echoed
     if ($method == 'handlePaymentNotification') {
         CRM_Utils_System::civiExit();
     }
 }
 function checkMD5($ids, $input)
 {
     $paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($ids['paymentProcessor'], $input['is_test'] ? 'test' : 'live');
     $paymentObject =& CRM_Core_Payment::singleton($input['is_test'] ? 'test' : 'live', $paymentProcessor);
     if (!$paymentObject->checkMD5($input['MD5_Hash'], $input['trxn_id'], $input['amount'], true)) {
         CRM_Core_Error::debug_log_message("MD5 Verification failed.");
         echo "Failure: Security verification failed<p>";
         exit;
     }
     return true;
 }
Beispiel #13
0
 /**
  * retrieve the default payment processor
  * 
  * @param NULL
  * 
  * @return object           The default payment processor object on success,
  *                          null otherwise
  * @static
  * @access public
  */
 static function &getDefault()
 {
     if (self::$_defaultPaymentProcessor == null) {
         $params = array('is_default' => 1);
         $defaults = array();
         self::$_defaultPaymentProcessor = self::retrieve($params, $defaults);
     }
     return self::$_defaultPaymentProcessor;
 }
Beispiel #14
0
 /**
  * Function to process the form
  *
  * @access public
  * @return None
  */
 public function postProcess()
 {
     require_once 'CRM/Member/BAO/Membership.php';
     require_once 'CRM/Member/BAO/MembershipType.php';
     require_once 'CRM/Member/BAO/MembershipStatus.php';
     if ($this->_action & CRM_Core_Action::DELETE) {
         CRM_Member_BAO_Membership::deleteRelatedMemberships($this->_id);
         CRM_Member_BAO_Membership::deleteMembership($this->_id);
         return;
     }
     $config =& CRM_Core_Config::singleton();
     // get the submitted form values.
     $this->_params = $formValues = $this->controller->exportValues($this->_name);
     $params = array();
     $ids = array();
     // set the contact, when contact is selected
     if (CRM_Utils_Array::value('contact_select_id', $formValues)) {
         $this->_contactID = CRM_Utils_Array::value('contact_select_id', $formValues);
     }
     $params['contact_id'] = $this->_contactID;
     // we need to retrieve email address
     if ($this->_context == 'standalone' && CRM_Utils_Array::value('send_receipt', $formValues)) {
         require_once 'CRM/Contact/BAO/Contact/Location.php';
         list($this->_contributorDisplayName, $this->_contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
     }
     $fields = array('status_id', 'source', 'is_override');
     foreach ($fields as $f) {
         $params[$f] = CRM_Utils_Array::value($f, $formValues);
     }
     // fix for CRM-3724
     // when is_override false ignore is_admin statuses during membership
     // status calculation. similarly we did fix for import in CRM-3570.
     if (!CRM_Utils_Array::value('is_override', $params)) {
         $params['exclude_is_admin'] = true;
     }
     $params['membership_type_id'] = $formValues['membership_type_id'][1];
     $joinDate = CRM_Utils_Date::processDate($formValues['join_date']);
     $startDate = CRM_Utils_Date::processDate($formValues['start_date']);
     $endDate = CRM_Utils_Date::processDate($formValues['end_date']);
     $calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($params['membership_type_id'], $joinDate, $startDate, $endDate);
     $dates = array('join_date', 'start_date', 'end_date', 'reminder_date', 'receive_date');
     $currentTime = getDate();
     foreach ($dates as $d) {
         if (isset($formValues[$d]) && !CRM_Utils_System::isNull($formValues[$d])) {
             $params[$d] = CRM_Utils_Date::processDate($formValues[$d]);
         } else {
             if (isset($calcDates[$d])) {
                 $params[$d] = CRM_Utils_Date::processDate($calcDates[$d]);
             }
         }
     }
     if ($this->_id) {
         $ids['membership'] = $params['id'] = $this->_id;
     }
     $session = CRM_Core_Session::singleton();
     $ids['userId'] = $session->get('userID');
     // membership type custom data
     $customFields = CRM_Core_BAO_CustomField::getFields('Membership', false, false, CRM_Utils_Array::value('membership_type_id', $params));
     $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Membership', false, false, null, null, true));
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($formValues, $customFields, $this->_id, 'Membership');
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     require_once 'CRM/Contact/BAO/Contact/Location.php';
     list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($ids['userId']);
     if (CRM_Utils_Array::value('record_contribution', $formValues)) {
         $recordContribution = array('total_amount', 'contribution_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'check_number');
         foreach ($recordContribution as $f) {
             $params[$f] = CRM_Utils_Array::value($f, $formValues);
         }
         $membershipType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $formValues['membership_type_id'][1]);
         if (!$this->_onlinePendingContributionId) {
             $params['contribution_source'] = "{$membershipType} Membership: Offline membership signup (by {$userName})";
         }
         if ($formValues['send_receipt']) {
             $params['receipt_date'] = $params['receive_date'];
         }
         //insert contribution type name in receipt.
         $formValues['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionType', $formValues['contribution_type_id']);
     }
     if ($this->_mode) {
         $params['total_amount'] = $formValues['total_amount'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $params['membership_type_id'], 'minimum_fee');
         $params['contribution_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $params['membership_type_id'], 'contribution_type_id');
         require_once 'CRM/Core/BAO/PaymentProcessor.php';
         $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($formValues['payment_processor_id'], $this->_mode);
         require_once "CRM/Contact/BAO/Contact.php";
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields["email-Primary"] = 1;
         $formValues["email-5"] = $formValues["email-Primary"] = $this->_contributorEmail;
         $params['register_date'] = $now;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $formValues["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_middle_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_last_name', $formValues);
         $formValues["address_name-{$this->_bltID}"] = trim($formValues["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         $fields["email-{$this->_bltID}"] = 1;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $formValues)) {
                 $formValues[$name] = $formValues["billing_{$name}"];
                 $formValues['preserveDBName'] = true;
             }
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($formValues, $fields, $this->_contactID, null, null, $ctype);
         // add all the additioanl payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = $this->_params['credit_card_exp_date']['Y'];
         $this->_params['month'] = $this->_params['credit_card_exp_date']['M'];
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $params['total_amount'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['payment_action'] = 'Sale';
         $this->_params['invoiceID'] = md5(uniqid(rand(), true));
         // 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;
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         require_once 'CRM/Core/Payment/Form.php';
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, true);
         $payment =& CRM_Core_Payment::singleton($this->_mode, 'Contribute', $this->_paymentProcessor, $this);
         $result =& $payment->doDirectPayment($paymentParams);
         if (is_a($result, 'CRM_Core_Error')) {
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=add&cid={$this->_contactID}&context=&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $params['contribution_status_id'] = 1;
         $params['receive_date'] = $now;
         $params['invoice_id'] = $this->_params['invoiceID'];
         $params['contribution_source'] = ts('Online Membership: Admin Interface');
         $params['source'] = $formValues['source'] ? $formValues['source'] : $params['contribution_source'];
         $params['trxn_id'] = $result['trxn_id'];
         $params['payment_instrument_id'] = 1;
         $params['is_test'] = $this->_mode == 'live' ? 0 : 1;
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $params['receipt_date'] = $now;
         } else {
             $params['receipt_date'] = null;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
         $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($params['receive_date']));
         // required for creating membership for related contacts
         $params['action'] = $this->_action;
         $membership =& CRM_Member_BAO_Membership::create($params, $ids);
         $contribution = new CRM_Contribute_BAO_Contribution();
         $contribution->trxn_id = $result['trxn_id'];
         if ($contribution->find(true)) {
             // next create the transaction record
             $trxnParams = array('contribution_id' => $contribution->id, 'trxn_date' => $now, 'trxn_type' => 'Debit', 'total_amount' => $params['total_amount'], 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['total_amount']), 'currency' => $config->defaultCurrency, 'payment_processor' => $this->_paymentProcessor['payment_processor_type'], 'trxn_id' => $result['trxn_id']);
             require_once 'CRM/Contribute/BAO/FinancialTrxn.php';
             $trxn =& CRM_Contribute_BAO_FinancialTrxn::create($trxnParams);
         }
     } else {
         $params['action'] = $this->_action;
         if ($this->_onlinePendingContributionId && CRM_Utils_Array::value('record_contribution', $formValues)) {
             // update membership as well as contribution object, CRM-4395
             require_once 'CRM/Contribute/Form/Contribution.php';
             $params['contribution_id'] = $this->_onlinePendingContributionId;
             $params['componentId'] = $params['id'];
             $params['componentName'] = 'contribute';
             $result = CRM_Contribute_BAO_Contribution::transitionComponents($params, true);
             //carry updated membership object.
             $membership =& new CRM_Member_DAO_Membership();
             $membership->id = $this->_id;
             $membership->find(true);
             $cancelled = true;
             if ($membership->end_date) {
                 //display end date w/ status message.
                 $endDate = $membership->end_date;
                 require_once 'CRM/Member/PseudoConstant.php';
                 $membershipStatues = CRM_Member_PseudoConstant::membershipStatus();
                 if (!in_array($membership->status_id, array(array_search('Cancelled', $membershipStatues), array_search('Expired', $membershipStatues)))) {
                     $cancelled = false;
                 }
             }
             // suppress form values in template.
             $this->assign('cancelled', $cancelled);
         } else {
             $membership =& CRM_Member_BAO_Membership::create($params, $ids);
         }
     }
     if (CRM_Utils_Array::value('send_receipt', $formValues)) {
         require_once 'CRM/Core/DAO.php';
         CRM_Core_DAO::setFieldValue('CRM_Member_DAO_MembershipType', $params['membership_type_id'], 'receipt_text_signup', $formValues['receipt_text_signup']);
     }
     $receiptSend = false;
     if (CRM_Utils_Array::value('send_receipt', $formValues)) {
         $receiptSend = true;
         $receiptFrom = "{$userName} <{$userEmail}>";
         if (CRM_Utils_Array::value('payment_instrument_id', $formValues)) {
             $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
             $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
         }
         // retrieve custom data
         require_once "CRM/Core/BAO/UFGroup.php";
         $customFields = $customValues = array();
         foreach ($this->_groupTree as $groupID => $group) {
             if ($groupID == 'info') {
                 continue;
             }
             foreach ($group['fields'] as $k => $field) {
                 $field['title'] = $field['label'];
                 $customFields["custom_{$k}"] = $field;
             }
         }
         $members = array(array('member_id', '=', $membership->id, 0, 0));
         // check whether its a test drive
         if ($this->_mode) {
             $members[] = array('member_test', '=', 1, 0, 0);
         }
         CRM_Core_BAO_UFGroup::getValues($this->_contactID, $customFields, $customValues, false, $members);
         if ($this->_mode) {
             if (CRM_Utils_Array::value('billing_first_name', $this->_params)) {
                 $name = $this->_params['billing_first_name'];
             }
             if (CRM_Utils_Array::value('billing_middle_name', $this->_params)) {
                 $name .= " {$this->_params['billing_middle_name']}";
             }
             if (CRM_Utils_Array::value('billing_last_name', $this->_params)) {
                 $name .= " {$this->_params['billing_last_name']}";
             }
             $this->assign('billingName', $name);
             // assign the address formatted up for display
             $addressParts = array("street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "state_province-{$this->_bltID}", "country-{$this->_bltID}");
             $addressFields = array();
             foreach ($addressParts as $part) {
                 list($n, $id) = explode('-', $part);
                 if (isset($this->_params['billing_' . $part])) {
                     $addressFields[$n] = $this->_params['billing_' . $part];
                 }
             }
             require_once 'CRM/Utils/Address.php';
             $this->assign('address', CRM_Utils_Address::format($addressFields));
             $date = CRM_Utils_Date::format($this->_params['credit_card_exp_date']);
             $date = CRM_Utils_Date::mysqlToIso($date);
             $this->assign('credit_card_exp_date', $date);
             $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($this->_params['credit_card_number']));
             $this->assign('credit_card_type', $this->_params['credit_card_type']);
             $this->assign('contributeMode', 'direct');
             $this->assign('isAmountzero', 0);
             $this->assign('is_pay_later', 0);
             $this->assign('isPrimary', 1);
         }
         $this->assign('module', 'Membership');
         $this->assign('contactID', $this->_contactID);
         $this->assign('membershipID', $params['membership_id']);
         $this->assign('receiptType', 'membership signup');
         $this->assign('receive_date', $params['receive_date']);
         $this->assign('formValues', $formValues);
         $this->assign('mem_start_date', CRM_Utils_Date::customFormat($calcDates['start_date']));
         $this->assign('mem_end_date', CRM_Utils_Date::customFormat($calcDates['end_date']));
         $this->assign('membership_name', CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $formValues['membership_type_id'][1]));
         $this->assign('customValues', $customValues);
         require_once 'CRM/Core/BAO/MessageTemplates.php';
         list($mailSend, $subject, $message, $html) = CRM_Core_BAO_MessageTemplates::sendTemplate(array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'contribution_offline_receipt', 'contactId' => $this->_contactID, 'from' => $receiptFrom, 'toName' => $this->_contributorDisplayName, 'toEmail' => $this->_contributorEmail, 'isTest' => (bool) ($this->_action & CRM_Core_Action::PREVIEW)));
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $statusMsg = ts('Membership for %1 has been updated.', array(1 => $this->_contributorDisplayName));
         if ($endDate) {
             $endDate = CRM_Utils_Date::customFormat($endDate);
             $statusMsg .= ' ' . ts('The membership End Date is %1.', array(1 => $endDate));
         }
         if ($receiptSend) {
             $statusMsg .= ' ' . ts('A confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
         }
     } elseif ($this->_action & CRM_Core_Action::ADD) {
         require_once 'CRM/Core/DAO.php';
         $memType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $params['membership_type_id']);
         $statusMsg = ts('%1 membership for %2 has been added.', array(1 => $memType, 2 => $this->_contributorDisplayName));
         //get the end date from calculated dates.
         $endDate = $endDate ? $endDate : CRM_Utils_Array::value('end_date', $calcDates);
         if ($endDate) {
             $endDate = CRM_Utils_Date::customFormat($endDate);
             $statusMsg .= ' ' . ts('The new membership End Date is %1.', array(1 => $endDate));
         }
         if ($receiptSend && $mailSend) {
             $statusMsg .= ' ' . ts('A membership confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
         }
     }
     CRM_Core_Session::setStatus($statusMsg);
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/member/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=member"));
         }
     } else {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=add&context=membership&cid={$this->_contactID}"));
         }
     }
 }
Beispiel #15
0
 /** 
  * Function to process the form 
  * 
  * @access public 
  * @return None 
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         require_once 'CRM/Contribute/BAO/Contribution.php';
         CRM_Contribute_BAO_Contribution::deleteContribution($this->_id);
         return;
     }
     // get the submitted form values.
     $submittedValues = $this->controller->exportValues($this->_name);
     // process price set and get total amount and line items.
     $lineItem = array();
     $priceSetId = null;
     if ($priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues)) {
         require_once 'CRM/Price/BAO/Set.php';
         CRM_Price_BAO_Set::processAmount($this->_priceSet['fields'], $submittedValues, $lineItem[$priceSetId]);
         $submittedValues['total_amount'] = $submittedValues['amount'];
     }
     if (!CRM_Utils_Array::value('total_amount', $submittedValues)) {
         $submittedValues['total_amount'] = $this->_values['total_amount'];
     }
     $this->assign('lineItem', !empty($lineItem) ? $lineItem : false);
     if (CRM_Utils_Array::value('soft_credit_to', $submittedValues)) {
         $submittedValues['soft_credit_to'] = $submittedValues['soft_contact_id'];
     }
     // set the contact, when contact is selected
     if (CRM_Utils_Array::value('contact_select_id', $submittedValues)) {
         $this->_contactID = CRM_Utils_Array::value('contact_select_id', $submittedValues);
     }
     $config =& CRM_Core_Config::singleton();
     $session =& CRM_Core_Session::singleton();
     //Credit Card Contribution.
     if ($this->_mode) {
         $unsetParams = array('trxn_id', 'payment_instrument_id', 'contribution_status_id', 'receive_date', 'cancel_date', 'cancel_reason');
         foreach ($unsetParams as $key) {
             if (isset($submittedValues[$key])) {
                 unset($submittedValues[$key]);
             }
         }
         //Get the rquire fields value only.
         $params = $this->_params = $submittedValues;
         require_once 'CRM/Core/BAO/PaymentProcessor.php';
         $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode);
         require_once "CRM/Contact/BAO/Contact.php";
         $now = date('YmdHis');
         $fields = array();
         // we need to retrieve email address
         if ($this->_context == 'standalone' && CRM_Utils_Array::value('is_email_receipt', $submittedValues)) {
             require_once 'CRM/Contact/BAO/Contact/Location.php';
             list($this->userDisplayName, $this->userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
             $this->assign('displayName', $this->userDisplayName);
         }
         //set email for primary location.
         $fields["email-Primary"] = 1;
         $params["email-Primary"] = $this->userEmail;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
         $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $params)) {
                 $params[$name] = $params["billing_{$name}"];
                 $params['preserveDBName'] = true;
             }
         }
         if (CRM_Utils_Array::value('source', $params)) {
             unset($params['source']);
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactID, null, null, $ctype);
         // add all the additioanl payment params we need
         $this->_params["state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         if ($this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_CREDIT_CARD) {
             $this->_params['year'] = $this->_params['credit_card_exp_date']['Y'];
             $this->_params['month'] = $this->_params['credit_card_exp_date']['M'];
         }
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $this->_params['total_amount'];
         $this->_params['amount_level'] = 0;
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['payment_action'] = 'Sale';
         if (CRM_Utils_Array::value('soft_credit_to', $params)) {
             $this->_params['soft_credit_to'] = $params['soft_credit_to'];
             $this->_params['pcp_made_through_id'] = $params['pcp_made_through_id'];
         }
         $this->_params['pcp_display_in_roll'] = $params['pcp_display_in_roll'];
         $this->_params['pcp_roll_nickname'] = $params['pcp_roll_nickname'];
         $this->_params['pcp_personal_note'] = $params['pcp_personal_note'];
         //Add common data to formatted params
         CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params);
         if (empty($this->_params['invoice_id'])) {
             $this->_params['invoiceID'] = md5(uniqid(rand(), true));
         } else {
             $this->_params['invoiceID'] = $this->_params['invoice_id'];
         }
         // 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;
         require_once 'CRM/Core/Payment/Form.php';
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, true);
         $contributionType =& new CRM_Contribute_DAO_ContributionType();
         $contributionType->id = $params['contribution_type_id'];
         if (!$contributionType->find(true)) {
             CRM_Core_Error::fatal("Could not find a system table");
         }
         // add some contribution type details to the params list
         // if folks need to use it
         $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $contributionType->name;
         $paymentParams['contributionType_accounting_code'] = $this->_params['contributionType_accounting_code'] = $contributionType->accounting_code;
         $paymentParams['contributionPageID'] = null;
         if (CRM_Utils_Array::value('is_email_receipt', $this->_params)) {
             $paymentParams['email'] = $this->userEmail;
         }
         $payment =& CRM_Core_Payment::singleton($this->_mode, 'Contribute', $this->_paymentProcessor, $this);
         $result =& $payment->doDirectPayment($paymentParams);
         if (is_a($result, 'CRM_Core_Error')) {
             //set the contribution mode.
             $urlParams = "action=add&cid={$this->_contactID}";
             if ($this->_mode) {
                 $urlParams .= "&mode={$this->_mode}";
             }
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $this->_params['receive_date'] = $now;
         if (CRM_Utils_Array::value('is_email_receipt', $this->_params)) {
             $this->_params['receipt_date'] = $now;
         } else {
             if (!CRM_Utils_System::isNull($this->_params['receipt_date'])) {
                 $this->_params['receipt_date'] = CRM_Utils_Date::processDate($this->_params['receipt_date']);
             } else {
                 $this->_params['receipt_date'] = 'null';
             }
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
         $this->assign('receive_date', CRM_Utils_Date::processDate($this->_params['receive_date']));
         // result has all the stuff we need
         // lets archive it to a financial transaction
         if ($contributionType->is_deductible) {
             $this->assign('is_deductible', true);
             $this->set('is_deductible', true);
         }
         // 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));
         }
         // build custom data getFields array
         $customFieldsContributionType = CRM_Core_BAO_CustomField::getFields('Contribution', false, false, CRM_Utils_Array::value('contribution_type_id', $params));
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsContributionType, CRM_Core_BAO_CustomField::getFields('Contribution', false, false, null, null, true));
         $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_id, 'Contribution');
         require_once 'CRM/Contribute/Form/Contribution/Confirm.php';
         $contribution =& CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $this->_params, $result, $this->_contactID, $contributionType, false, false, false);
         // process line items, until no previous line items.
         if (empty($this->_lineItems) && $contribution->id && !empty($lineItem)) {
             CRM_Contribute_Form_AdditionalInfo::processPriceSet($contribution->id, $lineItem);
         }
         //send receipt mail.
         if ($contribution->id && CRM_Utils_Array::value('is_email_receipt', $this->_params)) {
             $this->_params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
             $this->_params['contact_id'] = $this->_contactID;
             $this->_params['contribution_id'] = $contribution->id;
             $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $this->_params, true);
         }
         //process the note
         if ($contribution->id && isset($params['note'])) {
             CRM_Contribute_Form_AdditionalInfo::processNote($params, $contactID, $contribution->id, null);
         }
         //process premium
         if ($contribution->id && isset($params['product_name'][0])) {
             CRM_Contribute_Form_AdditionalInfo::processPremium($params, $contribution->id, null, $this->_options);
         }
         //update pledge payment status.
         if ($this->_ppID && $contribution->id) {
             //store contribution id in payment record.
             CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_Payment', $this->_ppID, 'contribution_id', $contribution->id);
             require_once 'CRM/Pledge/BAO/Payment.php';
             CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($this->_pledgeID, array($this->_ppID), $contribution->contribution_status_id);
         }
         if ($contribution->id) {
             $statusMsg = ts('The contribution record has been processed.');
             if (CRM_Utils_Array::value('is_email_receipt', $this->_params) && $sendReceipt) {
                 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
             }
             CRM_Core_Session::setStatus($statusMsg);
         }
         //submit credit card contribution ends.
     } else {
         //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]);
             }
         }
         // get the required field value only.
         $formValues = $submittedValues;
         $params = $ids = array();
         $params['contact_id'] = $this->_contactID;
         $params['currency'] = $config->defaultCurrency;
         if ($currency = CRM_Utils_Array::value('currency', $this->_values)) {
             $params['currency'] = $currency;
         }
         $fields = array('contribution_type_id', 'contribution_status_id', 'payment_instrument_id', 'cancel_reason', 'source', 'check_number', 'soft_credit_to', 'pcp_made_through_id', 'pcp_display_in_roll', 'pcp_roll_nickname', 'pcp_personal_note');
         foreach ($fields as $f) {
             $params[$f] = CRM_Utils_Array::value($f, $formValues);
         }
         if ($softID = CRM_Utils_Array::value('softID', $this->_values)) {
             $params['softID'] = $softID;
         }
         $dates = array('receive_date', 'receipt_date', 'cancel_date');
         foreach ($dates as $d) {
             if (!CRM_Utils_System::isNull($formValues[$d])) {
                 $params[$d] = CRM_Utils_Date::processDate($formValues[$d]);
             } else {
                 if (array_key_exists($d, $formValues)) {
                     $params[$d] = 'null';
                 }
             }
         }
         if (CRM_Utils_Array::value('is_email_receipt', $formValues)) {
             $params['receipt_date'] = date("Y-m-d");
         }
         if ($params["contribution_status_id"] == 3) {
             if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
                 $params['cancel_date'] = date("Y-m-d");
             }
         } else {
             $params['cancel_date'] = 'null';
             $params['cancel_reason'] = 'null';
         }
         $ids['contribution'] = $params['id'] = $this->_id;
         //Add Additinal common information  to formatted params
         CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params);
         //create contribution.
         require_once 'CRM/Contribute/BAO/Contribution.php';
         $contribution =& CRM_Contribute_BAO_Contribution::create($params, $ids);
         // process line items, until no previous line items.
         if (empty($this->_lineItems) && $contribution->id && !empty($lineItem)) {
             CRM_Contribute_Form_AdditionalInfo::processPriceSet($contribution->id, $lineItem);
         }
         // process associated membership / participant, CRM-4395
         $relatedComponentStatusMsg = null;
         if ($contribution->id && $this->_action & CRM_Core_Action::UPDATE) {
             $relatedComponentStatusMsg = $this->updateRelatedComponent($contribution->id, $contribution->contribution_status_id, CRM_Utils_Array::value('contribution_status_id', $this->_values));
         }
         //process  note
         if ($contribution->id && isset($formValues['note'])) {
             CRM_Contribute_Form_AdditionalInfo::processNote($formValues, $this->_contactID, $contribution->id, $this->_noteID);
         }
         //process premium
         if ($contribution->id && isset($formValues['product_name'][0])) {
             CRM_Contribute_Form_AdditionalInfo::processPremium($formValues, $contribution->id, $this->_premiumID, $this->_options);
         }
         //send receipt mail.
         if ($contribution->id && CRM_Utils_Array::value('is_email_receipt', $formValues)) {
             $formValues['contact_id'] = $this->_contactID;
             $formValues['contribution_id'] = $contribution->id;
             $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues);
         }
         //update pledge payment status.
         if ($this->_ppID && $contribution->id && $this->_action & CRM_Core_Action::ADD) {
             //store contribution id in payment record.
             CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_Payment', $this->_ppID, 'contribution_id', $contribution->id);
             require_once 'CRM/Pledge/BAO/Payment.php';
             CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($this->_pledgeID, array($this->_ppID), $contribution->contribution_status_id);
         }
         $statusMsg = ts('The contribution record has been saved.');
         if (CRM_Utils_Array::value('is_email_receipt', $formValues) && $sendReceipt) {
             $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
         }
         if ($relatedComponentStatusMsg) {
             $statusMsg .= ' ' . $relatedComponentStatusMsg;
         }
         CRM_Core_Session::setStatus($statusMsg);
         //Offline Contribution ends.
     }
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contribute/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=contribute"));
         }
     } else {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution', "reset=1&action=add&context=contribution&cid={$this->_contactID}"));
         }
     }
 }
 /**
  * Function to process the form
  *
  * @access public
  *
  * @return None
  */
 public function postProcess()
 {
     CRM_Utils_System::flushCache('CRM_Core_DAO_PaymentProcessor');
     if ($this->_action & CRM_Core_Action::DELETE) {
         CRM_Core_BAO_PaymentProcessor::del($this->_id);
         CRM_Core_Session::setStatus(ts('Selected Payment Processor has been deleted.'));
         return;
     }
     $values = $this->controller->exportValues($this->_name);
     $domainID = CRM_Core_Config::domainID();
     if (CRM_Utils_Array::value('is_default', $values)) {
         $query = "UPDATE civicrm_payment_processor SET is_default = 0 WHERE domain_id = {$domainID}";
         CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
     }
     $this->updatePaymentProcessor($values, $domainID, FALSE);
     $this->updatePaymentProcessor($values, $domainID, TRUE);
 }
 /**
  * Function to retrieve payment processor id / info/ object based on component-id.
  *
  * @param int    $componentID id of a component
  * @param string $component   component
  * @param string $type        type of payment information to be retrieved
  *
  * @return id / array / object based on type
  * @static
  * @access public
  */
 static function getProcessorForEntity($entityID, $component = 'contribute', $type = 'id')
 {
     $result = NULL;
     if (!in_array($component, array('membership', 'contribute', 'recur'))) {
         return $result;
     }
     //FIXME:
     if ($component == 'membership') {
         $sql = " \n    SELECT cr.payment_processor_id as ppID1, cp.payment_processor as ppID2, con.is_test \n      FROM civicrm_membership mem\nINNER JOIN civicrm_membership_payment mp  ON ( mem.id = mp.membership_id ) \nINNER JOIN civicrm_contribution       con ON ( mp.contribution_id = con.id )\n LEFT JOIN civicrm_contribution_recur cr  ON ( mem.contribution_recur_id = cr.id )\n LEFT JOIN civicrm_contribution_page  cp  ON ( con.contribution_page_id  = cp.id )\n     WHERE mp.membership_id = %1";
     } elseif ($component == 'contribute') {
         $sql = " \n    SELECT cr.payment_processor_id as ppID1, cp.payment_processor as ppID2, con.is_test \n      FROM civicrm_contribution       con\n LEFT JOIN civicrm_contribution_recur cr  ON ( con.contribution_recur_id = cr.id )\n LEFT JOIN civicrm_contribution_page  cp  ON ( con.contribution_page_id  = cp.id )\n     WHERE con.id = %1";
     } elseif ($component == 'recur') {
         $sql = " \n    SELECT cr.payment_processor_id as ppID1, NULL as ppID2, cr.is_test \n      FROM civicrm_contribution_recur cr\n     WHERE cr.id = %1";
     }
     //we are interesting in single record.
     $sql .= ' LIMIT 1';
     $params = array(1 => array($entityID, 'Integer'));
     $dao = CRM_Core_DAO::executeQuery($sql, $params);
     if (!$dao->fetch()) {
         return $result;
     }
     $ppID = isset($dao->ppID1) && $dao->ppID1 ? $dao->ppID1 : (isset($dao->ppID2) ? $dao->ppID2 : NULL);
     $mode = isset($dao->is_test) && $dao->is_test ? 'test' : 'live';
     if (!$ppID || $type == 'id') {
         $result = $ppID;
     } elseif ($type == 'info') {
         $result = CRM_Core_BAO_PaymentProcessor::getPayment($ppID, $mode);
     } elseif ($type == 'obj') {
         $payment = CRM_Core_BAO_PaymentProcessor::getPayment($ppID, $mode);
         $result = CRM_Core_Payment::singleton($mode, $payment);
     }
     return $result;
 }
 /**
  * Handles the response sent by the payment processor.
  * This is the entry point from datatransNotify.php.
  *
  * @param string $method
  *   Security method.  Always set to HMAC (highest) for now.
  * @param array $post_data
  *   The payment processor response data.
  */
 static function main($method, $post_data)
 {
     if (is_array($post_data)) {
         $post_data_exp = $post_data;
     } else {
         parse_str($post_data, $post_data_exp);
     }
     require_once 'CRM/Core/BAO/PaymentProcessor.php';
     $paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($post_data_exp['payment_processor_id'], $post_data_exp['mode']);
     $ipn = self::singleton($post_data_exp['mode'], $post_data_exp['component'], $paymentProcessor);
     //  Map errors to their definition and reroute to error page.
     if (isset($post_data_exp['errorCode'])) {
         $error_message = $ipn->_datatrans_map_error_code($post_data_exp['errorCode']);
         CRM_Core_Error::debug_log_message("DataTrans Response: {$error_message}");
         exit;
     }
     //  Handle canceled transactions & extra error layer.
     if (isset($post_data_exp['status'])) {
         switch ($post_data_exp['status']) {
             case 'error':
                 //  This is for errors other than dealing w/ the card.
                 $error_msg = "DataTrans Error, but no errorCode.";
                 if (!empty($post_data_exp[errorDetail])) {
                     $error_msg .= $post_data_exp[errorDetail];
                 }
                 if (!empty($post_data_exp[errorMessage])) {
                     $error_msg .= $post_data_exp[errorMessage];
                 }
                 CRM_Core_Error::debug_log_message($error_msg);
                 exit;
                 break;
             case 'cancel':
                 CRM_Core_Error::debug_log_message("Transaction canceled in DataTrans. {$cancel_url}");
                 exit;
                 break;
         }
     }
     //  Check if this transaction has already been handled.
     $duplicate_transaction = self::getContext($post_data_exp['component'], $post_data_exp, $post_data_exp['uppTransactionId']);
     if (!$duplicate_transaction) {
         $formatted_amount = $post_data_exp['amount'] / 100;
         $ipn->newOrderNotify($post_data_exp, $formatted_amount);
     }
     //CRM_Utils_System::redirect($success_url);
 }
 /**
  * Function to send the emails for Recurring Contribution Notication
  *
  * @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 object  $autoRenewMembership   is it a auto renew membership.
  *
  * @return void
  * @access public
  * @static
  */
 static function recurringNotify($type, $contactID, $pageID, $recur, $autoRenewMembership = FALSE)
 {
     $value = array();
     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]);
     $isOfflineRecur = FALSE;
     if (!$pageID && $recur->id) {
         $isOfflineRecur = TRUE;
     }
     if ($isEmailReceipt || $isOfflineRecur) {
         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);
         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_Core_BAO_PaymentProcessor::getProcessorForEntity($recur->id, 'recur', 'obj');
             $url = $paymentProcessor->subscriptionURL($recur->id, 'recur');
             $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, $subject, $message, $html) = CRM_Core_BAO_MessageTemplates::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.');
         }
     }
 }
Beispiel #20
0
 /**
  * This method is handles the response that will be invoked (from extern/googleNotify) every time
  * a notification or request is sent by the Google Server.
  *
  */
 static function main($xml_response)
 {
     require_once 'Google/library/googleresponse.php';
     require_once 'Google/library/googlemerchantcalculations.php';
     require_once 'Google/library/googleresult.php';
     require_once 'Google/library/xml-processing/xmlparser.php';
     $config = CRM_Core_Config::singleton();
     // Retrieve the XML sent in the HTTP POST request to the ResponseHandler
     if (get_magic_quotes_gpc()) {
         $xml_response = stripslashes($xml_response);
     }
     require_once 'CRM/Utils/System.php';
     $headers = CRM_Utils_System::getAllHeaders();
     if (GOOGLE_DEBUG_PP) {
         CRM_Core_Error::debug_var('RESPONSE', $xml_response, true, true, 'Google');
     }
     // Retrieve the root and data from the xml response
     $xmlParser = new XmlParser($xml_response);
     $root = $xmlParser->GetRoot();
     $data = $xmlParser->GetData();
     $orderNo = $data[$root]['google-order-number']['VALUE'];
     // lets retrieve the private-data
     $privateData = $data[$root]['shopping-cart']['merchant-private-data']['VALUE'];
     $privateData = $privateData ? self::stringToArray($privateData) : '';
     list($mode, $module, $paymentProcessorID) = self::getContext($xml_response, $privateData, $orderNo, $root);
     $mode = $mode ? 'test' : 'live';
     require_once 'CRM/Core/BAO/PaymentProcessor.php';
     $paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($paymentProcessorID, $mode);
     $ipn =& self::singleton($mode, $module, $paymentProcessor);
     // Create new response object
     $merchant_id = $paymentProcessor['user_name'];
     $merchant_key = $paymentProcessor['password'];
     $server_type = $mode == 'test' ? "sandbox" : '';
     $response = new GoogleResponse($merchant_id, $merchant_key, $xml_response, $server_type);
     if (GOOGLE_DEBUG_PP) {
         CRM_Core_Error::debug_var('RESPONSE-ROOT', $response->root, true, true, 'Google');
     }
     //Check status and take appropriate action
     $status = $response->HttpAuthentication($headers);
     switch ($root) {
         case "request-received":
         case "error":
         case "diagnosis":
         case "checkout-redirect":
         case "merchant-calculation-callback":
             break;
         case "new-order-notification":
             $response->SendAck();
             $ipn->newOrderNotify($data[$root], $privateData, $module);
             break;
         case "order-state-change-notification":
             $response->SendAck();
             $new_financial_state = $data[$root]['new-financial-order-state']['VALUE'];
             $new_fulfillment_order = $data[$root]['new-fulfillment-order-state']['VALUE'];
             switch ($new_financial_state) {
                 case 'CHARGEABLE':
                     $amount = $ipn->getAmount($orderNo);
                     if ($amount) {
                         $response->SendChargeOrder($data[$root]['google-order-number']['VALUE'], $amount, $message_log);
                         $response->SendProcessOrder($data[$root]['google-order-number']['VALUE'], $message_log);
                     }
                     break;
                 case 'CHARGED':
                 case 'PAYMENT_DECLINED':
                 case 'CANCELLED':
                     $ipn->orderStateChange($new_financial_state, $data[$root], $module);
                     break;
                 case 'REVIEWING':
                 case 'CHARGING':
                 case 'CANCELLED_BY_GOOGLE':
                     break;
                 default:
                     break;
             }
         case "charge-amount-notification":
         case "chargeback-amount-notification":
         case "refund-amount-notification":
         case "risk-information-notification":
             $response->SendAck();
             break;
         default:
             break;
     }
 }
Beispiel #21
0
 function loadObjects(&$input, &$ids, &$objects, $required)
 {
     $contribution =& $objects['contribution'];
     $objects['membership'] = null;
     $objects['contributionRecur'] = null;
     $objects['contributionType'] = null;
     $objects['event'] = null;
     $objects['participant'] = null;
     $objects['pledge_payment'] = null;
     require_once 'CRM/Contribute/DAO/ContributionType.php';
     $contributionType =& new CRM_Contribute_DAO_ContributionType();
     $contributionType->id = $contribution->contribution_type_id;
     if (!$contributionType->find(true)) {
         CRM_Core_Error::debug_log_message("Could not find contribution type record: {$contributionTypeID}");
         echo "Failure: Could not find contribution type record for {$contributionTypeID}<p>";
         return false;
     }
     $objects['contributionType'] = $contributionType;
     $paymentProcessorID = null;
     if ($input['component'] == 'contribute') {
         // get the contribution page id from the contribution
         // and then initialize the payment processor from it
         if (!$contribution->contribution_page_id) {
             if (!CRM_Utils_Array::value('pledge_payment', $ids)) {
                 // return if we are just doing an optional validation
                 if (!$required) {
                     return true;
                 }
                 CRM_Core_Error::debug_log_message("Could not find contribution page for contribution record: {$contributionID}");
                 echo "Failure: Could not find contribution page for contribution record: {$contributionID}<p>";
                 return false;
             }
         }
         //for offline pldedge we dont have contribution page.
         if (!CRM_Utils_Array::value('pledge_payment', $ids)) {
             // get the payment processor id from contribution page
             $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $contribution->contribution_page_id, 'payment_processor_id');
         }
         // now retrieve the other optional objects
         if (isset($ids['membership'])) {
             require_once 'CRM/Member/DAO/Membership.php';
             $membership = new CRM_Member_DAO_Membership();
             $membership->id = $ids['membership'];
             if (!$membership->find(true)) {
                 CRM_Core_Error::debug_log_message("Could not find membership record: {$membershipID}");
                 echo "Failure: Could not find membership record: {$membershipID}<p>";
                 return false;
             }
             $membership->join_date = CRM_Utils_Date::isoToMysql($membership->join_date);
             $membership->start_date = CRM_Utils_Date::isoToMysql($membership->start_date);
             $membership->end_date = CRM_Utils_Date::isoToMysql($membership->end_date);
             $membership->reminder_date = CRM_Utils_Date::isoToMysql($membership->reminder_date);
             $objects['membership'] =& $membership;
         }
         if (isset($ids['pledge_payment'])) {
             require_once 'CRM/Pledge/DAO/Payment.php';
             $objects['pledge_payment'] = array();
             foreach ($ids['pledge_payment'] as $key => $paymentID) {
                 $payment = new CRM_Pledge_DAO_Payment();
                 $payment->id = $paymentID;
                 if (!$payment->find(true)) {
                     CRM_Core_Error::debug_log_message("Could not find pledge payment record: {$pledge_paymentID}");
                     echo "Failure: Could not find pledge payment record: {$pledge_paymentID}<p>";
                     return false;
                 }
                 $objects['pledge_payment'][] = $payment;
             }
         }
         if (isset($ids['contributionRecur'])) {
             require_once 'CRM/Contribute/DAO/ContributionRecur.php';
             $recur =& new CRM_Contribute_DAO_ContributionRecur();
             $recur->id = $ids['contributionRecur'];
             if (!$recur->find(true)) {
                 CRM_Core_Error::debug_log_message("Could not find recur record: {$contributionRecurID}");
                 echo "Failure: Could not find recur record: {$contributionRecurID}<p>";
                 return false;
             }
             $objects['contributionRecur'] =& $recur;
         }
     } else {
         // we are in event mode
         // make sure event exists and is valid
         require_once 'CRM/Event/DAO/Event.php';
         $event =& new CRM_Event_DAO_Event();
         $event->id = $ids['event'];
         if ($ids['event'] && !$event->find(true)) {
             CRM_Core_Error::debug_log_message("Could not find event: {$eventID}");
             echo "Failure: Could not find event: {$eventID}<p>";
             return false;
         }
         $objects['event'] =& $event;
         require_once 'CRM/Event/DAO/Participant.php';
         $participant =& new CRM_Event_DAO_Participant();
         $participant->id = $ids['participant'];
         if ($ids['participant'] && !$participant->find(true)) {
             CRM_Core_Error::debug_log_message("Could not find participant: {$participantID}");
             echo "Failure: Could not find participant: {$participantID}<p>";
             return false;
         }
         $participant->register_date = CRM_Utils_Date::isoToMysql($participant->register_date);
         $objects['participant'] =& $participant;
         $paymentProcessorID = $objects['event']->payment_processor_id;
     }
     if (!$paymentProcessorID) {
         if ($required) {
             CRM_Core_Error::debug_log_message("Could not find payment processor for contribution record: {$contributionID}");
             echo "Failure: Could not find payment processor for contribution record: {$contributionID}<p>";
             return false;
         }
     } else {
         require_once 'CRM/Core/BAO/PaymentProcessor.php';
         $paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($paymentProcessorID, $contribution->is_test ? 'test' : 'live');
         $ids['paymentProcessor'] = $paymentProcessorID;
         $objects['paymentProcessor'] =& $paymentProcessor;
     }
     return true;
 }
Beispiel #22
0
 function loadObjects(&$input, &$ids, &$objects, $required)
 {
     $contribution =& $objects['contribution'];
     $objects['membership'] = null;
     $objects['contributionRecur'] = null;
     $objects['contributionType'] = null;
     $objects['event'] = null;
     $objects['participant'] = null;
     $objects['pledge_payment'] = null;
     require_once 'CRM/Contribute/DAO/ContributionType.php';
     $contributionType = new CRM_Contribute_DAO_ContributionType();
     $contributionType->id = $contribution->contribution_type_id;
     if (!$contributionType->find(true)) {
         CRM_Core_Error::debug_log_message("Could not find contribution type record: {$contributionTypeID}");
         echo "Failure: Could not find contribution type record for {$contributionTypeID}<p>";
         return false;
     }
     $objects['contributionType'] = $contributionType;
     $paymentProcessorID = null;
     if ($input['component'] == 'contribute') {
         // retrieve the other optional objects first so
         // stuff down the line can use this info and do things
         // CRM-6056
         if (isset($ids['membership'])) {
             require_once 'CRM/Member/DAO/Membership.php';
             $membership = new CRM_Member_DAO_Membership();
             $membership->id = $ids['membership'];
             if (!$membership->find(true)) {
                 CRM_Core_Error::debug_log_message("Could not find membership record: {$membershipID}");
                 echo "Failure: Could not find membership record: {$membershipID}<p>";
                 return false;
             }
             $membership->join_date = CRM_Utils_Date::isoToMysql($membership->join_date);
             $membership->start_date = CRM_Utils_Date::isoToMysql($membership->start_date);
             $membership->end_date = CRM_Utils_Date::isoToMysql($membership->end_date);
             $membership->reminder_date = CRM_Utils_Date::isoToMysql($membership->reminder_date);
             $objects['membership'] =& $membership;
         }
         if (isset($ids['pledge_payment'])) {
             require_once 'CRM/Pledge/DAO/Payment.php';
             $objects['pledge_payment'] = array();
             foreach ($ids['pledge_payment'] as $key => $paymentID) {
                 $payment = new CRM_Pledge_DAO_Payment();
                 $payment->id = $paymentID;
                 if (!$payment->find(true)) {
                     CRM_Core_Error::debug_log_message("Could not find pledge payment record: {$pledge_paymentID}");
                     echo "Failure: Could not find pledge payment record: {$pledge_paymentID}<p>";
                     return false;
                 }
                 $objects['pledge_payment'][] = $payment;
             }
         }
         if (isset($ids['contributionRecur'])) {
             require_once 'CRM/Contribute/DAO/ContributionRecur.php';
             $recur = new CRM_Contribute_DAO_ContributionRecur();
             $recur->id = $ids['contributionRecur'];
             if (!$recur->find(true)) {
                 CRM_Core_Error::debug_log_message("Could not find recur record: {$contributionRecurID}");
                 echo "Failure: Could not find recur record: {$contributionRecurID}<p>";
                 return false;
             }
             $objects['contributionRecur'] =& $recur;
             //get payment processor id from recur object.
             $paymentProcessorID = $recur->payment_processor_id;
         }
         //for normal contribution get the payment processor id.
         if (!$paymentProcessorID) {
             if ($contribution->contribution_page_id) {
                 // get the payment processor id from contribution page
                 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $contribution->contribution_page_id, 'payment_processor_id');
             }
             //fail to load payment processor id.
             if (!$paymentProcessorID && !$contribution->contribution_page_id && !CRM_Utils_Array::value('pledge_payment', $ids)) {
                 $loadObjectSuccess = true;
                 if ($required) {
                     $loadObjectSuccess = false;
                     CRM_Core_Error::debug_log_message("Could not find contribution page for contribution record: {$contributionID}");
                     echo "Failure: Could not find contribution page for contribution record: {$contributionID}<p>";
                 }
                 return $loadObjectSuccess;
             }
         }
     } else {
         // we are in event mode
         // make sure event exists and is valid
         require_once 'CRM/Event/DAO/Event.php';
         $event = new CRM_Event_DAO_Event();
         $event->id = $ids['event'];
         if ($ids['event'] && !$event->find(true)) {
             CRM_Core_Error::debug_log_message("Could not find event: {$eventID}");
             echo "Failure: Could not find event: {$eventID}<p>";
             return false;
         }
         $objects['event'] =& $event;
         require_once 'CRM/Event/DAO/Participant.php';
         $participant = new CRM_Event_DAO_Participant();
         $participant->id = $ids['participant'];
         if ($ids['participant'] && !$participant->find(true)) {
             CRM_Core_Error::debug_log_message("Could not find participant: {$participantID}");
             echo "Failure: Could not find participant: {$participantID}<p>";
             return false;
         }
         $participant->register_date = CRM_Utils_Date::isoToMysql($participant->register_date);
         $objects['participant'] =& $participant;
         if (!$paymentProcessorID) {
             $paymentProcessorID = $objects['event']->payment_processor_id;
         }
     }
     $loadObjectSuccess = true;
     if ($paymentProcessorID) {
         require_once 'CRM/Core/BAO/PaymentProcessor.php';
         $paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($paymentProcessorID, $contribution->is_test ? 'test' : 'live');
         $ids['paymentProcessor'] = $paymentProcessorID;
         $objects['paymentProcessor'] =& $paymentProcessor;
     } else {
         if ($required) {
             $loadObjectSuccess = false;
             CRM_Core_Error::debug_log_message("Could not find payment processor for contribution record: {$contributionID}");
             echo "Failure: Could not find payment processor for contribution record: {$contributionID}<p>";
         }
     }
     return $loadObjectSuccess;
 }
Beispiel #23
0
 /**
  * This method is handles the response that will be invoked by the
  * notification or request sent by the payment processor.
  *hex string from paymentexpress is passed to this function as hex string. Code based on googleIPN
  * mac_key is only passed if the processor is pxaccess as it is used for decryption
  * $dps_method is either pxaccess or pxpay
  */
 static function main($dps_method, $rawPostData, $dps_url, $dps_user, $dps_key, $mac_key)
 {
     $config =& CRM_Core_Config::singleton();
     define('RESPONSE_HANDLER_LOG_FILE', $config->uploadDir . 'CiviCRM.PaymentExpress.log');
     //Setup the log file
     if (!($message_log = fopen(RESPONSE_HANDLER_LOG_FILE, "a"))) {
         error_func("Cannot open " . RESPONSE_HANDLER_LOG_FILE . " file.\n", 0);
         exit(1);
     }
     if ($dps_method == "pxpay") {
         require_once 'CRM/Core/Payment/PaymentExpressUtils.php';
         $processResponse = _valueXml(array('PxPayUserId' => $dps_user, 'PxPayKey' => $dps_key, 'Response' => $_GET['result']));
         $processResponse = _valueXml('ProcessResponse', $processResponse);
         fwrite($message_log, sprintf("\n\r%s:- %s\n", date("D M j G:i:s T Y"), $processResponse));
         // Send the XML-formatted validation request to DPS so that we can receive a decrypted XML response which contains the transaction results
         $curl = _initCURL($processResponse, $dps_url);
         fwrite($message_log, sprintf("\n\r%s:- %s\n", date("D M j G:i:s T Y"), $curl));
         $success = false;
         if ($response = curl_exec($curl)) {
             fwrite($message_log, sprintf("\n\r%s:- %s\n", date("D M j G:i:s T Y"), $response));
             curl_close($curl);
             // Assign the returned XML values to variables
             $valid = _xmlAttribute($response, 'valid');
             $success = _xmlElement($response, 'Success');
             $txnId = _xmlElement($response, 'TxnId');
             $responseText = _xmlElement($response, 'ResponseText');
             $authCode = _xmlElement($response, 'AuthCode');
             $DPStxnRef = _xmlElement($response, 'DpsTxnRef');
             $qfKey = _xmlElement($response, "TxnData1");
             $privateData = _xmlElement($response, "TxnData2");
             $component = _xmlElement($response, "TxnData3");
             $amount = _xmlElement($response, "AmountSettlement");
             $merchantReference = _xmlElement($response, "MerchantReference");
         } else {
             // calling DPS failed
             CRM_Core_Error::fatal(ts('Unable to establish connection to the payment gateway to verify transaction response.'));
             exit;
         }
     } elseif ($dps_method == "pxaccess") {
         require_once 'PaymentExpress/pxaccess.php';
         global $pxaccess;
         $pxaccess = new PxAccess($dps_url, $dps_user, $dps_key, $mac_key);
         #getResponse method in PxAccess object returns PxPayResponse object
         #which encapsulates all the response data
         $rsp = $pxaccess->getResponse($rawPostData);
         $qfKey = $rsp->getTxnData1();
         $privateData = $rsp->getTxnData2();
         $component = $rsp->getTxnData3();
         $success = $rsp->getSuccess();
         $authCode = $rsp->getAuthCode();
         $DPStxnRef = $rsp->getDpsTxnRef();
         $amount = $rsp->getAmountSettlement();
         $MerchantReference = $rsp->getMerchantReference();
     }
     $privateData = $privateData ? self::stringToArray($privateData) : '';
     // Private Data consists of : a=contactID, b=contributionID,c=contributionTypeID,d=invoiceID,e=membershipID,f=participantID,g=eventID
     $privateData['contactID'] = $privateData['a'];
     $privateData['contributionID'] = $privateData['b'];
     $privateData['contributionTypeID'] = $privateData['c'];
     $privateData['invoiceID'] = $privateData['d'];
     if ($component == "event") {
         $privateData['participantID'] = $privateData['f'];
         $privateData['eventID'] = $privateData['g'];
     } else {
         if ($component == "contribute") {
             if (count($privateData) == 5) {
                 $privateData["membershipID"] = $privateData['e'];
             }
         }
     }
     $transactionReference = $authCode . "-" . $DPStxnRef;
     list($mode, $component, $paymentProcessorID, $duplicateTransaction) = self::getContext($privateData, $transactionReference);
     $mode = $mode ? 'test' : 'live';
     require_once 'CRM/Core/BAO/PaymentProcessor.php';
     $paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($paymentProcessorID, $mode);
     $ipn =& self::singleton($mode, $component, $paymentProcessor);
     //Check status and take appropriate action
     if ($success == 1) {
         if ($duplicateTransaction == 0) {
             $ipn->newOrderNotify($success, $privateData, $component, $amount, $transactionReference);
         }
         if ($component == "event") {
             $finalURL = CRM_Utils_System::url('civicrm/event/register', "_qf_ThankYou_display=1&qfKey={$params['qfKey']}", false, null, false);
         } elseif ($component == "contribute") {
             $finalURL = CRM_Utils_System::url('civicrm/contribute/transact', "_qf_ThankYou_display=1&qfKey={$params['qfKey']}", false, null, false);
         }
         CRM_Utils_System::redirect($finalURL);
     } else {
         if ($component == "event") {
             $finalURL = CRM_Utils_System::url('civicrm/event/register', "_qf_Register_display=1&cancel=1&qfKey={$params['qfKey']}", false, null, false);
         } elseif ($component == "contribute") {
             $finalURL = CRM_Utils_System::url('civicrm/contribute/transact', "_qf_Main_display=1&cancel=1&qfKey={$params['qfKey']}", false, null, false);
         }
         CRM_Utils_System::redirect($finalURL);
     }
 }
Beispiel #24
0
 /** 
  * Function to set variables up before form is built 
  *                                                           
  * @return void 
  * @access public 
  */
 function preProcess()
 {
     $this->_eventId = CRM_Utils_Request::retrieve('id', 'Positive', $this, true);
     $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, false);
     //CRM-4320
     $this->_participantId = CRM_Utils_Request::retrieve('participantId', 'Positive', $this);
     // current mode
     $this->_mode = $this->_action == 1024 ? 'test' : 'live';
     $this->_values = $this->get('values');
     $this->_fields = $this->get('fields');
     $this->_bltID = $this->get('bltID');
     $this->_paymentProcessor = $this->get('paymentProcessor');
     $this->_priceSetId = $this->get('priceSetId');
     $this->_priceSet = $this->get('priceSet');
     //check if participant allow to walk registration wizard.
     $this->_allowConfirmation = $this->get('allowConfirmation');
     // check for Approval
     $this->_requireApproval = $this->get('requireApproval');
     // check for waitlisting.
     $this->_allowWaitlist = $this->get('allowWaitlist');
     //get the additional participant ids.
     $this->_additionalParticipantIds = $this->get('additionalParticipantIds');
     $config =& CRM_Core_Config::singleton();
     if (!$this->_values) {
         // create redirect URL to send folks back to event info page is registration not available
         $infoUrl = CRM_Utils_System::url('civicrm/event/info', "reset=1&id={$this->_eventId}", false, null, false, true);
         // this is the first time we are hitting this, so check for permissions here
         if (!CRM_Core_Permission::event(CRM_Core_Permission::EDIT, $this->_eventId)) {
             CRM_Core_Error::statusBounce(ts('You do not have permission to register for this event'), $infoUrl);
         }
         // get all the values from the dao object
         $this->_values = array();
         $this->_fields = array();
         // get the participant values, CRM-4320
         $this->_allowConfirmation = false;
         if ($this->_participantId) {
             require_once 'CRM/Event/BAO/Event.php';
             $ids = $participantValues = array();
             $participantParams = array('id' => $this->_participantId);
             require_once 'CRM/Event/BAO/Participant.php';
             CRM_Event_BAO_Participant::getValues($participantParams, $participantValues, $ids);
             $this->_values['participant'] = $participantValues[$this->_participantId];
             //allow pending status class walk registration wizard.
             require_once 'CRM/Core/PseudoConstant.php';
             if (array_key_exists($participantValues[$this->_participantId]['status_id'], CRM_Event_PseudoConstant::participantStatus(null, "class = 'Pending'"))) {
                 $this->_allowConfirmation = true;
                 $this->set('allowConfirmation', true);
             }
         }
         //retrieve event information
         require_once 'CRM/Event/BAO/Event.php';
         $params = array('id' => $this->_eventId);
         CRM_Event_BAO_Event::retrieve($params, $this->_values['event']);
         require_once 'CRM/Event/BAO/Participant.php';
         //check for additional participants.
         if ($this->_allowConfirmation && $this->_values['event']['is_multiple_registrations']) {
             $this->_additionalParticipantIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_participantId);
             $this->set('additionalParticipantIds', $this->_additionalParticipantIds);
         }
         $eventFull = CRM_Event_BAO_Participant::eventFull($this->_eventId);
         $this->_allowWaitlist = false;
         if ($eventFull && !$this->_allowConfirmation) {
             //lets redirecting to info only when to waiting list.
             $this->_allowWaitlist = CRM_Utils_Array::value('has_waitlist', $this->_values['event']);
             if (!$this->_allowWaitlist) {
                 CRM_Utils_System::redirect($infoUrl);
             }
         }
         $this->set('allowWaitlist', $this->_allowWaitlist);
         //check for require requires approval.
         $this->_requireApproval = false;
         if (CRM_Utils_Array::value('requires_approval', $this->_values['event']) && !$this->_allowConfirmation) {
             $this->_requireApproval = true;
         }
         $this->set('requireApproval', $this->_requireApproval);
         // also get the accounting code
         if (CRM_Utils_Array::value('contribution_type_id', $this->_values['event'])) {
             $this->_values['event']['accountingCode'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionType', $this->_values['event']['contribution_type_id'], 'accounting_code');
         }
         if (isset($this->_values['event']['default_role_id'])) {
             require_once 'CRM/Core/OptionGroup.php';
             $participant_role = CRM_Core_OptionGroup::values('participant_role');
             $this->_values['event']['participant_role'] = $participant_role["{$this->_values['event']['default_role_id']}"];
         }
         // is the event active (enabled)?
         if (!$this->_values['event']['is_active']) {
             // form is inactive, die a fatal death
             CRM_Core_Error::statusBounce(ts('The event you requested is currently unavailable (contact the site administrator for assistance).'));
         }
         // is online registration is enabled?
         if (!$this->_values['event']['is_online_registration']) {
             CRM_Core_Error::statusBounce(ts('Online registration is not currently available for this event (contact the site administrator for assistance).'), $infoUrl);
         }
         // is this an event template ?
         if (CRM_Utils_Array::value('is_template', $this->_values['event'])) {
             CRM_Core_Error::statusBounce(ts('Event templates are not meant to be registered.'), $infoUrl);
         }
         $now = date('YmdHis');
         $startDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('registration_start_date', $this->_values['event']));
         if ($startDate && $startDate >= $now) {
             CRM_Core_Error::statusBounce(ts('Registration for this event begins on %1', array(1 => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('registration_start_date', $this->_values['event'])))), $infoUrl);
         }
         $endDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('registration_end_date', $this->_values['event']));
         if ($endDate && $endDate < $now) {
             CRM_Core_Error::statusBounce(ts('Registration for this event ended on %1', array(1 => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('registration_end_date', $this->_values['event'])))), $infoUrl);
         }
         // check for is_monetary status
         $isMonetary = CRM_Utils_Array::value('is_monetary', $this->_values['event']);
         //retrieve custom information
         $eventID = $this->_eventId;
         $isPayLater = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $eventID, 'is_pay_later');
         //check for variour combination for paylater, payment
         //process with paid event.
         if ($isMonetary && (!$isPayLater || CRM_Utils_Array::value('payment_processor_id', $this->_values['event']))) {
             $ppID = CRM_Utils_Array::value('payment_processor_id', $this->_values['event']);
             if (!$ppID) {
                 CRM_Core_Error::statusBounce(ts('A payment processor must be selected for this event registration page, or the event must be configured to give users the option to pay later (contact the site administrator for assistance).'), $infoUrl);
             }
             require_once 'CRM/Core/BAO/PaymentProcessor.php';
             $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($ppID, $this->_mode);
             // make sure we have a valid payment class, else abort
             if ($this->_values['event']['is_monetary']) {
                 if (!$this->_paymentProcessor) {
                     CRM_Core_Error::fatal(ts('The site administrator must set a Payment Processor for this event in order to use online registration.'));
                 }
                 // ensure that processor has a valid config
                 $payment =& CRM_Core_Payment::singleton($this->_mode, 'Event', $this->_paymentProcessor, $this);
                 $error = $payment->checkConfig();
                 if (!empty($error)) {
                     CRM_Core_Error::fatal($error);
                 }
             }
             $this->_paymentProcessor['processorName'] = $payment->_processorName;
             $this->set('paymentProcessor', $this->_paymentProcessor);
         }
         // get price info
         $price = self::initPriceSet($this, $eventID);
         if ($price == false) {
             if (!isset($this->_values['fee'])) {
                 $this->_values['fee'] = array();
             }
             require_once 'CRM/Core/OptionGroup.php';
             CRM_Core_OptionGroup::getAssoc("civicrm_event.amount.{$eventID}", $this->_values['fee'], true);
             //fix for non-upgraded price sets.CRM-4256.
             if ($isMonetary && empty($this->_values['fee'])) {
                 CRM_Core_Error::fatal(ts('No Fee Level(s) or Price Set is configured for this event.<br />Click <a href=\'%1\'>CiviEvent >> Manage Event >> Configure >> Event Fees</a> to configure the Fee Level(s) or Price Set for this event.', array(1 => CRM_Utils_System::url('civicrm/event/manage', 'reset=1&action=update&subPage=Fee&id=' . $this->_eventId))));
             }
         }
         // get the profile ids
         require_once 'CRM/Core/BAO/UFJoin.php';
         $ufJoinParams = array('entity_table' => 'civicrm_event', 'module' => 'CiviEvent', 'entity_id' => $this->_eventId);
         list($this->_values['custom_pre_id'], $this->_values['custom_post_id']) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
         // set profiles for additional participants
         if ($this->_values['event']['is_multiple_registrations']) {
             require_once 'CRM/Core/BAO/UFJoin.php';
             $ufJoinParams = array('entity_table' => 'civicrm_event', 'module' => 'CiviEvent_Additional', 'entity_id' => $this->_eventId);
             list($this->_values['additional_custom_pre_id'], $this->_values['additional_custom_post_id'], $preActive, $postActive) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
             // CRM-4377: we need to maintain backward compatibility, hence if there is profile for main contact
             // set same profile for additional contacts.
             if ($this->_values['custom_pre_id'] && !$this->_values['additional_custom_pre_id']) {
                 $this->_values['additional_custom_pre_id'] = $this->_values['custom_pre_id'];
             }
             if ($this->_values['custom_post_id'] && !$this->_values['additional_custom_post_id']) {
                 $this->_values['additional_custom_post_id'] = $this->_values['custom_post_id'];
             }
             // now check for no profile condition, in that case is_active = 0
             if (isset($preActive) && !$preActive) {
                 unset($this->_values['additional_custom_pre_id']);
             }
             if (isset($postActive) && !$postActive) {
                 unset($this->_values['additional_custom_post_id']);
             }
         }
         $params = array('id' => $this->_eventId);
         // get the billing location type
         $locationTypes =& CRM_Core_PseudoConstant::locationType();
         $this->_bltID = array_search('Billing', $locationTypes);
         if (!$this->_bltID) {
             CRM_Core_Error::fatal(ts('Please set a location type of %1', array(1 => 'Billing')));
         }
         $this->set('bltID', $this->_bltID);
         if ($this->_values['event']['is_monetary'] && $this->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM) {
             require_once 'CRM/Core/Payment/Form.php';
             CRM_Core_Payment_Form::setCreditCardFields($this);
         }
         $params = array('entity_id' => $this->_eventId, 'entity_table' => 'civicrm_event');
         require_once 'CRM/Core/BAO/Location.php';
         $this->_values['location'] = CRM_Core_BAO_Location::getValues($params, true);
         $this->set('values', $this->_values);
         $this->set('fields', $this->_fields);
     }
     $this->assign_by_ref('paymentProcessor', $this->_paymentProcessor);
     // check if this is a paypal auto return and redirect accordingly
     if (CRM_Core_Payment::paypalRedirect($this->_paymentProcessor)) {
         $url = CRM_Utils_System::url('civicrm/event/register', "_qf_ThankYou_display=1&qfKey={$this->controller->_key}");
         CRM_Utils_System::redirect($url);
     }
     $this->_contributeMode = $this->get('contributeMode');
     $this->assign('contributeMode', $this->_contributeMode);
     // setting CMS page title
     CRM_Utils_System::setTitle($this->_values['event']['title']);
     $this->assign('title', $this->_values['event']['title']);
     $this->assign('paidEvent', $this->_values['event']['is_monetary']);
     // we do not want to display recently viewed items on Registration pages
     $this->assign('displayRecent', false);
     // Registration page values are cleared from session, so can't use normal Printer Friendly view.
     // Use Browser Print instead.
     $this->assign('browserPrint', true);
     // assign all event properties so wizard templates can display event info.
     $this->assign('event', $this->_values['event']);
     $this->assign('location', $this->_values['location']);
     $this->assign('bltID', $this->_bltID);
     $isShowLocation = CRM_Utils_Array::value('is_show_location', $this->_values['event']);
     $this->assign('isShowLocation', $isShowLocation);
 }
 /**
  * This function is called when action is browse
  *
  * return null
  * @access public
  */
 function browse()
 {
     $links = self::links('all', $this->_isPaymentProcessor, $this->_accessContribution);
     $membership = array();
     $dao = new CRM_Member_DAO_Membership();
     $dao->contact_id = $this->_contactId;
     $dao->is_test = 0;
     //$dao->orderBy('name');
     $dao->find();
     //CRM--4418, check for view, edit, delete
     $permissions = array(CRM_Core_Permission::VIEW);
     if (CRM_Core_Permission::check('edit memberships')) {
         $permissions[] = CRM_Core_Permission::EDIT;
     }
     if (CRM_Core_Permission::check('delete in CiviMember')) {
         $permissions[] = CRM_Core_Permission::DELETE;
     }
     $mask = CRM_Core_Action::mask($permissions);
     // get deceased status id
     $allStatus = CRM_Member_PseudoConstant::membershipStatus();
     $deceasedStatusId = array_search('Deceased', $allStatus);
     //get all campaigns.
     $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
     //checks membership of contact itself
     while ($dao->fetch()) {
         $membership[$dao->id] = array();
         CRM_Core_DAO::storeValues($dao, $membership[$dao->id]);
         //carry campaign.
         $membership[$dao->id]['campaign'] = CRM_Utils_Array::value($dao->campaign_id, $allCampaigns);
         //get the membership status and type values.
         $statusANDType = CRM_Member_BAO_Membership::getStatusANDTypeValues($dao->id);
         foreach (array('status', 'membership_type') as $fld) {
             $membership[$dao->id][$fld] = CRM_Utils_Array::value($fld, $statusANDType[$dao->id]);
         }
         if (CRM_Utils_Array::value('is_current_member', $statusANDType[$dao->id])) {
             $membership[$dao->id]['active'] = TRUE;
         }
         if (empty($dao->owner_membership_id)) {
             // unset renew and followup link for deceased membership
             $currentMask = $mask;
             if ($dao->status_id == $deceasedStatusId) {
                 $currentMask = $currentMask & ~CRM_Core_Action::RENEW & ~CRM_Core_Action::FOLLOWUP;
             }
             $isUpdateBilling = false;
             $paymentObject = CRM_Core_BAO_PaymentProcessor::getProcessorForEntity($membership[$dao->id]['membership_id'], 'membership', 'obj');
             if (!empty($paymentObject)) {
                 $isUpdateBilling = $paymentObject->isSupported('updateSubscriptionBillingInfo');
             }
             $isCancelSupported = CRM_Member_BAO_Membership::isCancelSubscriptionSupported($membership[$dao->id]['membership_id']);
             $membership[$dao->id]['action'] = CRM_Core_Action::formLink(self::links('all', NULL, NULL, $isCancelSupported, $isUpdateBilling), $currentMask, array('id' => $dao->id, 'cid' => $this->_contactId));
         } else {
             $membership[$dao->id]['action'] = CRM_Core_Action::formLink(self::links('view'), $mask, array('id' => $dao->id, 'cid' => $this->_contactId));
         }
         //does membership have auto renew CRM-7137.
         if (CRM_Utils_Array::value('contribution_recur_id', $membership[$dao->id]) && !CRM_Member_BAO_Membership::isSubscriptionCancelled($membership[$dao->id]['membership_id'])) {
             $membership[$dao->id]['auto_renew'] = 1;
         } else {
             $membership[$dao->id]['auto_renew'] = 0;
         }
     }
     //Below code gives list of all Membership Types associated
     //with an Organization(CRM-2016)
     $membershipTypes = CRM_Member_BAO_MembershipType::getMembershipTypesByOrg($this->_contactId);
     foreach ($membershipTypes as $key => $value) {
         $membershipTypes[$key]['action'] = CRM_Core_Action::formLink(self::membershipTypeslinks(), $mask, array('id' => $value['id'], 'cid' => $this->_contactId));
     }
     $activeMembers = CRM_Member_BAO_Membership::activeMembers($membership);
     $inActiveMembers = CRM_Member_BAO_Membership::activeMembers($membership, 'inactive');
     $this->assign('activeMembers', $activeMembers);
     $this->assign('inActiveMembers', $inActiveMembers);
     $this->assign('membershipTypes', $membershipTypes);
     if ($this->_contactId) {
         $displayName = CRM_Contact_BAO_Contact::displayName($this->_contactId);
         $this->assign('displayName', $displayName);
     }
 }
 static function process()
 {
     require_once 'CRM/Utils/Request.php';
     $type = CRM_Utils_Request::retrieve('type', 'String', CRM_Core_DAO::$_nullObject, false, 'csv', 'REQUEST');
     $type = strtolower($type);
     switch ($type) {
         case 'paypal':
         case 'google':
             $start = CRM_Utils_Request::retrieve('start', 'String', CRM_Core_DAO::$_nullObject, false, 31, 'REQUEST');
             $end = CRM_Utils_Request::retrieve('end', 'String', CRM_Core_DAO::$_nullObject, false, 0, 'REQUEST');
             if ($start < $end) {
                 CRM_Core_Error::fatal("Start offset can't be less than End offset.");
             }
             $start = date('Y-m-d', time() - $start * 24 * 60 * 60) . 'T00:00:00.00Z';
             $end = date('Y-m-d', time() - $end * 24 * 60 * 60) . 'T23:59:00.00Z';
             $ppID = CRM_Utils_Request::retrieve('ppID', 'Integer', CRM_Core_DAO::$_nullObject, true, null, 'REQUEST');
             $mode = CRM_Utils_Request::retrieve('ppMode', 'String', CRM_Core_DAO::$_nullObject, false, 'live', 'REQUEST');
             require_once 'CRM/Core/BAO/PaymentProcessor.php';
             $paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($ppID, $mode);
             CRM_Core_Error::debug_log_message("Start Date={$start},  End Date={$end}, ppID={$ppID}, mode={$mode} <p>", true);
             return self::$type($paymentProcessor, $mode, $start, $end);
         case 'csv':
             return self::csv();
     }
 }
Beispiel #27
0
 /** 
  * Function to process the form 
  * 
  * @access public 
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         require_once "CRM/Event/BAO/Participant.php";
         CRM_Event_BAO_Participant::deleteParticipant($this->_participantId);
         return;
     }
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     // set the contact, when contact is selected
     if (CRM_Utils_Array::value('contact_select_id', $params)) {
         $this->_contactID = CRM_Utils_Array::value('contact_select_id', $params);
     }
     $config =& CRM_Core_Config::singleton();
     //check if discount is selected
     if (CRM_Utils_Array::value('discount_id', $params)) {
         $discountId = $params['discount_id'];
     } else {
         $params['discount_id'] = 'null';
         $discountId = null;
     }
     if ($this->_isPaidEvent) {
         //lets carry currency, CRM-4453
         $params['fee_currency'] = $config->defaultCurrency;
         // fix for CRM-3088
         if ($discountId && !empty($this->_values['discount'][$discountId])) {
             $params['amount_level'] = $this->_values['discount'][$discountId][$params['amount']]['label'];
             $params['amount'] = $this->_values['discount'][$discountId][$params['amount']]['value'];
             $this->assign('amount_level', $params['amount_level']);
         } else {
             if (!isset($params['priceSetId'])) {
                 $params['amount_level'] = $this->_values['fee'][$params['amount']]['label'];
                 $params['amount'] = $this->_values['fee'][$params['amount']]['value'];
                 $this->assign('amount_level', $params['amount_level']);
             } else {
                 if (!$this->_online) {
                     $lineItem = array();
                     CRM_Price_BAO_Set::processAmount($this->_values['fee']['fields'], $params, $lineItem[0]);
                     $this->set('lineItem', $lineItem);
                     $this->assign('lineItem', $lineItem);
                     $this->_lineItem = $lineItem;
                 }
             }
         }
         $params['fee_level'] = $params['amount_level'];
         $contributionParams = array();
         $contributionParams['total_amount'] = $params['amount'];
     }
     //fix for CRM-3086
     $params['fee_amount'] = $params['amount'];
     $this->_params = $params;
     unset($params['amount']);
     $params['register_date'] = CRM_Utils_Date::processDate($params['register_date'], $params['register_date_time']);
     $params['receive_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $params));
     $params['contact_id'] = $this->_contactID;
     if ($this->_participantId) {
         $params['id'] = $this->_participantId;
     }
     $status = null;
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $participantBAO =& new CRM_Event_BAO_Participant();
         $participantBAO->id = $this->_participantId;
         $participantBAO->find();
         while ($participantBAO->fetch()) {
             $status = $participantBAO->status_id;
             $contributionParams['total_amount'] = $participantBAO->fee_amount;
         }
         $params['discount_id'] = null;
         //re-enter the values for UPDATE mode
         $params['fee_level'] = $params['amount_level'] = $participantBAO->fee_level;
         $params['fee_amount'] = $participantBAO->fee_amount;
     }
     require_once 'CRM/Contact/BAO/Contact.php';
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     $session =& CRM_Core_Session::singleton();
     $userID = $session->get('userID');
     list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
     require_once "CRM/Event/BAO/Participant.php";
     if ($this->_mode) {
         if (!$this->_isPaidEvent) {
             CRM_Core_Error::fatal(ts('Selected Event is not Paid Event '));
         }
         //modify params according to parameter used in create
         //participant method (addParticipant)
         $params['participant_status_id'] = $params['status_id'];
         $params['participant_role_id'] = $params['role_id'];
         $params['participant_register_date'] = $params['register_date'];
         $params['participant_source'] = $params['source'];
         require_once 'CRM/Core/BAO/PaymentProcessor.php';
         $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode);
         require_once "CRM/Contact/BAO/Contact.php";
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields["email-Primary"] = 1;
         $params["email-Primary"] = $params["email-{$this->_bltID}"] = $this->_contributorEmail;
         $params['register_date'] = $now;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
         $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         $fields["email-{$this->_bltID}"] = 1;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $params)) {
                 $params[$name] = $params["billing_{$name}"];
                 $params['preserveDBName'] = true;
             }
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactID, null, null, $ctype);
     }
     // build custom data getFields array
     $customFieldsRole = CRM_Core_BAO_CustomField::getFields('Participant', false, false, CRM_Utils_Array::value('role_id', $params), $this->_roleCustomDataTypeID);
     $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant', false, false, CRM_Utils_Array::value('event_id', $params), $this->_eventNameCustomDataTypeID);
     $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole, CRM_Core_BAO_CustomField::getFields('Participant', false, false, null, null, true));
     $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_participantId, 'Participant');
     if ($this->_mode) {
         // add all the additioanl payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = $this->_params['credit_card_exp_date']['Y'];
         $this->_params['month'] = $this->_params['credit_card_exp_date']['M'];
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $params['fee_amount'];
         $this->_params['amount_level'] = $params['amount_level'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['payment_action'] = 'Sale';
         $this->_params['invoiceID'] = md5(uniqid(rand(), true));
         // 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;
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         require_once 'CRM/Core/Payment/Form.php';
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, true);
         $payment =& CRM_Core_Payment::singleton($this->_mode, 'Event', $this->_paymentProcessor, $this);
         $result =& $payment->doDirectPayment($paymentParams);
         if (is_a($result, 'CRM_Core_Error')) {
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&cid={$this->_contactID}&context=participant&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $this->_params['receive_date'] = $now;
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $this->_params['receipt_date'] = $now;
         } else {
             $this->_params['receipt_date'] = null;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
         $this->assign('receive_date', CRM_Utils_Date::processDate($this->_params['receive_date']));
         // set source if not set
         $this->_params['description'] = ts('Submit Credit Card for Event Registration by: %1', array(1 => $userName));
         require_once 'CRM/Event/Form/Registration/Confirm.php';
         require_once 'CRM/Event/Form/Registration.php';
         //add contribution record
         $this->_params['contribution_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'contribution_type_id');
         $this->_params['mode'] = $this->_mode;
         //add contribution reocord
         $contribution = CRM_Event_Form_Registration_Confirm::processContribution($this, $this->_params, $result, $contactID, false);
         // add participant record
         $participants = array();
         $participants[] = CRM_Event_Form_Registration::addParticipant($this->_params, $contactID);
         //add custom data for participant
         require_once 'CRM/Core/BAO/CustomValueTable.php';
         CRM_Core_BAO_CustomValueTable::postProcess($this->_params, CRM_Core_DAO::$_nullArray, 'civicrm_participant', $participants[0]->id, 'Participant');
         //add participant payment
         require_once 'CRM/Event/BAO/ParticipantPayment.php';
         $paymentParticipant = array('participant_id' => $participants[0]->id, 'contribution_id' => $contribution->id);
         $ids = array();
         CRM_Event_BAO_ParticipantPayment::create($paymentParticipant, $ids);
         $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         $this->_contactIds[] = $this->_contactID;
     } else {
         $participants = array();
         // fix note if deleted
         if (!$params['note']) {
             $params['note'] = 'null';
         }
         if ($this->_single) {
             $participants[] = CRM_Event_BAO_Participant::create($params);
         } else {
             foreach ($this->_contactIds as $contactID) {
                 $commonParams = $params;
                 $commonParams['contact_id'] = $contactID;
                 $participants[] = CRM_Event_BAO_Participant::create($commonParams);
             }
         }
         if (isset($params['event_id'])) {
             $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         }
         if ($this->_single) {
             $this->_contactIds[] = $this->_contactID;
         }
         if (CRM_Utils_Array::value('record_contribution', $params)) {
             if (CRM_Utils_Array::value('id', $params)) {
                 if ($this->_onlinePendingContributionId) {
                     $ids['contribution'] = $this->_onlinePendingContributionId;
                 } else {
                     $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $params['id'], 'contribution_id', 'participant_id');
                 }
             }
             unset($params['note']);
             //build contribution params
             if (!$this->_onlinePendingContributionId) {
                 $contributionParams['source'] = "{$eventTitle}: Offline registration (by {$userName})";
             }
             $contributionParams['currency'] = $config->defaultCurrency;
             $contributionParams['non_deductible_amount'] = 'null';
             $contributionParams['receipt_date'] = CRM_Utils_Array::value('send_receipt', $params) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
             $recordContribution = array('contact_id', 'contribution_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'receive_date', 'check_number');
             foreach ($recordContribution as $f) {
                 $contributionParams[$f] = CRM_Utils_Array::value($f, $params);
                 if ($f == 'trxn_id') {
                     $this->assign('trxn_id', $contributionParams[$f]);
                 }
             }
             //insert contribution type name in receipt.
             $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionType', $contributionParams['contribution_type_id']));
             require_once 'CRM/Contribute/BAO/Contribution.php';
             $contributions = array();
             if ($this->_single) {
                 $contributions[] =& CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
             } else {
                 $ids = array();
                 foreach ($this->_contactIds as $contactID) {
                     $contributionParams['contact_id'] = $contactID;
                     $contributions[] =& CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
                 }
             }
             //insert payment record for this participation
             if (!$ids['contribution']) {
                 require_once 'CRM/Event/DAO/ParticipantPayment.php';
                 foreach ($this->_contactIds as $num => $contactID) {
                     $ppDAO =& new CRM_Event_DAO_ParticipantPayment();
                     $ppDAO->participant_id = $participants[$num]->id;
                     $ppDAO->contribution_id = $contributions[$num]->id;
                     $ppDAO->save();
                 }
             }
         }
     }
     // also store lineitem stuff here
     if ($this->_lineItem) {
         require_once 'CRM/Price/BAO/LineItem.php';
         foreach ($this->_contactIds as $num => $contactID) {
             foreach ($this->_lineItem as $key => $value) {
                 if (is_array($value) && $value != 'skip') {
                     foreach ($value as $line) {
                         $line['entity_table'] = 'civicrm_participant';
                         $line['entity_id'] = $participants[$num]->id;
                         CRM_Price_BAO_LineItem::create($line);
                     }
                 }
             }
         }
     }
     $updateStatusMsg = null;
     //send mail when participant status changed, CRM-4326
     if ($this->_participantId && $this->_statusId && $this->_statusId != CRM_Utils_Array::value('status_id', $params) && CRM_Utils_Array::value('is_notify', $params)) {
         require_once "CRM/Event/BAO/Participant.php";
         $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_participantId, $params['status_id'], $this->_statusId);
     }
     if (CRM_Utils_Array::value('send_receipt', $params)) {
         $receiptFrom = "{$userName} <{$userEmail}>";
         $this->assign('module', 'Event Registration');
         //use of the message template below requires variables in different format
         $event = $events = array();
         $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
         //get all event details.
         CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
         $event = $events[$params['event_id']];
         unset($event['start_date']);
         unset($event['end_date']);
         $role = CRM_Event_PseudoConstant::participantRole();
         $event['participant_role'] = $role[$params['role_id']];
         $event['is_monetary'] = $this->_isPaidEvent;
         if ($params['receipt_text']) {
             $event['confirm_email_text'] = $params['receipt_text'];
         }
         $this->assign('isAmountzero', 1);
         $this->assign('event', $event);
         $this->assign('isShowLocation', $event['is_show_location']);
         if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
             $locationParams = array('entity_id' => $params['event_id'], 'entity_table' => 'civicrm_event');
             require_once 'CRM/Core/BAO/Location.php';
             $location = CRM_Core_BAO_Location::getValues($locationParams, true);
             $this->assign('location', $location);
         }
         $status = CRM_Event_PseudoConstant::participantStatus();
         if ($this->_isPaidEvent) {
             $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
             if (!$this->_mode) {
                 $this->assign('paidBy', CRM_Utils_Array::value($params['payment_instrument_id'], $paymentInstrument));
             }
             $this->assign('totalAmount', $contributionParams['total_amount']);
             $this->assign('isPrimary', 1);
             $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
         }
         if ($this->_mode) {
             if (CRM_Utils_Array::value('billing_first_name', $params)) {
                 $name = $params['billing_first_name'];
             }
             if (CRM_Utils_Array::value('billing_middle_name', $params)) {
                 $name .= " {$params['billing_middle_name']}";
             }
             if (CRM_Utils_Array::value('billing_last_name', $params)) {
                 $name .= " {$params['billing_last_name']}";
             }
             $this->assign('billingName', $name);
             // assign the address formatted up for display
             $addressParts = array("street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "state_province-{$this->_bltID}", "country-{$this->_bltID}");
             $addressFields = array();
             foreach ($addressParts as $part) {
                 list($n, $id) = explode('-', $part);
                 if (isset($this->_params['billing_' . $part])) {
                     $addressFields[$n] = $this->_params['billing_' . $part];
                 }
             }
             require_once 'CRM/Utils/Address.php';
             $this->assign('address', CRM_Utils_Address::format($addressFields));
             $date = CRM_Utils_Date::format($params['credit_card_exp_date']);
             $date = CRM_Utils_Date::mysqlToIso($date);
             $this->assign('credit_card_exp_date', $date);
             $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($params['credit_card_number']));
             $this->assign('credit_card_type', $params['credit_card_type']);
             $this->assign('contributeMode', 'direct');
             $this->assign('isAmountzero', 0);
             $this->assign('is_pay_later', 0);
             $this->assign('isPrimary', 1);
         }
         $this->assign('register_date', $params['register_date']);
         if ($params['receive_date']) {
             $this->assign('receive_date', $params['receive_date']);
         }
         $participant = array(array('participant_id', '=', $participants[0]->id, 0, 0));
         // check whether its a test drive ref CRM-3075
         if (CRM_Utils_Array::value('is_test', $this->_defaultValues)) {
             $participant[] = array('participant_test', '=', 1, 0, 0);
         }
         $template =& CRM_Core_Smarty::singleton();
         $customGroup = array();
         //format submitted data
         foreach ($params['custom'] as $fieldID => $values) {
             foreach ($values as $fieldValue) {
                 $customValue = array('data' => $fieldValue['value']);
                 $customFields[$fieldID]['id'] = $fieldID;
                 $formattedValue = CRM_Core_BAO_CustomGroup::formatCustomValues($customValue, $customFields[$fieldID]);
                 $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
             }
         }
         foreach ($this->_contactIds as $num => $contactID) {
             // Retrieve the name and email of the contact - this will be the TO for receipt email
             list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
             $this->_contributorDisplayName = $this->_contributorDisplayName == ' ' ? $this->_contributorEmail : $this->_contributorDisplayName;
             $this->assign('customGroup', $customGroup);
             $this->assign('contactID', $contactID);
             $this->assign('participantID', $participants[$num]->id);
             if ($this->_isPaidEvent) {
                 // fix amount for each of participants ( for bulk mode )
                 $eventAmount = array();
                 $eventAmount[$num] = array('label' => $params['amount_level'], 'amount' => $params['fee_amount']);
                 //as we are using same template for online & offline registration.
                 //So we have to build amount as array.
                 $this->assign('amount', $eventAmount);
             }
             $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'event_offline_receipt', 'contactId' => $contactID, 'isTest' => (bool) CRM_Utils_Array::value('is_test', $this->_defaultValues));
             // 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 and !$this->_toDoNotEmail) {
                 $sendTemplateParams['from'] = $receiptFrom;
                 $sendTemplateParams['toName'] = $this->_contributorDisplayName;
                 $sendTemplateParams['toEmail'] = $this->_contributorEmail;
             }
             require_once 'CRM/Core/BAO/MessageTemplates.php';
             list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplates::sendTemplate($sendTemplateParams);
             if ($mailSent) {
                 $sent[] = $contactID;
             } else {
                 $notSent[] = $contactID;
             }
         }
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contributorDisplayName));
         if ($params['send_receipt'] && count($sent)) {
             $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', array(1 => $this->_contributorEmail));
         }
         if ($updateStatusMsg) {
             $statusMsg = "{$statusMsg} {$updateStatusMsg}";
         }
     } elseif ($this->_action & CRM_Core_Action::ADD) {
         if ($this->_single) {
             $statusMsg = ts('Event registration for %1 has been added.', array(1 => $this->_contributorDisplayName));
             if (CRM_Utils_Array::value('send_receipt', $params) && count($sent)) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $this->_contributorEmail));
             }
         } else {
             $statusMsg = ts('Total Participant(s) added to event: %1.', array(1 => count($this->_contactIds)));
             if (count($notSent) > 0) {
                 $statusMsg .= ' ' . ts('Email has NOT been sent to %1 contact - communication preferences specify DO NOT EMAIL OR valid Email is NOT present. ', array(1 => count($notSent)));
             } elseif (isset($params['send_receipt'])) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to ALL participants');
             }
         }
     }
     require_once "CRM/Core/Session.php";
     CRM_Core_Session::setStatus("{$statusMsg}");
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=participant"));
         }
     } else {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&context=participant&cid={$this->_contactID}"));
         }
     }
 }
 /** 
  * Function to set variables up before form is built 
  *                                                           
  * @return void 
  * @access public 
  */
 public function preProcess()
 {
     $config = CRM_Core_Config::singleton();
     $session = CRM_Core_Session::singleton();
     // current contribution page id
     $this->_id = CRM_Utils_Request::retrieve('id', 'Positive', $this);
     if (!$this->_id) {
         $pastContributionID = $session->get('pastContributionID');
         if (!$pastContributionID) {
             CRM_Core_Error::fatal(ts('We can\'t load the requested web page due to an incomplete link. This can be caused by using your browser\'s Back button or by using an incomplete or invalid link.'));
         } else {
             CRM_Core_Error::fatal(ts('This contribution has already been submitted. Click <a href=\'%1\'>here</a> if you want to make another contribution.', array(1 => CRM_Utils_System::url('civicrm/contribute/transact', 'reset=1&id=' . $pastContributionID))));
         }
     } else {
         $session->set('pastContributionID', $this->_id);
     }
     $this->_userID = $session->get('userID');
     $this->_mid = null;
     if ($this->_userID) {
         $this->_mid = CRM_Utils_Request::retrieve('mid', 'Positive', $this);
         if ($this->_mid) {
             require_once 'CRM/Member/DAO/Membership.php';
             $membership = new CRM_Member_DAO_Membership();
             $membership->id = $this->_mid;
             if ($membership->find(true)) {
                 $this->_defaultMemTypeId = $membership->membership_type_id;
                 if ($membership->contact_id != $this->_userID) {
                     require_once 'CRM/Contact/BAO/Relationship.php';
                     $employers = CRM_Contact_BAO_Relationship::getPermissionedEmployer($this->_userID);
                     if (array_key_exists($membership->contact_id, $employers)) {
                         $this->_membershipContactID = $membership->contact_id;
                         $this->assign('membershipContactID', $this->_membershipContactID);
                         $this->assign('membershipContactName', $employers[$this->_membershipContactID]['name']);
                     } else {
                         CRM_Core_Session::setStatus(ts("Oops. The membership you're trying to renew appears to be invalid. Contact your site administrator if you need assistance. If you continue, you will be issued a new membership."));
                     }
                 }
             } else {
                 CRM_Core_Session::setStatus(ts("Oops. The membership you're trying to renew appears to be invalid. Contact your site administrator if you need assistance. If you continue, you will be issued a new membership."));
             }
             unset($membership);
         }
     }
     // we do not want to display recently viewed items, so turn off
     $this->assign('displayRecent', false);
     // Contribution page values are cleared from session, so can't use normal Printer Friendly view.
     // Use Browser Print instead.
     $this->assign('browserPrint', true);
     // action
     $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, false, 'add');
     $this->assign('action', $this->_action);
     // current mode
     $this->_mode = $this->_action == 1024 ? 'test' : 'live';
     $this->_values = $this->get('values');
     $this->_fields = $this->get('fields');
     $this->_bltID = $this->get('bltID');
     $this->_paymentProcessor = $this->get('paymentProcessor');
     $this->_priceSetId = $this->get('priceSetId');
     $this->_priceSet = $this->get('priceSet');
     if (!$this->_values) {
         // get all the values from the dao object
         $this->_values = array();
         $this->_fields = array();
         require_once 'CRM/Contribute/BAO/ContributionPage.php';
         CRM_Contribute_BAO_ContributionPage::setValues($this->_id, $this->_values);
         // check if form is active
         if (!$this->_values['is_active']) {
             // form is inactive, die a fatal death
             CRM_Core_Error::fatal(ts('The page you requested is currently unavailable.'));
         }
         // also check for billing informatin
         // get the billing location type
         $locationTypes =& CRM_Core_PseudoConstant::locationType();
         $this->_bltID = array_search('Billing', $locationTypes);
         if (!$this->_bltID) {
             CRM_Core_Error::fatal(ts('Please set a location type of %1', array(1 => 'Billing')));
         }
         $this->set('bltID', $this->_bltID);
         // check for is_monetary status
         $isMonetary = CRM_Utils_Array::value('is_monetary', $this->_values);
         $isPayLater = CRM_Utils_Array::value('is_pay_later', $this->_values);
         if ($isMonetary && (!$isPayLater || CRM_Utils_Array::value('payment_processor_id', $this->_values))) {
             $ppID = CRM_Utils_Array::value('payment_processor_id', $this->_values);
             if (!$ppID) {
                 CRM_Core_Error::fatal(ts('A payment processor must be selected for this contribution page (contact the site administrator for assistance).'));
             }
             require_once 'CRM/Core/BAO/PaymentProcessor.php';
             $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($ppID, $this->_mode);
             // check selected payment processor is active
             if (empty($this->_paymentProcessor)) {
                 CRM_Core_Error::fatal(ts('A payment processor configured for this page might be disabled (contact the site administrator for assistance).'));
             }
             // ensure that processor has a valid config
             $this->_paymentObject =& CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
             $error = $this->_paymentObject->checkConfig();
             if (!empty($error)) {
                 CRM_Core_Error::fatal($error);
             }
             $this->_paymentProcessor['processorName'] = $this->_paymentObject->_processorName;
             $this->set('paymentProcessor', $this->_paymentProcessor);
         }
         // get price info
         // CRM-5095
         require_once 'CRM/Price/BAO/Set.php';
         CRM_Price_BAO_Set::initSet($this, $this->_id, 'civicrm_contribution_page');
         // this avoids getting E_NOTICE errors in php
         $setNullFields = array('amount_block_is_active', 'honor_block_is_active', 'is_allow_other_amount', 'footer_text');
         foreach ($setNullFields as $f) {
             if (!isset($this->_values[$f])) {
                 $this->_values[$f] = null;
             }
         }
         //check if Membership Block is enabled, if Membership Fields are included in profile
         //get membership section for this contribution page
         require_once 'CRM/Member/BAO/Membership.php';
         $this->_membershipBlock = CRM_Member_BAO_Membership::getMembershipBlock($this->_id);
         $this->set('membershipBlock', $this->_membershipBlock);
         require_once "CRM/Core/BAO/UFField.php";
         if ($this->_values['custom_pre_id']) {
             $preProfileType = CRM_Core_BAO_UFField::getProfileType($this->_values['custom_pre_id']);
         }
         if ($this->_values['custom_post_id']) {
             $postProfileType = CRM_Core_BAO_UFField::getProfileType($this->_values['custom_post_id']);
         }
         // also set cancel subscription url
         if (CRM_Utils_Array::value('is_recur', $this->_paymentProcessor) && CRM_Utils_Array::value('is_recur', $this->_values)) {
             $this->_values['cancelSubscriptionUrl'] = $this->_paymentObject->cancelSubscriptionURL();
         }
         if ((isset($postProfileType) && $postProfileType == 'Membership' || isset($preProfileType) && $preProfileType == 'Membership') && !$this->_membershipBlock['is_active']) {
             CRM_Core_Error::fatal(ts('This page includes a Profile with Membership fields - but the Membership Block is NOT enabled. Please notify the site administrator.'));
         }
         require_once 'CRM/Pledge/BAO/PledgeBlock.php';
         $pledgeBlock = CRM_Pledge_BAO_PledgeBlock::getPledgeBlock($this->_id);
         if ($pledgeBlock) {
             $this->_values['pledge_block_id'] = CRM_Utils_Array::value('id', $pledgeBlock);
             $this->_values['max_reminders'] = CRM_Utils_Array::value('max_reminders', $pledgeBlock);
             $this->_values['initial_reminder_day'] = CRM_Utils_Array::value('initial_reminder_day', $pledgeBlock);
             $this->_values['additional_reminder_day'] = CRM_Utils_Array::value('additional_reminder_day', $pledgeBlock);
             //set pledge id in values
             $pledgeId = CRM_Utils_Request::retrieve('pledgeId', 'Positive', $this);
             //authenticate pledge user for pledge payment.
             if ($pledgeId) {
                 $this->_values['pledge_id'] = $pledgeId;
                 self::authenticatePledgeUser();
             }
         }
         $this->set('values', $this->_values);
         $this->set('fields', $this->_fields);
     }
     require_once 'CRM/Contribute/BAO/PCP.php';
     $pcpId = CRM_Utils_Request::retrieve('pcpId', 'Positive', $this);
     if ($pcpId) {
         require_once 'CRM/Core/OptionGroup.php';
         $approvedId = CRM_Core_OptionGroup::getValue('pcp_status', 'Approved', 'name');
         $prms = array('entity_id' => $this->_values['id'], 'entity_table' => 'civicrm_contribution_page');
         require_once 'CRM/Contribute/PseudoConstant.php';
         $pcpStatus = CRM_Contribute_PseudoConstant::pcpStatus();
         CRM_Core_DAO::commonRetrieve('CRM_Contribute_DAO_PCPBlock', $prms, $pcpBlock);
         $prms = array('id' => $pcpId);
         CRM_Core_DAO::commonRetrieve('CRM_Contribute_DAO_PCP', $prms, $pcpInfo);
         //start and end date of the contribution page
         $startDate = CRM_Utils_Date::unixTime(CRM_Utils_Array::value('start_date', $this->_values));
         $endDate = CRM_Utils_Date::unixTime(CRM_Utils_Array::value('end_date', $this->_values));
         $now = time();
         if ($pcpInfo['contribution_page_id'] != $this->_values['id']) {
             $statusMessage = ts('This contribution page is not related to the Personal Campaign Page you have just visited. However you can still make a contribution here.');
             CRM_Core_Error::statusBounce($statusMessage, CRM_Utils_System::url('civicrm/contribute/transact', "reset=1&id={$this->_values['id']}", false, null, false, true));
         } else {
             if ($pcpInfo['status_id'] != $approvedId) {
                 $statusMessage = ts('The Personal Campaign Page you have just visited is currently %1. However you can still support the campaign by making a contribution here.', array(1 => $pcpStatus[$pcpInfo['status_id']]));
                 CRM_Core_Error::statusBounce($statusMessage, CRM_Utils_System::url('civicrm/contribute/transact', "reset=1&id={$pcpInfo['contribution_page_id']}", false, null, false, true));
             } else {
                 if (!CRM_Utils_Array::value('is_active', $pcpBlock)) {
                     $statusMessage = ts('Personal Campaign Pages are currently not enabled for this contribution page. However you can still support the campaign by making a contribution here.');
                     CRM_Core_Error::statusBounce($statusMessage, CRM_Utils_System::url('civicrm/contribute/transact', "reset=1&id={$pcpInfo['contribution_page_id']}", false, null, false, true));
                 } else {
                     if (!CRM_Utils_Array::value('is_active', $pcpInfo)) {
                         $statusMessage = ts('The Personal Campaign Page you have just visited is current inactive. However you can still make a contribution here.');
                         CRM_Core_Error::statusBounce($statusMessage, CRM_Utils_System::url('civicrm/contribute/transact', "reset=1&id={$pcpInfo['contribution_page_id']}", false, null, false, true));
                     } else {
                         if ($startDate && $startDate > $now || $endDate && $endDate < $now) {
                             $customStartDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $this->_values));
                             $customEndDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $this->_values));
                             if ($startDate && $endDate) {
                                 $statusMessage = ts('The Personal Campaign Page you have just visited is only active between %1 to %2. However you can still support the campaign by making a contribution here.', array(1 => $customStartDate, 2 => $customEndDate));
                                 CRM_Core_Error::statusBounce($statusMessage, CRM_Utils_System::url('civicrm/contribute/transact', "reset=1&id={$pcpInfo['contribution_page_id']}", false, null, false, true));
                             } else {
                                 if ($startDate) {
                                     $statusMessage = ts('The Personal Campaign Page you have just visited will be active beginning on %1. However you can still support the campaign by making a contribution here.', array(1 => $customStartDate));
                                     CRM_Core_Error::statusBounce($statusMessage, CRM_Utils_System::url('civicrm/contribute/transact', "reset=1&id={$pcpInfo['contribution_page_id']}", false, null, false, true));
                                 } else {
                                     if ($endDate) {
                                         $statusMessage = ts('The Personal Campaign Page you have just visited is not longer active (as of %1). However you can still support the campaign by making a contribution here.', array(1 => $customEndDate));
                                         CRM_Core_Error::statusBounce($statusMessage, CRM_Utils_System::url('civicrm/contribute/transact', "reset=1&id={$pcpInfo['contribution_page_id']}", false, null, false, true));
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
         $this->_pcpId = $pcpId;
         $this->_pcpBlock = $pcpBlock;
         $this->_pcpInfo = $pcpInfo;
     }
     // Link (button) for users to create their own Personal Campaign page
     if ($linkText = CRM_Contribute_BAO_PCP::getPcpBlockStatus($this->_id)) {
         $linkTextUrl = CRM_Utils_System::url('civicrm/contribute/campaign', "action=add&reset=1&pageId={$this->_id}", false, null, true);
         $this->assign('linkTextUrl', $linkTextUrl);
         $this->assign('linkText', $linkText);
     }
     //set pledge block if block id is set
     if (CRM_Utils_Array::value('pledge_block_id', $this->_values)) {
         $this->assign('pledgeBlock', true);
     }
     // we do this outside of the above conditional to avoid
     // saving the country/state list in the session (which could be huge)
     if ($this->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM && CRM_Utils_Array::value('is_monetary', $this->_values)) {
         require_once 'CRM/Core/Payment/Form.php';
         require_once 'CRM/Core/Payment.php';
         // payment fields are depending on payment type
         if ($this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_DIRECT_DEBIT) {
             CRM_Core_Payment_Form::setDirectDebitFields($this);
         } else {
             CRM_Core_Payment_Form::setCreditCardFields($this);
         }
     }
     $this->assign_by_ref('paymentProcessor', $this->_paymentProcessor);
     // check if this is a paypal auto return and redirect accordingly
     if (CRM_Core_Payment::paypalRedirect($this->_paymentProcessor)) {
         $url = CRM_Utils_System::url('civicrm/contribute/transact', "_qf_ThankYou_display=1&qfKey={$this->controller->_key}");
         CRM_Utils_System::redirect($url);
     }
     // make sure we have a valid payment class, else abort
     if (CRM_Utils_Array::value('is_monetary', $this->_values) && !$this->_paymentProcessor['class_name'] && !CRM_Utils_Array::value('is_pay_later', $this->_values)) {
         CRM_Core_Error::fatal(ts('Payment processor is not set for this page'));
     }
     // check if one of the (amount , membership)  bloks is active or not
     require_once 'CRM/Member/BAO/Membership.php';
     $this->_membershipBlock = $this->get('membershipBlock');
     if (!$this->_values['amount_block_is_active'] && !$this->_membershipBlock['is_active'] && !$this->_priceSetId) {
         CRM_Core_Error::fatal(ts('The requested online contribution page is missing a required Contribution Amount section or Membership section or Price Set. Please check with the site administrator for assistance.'));
     }
     if ($this->_values['amount_block_is_active']) {
         $this->set('amount_block_is_active', $this->_values['amount_block_is_active']);
     }
     if (!empty($this->_membershipBlock) && CRM_Utils_Array::value('is_separate_payment', $this->_membershipBlock) && !($this->_paymentProcessor['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM)) {
         CRM_Core_Error::fatal(ts('This contribution page is configured to support separate contribution and membership payments. This %1 plugin does not currently support multiple simultaneous payments. Please contact the site administrator and notify them of this error', array(1 => $this->_paymentProcessor['payment_processor_type'])));
     }
     $this->_contributeMode = $this->get('contributeMode');
     $this->assign('contributeMode', $this->_contributeMode);
     //assigning is_monetary and is_email_receipt to template
     $this->assign('is_monetary', $this->_values['is_monetary']);
     $this->assign('is_email_receipt', $this->_values['is_email_receipt']);
     $this->assign('bltID', $this->_bltID);
     //assign cancelSubscription URL to templates
     $this->assign('cancelSubscriptionUrl', CRM_Utils_Array::value('cancelSubscriptionUrl', $this->_values));
     // assigning title to template in case someone wants to use it, also setting CMS page title
     if ($this->_pcpId) {
         $this->assign('title', $pcpInfo['title']);
         CRM_Utils_System::setTitle($pcpInfo['title']);
     } else {
         $this->assign('title', $this->_values['title']);
         CRM_Utils_System::setTitle($this->_values['title']);
     }
     $this->_defaults = array();
     $this->_amount = $this->get('amount');
     //CRM-6907
     $config = CRM_Core_Config::singleton();
     $config->defaultCurrency = CRM_Utils_Array::value('currency', $this->_values, $config->defaultCurrency);
 }
 /**
  * This method is handles the response that will be invoked (from extern/googleNotify) every time
  * a notification or request is sent by the Google Server.
  *
  */
 static function main($xml_response)
 {
     require_once 'Google/library/googleresponse.php';
     require_once 'Google/library/googlerequest.php';
     require_once 'Google/library/googlemerchantcalculations.php';
     require_once 'Google/library/googleresult.php';
     require_once 'Google/library/xml-processing/gc_xmlparser.php';
     $config = CRM_Core_Config::singleton();
     // Retrieve the XML sent in the HTTP POST request to the ResponseHandler
     if (get_magic_quotes_gpc()) {
         $xml_response = stripslashes($xml_response);
     }
     $headers = CRM_Utils_System::getAllHeaders();
     if (GOOGLE_DEBUG_PP) {
         CRM_Core_Error::debug_var('RESPONSE', $xml_response, TRUE, TRUE, 'Google');
     }
     // Retrieve the root and data from the xml response
     $response = new GoogleResponse();
     list($root, $data) = $response->GetParsedXML($xml_response);
     // lets retrieve the private-data & order-no
     $privateData = NULL;
     if (array_key_exists('shopping-cart', $data[$root])) {
         $privateData = $data[$root]['shopping-cart']['merchant-private-data']['VALUE'];
     }
     if (empty($privateData) && array_key_exists('order-summary', $data[$root]) && array_key_exists('shopping-cart', $data[$root]['order-summary'])) {
         $privateData = $data[$root]['order-summary']['shopping-cart']['merchant-private-data']['VALUE'];
     }
     $privateData = $privateData ? self::stringToArray($privateData) : '';
     $orderNo = $data[$root]['google-order-number']['VALUE'];
     $serial = $data[$root]['serial-number'];
     // a dummy object to call get context and a parent function inside it.
     $ipn = new CRM_Core_Payment_GoogleIPN('live', $dummyProcessor);
     list($mode, $module, $paymentProcessorID) = $ipn->getContext($privateData, $orderNo, $root, $response, $serial);
     $mode = $mode ? 'test' : 'live';
     $paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($paymentProcessorID, $mode);
     $merchant_id = $paymentProcessor['user_name'];
     $merchant_key = $paymentProcessor['password'];
     $response->SetMerchantAuthentication($merchant_id, $merchant_key);
     $server_type = $mode == 'test' ? 'sandbox' : 'production';
     $request = new GoogleRequest($merchant_id, $merchant_key, $server_type);
     $ipn = self::singleton($mode, $module, $paymentProcessor);
     if (GOOGLE_DEBUG_PP) {
         CRM_Core_Error::debug_var('RESPONSE-ROOT', $response->root, TRUE, TRUE, 'Google');
     }
     //Check status and take appropriate action
     $status = $response->HttpAuthentication($headers);
     switch ($root) {
         case "request-received":
         case "error":
         case "diagnosis":
         case "checkout-redirect":
         case "merchant-calculation-callback":
             break;
         case "new-order-notification":
             $response->SendAck($serial, FALSE);
             $ipn->newOrderNotify($data[$root], $privateData, $module);
             break;
         case "order-state-change-notification":
             $response->SendAck($serial, FALSE);
             $new_financial_state = $data[$root]['new-financial-order-state']['VALUE'];
             $new_fulfillment_order = $data[$root]['new-fulfillment-order-state']['VALUE'];
             switch ($new_financial_state) {
                 case 'CHARGEABLE':
                     break;
                 case 'CHARGED':
                 case 'PAYMENT_DECLINED':
                 case 'CANCELLED':
                 case 'CANCELLED_BY_GOOGLE':
                     $ipn->orderStateChange($new_financial_state, $data[$root], $privateData, $module);
                     break;
                 case 'REVIEWING':
                 case 'CHARGING':
                     break;
                 default:
                     break;
             }
             break;
         case "authorization-amount-notification":
             $response->SendAck($serial, FALSE);
             $new_financial_state = $data[$root]['order-summary']['financial-order-state']['VALUE'];
             $new_fulfillment_order = $data[$root]['order-summary']['fulfillment-order-state']['VALUE'];
             switch ($new_financial_state) {
                 case 'CHARGEABLE':
                     // For google-handled subscriptions chargeorder needn't be initiated,
                     // assuming auto-charging is turned on.
                     //$request->SendProcessOrder($data[$root]['google-order-number']['VALUE']);
                     //$request->SendChargeOrder($data[$root]['google-order-number']['VALUE'],'');
                     break;
                 case 'CHARGED':
                 case 'PAYMENT_DECLINED':
                 case 'CANCELLED':
                     break;
                 case 'REVIEWING':
                 case 'CHARGING':
                 case 'CANCELLED_BY_GOOGLE':
                     break;
                 default:
                     break;
             }
             break;
         case "charge-amount-notification":
         case "chargeback-amount-notification":
         case "refund-amount-notification":
         case "risk-information-notification":
             $response->SendAck($serial);
             break;
         default:
             break;
     }
 }
 /**
  * Function to retrieve payment processor id / info/ object based on component-id.
  *
  * @param int    $componentID id of a component
  * @param string $component   component
  * @param string $type        type of payment information to be retrieved
  *
  * @return id / array / object based on type
  * @static
  * @access public 
  */
 static function getProcessorForEntity($entityID, $component = 'contribute', $type = 'id')
 {
     if (!in_array($component, array('membership', 'contribute'))) {
         return null;
     }
     if ($component == 'membership') {
         $sql = " \n    SELECT cr.payment_processor_id as ppID1, cp.payment_processor_id as ppID2, con.is_test \n      FROM civicrm_membership mem\nINNER JOIN civicrm_membership_payment mp  ON ( mem.id = mp.membership_id ) \nINNER JOIN civicrm_contribution       con ON ( mp.contribution_id = con.id )\n LEFT JOIN civicrm_contribution_recur cr  ON ( mem.contribution_recur_id = cr.id )\n LEFT JOIN civicrm_contribution_page  cp  ON ( con.contribution_page_id  = cp.id )\n     WHERE mp.membership_id = %1";
     } else {
         if ($component == 'contribute') {
             $sql = " \n    SELECT cr.payment_processor_id as ppID1, cp.payment_processor_id as ppID2, con.is_test \n      FROM civicrm_contribution       con\n LEFT JOIN civicrm_contribution_recur cr  ON ( con.contribution_recur_id = cr.id )\n LEFT JOIN civicrm_contribution_page  cp  ON ( con.contribution_page_id  = cp.id )\n     WHERE con.id = %1";
         }
     }
     $params = array(1 => array($entityID, 'Integer'));
     $dao = CRM_Core_DAO::executeQuery($sql, $params);
     $dao->fetch();
     $ppID = $dao->ppID1 ? $dao->ppID1 : $dao->ppID2;
     $mode = $dao->is_test ? 'test' : 'live';
     if (!$ppID || $type == 'id') {
         return $ppID;
     } else {
         if ($type == 'info') {
             return CRM_Core_BAO_PaymentProcessor::getPayment($ppID, $mode);
         } else {
             if ($type == 'obj') {
                 $payment = CRM_Core_BAO_PaymentProcessor::getPayment($ppID, $mode);
                 return CRM_Core_Payment::singleton($mode, $payment);
             }
         }
     }
     return null;
 }