Example #1
0
 function create($id = null)
 {
     require_once "CRM/Contribute/BAO/ContributionPage.php";
     $params = array('title' => 'Help Test CiviCRM!', 'intro_text' => 'Created for Test Coverage Online Contribution Page', 'contribution_type_id' => 1, 'payment_processor_id' => $id, 'is_monetary' => 1, 'is_allow_other_amount' => 1, 'min_amount' => 10, 'max_amount' => 10000, 'goal_amount' => 100000, 'thankyou_title' => 'Thanks for Your Support!', 'thankyou_text' => 'Thank you for your support.', 'is_email_receipt' => 1, 'receipt_from_name' => 'From TEST', 'receipt_from_email' => '*****@*****.**', 'cc_receipt' => '*****@*****.**', 'bcc_receipt' => '*****@*****.**', 'is_active' => 1);
     $contributionPage = CRM_Contribute_BAO_ContributionPage::create($params);
     return $contributionPage->id;
 }
Example #2
0
 /**
  * Function used to build form element for soft credit block.
  *
  * @param CRM_Core_Form $form
  *
  * @return \CRM_Core_Form
  */
 public static function buildQuickForm(&$form)
 {
     if (!empty($form->_honor_block_is_active)) {
         $ufJoinDAO = new CRM_Core_DAO_UFJoin();
         $ufJoinDAO->module = 'soft_credit';
         $ufJoinDAO->entity_id = $form->_id;
         if ($ufJoinDAO->find(TRUE)) {
             $jsonData = CRM_Contribute_BAO_ContributionPage::formatModuleData($ufJoinDAO->module_data, TRUE, 'soft_credit');
             if ($jsonData) {
                 foreach (array('honor_block_title', 'honor_block_text') as $name) {
                     $form->assign($name, $jsonData[$name]);
                 }
                 $softCreditTypes = CRM_Core_OptionGroup::values("soft_credit_type", FALSE);
                 // radio button for Honor Type
                 foreach ($jsonData['soft_credit_types'] as $value) {
                     $honorTypes[$value] = $form->createElement('radio', NULL, NULL, $softCreditTypes[$value], $value);
                 }
                 $form->addGroup($honorTypes, 'soft_credit_type_id', NULL)->setAttribute('allowClear', TRUE);
             }
         }
         return $form;
     }
     // by default generate 10 blocks
     $item_count = 11;
     $showSoftCreditRow = 2;
     if ($form->getAction() & CRM_Core_Action::UPDATE) {
         $form->_softCreditInfo = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($form->_id, TRUE);
     } elseif (!empty($form->_pledgeID)) {
         //Check and select most recent completed contrubtion and use it to retrieve
         //soft-credit information to use as default for current pledge payment, CRM-13981
         $pledgePayments = CRM_Pledge_BAO_PledgePayment::getPledgePayments($form->_pledgeID);
         foreach ($pledgePayments as $id => $record) {
             if ($record['contribution_id']) {
                 $softCredits = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($record['contribution_id'], TRUE);
                 if ($record['status'] == 'Completed' && count($softCredits) > 0) {
                     $form->_softCreditInfo = $softCredits;
                 }
             }
         }
     }
     if (property_exists($form, "_softCreditInfo")) {
         if (!empty($form->_softCreditInfo['soft_credit'])) {
             $showSoftCreditRow = count($form->_softCreditInfo['soft_credit']);
             $showSoftCreditRow++;
         }
     }
     for ($rowNumber = 1; $rowNumber <= $item_count; $rowNumber++) {
         $form->addEntityRef("soft_credit_contact_id[{$rowNumber}]", ts('Contact'), array('create' => TRUE));
         $form->addMoney("soft_credit_amount[{$rowNumber}]", ts('Amount'), FALSE, NULL, FALSE);
         $form->addSelect("soft_credit_type[{$rowNumber}]", array('entity' => 'contribution_soft', 'field' => 'soft_credit_type_id', 'label' => ts('Type')));
         if (!empty($form->_softCreditInfo['soft_credit'][$rowNumber]['soft_credit_id'])) {
             $form->add('hidden', "soft_credit_id[{$rowNumber}]", $form->_softCreditInfo['soft_credit'][$rowNumber]['soft_credit_id']);
         }
     }
     self::addPCPFields($form);
     $form->assign('showSoftCreditRow', $showSoftCreditRow);
     $form->assign('rowCount', $item_count);
     $form->addElement('hidden', 'sct_default_id', CRM_Core_OptionGroup::getDefaultValue("soft_credit_type"), array('id' => 'sct_default_id'));
 }
Example #3
0
 /**
  * Process the form
  *
  * @return void
  * @access public
  */
 function postProcess()
 {
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     // we do this in case the user has hit the forward/back button
     if ($this->_id) {
         $params['id'] = $this->_id;
     }
     $params['domain_id'] = CRM_Core_Config::domainID();
     $params['is_active'] = CRM_Utils_Array::value('is_active', $params, false);
     $params['is_credit_card_only'] = CRM_Utils_Array::value('is_credit_card_only', $params, false);
     require_once 'CRM/Contribute/BAO/ContributionPage.php';
     $dao =& CRM_Contribute_BAO_ContributionPage::create($params);
     $this->set('id', $dao->id);
 }
 static function process(&$form)
 {
     if ($form->getVar('_id') <= 0) {
         return NULL;
     }
     $tabs = array('settings' => array('title' => ts('Title'), 'link' => NULL, 'valid' => FALSE, 'active' => FALSE, 'current' => FALSE), 'amount' => array('title' => ts('Amounts'), 'link' => NULL, 'valid' => FALSE, 'active' => FALSE, 'current' => FALSE), 'membership' => array('title' => ts('Memberships'), 'link' => NULL, 'valid' => FALSE, 'active' => FALSE, 'current' => FALSE), 'thankyou' => array('title' => ts('Receipt'), 'link' => NULL, 'valid' => FALSE, 'active' => FALSE, 'current' => FALSE), 'friend' => array('title' => ts('Tell a Friend'), 'link' => NULL, 'valid' => FALSE, 'active' => FALSE, 'current' => FALSE), 'custom' => array('title' => ts('Profiles'), 'link' => NULL, 'valid' => FALSE, 'active' => FALSE, 'current' => FALSE), 'premium' => array('title' => ts('Premiums'), 'link' => NULL, 'valid' => FALSE, 'active' => FALSE, 'current' => FALSE), 'widget' => array('title' => ts('Widgets'), 'link' => NULL, 'valid' => FALSE, 'active' => FALSE, 'current' => FALSE), 'pcp' => array('title' => ts('Personal Campaigns'), 'link' => NULL, 'valid' => FALSE, 'active' => FALSE, 'current' => FALSE));
     $contribPageId = $form->getVar('_id');
     $fullName = $form->getVar('_name');
     $className = CRM_Utils_String::getClassName($fullName);
     // Hack for special cases.
     switch ($className) {
         case 'Contribute':
             $attributes = $form->getVar('_attributes');
             $class = strtolower(basename(CRM_Utils_Array::value('action', $attributes)));
             break;
         case 'MembershipBlock':
             $class = 'membership';
             break;
         default:
             $class = strtolower($className);
             break;
     }
     $qfKey = $form->get('qfKey');
     $form->assign('qfKey', $qfKey);
     if (array_key_exists($class, $tabs)) {
         $tabs[$class]['current'] = TRUE;
     }
     if ($contribPageId) {
         $reset = CRM_Utils_Array::value('reset', $_GET) ? 'reset=1&' : '';
         foreach ($tabs as $key => $value) {
             $tabs[$key]['link'] = CRM_Utils_System::url("civicrm/admin/contribute/{$key}", "{$reset}action=update&snippet=4&id={$contribPageId}&qfKey={$qfKey}");
             $tabs[$key]['active'] = $tabs[$key]['valid'] = TRUE;
         }
         //get all section info.
         $contriPageInfo = CRM_Contribute_BAO_ContributionPage::getSectionInfo(array($contribPageId));
         foreach ($contriPageInfo[$contribPageId] as $section => $info) {
             if (!$info) {
                 $tabs[$section]['valid'] = FALSE;
             }
         }
     }
     return $tabs;
 }
Example #5
0
/**
 * 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_contributionpage_create( &$params ) {
    _civicrm_initialize( );
	
    $values  = array( );
   
    require_once 'CRM/Contribute/BAO/ContributionPage.php';

    $ids     = array( );
    if ( CRM_Utils_Array::value( 'id', $params ) ) {
    
	}
	
    $contributionPage = CRM_Contribute_BAO_ContributionPage::create( $params );
    if ( is_a( $contributionPage, 'CRM_Core_Error' ) ) {
        return civicrm_create_error( ts( 'Failed to create contributionPage' ) );
    }

    _civicrm_object_to_array($contributionPage, $contributeArray);
    
    return $contributeArray;
}
 function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE)
 {
     $contribution =& $objects['contribution'];
     $primaryContributionID = isset($contribution->id) ? $contribution->id : $objects['first_contribution']->id;
     $memberships =& $objects['membership'];
     if (is_numeric($memberships)) {
         $memberships = array($objects['membership']);
     }
     $participant =& $objects['participant'];
     $event =& $objects['event'];
     $changeToday = CRM_Utils_Array::value('trxn_date', $input, self::$_now);
     $recurContrib =& $objects['contributionRecur'];
     $values = array();
     if (isset($input['is_email_receipt'])) {
         $values['is_email_receipt'] = $input['is_email_receipt'];
     }
     $source = NULL;
     if ($input['component'] == 'contribute') {
         if ($contribution->contribution_page_id) {
             CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
             $source = ts('Online Contribution') . ': ' . $values['title'];
         } elseif ($recurContrib && $recurContrib->id) {
             $contribution->contribution_page_id = NULL;
             $values['amount'] = $recurContrib->amount;
             $values['financial_type_id'] = $objects['contributionType']->id;
             $values['title'] = $source = ts('Offline Recurring Contribution');
             $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
             $values['receipt_from_name'] = $domainValues[0];
             $values['receipt_from_email'] = $domainValues[1];
         }
         if ($recurContrib && $recurContrib->id && !isset($input['is_email_receipt'])) {
             //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
             // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
             $values['is_email_receipt'] = $recurContrib->is_email_receipt;
         }
         $contribution->source = $source;
         if (CRM_Utils_Array::value('is_email_receipt', $values)) {
             $contribution->receipt_date = self::$_now;
         }
         if (!empty($memberships)) {
             $membershipsUpdate = array();
             foreach ($memberships as $membershipTypeIdKey => $membership) {
                 if ($membership) {
                     $format = '%Y%m%d';
                     $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, $membership->membership_type_id, $membership->is_test, $membership->id);
                     // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
                     // this picks up membership type changes during renewals
                     $sql = "\nSELECT    membership_type_id\nFROM      civicrm_membership_log\nWHERE     membership_id={$membership->id}\nORDER BY  id DESC\nLIMIT 1;";
                     $dao = new CRM_Core_DAO();
                     $dao->query($sql);
                     if ($dao->fetch()) {
                         if (!empty($dao->membership_type_id)) {
                             $membership->membership_type_id = $dao->membership_type_id;
                             $membership->save();
                         }
                         // else fall back to using current membership type
                     }
                     // else fall back to using current membership type
                     $dao->free();
                     $num_terms = $contribution->getNumTermsByContributionAndMembershipType($membership->membership_type_id, $primaryContributionID);
                     if ($currentMembership) {
                         /*
                          * Fixed FOR CRM-4433
                          * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
                          * when Contribution mode is notify and membership is for renewal )
                          */
                         CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
                         // @todo - we should pass membership_type_id instead of null here but not
                         // adding as not sure of testing
                         $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, $changeToday, NULL, $num_terms);
                         $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
                     } else {
                         $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, NULL, NULL, NULL, $num_terms);
                     }
                     //get the status for membership.
                     $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', TRUE, $membership->membership_type_id, (array) $membership);
                     $formatedParams = array('status_id' => CRM_Utils_Array::value('id', $calcStatus, 2), 'join_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $dates), $format), 'start_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $dates), $format), 'end_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $dates), $format));
                     //we might be renewing membership,
                     //so make status override false.
                     $formatedParams['is_override'] = FALSE;
                     $membership->copyValues($formatedParams);
                     $membership->save();
                     //updating the membership log
                     $membershipLog = array();
                     $membershipLog = $formatedParams;
                     $logStartDate = $formatedParams['start_date'];
                     if (CRM_Utils_Array::value('log_start_date', $dates)) {
                         $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
                         $logStartDate = CRM_Utils_Date::isoToMysql($logStartDate);
                     }
                     $membershipLog['start_date'] = $logStartDate;
                     $membershipLog['membership_id'] = $membership->id;
                     $membershipLog['modified_id'] = $membership->contact_id;
                     $membershipLog['modified_date'] = date('Ymd');
                     $membershipLog['membership_type_id'] = $membership->membership_type_id;
                     CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
                     //update related Memberships.
                     CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams);
                     //update the membership type key of membership relatedObjects array
                     //if it has changed after membership update
                     if ($membershipTypeIdKey != $membership->membership_type_id) {
                         $membershipsUpdate[$membership->membership_type_id] = $membership;
                         $contribution->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
                         unset($contribution->_relatedObjects['membership'][$membershipTypeIdKey]);
                         unset($memberships[$membershipTypeIdKey]);
                     }
                 }
             }
             //update the memberships object with updated membershipTypeId data
             //if membershipTypeId has changed after membership update
             if (!empty($membershipsUpdate)) {
                 $memberships = $memberships + $membershipsUpdate;
             }
         }
     } else {
         // event
         $eventParams = array('id' => $objects['event']->id);
         $values['event'] = array();
         CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
         //get location details
         $locationParams = array('entity_id' => $objects['event']->id, 'entity_table' => 'civicrm_event');
         $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
         $ufJoinParams = array('entity_table' => 'civicrm_event', 'entity_id' => $ids['event'], 'module' => 'CiviEvent');
         list($custom_pre_id, $custom_post_ids) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
         $values['custom_pre_id'] = $custom_pre_id;
         $values['custom_post_id'] = $custom_post_ids;
         //for tasks 'Change Participant Status' and 'Batch Update Participants Via Profile' case
         //and cases involving status updation through ipn
         $values['totalAmount'] = $input['amount'];
         $contribution->source = ts('Online Event Registration') . ': ' . $values['event']['title'];
         if ($values['event']['is_email_confirm']) {
             $contribution->receipt_date = self::$_now;
             $values['is_email_receipt'] = 1;
         }
         if (!CRM_Utils_Array::value('skipComponentSync', $input)) {
             $participant->status_id = 1;
         }
         $participant->save();
     }
     if (CRM_Utils_Array::value('net_amount', $input, 0) == 0 && CRM_Utils_Array::value('fee_amount', $input, 0) != 0) {
         $input['net_amount'] = $input['amount'] - $input['fee_amount'];
     }
     // This complete transaction function is being overloaded to create new contributions too.
     // here we record if it is a new contribution.
     // @todo separate the 2 more appropriately.
     $isNewContribution = FALSE;
     if (empty($contribution->id)) {
         $isNewContribution = TRUE;
         if (!empty($input['amount']) && $input['amount'] != $contribution->total_amount) {
             $contribution->total_amount = $input['amount'];
             // The BAO does this stuff but we are actually kinda bypassing it here (bad code! go sit in the corner)
             // so we have to handle net_amount in this (naughty) code.
             if (isset($input['fee_amount']) && is_numeric($input['fee_amount'])) {
                 $contribution->fee_amount = $input['fee_amount'];
             }
             $contribution->net_amount = $contribution->total_amount - $contribution->fee_amount;
         }
         if (!empty($input['campaign_id'])) {
             $contribution->campaign_id = $input['campaign_id'];
         }
     }
     $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array('labelColumn' => 'name', 'flip' => 1));
     // @todo this section should call the api  in order to have hooks called &
     // because all this 'messiness' setting variables could be avoided
     // by letting the api resolve pseudoconstants & copy set values and format dates.
     $contribution->contribution_status_id = $contributionStatuses['Completed'];
     $contribution->is_test = $input['is_test'];
     // CRM-15960 If we don't have a value we 'want' for the amounts, leave it to the BAO to sort out.
     if (isset($input['net_amount'])) {
         $contribution->fee_amount = CRM_Utils_Array::value('fee_amount', $input, 0);
     }
     if (isset($input['net_amount'])) {
         $contribution->net_amount = $input['net_amount'];
     }
     $contribution->trxn_id = $input['trxn_id'];
     $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
     $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
     $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
     $contribution->cancel_date = 'null';
     if (CRM_Utils_Array::value('check_number', $input)) {
         $contribution->check_number = $input['check_number'];
     }
     if (CRM_Utils_Array::value('payment_instrument_id', $input)) {
         $contribution->payment_instrument_id = $input['payment_instrument_id'];
     }
     if (!empty($contribution->id)) {
         $contributionId['id'] = $contribution->id;
         $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues($contributionId, CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
     }
     $contribution->save();
     //add line items for recurring payments
     if (!empty($contribution->contribution_recur_id)) {
         if ($isNewContribution) {
             $input['line_item'] = $this->addRecurLineItems($contribution->contribution_recur_id, $contribution);
         } else {
             // this is just to prevent e-notices when we call recordFinancialAccounts - per comments on that line - intention is somewhat unclear
             $input['line_item'] = array();
         }
         if (!empty($memberships) && $primaryContributionID != $contribution->id) {
             foreach ($memberships as $membership) {
                 try {
                     $membershipPayment = array('membership_id' => $membership->id, 'contribution_id' => $contribution->id);
                     if (!civicrm_api3('membership_payment', 'getcount', $membershipPayment)) {
                         civicrm_api3('membership_payment', 'create', $membershipPayment);
                     }
                 } catch (CiviCRM_API3_Exception $e) {
                     echo $e->getMessage();
                     // we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data
                     // this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated
                 }
             }
         }
     }
     //copy initial contribution custom fields for recurring contributions
     if ($recurContrib && $recurContrib->id) {
         $this->copyCustomValues($recurContrib->id, $contribution->id);
     }
     // next create the transaction record
     $paymentProcessor = $paymentProcessorId = '';
     if (isset($objects['paymentProcessor'])) {
         if (is_array($objects['paymentProcessor'])) {
             $paymentProcessor = $objects['paymentProcessor']['payment_processor_type'];
             $paymentProcessorId = $objects['paymentProcessor']['id'];
         } else {
             $paymentProcessor = $objects['paymentProcessor']->payment_processor_type;
             $paymentProcessorId = $objects['paymentProcessor']->id;
         }
     }
     //it's hard to see how it could reach this point without a contributon id as it is saved in line 511 above
     // which raised the question as to whether this check preceded line 511 & if so whether something could be broken
     // From a lot of code reading /debugging I'm still not sure the intent WRT first & subsequent payments in this code
     // it would be good if someone added some comments or refactored this
     if ($contribution->id) {
         $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
         if (empty($input['prevContribution']) && $paymentProcessorId || !$input['prevContribution']->is_pay_later && $input['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses)) {
             $input['payment_processor'] = $paymentProcessorId;
         }
         $input['contribution_status_id'] = array_search('Completed', $contributionStatuses);
         $input['total_amount'] = $input['amount'];
         $input['contribution'] = $contribution;
         $input['financial_type_id'] = $contribution->financial_type_id;
         if (CRM_Utils_Array::value('participant', $contribution->_relatedObjects)) {
             $input['contribution_mode'] = 'participant';
             $input['participant_id'] = $contribution->_relatedObjects['participant']->id;
             $input['skipLineItem'] = 1;
         }
         //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
         // and subsequent payments. In this case the line items are created at $this->addRecurLineItems
         // and since the contribution is saved prior to this line there is always a contribution-id,
         // however there is never a prevContribution (which appears to mean original contribution not previous
         // contribution - or preUpdateContributionObject most accurately)
         // so, this is always called & only appears to succeed when prevContribution exists - which appears
         // to mean "are we updating an exisitng pending contribution"
         //I was able to make the unit test complete as fataling here doesn't prevent
         // the contribution being created - but activities would not be created or emails sent
         CRM_Contribute_BAO_Contribution::recordFinancialAccounts($input, NULL);
     }
     self::updateRecurLinkedPledge($contribution);
     // create an activity record
     if ($input['component'] == 'contribute') {
         //CRM-4027
         $targetContactID = NULL;
         if (CRM_Utils_Array::value('related_contact', $ids)) {
             $targetContactID = $contribution->contact_id;
             $contribution->contact_id = $ids['related_contact'];
         }
         CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
         // event
     } else {
         CRM_Activity_BAO_Activity::addActivity($participant);
     }
     CRM_Core_Error::debug_log_message("Contribution record updated successfully");
     $transaction->commit();
     // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
     // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
     if (!array_key_exists('is_email_receipt', $values) || $values['is_email_receipt'] == 1) {
         self::sendMail($input, $ids, $objects, $values, $recur, FALSE);
         CRM_Core_Error::debug_log_message("Receipt sent");
     }
     CRM_Core_Error::debug_log_message("Success: Database updated");
 }
Example #7
0
 /**
  * Process the form
  *
  * @return void
  * @access public
  */
 public function postProcess()
 {
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     if (CRM_Utils_Array::value('payment_processor_id', $params) == CRM_Core_DAO::getFieldValue('CRM_Core_DAO_PaymentProcessor', 'AuthNet', 'id', 'payment_processor_type')) {
         CRM_Core_Session::setStatus(ts(' Please note that the Authorize.net payment processor only allows recurring contributions and auto-renew memberships with payment intervals from 7-365 days or 1-12 months (i.e. not greater than 1 year).'));
     }
     // check for price set.
     $priceSetID = CRM_Utils_Array::value('price_set_id', $params);
     // get required fields.
     $fields = array('id' => $this->_id, 'is_recur' => false, 'min_amount' => "null", 'max_amount' => "null", 'is_monetary' => false, 'is_pay_later' => false, 'is_recur_interval' => false, 'recur_frequency_unit' => "null", 'default_amount_id' => "null", 'is_allow_other_amount' => false, 'amount_block_is_active' => false);
     $resetFields = array();
     if ($priceSetID) {
         $resetFields = array('min_amount', 'max_amount', 'is_allow_other_amount');
     }
     if (!CRM_Utils_Array::value('is_recur', $params)) {
         $resetFields = array_merge($resetFields, array('is_recur_interval', 'recur_frequency_unit'));
     }
     foreach ($fields as $field => $defaultVal) {
         $val = CRM_Utils_Array::value($field, $params, $defaultVal);
         if (in_array($field, $resetFields)) {
             $val = $defaultVal;
         }
         if (in_array($field, array('min_amount', 'max_amount'))) {
             $val = CRM_Utils_Rule::cleanMoney($val);
         }
         $params[$field] = $val;
     }
     if ($params['is_recur']) {
         require_once 'CRM/Core/BAO/CustomOption.php';
         $params['recur_frequency_unit'] = implode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, array_keys($params['recur_frequency_unit']));
         $params['is_recur_interval'] = CRM_Utils_Array::value('is_recur_interval', $params, false);
     }
     require_once 'CRM/Contribute/BAO/ContributionPage.php';
     $contributionPage = CRM_Contribute_BAO_ContributionPage::create($params);
     $contributionPageID = $contributionPage->id;
     // prepare for data cleanup.
     $deleteAmountBlk = $deletePledgeBlk = $deletePriceSet = false;
     if ($this->_priceSetID) {
         $deletePriceSet = true;
     }
     if ($this->_pledgeBlockID) {
         $deletePledgeBlk = true;
     }
     if (!empty($this->_amountBlock)) {
         $deleteAmountBlk = true;
     }
     if ($contributionPageID) {
         require_once 'CRM/Price/BAO/Set.php';
         require_once 'CRM/Core/OptionGroup.php';
         require_once 'CRM/Pledge/BAO/PledgeBlock.php';
         if (CRM_Utils_Array::value('amount_block_is_active', $params)) {
             // handle price set.
             if ($priceSetID) {
                 // add/update price set.
                 $deletePriceSet = false;
                 CRM_Price_BAO_Set::addTo('civicrm_contribution_page', $contributionPageID, $priceSetID);
             } else {
                 // process contribution amount block
                 $deleteAmountBlk = false;
                 $labels = CRM_Utils_Array::value('label', $params);
                 $values = CRM_Utils_Array::value('value', $params);
                 $default = CRM_Utils_Array::value('default', $params);
                 $options = array();
                 for ($i = 1; $i < self::NUM_OPTION; $i++) {
                     if (isset($values[$i]) && strlen(trim($values[$i])) > 0) {
                         $options[] = array('label' => trim($labels[$i]), 'value' => CRM_Utils_Rule::cleanMoney(trim($values[$i])), 'weight' => $i, 'is_active' => 1, 'is_default' => $default == $i);
                     }
                 }
                 CRM_Core_OptionGroup::createAssoc("civicrm_contribution_page.amount.{$contributionPageID}", $options, $params['default_amount_id']);
                 if ($params['default_amount_id']) {
                     CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_ContributionPage', $contributionPageID, 'default_amount_id', $params['default_amount_id']);
                 }
                 if (CRM_Utils_Array::value('is_pledge_active', $params)) {
                     $deletePledgeBlk = false;
                     $pledgeBlockParams = array('entity_id' => $contributionPageID, 'entity_table' => ts('civicrm_contribution_page'));
                     if ($this->_pledgeBlockID) {
                         $pledgeBlockParams['id'] = $this->_pledgeBlockID;
                     }
                     $pledgeBlock = array('pledge_frequency_unit', 'max_reminders', 'initial_reminder_day', 'additional_reminder_day');
                     foreach ($pledgeBlock as $key) {
                         $pledgeBlockParams[$key] = CRM_Utils_Array::value($key, $params);
                     }
                     $pledgeBlockParams['is_pledge_interval'] = CRM_Utils_Array::value('is_pledge_interval', $params, false);
                     // create pledge block.
                     require_once 'CRM/Pledge/BAO/PledgeBlock.php';
                     CRM_Pledge_BAO_PledgeBlock::create($pledgeBlockParams);
                 }
             }
         }
         // delete pledge block.
         if ($deletePledgeBlk) {
             CRM_Pledge_BAO_PledgeBlock::deletePledgeBlock($this->_pledgeBlockID);
         }
         // delete previous price set.
         if ($deletePriceSet) {
             CRM_Price_BAO_Set::removeFrom('civicrm_contribution_page', $contributionPageID);
         }
         // delete amount block.
         if ($deleteAmountBlk) {
             CRM_Core_OptionGroup::deleteAssoc("civicrm_contribution_page.amount.{$contributionPageID}");
         }
     }
 }
 function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE)
 {
     $contribution =& $objects['contribution'];
     $memberships =& $objects['membership'];
     if (is_numeric($memberships)) {
         $memberships = array($objects['membership']);
     }
     $participant =& $objects['participant'];
     $event =& $objects['event'];
     $changeToday = CRM_Utils_Array::value('trxn_date', $input, self::$_now);
     $recurContrib =& $objects['contributionRecur'];
     $values = array();
     if ($input['component'] == 'contribute') {
         if ($contribution->contribution_page_id) {
             CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
             $source = ts('Online Contribution') . ': ' . $values['title'];
         } elseif ($recurContrib->id) {
             $contribution->contribution_page_id = NULL;
             $values['amount'] = $recurContrib->amount;
             $values['contribution_type_id'] = $objects['contributionType']->id;
             $values['title'] = $source = ts('Offline Recurring Contribution');
             $values['is_email_receipt'] = $recurContrib->is_email_receipt;
             $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
             $values['receipt_from_name'] = $domainValues[0];
             $values['receipt_from_email'] = $domainValues[1];
         }
         $contribution->source = $source;
         if (CRM_Utils_Array::value('is_email_receipt', $values)) {
             $contribution->receipt_date = self::$_now;
         }
         if (!empty($memberships)) {
             foreach ($memberships as $membershipTypeIdKey => $membership) {
                 if ($membership) {
                     $format = '%Y%m%d';
                     $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, $membership->membership_type_id, $membership->is_test, $membership->id);
                     // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
                     // this picks up membership type changes during renewals
                     $sql = "\nSELECT    membership_type_id\nFROM      civicrm_membership_log\nWHERE     membership_id={$membership->id}\nORDER BY  id DESC\nLIMIT 1;";
                     $dao = new CRM_Core_DAO();
                     $dao->query($sql);
                     if ($dao->fetch()) {
                         if (!empty($dao->membership_type_id)) {
                             $membership->membership_type_id = $dao->membership_type_id;
                             $membership->save();
                         }
                         // else fall back to using current membership type
                     }
                     // else fall back to using current membership type
                     $dao->free();
                     if ($currentMembership) {
                         /*
                          * Fixed FOR CRM-4433
                          * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
                          * when Contribution mode is notify and membership is for renewal )
                          */
                         CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
                         $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, $changeToday);
                         $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
                     } else {
                         $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id);
                     }
                     //get the status for membership.
                     $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', TRUE);
                     $formatedParams = array('status_id' => CRM_Utils_Array::value('id', $calcStatus, 2), 'join_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $dates), $format), 'start_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $dates), $format), 'end_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $dates), $format), 'reminder_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('reminder_date', $dates), $format));
                     //we might be renewing membership,
                     //so make status override false.
                     $formatedParams['is_override'] = FALSE;
                     $membership->copyValues($formatedParams);
                     $membership->save();
                     //updating the membership log
                     $membershipLog = array();
                     $membershipLog = $formatedParams;
                     $logStartDate = $formatedParams['start_date'];
                     if (CRM_Utils_Array::value('log_start_date', $dates)) {
                         $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
                         $logStartDate = CRM_Utils_Date::isoToMysql($logStartDate);
                     }
                     $membershipLog['start_date'] = $logStartDate;
                     $membershipLog['membership_id'] = $membership->id;
                     $membershipLog['modified_id'] = $membership->contact_id;
                     $membershipLog['modified_date'] = date('Ymd');
                     $membershipLog['membership_type_id'] = $membership->membership_type_id;
                     CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
                     //update related Memberships.
                     CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams);
                     //update the membership type key of membership relatedObjects array
                     //if it has changed after membership update
                     if ($membershipTypeIdKey != $membership->membership_type_id) {
                         $memberships[$membership->membership_type_id] = $membership;
                         $contribution->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
                         unset($contribution->_relatedObjects['membership'][$membershipTypeIdKey]);
                         unset($memberships[$membershipTypeIdKey]);
                     }
                 }
             }
         }
     } else {
         // event
         $eventParams = array('id' => $objects['event']->id);
         $values['event'] = array();
         CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
         $eventParams = array('id' => $objects['event']->id);
         $values['event'] = array();
         CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
         //get location details
         $locationParams = array('entity_id' => $objects['event']->id, 'entity_table' => 'civicrm_event');
         $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
         $ufJoinParams = array('entity_table' => 'civicrm_event', 'entity_id' => $ids['event'], 'module' => 'CiviEvent');
         list($custom_pre_id, $custom_post_ids) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
         $values['custom_pre_id'] = $custom_pre_id;
         $values['custom_post_id'] = $custom_post_ids;
         $contribution->source = ts('Online Event Registration') . ': ' . $values['event']['title'];
         if ($values['event']['is_email_confirm']) {
             $contribution->receipt_date = self::$_now;
             $values['is_email_receipt'] = 1;
         }
         $participant->status_id = 1;
         $participant->save();
     }
     if (CRM_Utils_Array::value('net_amount', $input, 0) == 0 && CRM_Utils_Array::value('fee_amount', $input, 0) != 0) {
         $input['net_amount'] = $input['amount'] - $input['fee_amount'];
     }
     $addLineItems = FALSE;
     if (empty($contribution->id)) {
         $addLineItems = TRUE;
     }
     $contribution->contribution_status_id = 1;
     $contribution->is_test = $input['is_test'];
     $contribution->fee_amount = CRM_Utils_Array::value('fee_amount', $input, 0);
     $contribution->net_amount = CRM_Utils_Array::value('net_amount', $input, 0);
     $contribution->trxn_id = $input['trxn_id'];
     $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
     $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
     $contribution->cancel_date = 'null';
     if (CRM_Utils_Array::value('check_number', $input)) {
         $contribution->check_number = $input['check_number'];
     }
     if (CRM_Utils_Array::value('payment_instrument_id', $input)) {
         $contribution->payment_instrument_id = $input['payment_instrument_id'];
     }
     $contribution->save();
     //add lineitems for recurring payments
     if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id && $addLineItems) {
         $this->addrecurLineItems($objects['contributionRecur']->id, $contribution->id);
     }
     // next create the transaction record
     $paymentProcessor = '';
     if (isset($objects['paymentProcessor'])) {
         if (is_array($objects['paymentProcessor'])) {
             $paymentProcessor = $objects['paymentProcessor']['payment_processor_type'];
         } else {
             $paymentProcessor = $objects['paymentProcessor']->payment_processor_type;
         }
     }
     if ($contribution->trxn_id) {
         $trxnParams = array('contribution_id' => $contribution->id, 'trxn_date' => isset($input['trxn_date']) ? $input['trxn_date'] : self::$_now, 'trxn_type' => 'Debit', 'total_amount' => $input['amount'], 'fee_amount' => $contribution->fee_amount, 'net_amount' => $contribution->net_amount, 'currency' => $contribution->currency, 'payment_processor' => $paymentProcessor, 'trxn_id' => $contribution->trxn_id);
         $trxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
     }
     self::updateRecurLinkedPledge($contribution);
     // create an activity record
     if ($input['component'] == 'contribute') {
         //CRM-4027
         $targetContactID = NULL;
         if (CRM_Utils_Array::value('related_contact', $ids)) {
             $targetContactID = $contribution->contact_id;
             $contribution->contact_id = $ids['related_contact'];
         }
         CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
         // event
     } else {
         CRM_Activity_BAO_Activity::addActivity($participant);
     }
     CRM_Core_Error::debug_log_message("Contribution record updated successfully");
     $transaction->commit();
     // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
     // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
     if (!array_key_exists('is_email_receipt', $values) || $values['is_email_receipt'] == 1) {
         self::sendMail($input, $ids, $objects, $values, $recur, FALSE);
     }
     CRM_Core_Error::debug_log_message("Success: Database updated and mail sent");
 }
 public function doDirectPayment(&$params)
 {
     if (!defined('CURLOPT_SSLCERT')) {
         CRM_Core_Error::fatal(ts('eWAY - Gateway requires curl with SSL support'));
     }
     /*
      * OPTIONAL: If TEST Card Number force an Override of URL and CustomerID.
      * During testing CiviCRM once used the LIVE URL.
      * This code can be uncommented to override the LIVE URL that if CiviCRM does that again.
      * if ( ( $gateway_URL == "https://www.eway.com.au/gateway_cvn/xmlpayment.asp")
      *   && ( $params['credit_card_number'] == "4444333322221111" ) ) {
      *   $ewayCustomerID = "87654321";
      *   $gateway_URL    = "https://www.eway.com.au/gateway/rebill/test/Upload_test.aspx";
      * }
      */
     // Was the recurring payment check box checked?
     if (isset($params['is_recur']) && $params['is_recur'] == 1) {
         // Create the customer via the API.
         try {
             $result = $this->createToken($this->_paymentProcessor, $params);
         } catch (Exception $e) {
             return self::errorExit(9010, $e->getMessage());
         }
         // We've created the customer successfully.
         $managed_customer_id = $result;
         try {
             $initialPayment = civicrm_api3('ewayrecurring', 'payment', array('invoice_id' => $params['invoiceID'], 'amount_in_cents' => round((double) $params['amount'] * 100), 'managed_customer_id' => $managed_customer_id, 'description' => $params['description'] . ts('first payment'), 'payment_processor_id' => $this->_paymentProcessor['id']));
             // Here we compensate for the fact core accepts 0 as a valid frequency
             // interval and set it.
             $extra = array();
             if (empty($params['frequency_interval'])) {
                 $params['frequency_interval'] = 1;
                 $extra['frequency_interval'] = 1;
             }
             $params['trxn_id'] = $initialPayment['values'][$managed_customer_id]['trxn_id'];
             $params['contribution_status_id'] = 1;
             $params['payment_status_id'] = 1;
             // If there's only one installment, then the recurring contribution is now complete
             if (isset($params['installments']) && $params['installments'] == 1) {
                 $status = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
             } else {
                 $status = CRM_Core_OptionGroup::getValue('contribution_status', 'In Progress', 'name');
             }
             // Save the eWay customer token in the recurring contribution's processor_id field.
             civicrm_api3('contribution_recur', 'create', array_merge(array('id' => $params['contributionRecurID'], 'processor_id' => $managed_customer_id, 'contribution_status_id' => $status, 'next_sched_contribution_date' => CRM_Utils_Date::isoToMysql(date('Y-m-d 00:00:00', strtotime('+' . $params['frequency_interval'] . ' ' . $params['frequency_unit'])))), $extra));
             // Send recurring Notification email for user.
             $recur = new CRM_Contribute_BAO_ContributionRecur();
             $recur->id = $params['contributionRecurID'];
             $recur->find(TRUE);
             // If none found then effectively FALSE.
             $autoRenewMembership = civicrm_api3('membership', 'getcount', array('contribution_recur_id' => $recur->id));
             if (!empty($params['selectMembership']) || !empty($params['membership_type_id']) && !empty($params['auto_renew'])) {
                 $autoRenewMembership = TRUE;
             }
             CRM_Contribute_BAO_ContributionPage::recurringNotify(CRM_Core_Payment::RECURRING_PAYMENT_START, $params['contactID'], CRM_Utils_Array::value('contributionPageID', $params), $recur, $autoRenewMembership);
         } catch (CiviCRM_API3_Exception $e) {
             return self::errorExit(9014, 'Initial payment not processed' . $e->getMessage());
         }
     } else {
         try {
             $result = $this->processSinglePayment($params);
             $params = array_merge($params, $result);
         } catch (CRM_Core_Exception $e) {
             return self::errorExit(9001, $e->getMessage());
         }
     }
     return $params;
 }
Example #10
0
 /**
  * Process the form
  *
  * @return void
  * @access public
  */
 public function postProcess()
 {
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     $params['id'] = $this->_id;
     $params['is_email_receipt'] = CRM_Utils_Array::value('is_email_receipt', $params, FALSE);
     if (!$params['is_email_receipt']) {
         $params['receipt_from_name'] = NULL;
         $params['receipt_from_email'] = NULL;
         $params['receipt_text'] = NULL;
         $params['cc_receipt'] = NULL;
         $params['bcc_receipt'] = NULL;
     }
     $dao = CRM_Contribute_BAO_ContributionPage::create($params);
     parent::endPostProcess();
 }
Example #11
0
 /**
  * Submit function.
  *
  * @param array $params
  *
  * @throws CiviCRM_API3_Exception
  */
 public static function submit($params)
 {
     $form = new CRM_Contribute_Form_Contribution_Confirm();
     $form->_id = $params['id'];
     CRM_Contribute_BAO_ContributionPage::setValues($form->_id, $form->_values);
     $form->_separateMembershipPayment = CRM_Contribute_BAO_ContributionPage::getIsMembershipPayment($form->_id);
     //this way the mocked up controller ignores the session stuff
     $_SERVER['REQUEST_METHOD'] = 'GET';
     $form->controller = new CRM_Contribute_Controller_Contribution();
     $params['invoiceID'] = md5(uniqid(rand(), TRUE));
     $paramsProcessedForForm = $form->_params = self::getFormParams($params['id'], $params);
     $form->_amount = $params['amount'];
     // hack these in for test support.
     $form->_fields['billing_first_name'] = 1;
     $form->_fields['billing_last_name'] = 1;
     $priceSetID = $form->_params['priceSetId'] = $paramsProcessedForForm['price_set_id'];
     $priceFields = CRM_Price_BAO_PriceSet::getSetDetail($priceSetID);
     $priceSetFields = reset($priceFields);
     $form->_values['fee'] = $priceSetFields['fields'];
     $form->_priceSetId = $priceSetID;
     $form->setFormAmountFields($priceSetID);
     if (!empty($params['payment_processor_id'])) {
         $form->_paymentProcessor = civicrm_api3('payment_processor', 'getsingle', array('id' => $params['payment_processor_id']));
         // The concept of contributeMode is deprecated as is the billing_mode concept.
         if ($form->_paymentProcessor['billing_mode'] == 1) {
             $form->_contributeMode = 'direct';
         } else {
             $form->_contributeMode = 'notify';
         }
     } else {
         $form->_params['payment_processor_id'] = 0;
     }
     $priceFields = $priceFields[$priceSetID]['fields'];
     CRM_Price_BAO_PriceSet::processAmount($priceFields, $paramsProcessedForForm, $lineItems, 'civicrm_contribution');
     $form->_lineItem = array($priceSetID => $lineItems);
     $form->processFormSubmission(CRM_Utils_Array::value('contact_id', $params));
 }
Example #12
0
 /**
  * Process the form.
  */
 public function postProcess()
 {
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     // we do this in case the user has hit the forward/back button
     if ($this->_id) {
         $params['id'] = $this->_id;
     } else {
         $session = CRM_Core_Session::singleton();
         $params['created_id'] = $session->get('userID');
         $params['created_date'] = date('YmdHis');
         $config = CRM_Core_Config::singleton();
         $params['currency'] = $config->defaultCurrency;
     }
     $params['is_confirm_enabled'] = CRM_Utils_Array::value('is_confirm_enabled', $params, FALSE);
     $params['is_share'] = CRM_Utils_Array::value('is_share', $params, FALSE);
     $params['is_active'] = CRM_Utils_Array::value('is_active', $params, FALSE);
     $params['is_credit_card_only'] = CRM_Utils_Array::value('is_credit_card_only', $params, FALSE);
     $params['honor_block_is_active'] = CRM_Utils_Array::value('honor_block_is_active', $params, FALSE);
     $params['is_for_organization'] = !empty($params['is_organization']) ? CRM_Utils_Array::value('is_for_organization', $params, FALSE) : 0;
     $params['start_date'] = CRM_Utils_Date::processDate($params['start_date'], $params['start_date_time'], TRUE);
     $params['end_date'] = CRM_Utils_Date::processDate($params['end_date'], $params['end_date_time'], TRUE);
     $params['goal_amount'] = CRM_Utils_Rule::cleanMoney($params['goal_amount']);
     if (!$params['honor_block_is_active']) {
         $params['honor_block_title'] = NULL;
         $params['honor_block_text'] = NULL;
     }
     $dao = CRM_Contribute_BAO_ContributionPage::create($params);
     $ufJoinParams = array('is_organization' => array('module' => 'on_behalf', 'entity_table' => 'civicrm_contribution_page', 'entity_id' => $dao->id), 'honor_block_is_active' => array('module' => 'soft_credit', 'entity_table' => 'civicrm_contribution_page', 'entity_id' => $dao->id));
     foreach ($ufJoinParams as $index => $ufJoinParam) {
         if (!empty($params[$index])) {
             // first delete all past entries
             CRM_Core_BAO_UFJoin::deleteAll($ufJoinParam);
             $ufJoinParam['uf_group_id'] = $params[$index];
             $ufJoinParam['weight'] = 1;
             $ufJoinParam['is_active'] = 1;
             if ($index == 'honor_block_is_active') {
                 $ufJoinParam['uf_group_id'] = $params['honoree_profile'];
                 $ufJoinParam['module_data'] = CRM_Contribute_BAO_ContributionPage::formatModuleData($params, FALSE, 'soft_credit');
             } else {
                 $ufJoinParam['uf_group_id'] = $params['onbehalf_profile_id'];
                 $ufJoinParam['module_data'] = CRM_Contribute_BAO_ContributionPage::formatModuleData($params, FALSE, 'on_behalf');
             }
             CRM_Core_BAO_UFJoin::create($ufJoinParam);
         } else {
             if ($index == 'honor_block_is_active') {
                 $params['honor_block_title'] = NULL;
                 $params['honor_block_text'] = NULL;
             } else {
                 $params['for_organization'] = NULL;
             }
             //On subsequent honor_block_is_active uncheck, disable(don't delete)
             //that particular honoree profile entry in UFjoin table, CRM-13981
             $ufId = CRM_Core_BAO_UFJoin::findJoinEntryId($ufJoinParam);
             if ($ufId) {
                 $ufJoinParam['uf_group_id'] = CRM_Core_BAO_UFJoin::findUFGroupId($ufJoinParam);
                 $ufJoinParam['is_active'] = 0;
                 CRM_Core_BAO_UFJoin::create($ufJoinParam);
             }
         }
     }
     $this->set('id', $dao->id);
     if ($this->_action & CRM_Core_Action::ADD) {
         $url = 'civicrm/admin/contribute/amount';
         $urlParams = "action=update&reset=1&id={$dao->id}";
         // special case for 'Save and Done' consistency.
         if ($this->controller->getButtonName('submit') == '_qf_Amount_upload_done') {
             $url = 'civicrm/admin/contribute';
             $urlParams = 'reset=1';
             CRM_Core_Session::setStatus(ts("'%1' information has been saved.", array(1 => $this->getTitle())), ts('Saved'), 'success');
         }
         CRM_Utils_System::redirect(CRM_Utils_System::url($url, $urlParams));
     }
     parent::endPostProcess();
 }
Example #13
0
 /**
  * Process the Memberships.
  *
  * @param array $membershipParams
  *   Array of membership fields.
  * @param int $contactID
  *   Contact id.
  * @param CRM_Contribute_Form_Contribution_Confirm $form
  *   Confirmation form object.
  *
  * @param array $premiumParams
  * @param null $customFieldsFormatted
  * @param null $includeFieldTypes
  *
  * @param array $membershipDetails
  *
  * @param array $membershipTypeIDs
  *
  * @param bool $isPaidMembership
  * @param array $membershipID
  *
  * @param $isProcessSeparateMembershipTransaction
  *
  * @param int $defaultContributionTypeID
  * @param array $membershipLineItems
  *   Line items specific to membership payment that is separate to contribution.
  * @param $isPayLater
  *
  * @throws \CRM_Core_Exception
  */
 public static function postProcessMembership($membershipParams, $contactID, &$form, $premiumParams, $customFieldsFormatted = NULL, $includeFieldTypes = NULL, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID, $isProcessSeparateMembershipTransaction, $defaultContributionTypeID, $membershipLineItems, $isPayLater)
 {
     $result = $membershipContribution = NULL;
     $isTest = CRM_Utils_Array::value('is_test', $membershipParams, FALSE);
     $errors = $createdMemberships = array();
     //@todo move this into the calling function & pass in the correct financialTypeID
     if (isset($paymentParams['financial_type'])) {
         $financialTypeID = $paymentParams['financial_type'];
     } else {
         $financialTypeID = $defaultContributionTypeID;
     }
     if (CRM_Utils_Array::value('membership_source', $form->_params)) {
         $membershipParams['contribution_source'] = $form->_params['membership_source'];
     }
     if ($isPaidMembership) {
         $result = CRM_Contribute_BAO_Contribution_Utils::processConfirm($form, $membershipParams, $premiumParams, $contactID, $financialTypeID, 'membership', array(), $isTest, $isPayLater);
         if (is_a($result[1], 'CRM_Core_Error')) {
             $errors[1] = CRM_Core_Error::getMessages($result[1]);
         } elseif (!empty($result[1])) {
             // Save the contribution ID so that I can be used in email receipts
             // For example, if you need to generate a tax receipt for the donation only.
             $form->_values['contribution_other_id'] = $result[1]->id;
             //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
             $membershipContribution = $result[1];
         }
     }
     if ($isProcessSeparateMembershipTransaction) {
         try {
             $lineItems = $form->_lineItem = $membershipLineItems;
             if (empty($form->_params['auto_renew']) && !empty($membershipParams['is_recur'])) {
                 unset($membershipParams['is_recur']);
             }
             $membershipContribution = self::processSecondaryFinancialTransaction($contactID, $form, $membershipParams, $isTest, $membershipLineItems, CRM_Utils_Array::value('minimum_fee', $membershipDetails, 0), CRM_Utils_Array::value('financial_type_id', $membershipDetails));
         } catch (CRM_Core_Exception $e) {
             $errors[2] = $e->getMessage();
             $membershipContribution = NULL;
         }
     }
     $membership = NULL;
     if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
         $membershipContributionID = $membershipContribution->id;
     }
     //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
     if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
         $form->_params['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
     }
     //@todo it should no longer be possible for it to get to this point & membership to not be an array
     if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
         $typesTerms = CRM_Utils_Array::value('types_terms', $membershipParams, array());
         foreach ($membershipTypeIDs as $memType) {
             $numTerms = CRM_Utils_Array::value($memType, $typesTerms, 1);
             $createdMemberships[$memType] = self::createOrRenewMembership($membershipParams, $contactID, $customFieldsFormatted, $membershipID, $memType, $isTest, $numTerms, $membershipContribution, $form);
         }
         if ($form->_priceSetId && !empty($form->_useForMember) && !empty($form->_lineItem)) {
             foreach ($form->_lineItem[$form->_priceSetId] as &$priceFieldOp) {
                 if (!empty($priceFieldOp['membership_type_id']) && isset($createdMemberships[$priceFieldOp['membership_type_id']])) {
                     $membershipOb = $createdMemberships[$priceFieldOp['membership_type_id']];
                     $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date::customFormat($membershipOb->start_date, '%B %E%f, %Y') : '-';
                     $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date::customFormat($membershipOb->end_date, '%B %E%f, %Y') : '-';
                 } else {
                     $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
                 }
             }
             $form->_values['lineItem'] = $form->_lineItem;
             $form->assign('lineItem', $form->_lineItem);
         }
     }
     if (!empty($errors)) {
         $message = self::compileErrorMessage($errors);
         throw new CRM_Core_Exception($message);
     }
     $form->_params['createdMembershipIDs'] = array();
     // CRM-7851 - Moved after processing Payment Errors
     //@todo - the reasoning for this being here seems a little outdated
     foreach ($createdMemberships as $createdMembership) {
         CRM_Core_BAO_CustomValueTable::postProcess($form->_params, CRM_Core_DAO::$_nullArray, 'civicrm_membership', $createdMembership->id, 'Membership');
         $form->_params['createdMembershipIDs'][] = $createdMembership->id;
     }
     if (count($createdMemberships) == 1) {
         //presumably this is only relevant for exactly 1 membership
         $form->_params['membershipID'] = $createdMembership->id;
     }
     //CRM-15232: Check if membership is created and on the basis of it use
     //membership reciept template to send payment reciept
     if (count($createdMemberships)) {
         $form->_values['isMembership'] = TRUE;
     }
     if ($form->_contributeMode == 'notify') {
         if ($form->_values['is_monetary'] && $form->_amount > 0.0 && !$form->_params['is_pay_later']) {
             // call postProcess hook before leaving
             $form->postProcessHook();
             // this does not return
             $payment = CRM_Core_Payment::singleton($form->_mode, $form->_paymentProcessor, $form);
             $payment->doTransferCheckout($form->_params, 'contribute');
         }
     }
     if (isset($membershipContributionID)) {
         $form->_values['contribution_id'] = $membershipContributionID;
     }
     // Refer to CRM-16737. Payment processors 'should' return payment_status_id
     // to denote the outcome of the transaction.
     //
     // In 4.7 trxn_id will no longer denote the outcome & all processor transactions must return an array
     // containing payment_status_id.
     // In 4.6 support (such as there was) for other ways of denoting payment outcome is retained but the use
     // of payment_status_id is strongly encouraged.
     if (!empty($form->_params['is_recur']) && $form->_contributeMode == 'direct') {
         if (!empty($membershipContribution->trxn_id) && !isset($membershipContribution->payment_status_id) || !empty($membershipContribution->payment_status_id) && $membershipContribution->payment_status_id == 1) {
             try {
                 civicrm_api3('contribution', 'completetransaction', array('id' => $membershipContribution->id, 'trxn_id' => $membershipContribution->trxn_id));
             } catch (CiviCRM_API3_Exception $e) {
                 // if for any reason it is already completed this will fail - e.g extensions hacking around core not completing transactions prior to CRM-15296
                 // so let's be gentle here
                 CRM_Core_Error::debug_log_message('contribution ' . $membershipContribution->id . ' not completed with trxn_id ' . $membershipContribution->trxn_id . ' and message ' . $e->getMessage());
             }
         }
         // Do not send an email if Recurring transaction is done via Direct Mode
         // Email will we sent when the IPN is received.
         return;
     }
     //finally send an email receipt
     CRM_Contribute_BAO_ContributionPage::sendMail($contactID, $form->_values, $isTest, FALSE, $includeFieldTypes);
 }
 function recur(&$input, &$ids, &$objects, $first)
 {
     $recur =& $objects['contributionRecur'];
     // do a subscription check
     if ($recur->processor_id != $input['subscription_id']) {
         CRM_Core_Error::debug_log_message("Unrecognized subscription.");
         echo "Failure: Unrecognized subscription<p>";
         return FALSE;
     }
     // At this point $object has first contribution loaded.
     // Lets do a check to make sure this payment has the amount same as that of first contribution.
     if ($objects['contribution']->total_amount != $input['amount']) {
         CRM_Core_Error::debug_log_message("Subscription amount mismatch.");
         echo "Failure: Subscription amount mismatch<p>";
         return FALSE;
     }
     $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     $transaction = new CRM_Core_Transaction();
     $now = date('YmdHis');
     // fix dates that already exist
     $dates = array('create_date', 'start_date', 'end_date', 'cancel_date', 'modified_date');
     foreach ($dates as $name) {
         if ($recur->{$name}) {
             $recur->{$name} = CRM_Utils_Date::isoToMysql($recur->{$name});
         }
     }
     //load new contribution object if required.
     if (!$first) {
         // create a contribution and then get it processed
         $contribution = new CRM_Contribute_BAO_Contribution();
         $contribution->contact_id = $ids['contact'];
         $contribution->financial_type_id = $objects['contributionType']->id;
         $contribution->contribution_page_id = $ids['contributionPage'];
         $contribution->contribution_recur_id = $ids['contributionRecur'];
         $contribution->receive_date = $now;
         $contribution->currency = $objects['contribution']->currency;
         $contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id;
         $contribution->amount_level = $objects['contribution']->amount_level;
         $contribution->address_id = $objects['contribution']->address_id;
         $contribution->campaign_id = $objects['contribution']->campaign_id;
         $objects['contribution'] =& $contribution;
     }
     $objects['contribution']->invoice_id = md5(uniqid(rand(), TRUE));
     $objects['contribution']->total_amount = $input['amount'];
     $objects['contribution']->trxn_id = $input['trxn_id'];
     // since we have processor loaded for sure at this point,
     // check and validate gateway MD5 response if present
     $this->checkMD5($ids, $input);
     $sendNotification = FALSE;
     if ($input['response_code'] == 1) {
         // Approved
         if ($first) {
             $recur->start_date = $now;
             $recur->trxn_id = $recur->processor_id;
             $sendNotification = TRUE;
             $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_START;
         }
         $statusName = 'In Progress';
         if ($recur->installments > 0 && $input['subscription_paynum'] >= $recur->installments) {
             // this is the last payment
             $statusName = 'Completed';
             $recur->end_date = $now;
             $sendNotification = TRUE;
             $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
         }
         $recur->modified_date = $now;
         $recur->contribution_status_id = array_search($statusName, $contributionStatus);
         $recur->save();
     } else {
         // Declined
         // failed status
         $recur->contribution_status_id = array_search('Failed', $contributionStatus);
         $recur->cancel_date = $now;
         $recur->save();
         CRM_Core_Error::debug_log_message("Subscription payment failed - '{$input['response_reason_text']}'");
         // the recurring contribution has declined a payment or has failed
         // so we just fix the recurring contribution and not change any of
         // the existing contribiutions
         // CRM-9036
         return TRUE;
     }
     // check if contribution is already completed, if so we ignore this ipn
     if ($objects['contribution']->contribution_status_id == 1) {
         $transaction->commit();
         CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
         echo "Success: Contribution has already been handled<p>";
         return TRUE;
     }
     $this->completeTransaction($input, $ids, $objects, $transaction, $recur);
     if ($sendNotification) {
         $autoRenewMembership = FALSE;
         if ($recur->id && isset($ids['membership']) && $ids['membership']) {
             $autoRenewMembership = TRUE;
         }
         //send recurring Notification email for user
         CRM_Contribute_BAO_ContributionPage::recurringNotify($subscriptionPaymentStatus, $ids['contact'], $ids['contributionPage'], $recur, $autoRenewMembership);
     }
 }
Example #15
0
 function sendMail(&$input, &$ids, &$objects, &$values, $recur = false, $returnMessageText = false)
 {
     $contribution =& $objects['contribution'];
     $membership =& $objects['membership'];
     $participant =& $objects['participant'];
     $event =& $objects['event'];
     if (empty($values)) {
         $values = array();
         if ($input['component'] == 'contribute') {
             require_once 'CRM/Contribute/BAO/ContributionPage.php';
             if (isset($contribution->contribution_page_id)) {
                 CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
             } else {
                 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
                 $values['is_email_receipt'] = 1;
                 $values['title'] = 'Contribution';
             }
         } else {
             // event
             $eventParams = array('id' => $objects['event']->id);
             $values['event'] = array();
             require_once 'CRM/Event/BAO/Event.php';
             CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
             $eventParams = array('id' => $objects['event']->id);
             $values['event'] = array();
             require_once 'CRM/Event/BAO/Event.php';
             CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
             //get location details
             $locationParams = array('entity_id' => $objects['event']->id, 'entity_table' => 'civicrm_event');
             require_once 'CRM/Core/BAO/Location.php';
             require_once 'CRM/Event/Form/ManageEvent/Location.php';
             $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
             require_once 'CRM/Core/BAO/UFJoin.php';
             $ufJoinParams = array('entity_table' => 'civicrm_event', 'entity_id' => $ids['event'], 'weight' => 1);
             $values['custom_pre_id'] = CRM_Core_BAO_UFJoin::findUFGroupId($ufJoinParams);
             $ufJoinParams['weight'] = 2;
             $values['custom_post_id'] = CRM_Core_BAO_UFJoin::findUFGroupId($ufJoinParams);
         }
     }
     $template =& CRM_Core_Smarty::singleton();
     // CRM_Core_Error::debug('tpl',$template);
     //assign honor infomation to receiptmessage
     if ($honarID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'honor_contact_id')) {
         $honorDefault = array();
         $honorIds = array();
         $honorIds['contribution'] = $contribution->id;
         $idParams = array('id' => $honarID, 'contact_id' => $honarID);
         require_once "CRM/Contact/BAO/Contact.php";
         CRM_Contact_BAO_Contact::retrieve($idParams, $honorDefault, $honorIds);
         require_once "CRM/Core/PseudoConstant.php";
         $honorType = CRM_Core_PseudoConstant::honor();
         $prefix = CRM_Core_PseudoConstant::individualPrefix();
         $template->assign('honor_block_is_active', 1);
         $template->assign('honor_prefix', $prefix[$honorDefault["prefix_id"]]);
         $template->assign('honor_first_name', CRM_Utils_Array::value("first_name", $honorDefault));
         $template->assign('honor_last_name', CRM_Utils_Array::value("last_name", $honorDefault));
         $template->assign('honor_email', CRM_Utils_Array::value("email", $honorDefault["email"][1]));
         $template->assign('honor_type', $honorType[$contribution->honor_type_id]);
     }
     require_once 'CRM/Contribute/DAO/ContributionProduct.php';
     $dao =& new CRM_Contribute_DAO_ContributionProduct();
     $dao->contribution_id = $contribution->id;
     if ($dao->find(true)) {
         $premiumId = $dao->product_id;
         $template->assign('option', $dao->product_option);
         require_once 'CRM/Contribute/DAO/Product.php';
         $productDAO =& new CRM_Contribute_DAO_Product();
         $productDAO->id = $premiumId;
         $productDAO->find(true);
         $template->assign('selectPremium', true);
         $template->assign('product_name', $productDAO->name);
         $template->assign('price', $productDAO->price);
         $template->assign('sku', $productDAO->sku);
     }
     // add the new contribution values
     if ($input['component'] == 'contribute') {
         $template->assign('title', $values['title']);
         $template->assign('amount', $input['amount']);
         //PCP Info
         require_once 'CRM/Contribute/DAO/ContributionSoft.php';
         $softDAO =& new CRM_Contribute_DAO_ContributionSoft();
         $softDAO->contribution_id = $contribution->id;
         if ($softDAO->find(true)) {
             $template->assign('pcpBlock', true);
             $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll);
             $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname);
             $template->assign('pcp_personal_note', $softDAO->pcp_personal_note);
             //assign the pcp page title for email subject
             require_once 'CRM/Contribute/DAO/PCP.php';
             $pcpDAO =& new CRM_Contribute_DAO_PCP();
             $pcpDAO->id = $softDAO->pcp_id;
             if ($pcpDAO->find(true)) {
                 $template->assign('title', $pcpDAO->title);
             }
         }
     } else {
         $template->assign('title', $values['event']['title']);
         $template->assign('totalAmount', $input['amount']);
     }
     $template->assign('trxn_id', $contribution->trxn_id);
     $template->assign('receive_date', CRM_Utils_Date::mysqlToIso($contribution->receive_date));
     $template->assign('contributeMode', 'notify');
     $template->assign('action', $contribution->is_test ? 1024 : 1);
     $template->assign('receipt_text', CRM_Utils_Array::value('receipt_text', $values));
     $template->assign('is_monetary', 1);
     $template->assign('is_recur', $recur);
     if ($recur) {
         require_once 'CRM/Core/Payment.php';
         $paymentObject =& CRM_Core_Payment::singleton($contribution->is_test ? 'test' : 'live', 'Contribute', $objects['paymentProcessor']);
         $url = $paymentObject->cancelSubscriptionURL();
         $template->assign('cancelSubscriptionUrl', $url);
         if ($objects['paymentProcessor']['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM) {
             //direct mode showing billing block, so use directIPN for temporary
             $template->assign('contributeMode', 'directIPN');
         }
     }
     require_once 'CRM/Utils/Address.php';
     $template->assign('address', CRM_Utils_Address::format($input));
     if ($input['component'] == 'event') {
         require_once 'CRM/Core/OptionGroup.php';
         $participant_role = CRM_Core_OptionGroup::values('participant_role');
         $values['event']['participant_role'] = $participant_role[$participant->role_id];
         $template->assign('event', $values['event']);
         $template->assign('location', $values['location']);
         $template->assign('customPre', $values['custom_pre_id']);
         $template->assign('customPost', $values['custom_post_id']);
         $isTest = false;
         if ($participant->is_test) {
             $isTest = true;
         }
         $values['params'] = array();
         require_once "CRM/Event/BAO/Event.php";
         //to get email of primary participant.
         $primaryEmail = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $participant->contact_id, 'email', 'contact_id');
         $primaryAmount[] = array('label' => $participant->fee_level . ' - ' . $primaryEmail, 'amount' => $participant->fee_amount);
         //build an array of cId/pId of participants
         $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($participant->id, null, $ids['contact'], $isTest, true);
         unset($additionalIDs[$participant->id]);
         //send receipt to additional participant if exists
         if (count($additionalIDs)) {
             $template->assign('isPrimary', 0);
             $template->assign('customProfile', null);
             //set additionalParticipant true
             $values['params']['additionalParticipant'] = true;
             foreach ($additionalIDs as $pId => $cId) {
                 $amount = array();
                 //to change the status pending to completed
                 $additional =& new CRM_Event_DAO_Participant();
                 $additional->id = $pId;
                 $additional->contact_id = $cId;
                 $additional->find(true);
                 $additional->register_date = $participant->register_date;
                 $additional->status_id = 1;
                 $additionalParticipantInfo = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id, 'email', 'contact_id');
                 //if additional participant dont have email
                 //use display name.
                 if (!$additionalParticipantInfo) {
                     require_once "CRM/Contact/BAO/Contact.php";
                     $additionalParticipantInfo = CRM_Contact_BAO_Contact::displayName($additional->contact_id);
                 }
                 $amount[0] = array('label' => $additional->fee_level, 'amount' => $additional->fee_amount);
                 $primaryAmount[] = array('label' => $additional->fee_level . ' - ' . $additionalParticipantInfo, 'amount' => $additional->fee_amount);
                 $additional->save();
                 $additional->free();
                 $template->assign('amount', $amount);
                 CRM_Event_BAO_Event::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
             }
         }
         //build an array of custom profile and assigning it to template
         $customProfile = CRM_Event_BAO_Event::buildCustomProfile($participant->id, $values, null, $isTest);
         if (count($customProfile)) {
             $template->assign('customProfile', $customProfile);
         }
         // for primary contact
         $values['params']['additionalParticipant'] = false;
         $template->assign('isPrimary', 1);
         $template->assign('amount', $primaryAmount);
         // carry paylater, since we did not created billing,
         // so need to pull email from primary location, CRM-4395
         $values['params']['is_pay_later'] = $participant->is_pay_later;
         return CRM_Event_BAO_Event::sendMail($ids['contact'], $values, $participant->id, $isTest, $returnMessageText);
     } else {
         if ($membership) {
             $values['membership_id'] = $membership->id;
             // need to set the membership values here
             $template->assign('membership_assign', 1);
             require_once 'CRM/Member/PseudoConstant.php';
             $template->assign('membership_name', CRM_Member_PseudoConstant::membershipType($membership->membership_type_id));
             $template->assign('mem_start_date', $membership->start_date);
             $template->assign('mem_end_date', $membership->end_date);
             // if separate payment there are two contributions recorded and the
             // admin will need to send a receipt for each of them separately.
             // we dont link the two in the db (but can potentially infer it if needed)
             $template->assign('is_separate_payment', 0);
         }
         $values['contribution_id'] = $contribution->id;
         if (CRM_Utils_Array::value('related_contact', $ids)) {
             $values['related_contact'] = $ids['related_contact'];
             if (isset($ids['onbehalf_dupe_alert'])) {
                 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
             }
             require_once 'CRM/Core/BAO/Address.php';
             $entityBlock = array('contact_id' => $ids['contact'], 'location_type_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType', 'Main', 'id', 'name'));
             $address = CRM_Core_BAO_Address::getValues($entityBlock);
             $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
         }
         $isTest = false;
         if ($contribution->is_test) {
             $isTest = true;
         }
         // CRM_Core_Error::debug('val',$values);
         return CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
     }
 }
Example #16
0
 /**
  * Function to process payment after confirmation
  * 
  * @param object  $form   form object  
  * @param array   $paymentParams   array with payment related key
  * value pairs  
  * @param array   $premiumParams   array with premium related key
  * value pairs  
  * @param int     $contactID       contact id  
  * @param int     $contributionTypeId   contribution type id  
  * @param int     $component   component id  
  * 
  * @return array associated array
  *
  * @static
  * @access public
  */
 static function processConfirm(&$form, &$paymentParams, &$premiumParams, $contactID, $contributionTypeId, $component = 'contribution')
 {
     require_once 'CRM/Core/Payment/Form.php';
     CRM_Core_Payment_Form::mapParams($form->_bltID, $form->_params, $paymentParams, true);
     require_once 'CRM/Contribute/DAO/ContributionType.php';
     $contributionType = new CRM_Contribute_DAO_ContributionType();
     if (isset($paymentParams['contribution_type'])) {
         $contributionType->id = $paymentParams['contribution_type'];
     } else {
         if (CRM_Utils_Array::value('pledge_id', $form->_values)) {
             $contributionType->id = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge', $form->_values['pledge_id'], 'contribution_type_id');
         } else {
             $contributionType->id = $contributionTypeId;
         }
     }
     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'] = $form->_params['contributionType_name'] = $contributionType->name;
     $paymentParams['contributionType_accounting_code'] = $form->_params['contributionType_accounting_code'] = $contributionType->accounting_code;
     $paymentParams['contributionPageID'] = $form->_params['contributionPageID'] = $form->_values['id'];
     if ($form->_values['is_monetary'] && $form->_amount > 0.0 && is_array($form->_paymentProcessor)) {
         require_once 'CRM/Core/Payment.php';
         $payment =& CRM_Core_Payment::singleton($form->_mode, $form->_paymentProcessor, $form);
     }
     //fix for CRM-2062
     $now = date('YmdHis');
     $result = null;
     if ($form->_contributeMode == 'notify' || $form->_params['is_pay_later']) {
         // this is not going to come back, i.e. we fill in the other details
         // when we get a callback from the payment processor
         // also add the contact ID and contribution ID to the params list
         $paymentParams['contactID'] = $form->_params['contactID'] = $contactID;
         $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($form, $paymentParams, null, $contactID, $contributionType, true, true, true);
         $form->_params['contributionID'] = $contribution->id;
         $form->_params['contributionTypeID'] = $contributionType->id;
         $form->_params['item_name'] = $form->_params['description'];
         $form->_params['receive_date'] = $now;
         if ($form->_values['is_recur'] && $contribution->contribution_recur_id) {
             $form->_params['contributionRecurID'] = $contribution->contribution_recur_id;
         }
         $form->set('params', $form->_params);
         $form->postProcessPremium($premiumParams, $contribution);
         if ($form->_values['is_monetary'] && $form->_amount > 0.0) {
             // add qfKey so we can send to paypal
             $form->_params['qfKey'] = $form->controller->_key;
             if ($component == 'membership') {
                 $membershipResult = array(1 => $contribution);
                 return $membershipResult;
             } else {
                 if (!$form->_params['is_pay_later']) {
                     $result =& $payment->doTransferCheckout($form->_params, 'contribute');
                 } else {
                     // follow similar flow as IPN
                     // send the receipt mail
                     $form->set('params', $form->_params);
                     if ($contributionType->is_deductible) {
                         $form->assign('is_deductible', true);
                         $form->set('is_deductible', true);
                     }
                     if (isset($paymentParams['contribution_source'])) {
                         $form->_params['source'] = $paymentParams['contribution_source'];
                     }
                     // get the price set values for receipt.
                     if ($form->_priceSetId && $form->_lineItem) {
                         $form->_values['lineItem'] = $form->_lineItem;
                         $form->_values['priceSetID'] = $form->_priceSetId;
                     }
                     require_once 'CRM/Contribute/BAO/ContributionPage.php';
                     $form->_values['contribution_id'] = $contribution->id;
                     CRM_Contribute_BAO_ContributionPage::sendMail($contactID, $form->_values, $contribution->is_test);
                     return;
                 }
             }
         }
     } elseif ($form->_contributeMode == 'express') {
         if ($form->_values['is_monetary'] && $form->_amount > 0.0) {
             //LCD determine if express + recurring and direct accordingly
             if ($paymentParams['is_recur'] == 1) {
                 $result =& $payment->createRecurringPayments($paymentParams);
             } else {
                 $result =& $payment->doExpressCheckout($paymentParams);
             }
         }
     } elseif ($form->_values['is_monetary'] && $form->_amount > 0.0) {
         if ($paymentParams['is_recur'] && $form->_contributeMode == 'direct') {
             // For recurring contribution, create Contribution Record first.
             // Contribution ID, Recurring ID and Contact ID needed
             // When we get a callback from the payment processor
             $paymentParams['contactID'] = $contactID;
             $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($form, $paymentParams, null, $contactID, $contributionType, true, true, true);
             $paymentParams['contributionID'] = $contribution->id;
             $paymentParams['contributionTypeID'] = $contribution->contribution_type_id;
             $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
             if ($form->_values['is_recur'] && $contribution->contribution_recur_id) {
                 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
             }
         }
         $result =& $payment->doDirectPayment($paymentParams);
     }
     if ($component == 'membership') {
         $membershipResult = array();
     }
     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']);
         }
         if ($component !== 'membership') {
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$form->_params['qfKey']}"));
         }
         $membershipResult[1] = $result;
     } else {
         if ($result) {
             $form->_params = array_merge($form->_params, $result);
         }
         $form->_params['receive_date'] = $now;
         $form->set('params', $form->_params);
         $form->assign('trxn_id', $result['trxn_id']);
         $form->assign('receive_date', CRM_Utils_Date::mysqlToIso($form->_params['receive_date']));
         // result has all the stuff we need
         // lets archive it to a financial transaction
         if ($contributionType->is_deductible) {
             $form->assign('is_deductible', true);
             $form->set('is_deductible', true);
         }
         if (isset($paymentParams['contribution_source'])) {
             $form->_params['source'] = $paymentParams['contribution_source'];
         }
         // check if pending was set to true by payment processor
         $pending = false;
         if (CRM_Utils_Array::value('contribution_status_pending', $form->_params)) {
             $pending = true;
         }
         if (!($paymentParams['is_recur'] && $form->_contributeMode == 'direct')) {
             $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($form, $form->_params, $result, $contactID, $contributionType, true, $pending, true);
         }
         $form->postProcessPremium($premiumParams, $contribution);
         $membershipResult[1] = $contribution;
     }
     if ($component == 'membership') {
         return $membershipResult;
     }
     //Do not send an email if Recurring contribution is done via Direct Mode
     //Email will we send once the IPN will receive.
     if ($paymentParams['is_recur'] && $form->_contributeMode == 'direct') {
         return true;
     }
     // get the price set values for receipt.
     if ($form->_priceSetId && $form->_lineItem) {
         $form->_values['lineItem'] = $form->_lineItem;
         $form->_values['priceSetID'] = $form->_priceSetId;
     }
     // finally send an email receipt
     require_once 'CRM/Contribute/BAO/ContributionPage.php';
     $form->_values['contribution_id'] = $contribution->id;
     CRM_Contribute_BAO_ContributionPage::sendMail($contactID, $form->_values, $contribution->is_test);
 }
 function completeRecur($input, $ids, $objects)
 {
     if ($ids['contributionRecur']) {
         $recur =& $objects['contributionRecur'];
         $contributionCount = CRM_Core_DAO::singleValueQuery("\nSELECT count(*)\nFROM   civicrm_contribution\nWHERE  contribution_recur_id = {$ids['contributionRecur']}\n");
         $autoRenewMembership = FALSE;
         if ($recur->id && isset($ids['membership']) && $ids['membership']) {
             $autoRenewMembership = TRUE;
         }
         if ($recur->installments && $contributionCount >= $recur->installments) {
             $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
             $recur->create_date = CRM_Utils_Date::isoToMysql($recur->create_date);
             $recur->start_date = CRM_Utils_Date::isoToMysql($recur->start_date);
             $recur->cancel_date = CRM_Utils_Date::isoToMysql($recur->cancel_date);
             $recur->end_date = date('YmdHis');
             $recur->modified_date = date('YmdHis');
             $recur->contribution_status_id = array_search('Completed', $contributionStatus);
             $recur->trnx_id = $dataRoot['google-order-number']['VALUE'];
             $recur->save();
             //send recurring Notification email for user
             CRM_Contribute_BAO_ContributionPage::recurringNotify(CRM_Core_Payment::RECURRING_PAYMENT_END, $ids['contact'], $ids['contributionPage'], $recur, $autoRenewMembership);
         } elseif ($contributionCount == 1) {
             CRM_Contribute_BAO_ContributionPage::recurringNotify(CRM_Core_Payment::RECURRING_PAYMENT_START, $ids['contact'], $ids['contributionPage'], $recur, $autoRenewMembership);
         }
     }
 }
 /**
  * Test copy() method
  */
 public function testcopy()
 {
     $params = array('qfkey' => '9a3ef3c08879ad4c8c109b21c583400e', 'title' => 'Test Contribution Page', 'financial_type_id' => $this->_financialTypeID, 'intro_text' => '', 'footer_text' => 'Thanks', 'is_for_organization' => 0, 'for_organization' => ' I am contributing on behalf of an organization', 'goal_amount' => '400', 'is_active' => 1, 'honor_block_title' => '', 'honor_block_text' => '', 'start_date' => '20091022105900', 'start_date_time' => '10:59AM', 'end_date' => '19700101000000', 'end_date_time' => '', 'is_credit_card_only' => '');
     $contributionpage = CRM_Contribute_BAO_ContributionPage::create($params);
     $copycontributionpage = CRM_Contribute_BAO_ContributionPage::copy($contributionpage->id);
     $this->assertEquals($copycontributionpage->financial_type_id, $this->_financialTypeID, 'Check for Financial type id.');
     $this->assertEquals($copycontributionpage->goal_amount, 400, 'Check for goal amount.');
     ContributionPage::delete($contributionpage->id);
     ContributionPage::delete($copycontributionpage->id);
 }
Example #19
0
 /**
  * Complete an order.
  *
  * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
  *
  * Currently overloaded to complete a transaction & repeat a transaction - fix!
  *
  * Moving it out of the BaseIPN class is just the first step.
  *
  * @param array $input
  * @param array $ids
  * @param array $objects
  * @param CRM_Core_Transaction $transaction
  * @param int $recur
  * @param CRM_Contribute_BAO_Contribution $contribution
  * @param bool $isRecurring
  *   Duplication of param needs review. Only used by AuthorizeNetIPN
  * @param int $isFirstOrLastRecurringPayment
  *   Deprecated param only used by AuthorizeNetIPN.
  */
 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment)
 {
     $primaryContributionID = isset($contribution->id) ? $contribution->id : $objects['first_contribution']->id;
     // The previous details are used when calculating line items so keep it before any code that 'does something'
     if (!empty($contribution->id)) {
         $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues(array('id' => $contribution->id), CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
     }
     $inputContributionWhiteList = array('fee_amount', 'net_amount', 'trxn_id', 'check_number', 'payment_instrument_id', 'is_test', 'campaign_id', 'receive_date');
     $contributionParams = array_merge(array('contribution_status_id' => 'Completed'), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)));
     $participant = CRM_Utils_Array::value('participant', $objects);
     $memberships = CRM_Utils_Array::value('membership', $objects);
     $recurContrib = CRM_Utils_Array::value('contributionRecur', $objects);
     if (!empty($recurContrib->id)) {
         $contributionParams['contribution_recur_id'] = $recurContrib->id;
     }
     self::repeatTransaction($contribution, $input, $contributionParams);
     if (is_numeric($memberships)) {
         $memberships = array($objects['membership']);
     }
     $changeDate = CRM_Utils_Array::value('trxn_date', $input, date('YmdHis'));
     $values = array();
     if (isset($input['is_email_receipt'])) {
         $values['is_email_receipt'] = $input['is_email_receipt'];
     }
     if ($input['component'] == 'contribute') {
         if ($contribution->contribution_page_id) {
             CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
             $contributionParams['source'] = ts('Online Contribution') . ': ' . $values['title'];
         } elseif ($recurContrib && $recurContrib->id) {
             $contributionParams['contribution_page_id'] = NULL;
             $values['amount'] = $recurContrib->amount;
             $values['financial_type_id'] = $objects['contributionType']->id;
             $values['title'] = $source = ts('Offline Recurring Contribution');
             $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
             $values['receipt_from_name'] = $domainValues[0];
             $values['receipt_from_email'] = $domainValues[1];
         }
         if ($recurContrib && $recurContrib->id && !isset($input['is_email_receipt'])) {
             //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
             // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
             $values['is_email_receipt'] = $recurContrib->is_email_receipt;
         }
         if (!empty($values['is_email_receipt'])) {
             $contributionParams['receipt_date'] = $changeDate;
         }
         if (!empty($memberships)) {
             foreach ($memberships as $membershipTypeIdKey => $membership) {
                 if ($membership) {
                     $membershipParams = array('id' => $membership->id, 'contact_id' => $membership->contact_id, 'is_test' => $membership->is_test, 'membership_type_id' => $membership->membership_type_id);
                     $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membershipParams['contact_id'], $membershipParams['membership_type_id'], $membershipParams['is_test'], $membershipParams['id']);
                     // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
                     // this picks up membership type changes during renewals
                     $sql = "\nSELECT    membership_type_id\nFROM      civicrm_membership_log\nWHERE     membership_id={$membershipParams['id']}\nORDER BY  id DESC\nLIMIT 1;";
                     $dao = CRM_Core_DAO::executeQuery($sql);
                     if ($dao->fetch()) {
                         if (!empty($dao->membership_type_id)) {
                             $membershipParams['membership_type_id'] = $dao->membership_type_id;
                         }
                     }
                     $dao->free();
                     $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType($membershipParams['membership_type_id'], $primaryContributionID);
                     $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
                     if ($currentMembership) {
                         /*
                          * Fixed FOR CRM-4433
                          * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
                          * when Contribution mode is notify and membership is for renewal )
                          */
                         CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
                         // @todo - we should pass membership_type_id instead of null here but not
                         // adding as not sure of testing
                         $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membershipParams['id'], $changeDate, NULL, $membershipParams['num_terms']);
                         $dates['join_date'] = $currentMembership['join_date'];
                     }
                     //get the status for membership.
                     $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', TRUE, $membershipParams['membership_type_id'], $membershipParams);
                     $membershipParams['status_id'] = CRM_Utils_Array::value('id', $calcStatus, 'New');
                     //we might be renewing membership,
                     //so make status override false.
                     $membershipParams['is_override'] = FALSE;
                     civicrm_api3('Membership', 'create', $membershipParams);
                     //update related Memberships.
                     CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $membershipParams);
                 }
             }
         }
     } else {
         if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
             $eventDetail = civicrm_api3('Event', 'getsingle', array('id' => $objects['event']->id));
             $contributionParams['source'] = ts('Online Event Registration') . ': ' . $eventDetail['title'];
             if ($eventDetail['is_email_confirm']) {
                 // @todo this should be set by the function that sends the mail after sending.
                 $contributionParams['receipt_date'] = $changeDate;
             }
             $participantParams['id'] = $participant->id;
             $participantParams['status_id'] = 'Registered';
             civicrm_api3('Participant', 'create', $participantParams);
         }
     }
     $contributionParams['id'] = $contribution->id;
     civicrm_api3('Contribution', 'create', $contributionParams);
     // Add new soft credit against current $contribution.
     if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id) {
         CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
     }
     $paymentProcessorId = '';
     if (isset($objects['paymentProcessor'])) {
         if (is_array($objects['paymentProcessor'])) {
             $paymentProcessorId = $objects['paymentProcessor']['id'];
         } else {
             $paymentProcessorId = $objects['paymentProcessor']->id;
         }
     }
     $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array('labelColumn' => 'name', 'flip' => 1));
     if (empty($input['prevContribution']) && $paymentProcessorId || !$input['prevContribution']->is_pay_later && $input['prevContribution']->contribution_status_id == $contributionStatuses['Pending']) {
         $input['payment_processor'] = $paymentProcessorId;
     }
     $input['contribution_status_id'] = $contributionStatuses['Completed'];
     $input['total_amount'] = $input['amount'];
     $input['contribution'] = $contribution;
     $input['financial_type_id'] = $contribution->financial_type_id;
     if (!empty($contribution->_relatedObjects['participant'])) {
         $input['contribution_mode'] = 'participant';
         $input['participant_id'] = $contribution->_relatedObjects['participant']->id;
         $input['skipLineItem'] = 1;
     } elseif (!empty($contribution->_relatedObjects['membership'])) {
         $input['skipLineItem'] = TRUE;
         $input['contribution_mode'] = 'membership';
     }
     //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
     // and subsequent payments. In this case the line items are created at
     // CRM_Contribute_BAO_ContributionRecur::addRecurLineItems
     // and since the contribution is saved prior to this line there is always a contribution-id,
     // however there is never a prevContribution (which appears to mean original contribution not previous
     // contribution - or preUpdateContributionObject most accurately)
     // so, this is always called & only appears to succeed when prevContribution exists - which appears
     // to mean "are we updating an exisitng pending contribution"
     //I was able to make the unit test complete as fataling here doesn't prevent
     // the contribution being created - but activities would not be created or emails sent
     CRM_Contribute_BAO_Contribution::recordFinancialAccounts($input, NULL);
     CRM_Core_Error::debug_log_message("Contribution record updated successfully");
     $transaction->commit();
     CRM_Contribute_BAO_ContributionRecur::updateRecurLinkedPledge($contribution);
     // create an activity record
     if ($input['component'] == 'contribute') {
         //CRM-4027
         $targetContactID = NULL;
         if (!empty($ids['related_contact'])) {
             $targetContactID = $contribution->contact_id;
             $contribution->contact_id = $ids['related_contact'];
         }
         CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
         // event
     } else {
         CRM_Activity_BAO_Activity::addActivity($participant);
     }
     // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
     // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
     if (!array_key_exists('is_email_receipt', $values) || $values['is_email_receipt'] == 1) {
         self::sendMail($input, $ids, $objects['contribution'], $values, $recur, FALSE);
         CRM_Core_Error::debug_log_message("Receipt sent");
     }
     CRM_Core_Error::debug_log_message("Success: Database updated");
     if ($isRecurring) {
         CRM_Contribute_BAO_ContributionRecur::sendRecurringStartOrEndNotification($ids, $recur, $isFirstOrLastRecurringPayment);
     }
 }
Example #20
0
 /**
  * Gather values for contribution mail - this function has been created
  * as part of CRM-9996 refactoring as a step towards simplifying the composeMessage function
  * Values related to the contribution in question are gathered
  *
  * @param array $input
  *   Input into function (probably from payment processor).
  * @param array $values
  * @param array $ids
  *   The set of ids related to the input.
  *
  * @return array
  */
 public function _gatherMessageValues($input, &$values, $ids = array())
 {
     // set display address of contributor
     if ($this->address_id) {
         $addressParams = array('id' => $this->address_id);
         $addressDetails = CRM_Core_BAO_Address::getValues($addressParams, FALSE, 'id');
         $addressDetails = array_values($addressDetails);
         $values['address'] = $addressDetails[0]['display'];
     }
     if ($this->_component == 'contribute') {
         if (isset($this->contribution_page_id)) {
             CRM_Contribute_BAO_ContributionPage::setValues($this->contribution_page_id, $values);
             if ($this->contribution_page_id) {
                 // CRM-8254 - override default currency if applicable
                 $config = CRM_Core_Config::singleton();
                 $config->defaultCurrency = CRM_Utils_Array::value('currency', $values, $config->defaultCurrency);
             }
         } else {
             // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
             $values['is_email_receipt'] = 1;
             $values['title'] = 'Contribution';
         }
         // set lineItem for contribution
         if ($this->id) {
             $lineItem = CRM_Price_BAO_LineItem::getLineItems($this->id, 'contribution', 1);
             if (!empty($lineItem)) {
                 $itemId = key($lineItem);
                 foreach ($lineItem as &$eachItem) {
                     if (array_key_exists($eachItem['membership_type_id'], $this->_relatedObjects['membership'])) {
                         $eachItem['join_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->join_date);
                         $eachItem['start_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->start_date);
                         $eachItem['end_date'] = CRM_Utils_Date::customFormat($this->_relatedObjects['membership'][$eachItem['membership_type_id']]->end_date);
                     }
                 }
                 $values['lineItem'][0] = $lineItem;
                 $values['priceSetID'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItem[$itemId]['price_field_id'], 'price_set_id');
             }
         }
         $relatedContact = CRM_Contribute_BAO_Contribution::getOnbehalfIds($this->id, $this->contact_id);
         // if this is onbehalf of contribution then set related contact
         if (!empty($relatedContact['individual_id'])) {
             $values['related_contact'] = $ids['related_contact'] = $relatedContact['individual_id'];
         }
     } else {
         // event
         $eventParams = array('id' => $this->_relatedObjects['event']->id);
         $values['event'] = array();
         CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
         //get location details
         $locationParams = array('entity_id' => $this->_relatedObjects['event']->id, 'entity_table' => 'civicrm_event');
         $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
         $ufJoinParams = array('entity_table' => 'civicrm_event', 'entity_id' => $ids['event'], 'module' => 'CiviEvent');
         list($custom_pre_id, $custom_post_ids) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
         $values['custom_pre_id'] = $custom_pre_id;
         $values['custom_post_id'] = $custom_post_ids;
         // set lineItem for event contribution
         if ($this->id) {
             $participantIds = CRM_Event_BAO_Participant::getParticipantIds($this->id);
             if (!empty($participantIds)) {
                 foreach ($participantIds as $pIDs) {
                     $lineItem = CRM_Price_BAO_LineItem::getLineItems($pIDs);
                     if (!CRM_Utils_System::isNull($lineItem)) {
                         $values['lineItem'][] = $lineItem;
                     }
                 }
             }
         }
     }
     return $values;
 }
 /**
  * Send start or end notification for recurring payments.
  *
  * @param array $ids
  * @param CRM_Contribute_BAO_ContributionRecur $recur
  * @param bool $isFirstOrLastRecurringPayment
  */
 public static function sendRecurringStartOrEndNotification($ids, $recur, $isFirstOrLastRecurringPayment)
 {
     if ($isFirstOrLastRecurringPayment) {
         $autoRenewMembership = FALSE;
         if ($recur->id && isset($ids['membership']) && $ids['membership']) {
             $autoRenewMembership = TRUE;
         }
         //send recurring Notification email for user
         CRM_Contribute_BAO_ContributionPage::recurringNotify($isFirstOrLastRecurringPayment, $ids['contact'], $ids['contributionPage'], $recur, $autoRenewMembership);
     }
 }
Example #22
0
 /**
  * This function is to make a copy of a contribution page, including
  * all the fields in the page
  *
  * @return void
  * @access public
  */
 function copy()
 {
     $gid = CRM_Utils_Request::retrieve('gid', 'Positive', $this, true, 0, 'GET');
     require_once 'CRM/Contribute/BAO/ContributionPage.php';
     CRM_Contribute_BAO_ContributionPage::copy($gid);
     CRM_Utils_System::redirect(CRM_Utils_System::url(CRM_Utils_System::currentPath(), 'reset=1'));
 }
Example #23
0
 function recur(&$input, &$ids, &$objects, $first)
 {
     if (!isset($input['txnType'])) {
         CRM_Core_Error::debug_log_message("Could not find txn_type in input request");
         echo "Failure: Invalid parameters<p>";
         return false;
     }
     if ($input['txnType'] == 'recurring_payment' && $input['paymentStatus'] != 'Completed') {
         CRM_Core_Error::debug_log_message("Ignore all IPN payments that are not completed");
         echo "Failure: Invalid parameters<p>";
         return false;
     }
     $recur =& $objects['contributionRecur'];
     // make sure the invoice ids match
     // make sure the invoice is valid and matches what we have in
     // the contribution record
     if ($recur->invoice_id != $input['invoice']) {
         CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request");
         echo "Failure: Invoice values dont match between database and IPN request<p>";
         return false;
     }
     $now = date('YmdHis');
     // fix dates that already exist
     $dates = array('create', 'start', 'end', 'cancel', 'modified');
     foreach ($dates as $date) {
         $name = "{$date}_date";
         if ($recur->{$name}) {
             $recur->{$name} = CRM_Utils_Date::isoToMysql($recur->{$name});
         }
     }
     $sendNotification = false;
     $subscriptionPaymentStatus = null;
     //List of Transaction Type
     /*
      recurring_payment_profile_created    			RP Profile Created
      recurring_payment 					RP Sucessful Payment
      recurring_payment_failed                               RP Failed Payment
      recurring_payment_profile_cancel     			RP Profile Cancelled
      recurring_payment_expired 				RP Profile Expired
      recurring_payment_skipped				RP Profile Skipped
      recurring_payment_outstanding_payment			RP Sucessful Outstanding Payment
      recurring_payment_outstanding_payment_failed	        RP Failed Outstanding Payment
      recurring_payment_suspended				RP Profile Suspended
      recurring_payment_suspended_due_to_max_failed_payment	RP Profile Suspended due to Max Failed Payment
     */
     //set transaction type
     $txnType = $_POST['txn_type'];
     require_once 'CRM/Core/Payment.php';
     //Changes for paypal pro recurring payment
     switch ($txnType) {
         case 'recurring_payment_profile_created':
             $recur->create_date = $now;
             $recur->contribution_status_id = 2;
             $recur->processor_id = $_POST['recurring_payment_id'];
             $recur->trxn_id = $recur->processor_id;
             $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_START;
             $sendNotification = true;
             break;
         case 'recurring_payment':
             if ($first) {
                 $recur->start_date = $now;
             } else {
                 $recur->modified_date = $now;
             }
             //contribution installment is completed
             if ($_POST['profile_status'] == 'Expired') {
                 $recur->contribution_status_id = 1;
                 $recur->end_date = $now;
                 $sendNotification = true;
                 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
             }
             // make sure the contribution status is not done
             // since order of ipn's is unknown
             if ($recur->contribution_status_id != 1) {
                 $recur->contribution_status_id = 5;
             }
             break;
     }
     $recur->save();
     if ($sendNotification) {
         //send recurring Notification email for user
         require_once 'CRM/Contribute/BAO/ContributionPage.php';
         CRM_Contribute_BAO_ContributionPage::recurringNofify($subscriptionPaymentStatus, $ids['contact'], $ids['contributionPage'], $recur);
     }
     if ($txnType != 'recurring_payment') {
         return;
     }
     if (!$first) {
         // create a contribution and then get it processed
         $contribution =& new CRM_Contribute_DAO_Contribution();
         $contribution->contact_id = $ids['contact'];
         $contribution->contribution_type_id = $objects['contributionType']->id;
         $contribution->contribution_page_id = $ids['contributionPage'];
         $contribution->contribution_recur_id = $ids['contributionRecur'];
         $contribution->receive_date = $now;
         $contribution->currency = $objects['contribution']->currency;
         $contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id;
         $contribution->amount_level = $objects['contribution']->amount_level;
         $objects['contribution'] =& $contribution;
     }
     $this->single($input, $ids, $objects, true, $first);
 }
Example #24
0
 /**
  * Process payment after confirmation.
  *
  * @param CRM_Core_Form $form
  *   Form object.
  * @param array $paymentParams
  *   Array with payment related key.
  *   value pairs
  * @param int $contactID
  *   Contact id.
  * @param int $contributionTypeId
  *   Financial type id.
  * @param int|string $component component id
  * @param $isTest
  *
  * @throws CRM_Core_Exception
  * @throws Exception
  * @return array
  *   associated array
  *
  */
 public static function processConfirm(&$form, &$paymentParams, $contactID, $contributionTypeId, $component = 'contribution', $isTest)
 {
     CRM_Core_Payment_Form::mapParams($form->_bltID, $form->_params, $paymentParams, TRUE);
     $lineItems = $form->_lineItem;
     $isPaymentTransaction = self::isPaymentTransaction($form);
     $financialType = new CRM_Financial_DAO_FinancialType();
     $financialType->id = $contributionTypeId;
     $financialType->find(TRUE);
     if ($financialType->is_deductible) {
         $form->assign('is_deductible', TRUE);
         $form->set('is_deductible', TRUE);
     }
     // add some financial type details to the params list
     // if folks need to use it
     //CRM-15297 - contributionType is obsolete - pass financial type as well so people can deprecate it
     $paymentParams['financialType_name'] = $paymentParams['contributionType_name'] = $form->_params['contributionType_name'] = $financialType->name;
     //CRM-11456
     $paymentParams['financialType_accounting_code'] = $paymentParams['contributionType_accounting_code'] = $form->_params['contributionType_accounting_code'] = CRM_Financial_BAO_FinancialAccount::getAccountingCode($contributionTypeId);
     $paymentParams['contributionPageID'] = $form->_params['contributionPageID'] = $form->_values['id'];
     $paymentParams['contactID'] = $form->_params['contactID'] = $contactID;
     //fix for CRM-16317
     $form->_params['receive_date'] = date('YmdHis');
     $form->assign('receive_date', CRM_Utils_Date::mysqlToIso($form->_params['receive_date']));
     if ($isPaymentTransaction) {
         // Fix for CRM-14354. If the membership is recurring, don't create a
         // civicrm_contribution_recur record for the additional contribution
         // (i.e., the amount NOT associated with the membership). Temporarily
         // cache the is_recur values so we can process the additional gift as a
         // one-off payment.
         if (!empty($form->_values['is_recur'])) {
             if ($form->_membershipBlock['is_separate_payment'] && !empty($form->_params['auto_renew'])) {
                 $cachedFormValue = CRM_Utils_Array::value('is_recur', $form->_values);
                 $cachedParamValue = CRM_Utils_Array::value('is_recur', $paymentParams);
                 unset($form->_values['is_recur']);
                 unset($paymentParams['is_recur']);
             }
         }
         $contributionParams = array('contact_id' => $contactID, 'line_item' => $lineItems, 'is_test' => $isTest, 'campaign_id' => CRM_Utils_Array::value('campaign_id', $paymentParams, CRM_Utils_Array::value('campaign_id', $form->_values)), 'contribution_page_id' => $form->_id, 'source' => CRM_Utils_Array::value('source', $paymentParams, CRM_Utils_Array::value('description', $paymentParams)));
         $isMonetary = !empty($form->_values['is_monetary']);
         if ($isMonetary) {
             if (empty($paymentParams['is_pay_later'])) {
                 // @todo look up payment_instrument_id on payment processor table.
                 $contributionParams['payment_instrument_id'] = 1;
             }
         }
         $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($form, $paymentParams, NULL, $contributionParams, $financialType, TRUE, TRUE, $form->_bltID);
         $paymentParams['contributionTypeID'] = $contributionTypeId;
         $paymentParams['item_name'] = $form->_params['description'];
         if ($contribution && $form->_values['is_recur'] && $contribution->contribution_recur_id) {
             $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
         }
         $paymentParams['qfKey'] = $form->controller->_key;
         if ($component == 'membership') {
             return array('contribution' => $contribution);
         }
         // restore cached values (part of fix for CRM-14354)
         if (!empty($cachedFormValue)) {
             $form->_values['is_recur'] = $cachedFormValue;
             $paymentParams['is_recur'] = $cachedParamValue;
         }
         $paymentParams['contributionID'] = $contribution->id;
         //CRM-15297 deprecate contributionTypeID
         $paymentParams['financialTypeID'] = $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
         $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
         if (isset($paymentParams['contribution_source'])) {
             $paymentParams['source'] = $paymentParams['contribution_source'];
         }
         if ($form->_values['is_recur'] && $contribution->contribution_recur_id) {
             $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
         }
         if ($form->_contributeMode && $form->_amount > 0.0) {
             try {
                 $payment = Civi\Payment\System::singleton()->getByProcessor($form->_paymentProcessor);
                 if ($form->_contributeMode == 'notify') {
                     // We want to get rid of this & make it generic - eg. by making payment processing the last thing
                     // and always calling it first.
                     $form->postProcessHook();
                 }
                 $result = $payment->doPayment($paymentParams);
                 $form->_params = array_merge($form->_params, $result);
                 $form->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $result));
                 if (!empty($result['trxn_id'])) {
                     $contribution->trxn_id = $result['trxn_id'];
                 }
                 if (!empty($result['payment_status_id'])) {
                     $contribution->payment_status_id = $result['payment_status_id'];
                 }
                 $result['contribution'] = $contribution;
                 return $result;
             } catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
                 // Clean up DB as appropriate.
                 if (!empty($paymentParams['contributionID'])) {
                     CRM_Contribute_BAO_Contribution::failPayment($paymentParams['contributionID'], $paymentParams['contactID'], $e->getMessage());
                 }
                 if (!empty($paymentParams['contributionRecurID'])) {
                     CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
                 }
                 $result['is_payment_failure'] = TRUE;
                 $result['error'] = $e;
                 return $result;
             }
         }
     }
     // Only pay later or unpaid should reach this point. The theory is that paylater should get a receipt now &
     // processor
     // transaction receipts should be outcome driven.
     $form->set('params', $form->_params);
     if (isset($paymentParams['contribution_source'])) {
         $form->_params['source'] = $paymentParams['contribution_source'];
     }
     // get the price set values for receipt.
     if ($form->_priceSetId && $form->_lineItem) {
         $form->_values['lineItem'] = $form->_lineItem;
         $form->_values['priceSetID'] = $form->_priceSetId;
     }
     $form->_values['contribution_id'] = $contribution->id;
     $form->_values['contribution_page_id'] = $contribution->contribution_page_id;
     CRM_Contribute_BAO_ContributionPage::sendMail($contactID, $form->_values, $contribution->is_test);
 }
Example #25
0
 /**
  * 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) {
         // seems like the session is corrupted and/or we lost the id trail
         // lets just bump this to a regular session error and redirect user to main page
         $this->controller->invalidKeyRedirect();
     }
     // this was used prior to the cleverer this_>getContactID - unsure now
     $this->_userID = $session->get('userID');
     $this->_contactID = $this->_membershipContactID = $this->getContactID();
     $this->_mid = NULL;
     if ($this->_contactID) {
         $this->_mid = CRM_Utils_Request::retrieve('mid', 'Positive', $this);
         if ($this->_mid) {
             $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->_contactID) {
                     $validMembership = FALSE;
                     $employers = CRM_Contact_BAO_Relationship::getPermissionedEmployer($this->_userID);
                     if (!empty($employers) && array_key_exists($membership->contact_id, $employers)) {
                         $this->_membershipContactID = $membership->contact_id;
                         $this->assign('membershipContactID', $this->_membershipContactID);
                         $this->assign('membershipContactName', $employers[$this->_membershipContactID]['name']);
                         $validMembership = TRUE;
                     } else {
                         $membershipType = new CRM_Member_BAO_MembershipType();
                         $membershipType->id = $membership->membership_type_id;
                         if ($membershipType->find(TRUE)) {
                             // CRM-14051 - membership_type.relationship_type_id is a CTRL-A padded string w one or more ID values.
                             // Convert to commma separated list.
                             $inheritedRelTypes = implode(CRM_Utils_Array::explodePadded($membershipType->relationship_type_id), ',');
                             $permContacts = CRM_Contact_BAO_Relationship::getPermissionedContacts($this->_userID, $membershipType->relationship_type_id);
                             if (array_key_exists($membership->contact_id, $permContacts)) {
                                 $this->_membershipContactID = $membership->contact_id;
                                 $validMembership = TRUE;
                             }
                         }
                     }
                     if (!$validMembership) {
                         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."), ts('Membership Invalid'), 'alert');
                     }
                 }
             } 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."), ts('Membership Invalid'), 'alert');
             }
             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();
         CRM_Contribute_BAO_ContributionPage::setValues($this->_id, $this->_values);
         // check if form is active
         if (!CRM_Utils_Array::value('is_active', $this->_values)) {
             // 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::get('CRM_Core_DAO_Address', 'location_type_id', array(), 'validate');
         // CRM-8108 remove ts around Billing location type
         //$this->_bltID = array_search( ts('Billing'),  $locationTypes );
         $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);
         //FIXME: to support multiple payment processors
         if ($isMonetary && (!$isPayLater || CRM_Utils_Array::value('payment_processor', $this->_values))) {
             $ppID = CRM_Utils_Array::value('payment_processor', $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).'));
             }
             $ppIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $ppID);
             $this->_paymentProcessors = CRM_Financial_BAO_PaymentProcessor::getPayments($ppIds, $this->_mode);
             $this->set('paymentProcessors', $this->_paymentProcessors);
             //set default payment processor
             if (!empty($this->_paymentProcessors) && empty($this->_paymentProcessor)) {
                 foreach ($this->_paymentProcessors as $ppId => $values) {
                     if ($values['is_default'] == 1 || count($this->_paymentProcessors) == 1) {
                         $defaultProcessorId = $ppId;
                         break;
                     }
                 }
             }
             if (isset($defaultProcessorId)) {
                 $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($defaultProcessorId, $this->_mode);
                 $this->assign_by_ref('paymentProcessor', $this->_paymentProcessor);
             }
             if (!CRM_Utils_System::isNull($this->_paymentProcessors)) {
                 foreach ($this->_paymentProcessors as $eachPaymentProcessor) {
                     // check selected payment processor is active
                     if (empty($eachPaymentProcessor)) {
                         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, $eachPaymentProcessor, $this);
                     $error = $this->_paymentObject->checkConfig();
                     if (!empty($error)) {
                         CRM_Core_Error::fatal($error);
                     }
                 }
             }
         }
         // get price info
         // CRM-5095
         CRM_Price_BAO_PriceSet::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
         $this->_membershipBlock = CRM_Member_BAO_Membership::getMembershipBlock($this->_id);
         $this->set('membershipBlock', $this->_membershipBlock);
         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']);
         }
         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.'));
         }
         $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;
                 //lets override w/ pledge campaign.
                 $this->_values['campaign_id'] = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge', $pledgeId, 'campaign_id');
                 self::authenticatePledgeUser();
             }
         }
         $this->set('values', $this->_values);
         $this->set('fields', $this->_fields);
     }
     // Handle PCP
     $pcpId = CRM_Utils_Request::retrieve('pcpId', 'Positive', $this);
     if ($pcpId) {
         $pcp = CRM_PCP_BAO_PCP::handlePcp($pcpId, 'contribute', $this->_values);
         $this->_pcpId = $pcp['pcpId'];
         $this->_pcpBlock = $pcp['pcpBlock'];
         $this->_pcpInfo = $pcp['pcpInfo'];
     }
     // Link (button) for users to create their own Personal Campaign page
     if ($linkText = CRM_PCP_BAO_PCP::getPcpBlockStatus($this->_id, 'contribute')) {
         $linkTextUrl = CRM_Utils_System::url('civicrm/contribute/campaign', "action=add&reset=1&pageId={$this->_id}&component=contribute", 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);
     }
     // check if one of the (amount , membership)  bloks is active or not
     $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']);
     }
     $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', $this->_pcpInfo['title']);
         CRM_Utils_System::setTitle($this->_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);
     //lets allow user to override campaign.
     $campID = CRM_Utils_Request::retrieve('campID', 'Positive', $this);
     if ($campID && CRM_Core_DAO::getFieldValue('CRM_Campaign_DAO_Campaign', $campID)) {
         $this->_values['campaign_id'] = $campID;
     }
     //do check for cancel recurring and clean db, CRM-7696
     if (CRM_Utils_Request::retrieve('cancel', 'Boolean', CRM_Core_DAO::$_nullObject)) {
         self::cancelRecurring();
     }
 }
Example #26
0
 /**
  * Process the Memberships
  *
  * @param array  $membershipParams array of membership fields
  * @param int    $contactID        contact id 
  * @param object $form             form object  
  *
  * @return void
  * @access public
  */
 public function postProcessMembership($membershipParams, $contactID, &$form, &$premiumParams)
 {
     $tempParams = $membershipParams;
     $paymentDone = false;
     $result = null;
     $isTest = CRM_Utils_Array::value('is_test', $membershipParams, false);
     $form->assign('membership_assign', true);
     $form->set('membershipTypeID', $membershipParams['selectMembership']);
     require_once 'CRM/Member/BAO/MembershipType.php';
     require_once 'CRM/Member/BAO/Membership.php';
     $membershipTypeID = $membershipParams['selectMembership'];
     $membershipDetails = self::buildMembershipTypeValues($form, $membershipTypeID);
     $form->assign('membership_name', $membershipDetails['name']);
     $minimumFee = CRM_Utils_Array::value('minimum_fee', $membershipDetails);
     $contributionTypeId = null;
     if ($form->_values['amount_block_is_active']) {
         $contributionTypeId = $form->_values['contribution_type_id'];
     } else {
         $paymentDone = true;
         $params['amount'] = $minimumFee;
         $contributionTypeId = $membershipDetails['contribution_type_id'];
     }
     //amount must be greater than zero for
     //adding contribution record  to contribution table.
     //this condition is arises when separate membership payment is
     //enable and contribution amount is not selected. fix for CRM-3010
     require_once 'CRM/Contribute/BAO/Contribution/Utils.php';
     if ($form->_amount > 0.0) {
         $result = CRM_Contribute_BAO_Contribution_Utils::processConfirm($form, $membershipParams, $premiumParams, $contactID, $contributionTypeId, 'membership');
     } else {
         // create the CMS contact here since we normally do this under processConfirm
         CRM_Contribute_BAO_Contribution_Utils::createCMSUser($membershipParams, $membershipParams['cms_contactID'], 'email-' . $form->_bltID);
     }
     $errors = array();
     if (is_a($result[1], 'CRM_Core_Error')) {
         $errors[1] = CRM_Core_Error::getMessages($result[1]);
     } else {
         $contribution[1] = $result[1];
     }
     $memBlockDetails = CRM_Member_BAO_Membership::getMembershipBlock($form->_id);
     if ($memBlockDetails['is_separate_payment'] && !$paymentDone) {
         require_once 'CRM/Contribute/DAO/ContributionType.php';
         $contributionType = new CRM_Contribute_DAO_ContributionType();
         $contributionType->id = $membershipDetails['contribution_type_id'];
         if (!$contributionType->find(true)) {
             CRM_Core_Error::fatal("Could not find a system table");
         }
         $tempParams['amount'] = $minimumFee;
         $invoiceID = md5(uniqid(rand(), true));
         $tempParams['invoiceID'] = $invoiceID;
         //we don't allow recurring membership.CRM-3781.
         if (CRM_Utils_Array::value('is_recur', $tempParams)) {
             $tempParams['is_recur'] = 0;
         }
         $result = null;
         if ($form->_values['is_monetary'] && !$form->_params['is_pay_later']) {
             require_once 'CRM/Core/Payment.php';
             $payment =& CRM_Core_Payment::singleton($form->_mode, $form->_paymentProcessor, $form);
             if ($form->_contributeMode == 'express') {
                 $result =& $payment->doExpressCheckout($tempParams);
             } else {
                 $result =& $payment->doDirectPayment($tempParams);
             }
         }
         if (is_a($result, 'CRM_Core_Error')) {
             $errors[2] = CRM_Core_Error::getMessages($result);
         } else {
             //assign receive date when separate membership payment
             //and contribution amount not selected.
             if ($form->_amount == 0) {
                 $now = date('YmdHis');
                 $form->_params['receive_date'] = $now;
                 $receiveDate = CRM_Utils_Date::mysqlToIso($now);
                 $form->set('params', $form->_params);
                 $form->assign('receive_date', $receiveDate);
             }
             $form->set('membership_trx_id', $result['trxn_id']);
             $form->set('membership_amount', $minimumFee);
             $form->assign('membership_trx_id', $result['trxn_id']);
             $form->assign('membership_amount', $minimumFee);
             // we dont need to create the user twice, so lets disable cms_create_account
             // irrespective of the value, CRM-2888
             $tempParams['cms_create_account'] = 0;
             $pending = $form->_params['is_pay_later'] ? true : false;
             //set this variable as we are not creating pledge for
             //separate membership payment contribution.
             //so for differentiating membership contributon from
             //main contribution.
             $form->_params['separate_membership_payment'] = 1;
             $contribution[2] = CRM_Contribute_Form_Contribution_Confirm::processContribution($form, $tempParams, $result, $contactID, $contributionType, false, $pending);
         }
     }
     $index = $memBlockDetails['is_separate_payment'] ? 2 : 1;
     if (!CRM_Utils_Array::value($index, $errors)) {
         $membership = self::renewMembership($contactID, $membershipTypeID, $isTest, $form, null, CRM_Utils_Array::value('cms_contactID', $membershipParams));
         if (isset($contribution[$index])) {
             //insert payment record
             require_once 'CRM/Member/DAO/MembershipPayment.php';
             $dao = new CRM_Member_DAO_MembershipPayment();
             $dao->membership_id = $membership->id;
             $dao->contribution_id = $contribution[$index]->id;
             //Fixed for avoiding duplicate entry error when user goes
             //back and forward during payment mode is notify
             if (!$dao->find(true)) {
                 CRM_Utils_Hook::pre('create', 'MembershipPayment', null, $dao);
                 $dao->save();
                 CRM_Utils_Hook::post('create', 'MembershipPayment', $dao->id, $dao);
             }
         }
     }
     require_once 'CRM/Core/BAO/CustomValueTable.php';
     CRM_Core_BAO_CustomValueTable::postProcess($form->_params, CRM_Core_DAO::$_nullArray, 'civicrm_membership', $membership->id, 'Membership');
     if (!empty($errors)) {
         foreach ($errors as $error) {
             if (is_string($error)) {
                 $message[] = $error;
             }
         }
         $message = ts("Payment Processor Error message") . ": " . implode('<br/>', $message);
         $session = CRM_Core_Session::singleton();
         $session->setStatus($message);
         CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$form->_params['qfKey']}"));
     }
     $form->_params['membershipID'] = $membership->id;
     if ($form->_contributeMode == 'notify') {
         if ($form->_values['is_monetary'] && $form->_amount > 0.0 && !$form->_params['is_pay_later']) {
             // this does not return
             require_once 'CRM/Core/Payment.php';
             $payment =& CRM_Core_Payment::singleton($form->_mode, $form->_paymentProcessor, $form);
             $payment->doTransferCheckout($form->_params, 'contribute');
         }
     }
     $form->_values['membership_id'] = $membership->id;
     if (isset($contribution[$index]->id)) {
         $form->_values['contribution_id'] = $contribution[$index]->id;
     }
     // Do not send an email if Recurring transaction is done via Direct Mode
     // Email will we sent when the IPN is received.
     if ($form->_params['is_recur'] && $form->_contributeMode == 'direct') {
         return true;
     }
     //finally send an email receipt
     require_once "CRM/Contribute/BAO/ContributionPage.php";
     CRM_Contribute_BAO_ContributionPage::sendMail($contactID, $form->_values, $isTest);
 }
Example #27
0
 function recur(&$input, &$ids, &$objects, $first)
 {
     if (!isset($input['txnType'])) {
         CRM_Core_Error::debug_log_message("Could not find txn_type in input request");
         echo "Failure: Invalid parameters<p>";
         return false;
     }
     if ($input['txnType'] == 'subscr_payment' && $input['paymentStatus'] != 'Completed') {
         CRM_Core_Error::debug_log_message("Ignore all IPN payments that are not completed");
         echo "Failure: Invalid parameters<p>";
         return false;
     }
     $recur =& $objects['contributionRecur'];
     // make sure the invoice ids match
     // make sure the invoice is valid and matches what we have in the contribution record
     if ($recur->invoice_id != $input['invoice']) {
         CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request");
         echo "Failure: Invoice values dont match between database and IPN request<p>";
         return false;
     }
     $now = date('YmdHis');
     // fix dates that already exist
     $dates = array('create', 'start', 'end', 'cancel', 'modified');
     foreach ($dates as $date) {
         $name = "{$date}_date";
         if ($recur->{$name}) {
             $recur->{$name} = CRM_Utils_Date::isoToMysql($recur->{$name});
         }
     }
     $sendNotification = false;
     $subscriptionPaymentStatus = null;
     require_once 'CRM/Core/Payment.php';
     //set transaction type
     $txnType = $_POST['txn_type'];
     switch ($txnType) {
         case 'subscr_signup':
             $recur->create_date = $now;
             //some times subscr_signup response come after the
             //subscr_payment and set to pending mode.
             $statusID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionRecur', $recur->id, 'contribution_status_id');
             if ($statusID != 5) {
                 $recur->contribution_status_id = 2;
             }
             $recur->processor_id = $_POST['subscr_id'];
             $recur->trxn_id = $recur->processor_id;
             $sendNotification = true;
             $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_START;
             break;
         case 'subscr_eot':
             $recur->contribution_status_id = 1;
             $recur->end_date = $now;
             $sendNotification = true;
             $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
             break;
         case 'subscr_cancel':
             $recur->contribution_status_id = 3;
             $recur->cancel_date = $now;
             break;
         case 'subscr_failed':
             $recur->contribution_status_id = 4;
             $recur->cancel_date = $now;
             break;
         case 'subscr_modify':
             CRM_Core_Error::debug_log_message("We do not handle modifications to subscriptions right now");
             echo "Failure: We do not handle modifications to subscriptions right now<p>";
             return false;
         case 'subscr_payment':
             if ($first) {
                 $recur->start_date = $now;
             } else {
                 $recur->modified_date = $now;
             }
             // make sure the contribution status is not done
             // since order of ipn's is unknown
             if ($recur->contribution_status_id != 1) {
                 $recur->contribution_status_id = 5;
             }
             break;
     }
     $recur->save();
     if ($sendNotification) {
         //send recurring Notification email for user
         require_once 'CRM/Contribute/BAO/ContributionPage.php';
         CRM_Contribute_BAO_ContributionPage::recurringNofify($subscriptionPaymentStatus, $ids['contact'], $ids['contributionPage'], $recur);
     }
     if ($txnType != 'subscr_payment') {
         return;
     }
     if (!$first) {
         // create a contribution and then get it processed
         $contribution =& new CRM_Contribute_DAO_Contribution();
         $contribution->contact_id = $ids['contact'];
         $contribution->contribution_type_id = $objects['contributionType']->id;
         $contribution->contribution_page_id = $ids['contributionPage'];
         $contribution->contribution_recur_id = $ids['contributionRecur'];
         $contribution->receive_date = $now;
         $contribution->currency = $objects['contribution']->currency;
         $contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id;
         $contribution->amount_level = $objects['contribution']->amount_level;
         $objects['contribution'] =& $contribution;
     }
     $this->single($input, $ids, $objects, true, $first);
 }
Example #28
0
 /**
  * Browse all contribution pages.
  *
  * @param mixed $action
  *   Unused parameter.
  */
 public function browse($action = NULL)
 {
     Civi::resources()->addStyleFile('civicrm', 'css/searchForm.css', 1, 'html-header');
     $this->_sortByCharacter = CRM_Utils_Request::retrieve('sortByCharacter', 'String', $this);
     // @todo Unused local variable can be safely removed.
     // But are there any side effects of CRM_Utils_Request::retrieve() that we
     // need to preserve?
     $createdId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, FALSE, 0);
     if ($this->_sortByCharacter == 'all' || !empty($_POST)) {
         $this->_sortByCharacter = '';
         $this->set('sortByCharacter', '');
     }
     $this->search();
     $params = array();
     $whereClause = $this->whereClause($params, FALSE);
     $this->pagerAToZ($whereClause, $params);
     $params = array();
     $whereClause = $this->whereClause($params, TRUE);
     $this->pager($whereClause, $params);
     list($offset, $rowCount) = $this->_pager->getOffsetAndRowCount();
     //check for delete CRM-4418
     $allowToDelete = CRM_Core_Permission::check('delete in CiviContribute');
     $query = "\n  SELECT  id\n    FROM  civicrm_contribution_page\n   WHERE  {$whereClause}\n   ORDER BY is_active desc, title asc\n   LIMIT  {$offset}, {$rowCount}";
     $contribPage = CRM_Core_DAO::executeQuery($query, $params, TRUE, 'CRM_Contribute_DAO_ContributionPage');
     $contribPageIds = array();
     while ($contribPage->fetch()) {
         $contribPageIds[$contribPage->id] = $contribPage->id;
     }
     //get all section info.
     $contriPageSectionInfo = CRM_Contribute_BAO_ContributionPage::getSectionInfo($contribPageIds);
     $query = "\nSELECT *\nFROM civicrm_contribution_page\nWHERE {$whereClause}\nORDER BY is_active desc, title asc\n   LIMIT {$offset}, {$rowCount}";
     $dao = CRM_Core_DAO::executeQuery($query, $params, TRUE, 'CRM_Contribute_DAO_ContributionPage');
     //get all campaigns.
     $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
     //get configure actions links.
     $configureActionLinks = self::configureActionLinks();
     while ($dao->fetch()) {
         $contribution[$dao->id] = array();
         CRM_Core_DAO::storeValues($dao, $contribution[$dao->id]);
         // form all action links
         $action = array_sum(array_keys($this->actionLinks()));
         //add configure actions links.
         $action += array_sum(array_keys($configureActionLinks));
         //add online contribution links.
         $action += array_sum(array_keys(self::onlineContributionLinks()));
         //add contribution search links.
         $action += array_sum(array_keys(self::contributionLinks()));
         if ($dao->is_active) {
             $action -= (int) CRM_Core_Action::ENABLE;
         } else {
             $action -= (int) CRM_Core_Action::DISABLE;
         }
         //CRM-4418
         if (!$allowToDelete) {
             $action -= (int) CRM_Core_Action::DELETE;
         }
         //build the configure links.
         $sectionsInfo = CRM_Utils_Array::value($dao->id, $contriPageSectionInfo, array());
         $contribution[$dao->id]['configureActionLinks'] = CRM_Core_Action::formLink(self::formatConfigureLinks($sectionsInfo), $action, array('id' => $dao->id), ts('Configure'), TRUE, 'contributionpage.configure.actions', 'ContributionPage', $dao->id);
         //build the contributions links.
         $contribution[$dao->id]['contributionLinks'] = CRM_Core_Action::formLink(self::contributionLinks(), $action, array('id' => $dao->id), ts('Contributions'), TRUE, 'contributionpage.contributions.search', 'ContributionPage', $dao->id);
         //build the online contribution links.
         $contribution[$dao->id]['onlineContributionLinks'] = CRM_Core_Action::formLink(self::onlineContributionLinks(), $action, array('id' => $dao->id), ts('Links'), TRUE, 'contributionpage.online.links', 'ContributionPage', $dao->id);
         //build the normal action links.
         $contribution[$dao->id]['action'] = CRM_Core_Action::formLink(self::actionLinks(), $action, array('id' => $dao->id), ts('more'), TRUE, 'contributionpage.action.links', 'ContributionPage', $dao->id);
         //show campaigns on selector.
         $contribution[$dao->id]['campaign'] = CRM_Utils_Array::value($dao->campaign_id, $allCampaigns);
     }
     if (isset($contribution)) {
         $this->assign('rows', $contribution);
     }
 }
 /**
  * Process recurring contributions
  * @param array $input
  * @param array $ids
  * @param array $objects
  * @param boolean $first
  * @return void|boolean
  */
 function recur(&$input, &$ids, &$objects, $first)
 {
     if (!isset($input['txnType'])) {
         CRM_Core_Error::debug_log_message("Could not find txn_type in input request");
         echo "Failure: Invalid parameters<p>";
         return FALSE;
     }
     if ($input['txnType'] == 'recurring_payment' && $input['paymentStatus'] != 'Completed') {
         CRM_Core_Error::debug_log_message("Ignore all IPN payments that are not completed");
         echo "Failure: Invalid parameters<p>";
         return FALSE;
     }
     $recur =& $objects['contributionRecur'];
     // make sure the invoice ids match
     // make sure the invoice is valid and matches what we have in
     // the contribution record
     if ($recur->invoice_id != $input['invoice']) {
         CRM_Core_Error::debug_log_message("Invoice values dont match between database and IPN request recur is " . $recur->invoice_id . " input is " . $input['invoice']);
         echo "Failure: Invoice values dont match between database and IPN request recur is " . $recur->invoice_id . " input is " . $input['invoice'];
         return FALSE;
     }
     $now = date('YmdHis');
     // fix dates that already exist
     $dates = array('create', 'start', 'end', 'cancel', 'modified');
     foreach ($dates as $date) {
         $name = "{$date}_date";
         if ($recur->{$name}) {
             $recur->{$name} = CRM_Utils_Date::isoToMysql($recur->{$name});
         }
     }
     $sendNotification = FALSE;
     $subscriptionPaymentStatus = NULL;
     //List of Transaction Type
     /*
      recurring_payment_profile_created          RP Profile Created
      recurring_payment           RP Sucessful Payment
      recurring_payment_failed                               RP Failed Payment
      recurring_payment_profile_cancel           RP Profile Cancelled
      recurring_payment_expired         RP Profile Expired
      recurring_payment_skipped        RP Profile Skipped
      recurring_payment_outstanding_payment      RP Sucessful Outstanding Payment
      recurring_payment_outstanding_payment_failed          RP Failed Outstanding Payment
      recurring_payment_suspended        RP Profile Suspended
      recurring_payment_suspended_due_to_max_failed_payment  RP Profile Suspended due to Max Failed Payment
     */
     //set transaction type
     $txnType = $this->retrieve('txn_type', 'String');
     //Changes for paypal pro recurring payment
     $contributionStatuses = civicrm_api3('contribution', 'getoptions', array('field' => 'contribution_status_id'));
     $contributionStatuses = $contributionStatuses['values'];
     switch ($txnType) {
         case 'recurring_payment_profile_created':
             if (in_array($recur->contribution_status_id, array(array_search('Pending', $contributionStatuses), array_search('In Progress', $contributionStatuses))) && !empty($recur->processor_id)) {
                 echo "already handled";
                 return;
             }
             $recur->create_date = $now;
             $recur->contribution_status_id = 2;
             $recur->processor_id = $this->retrieve('recurring_payment_id', 'String');
             $recur->trxn_id = $recur->processor_id;
             $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_START;
             $sendNotification = TRUE;
             break;
         case 'recurring_payment':
             if ($first) {
                 $recur->start_date = $now;
             } else {
                 $recur->modified_date = $now;
             }
             //contribution installment is completed
             if ($this->retrieve('profile_status', 'String') == 'Expired') {
                 if (!empty($recur->end_date)) {
                     echo "already handled";
                     return;
                 }
                 $recur->contribution_status_id = 1;
                 $recur->end_date = $now;
                 $sendNotification = TRUE;
                 $subscriptionPaymentStatus = CRM_Core_Payment::RECURRING_PAYMENT_END;
             }
             // make sure the contribution status is not done
             // since order of ipn's is unknown
             if ($recur->contribution_status_id != 1) {
                 $recur->contribution_status_id = 5;
             }
             break;
     }
     $recur->save();
     if ($sendNotification) {
         $autoRenewMembership = FALSE;
         if ($recur->id && isset($ids['membership']) && $ids['membership']) {
             $autoRenewMembership = TRUE;
         }
         //send recurring Notification email for user
         CRM_Contribute_BAO_ContributionPage::recurringNotify($subscriptionPaymentStatus, $ids['contact'], $ids['contributionPage'], $recur, $autoRenewMembership);
     }
     if ($txnType != 'recurring_payment') {
         return;
     }
     if (!$first) {
         //check if this contribution transaction is already processed
         //if not create a contribution and then get it processed
         $contribution = new CRM_Contribute_BAO_Contribution();
         $contribution->trxn_id = $input['trxn_id'];
         if ($contribution->trxn_id && $contribution->find()) {
             CRM_Core_Error::debug_log_message("returning since contribution has already been handled");
             echo "Success: Contribution has already been handled<p>";
             return TRUE;
         }
         $contribution->contact_id = $recur->contact_id;
         $contribution->financial_type_id = $objects['contributionType']->id;
         $contribution->contribution_page_id = $ids['contributionPage'];
         $contribution->contribution_recur_id = $ids['contributionRecur'];
         $contribution->currency = $objects['contribution']->currency;
         $contribution->payment_instrument_id = $objects['contribution']->payment_instrument_id;
         $contribution->amount_level = $objects['contribution']->amount_level;
         $contribution->campaign_id = $objects['contribution']->campaign_id;
         $objects['contribution'] =& $contribution;
     }
     // CRM-13737 - am not aware of any reason why payment_date would not be set - this if is a belt & braces
     $objects['contribution']->receive_date = !empty($input['payment_date']) ? date('YmdHis', strtotime($input['payment_date'])) : $now;
     $this->single($input, $ids, $objects, TRUE, $first);
 }
 /**
  * Process the form
  *
  * @return void
  * @access public
  */
 public function postProcess()
 {
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     if (array_key_exists('payment_processor', $params)) {
         if (array_key_exists(CRM_Core_DAO::getFieldValue('CRM_Core_DAO_PaymentProcessor', 'AuthNet', 'id', 'payment_processor_type'), CRM_Utils_Array::value('payment_processor', $params))) {
             CRM_Core_Session::setStatus(ts(' Please note that the Authorize.net payment processor only allows recurring contributions and auto-renew memberships with payment intervals from 7-365 days or 1-12 months (i.e. not greater than 1 year).'));
         }
     }
     // check for price set.
     $priceSetID = CRM_Utils_Array::value('price_set_id', $params);
     // get required fields.
     $fields = array('id' => $this->_id, 'is_recur' => FALSE, 'min_amount' => "null", 'max_amount' => "null", 'is_monetary' => FALSE, 'is_pay_later' => FALSE, 'is_recur_interval' => FALSE, 'recur_frequency_unit' => "null", 'default_amount_id' => "null", 'is_allow_other_amount' => FALSE, 'amount_block_is_active' => FALSE);
     $resetFields = array();
     if ($priceSetID) {
         $resetFields = array('min_amount', 'max_amount', 'is_allow_other_amount');
     }
     if (!CRM_Utils_Array::value('is_recur', $params)) {
         $resetFields = array_merge($resetFields, array('is_recur_interval', 'recur_frequency_unit'));
     }
     foreach ($fields as $field => $defaultVal) {
         $val = CRM_Utils_Array::value($field, $params, $defaultVal);
         if (in_array($field, $resetFields)) {
             $val = $defaultVal;
         }
         if (in_array($field, array('min_amount', 'max_amount'))) {
             $val = CRM_Utils_Rule::cleanMoney($val);
         }
         $params[$field] = $val;
     }
     if ($params['is_recur']) {
         $params['recur_frequency_unit'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($params['recur_frequency_unit']));
         $params['is_recur_interval'] = CRM_Utils_Array::value('is_recur_interval', $params, FALSE);
     }
     if (array_key_exists('payment_processor', $params) && !CRM_Utils_System::isNull($params['payment_processor'])) {
         $params['payment_processor'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($params['payment_processor']));
     } else {
         $params['payment_processor'] = 'null';
     }
     $contributionPage = CRM_Contribute_BAO_ContributionPage::create($params);
     $contributionPageID = $contributionPage->id;
     // prepare for data cleanup.
     $deleteAmountBlk = $deletePledgeBlk = $deletePriceSet = FALSE;
     if ($this->_priceSetID) {
         $deletePriceSet = TRUE;
     }
     if ($this->_pledgeBlockID) {
         $deletePledgeBlk = TRUE;
     }
     if (!empty($this->_amountBlock)) {
         $deleteAmountBlk = TRUE;
     }
     if ($contributionPageID) {
         if (CRM_Utils_Array::value('amount_block_is_active', $params)) {
             // handle price set.
             if ($priceSetID) {
                 // add/update price set.
                 $deletePriceSet = FALSE;
                 if (CRM_Utils_Array::value('price_field_id', $params) || CRM_Utils_Array::value('price_field_other', $params)) {
                     $deleteAmountBlk = TRUE;
                 }
                 CRM_Price_BAO_Set::addTo('civicrm_contribution_page', $contributionPageID, $priceSetID);
             } else {
                 $deletePriceSet = FALSE;
                 // process contribution amount block
                 $deleteAmountBlk = FALSE;
                 $labels = CRM_Utils_Array::value('label', $params);
                 $values = CRM_Utils_Array::value('value', $params);
                 $default = CRM_Utils_Array::value('default', $params);
                 $options = array();
                 for ($i = 1; $i < self::NUM_OPTION; $i++) {
                     if (isset($values[$i]) && strlen(trim($values[$i])) > 0) {
                         $options[] = array('label' => trim($labels[$i]), 'value' => CRM_Utils_Rule::cleanMoney(trim($values[$i])), 'weight' => $i, 'is_active' => 1, 'is_default' => $default == $i);
                     }
                 }
                 /* || CRM_Utils_Array::value( 'price_field_value', $params )|| CRM_Utils_Array::value( 'price_field_other', $params )*/
                 if (!empty($options) || CRM_Utils_Array::value('is_allow_other_amount', $params)) {
                     $fieldParams['is_quick_config'] = 1;
                     $noContriAmount = NULL;
                     $usedPriceSetId = CRM_Price_BAO_Set::getFor('civicrm_contribution_page', $this->_id, 3);
                     if (!(CRM_Utils_Array::value('price_field_id', $params) || CRM_Utils_Array::value('price_field_other', $params)) && !$usedPriceSetId) {
                         $pageTitle = strtolower(CRM_Utils_String::munge($this->_values['title'], '_', 245));
                         $setParams['title'] = $this->_values['title'];
                         if (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_Set', $pageTitle, 'id', 'name')) {
                             $setParams['name'] = $pageTitle;
                         } elseif (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_Set', $pageTitle . '_' . $this->_id, 'id', 'name')) {
                             $setParams['name'] = $pageTitle . '_' . $this->_id;
                         } else {
                             $timeSec = explode(".", microtime(true));
                             $setParams['name'] = $pageTitle . '_' . date('is', $timeSec[0]) . $timeSec[1];
                         }
                         $setParams['is_quick_config'] = 1;
                         $setParams['extends'] = CRM_Core_Component::getComponentID('CiviContribute');
                         $priceSet = CRM_Price_BAO_Set::create($setParams);
                         $priceSetId = $priceSet->id;
                     } elseif ($usedPriceSetId && !CRM_Utils_Array::value('price_field_id', $params)) {
                         $priceSetId = $usedPriceSetId;
                     } else {
                         if ($priceFieldId = CRM_Utils_Array::value('price_field_id', $params)) {
                             foreach ($params['price_field_value'] as $arrayID => $fieldValueID) {
                                 if (empty($params['label'][$arrayID]) && empty($params['value'][$arrayID]) && !empty($fieldValueID)) {
                                     CRM_Price_BAO_FieldValue::setIsActive($fieldValueID, '0');
                                     unset($params['price_field_value'][$arrayID]);
                                 }
                             }
                             if (implode('', $params['price_field_value'])) {
                                 $fieldParams['id'] = CRM_Utils_Array::value('price_field_id', $params);
                                 $fieldParams['option_id'] = $params['price_field_value'];
                             } else {
                                 $noContriAmount = 0;
                                 CRM_Price_BAO_Field::setIsActive($priceFieldId, '0');
                             }
                         } else {
                             $priceFieldId = CRM_Utils_Array::value('price_field_other', $params);
                         }
                         $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Field', $priceFieldId, 'price_set_id');
                     }
                     CRM_Price_BAO_Set::addTo('civicrm_contribution_page', $this->_id, $priceSetId);
                     if (!empty($options)) {
                         $editedFieldParams = array('price_set_id' => $priceSetId, 'name' => 'contribution_amount');
                         $editedResults = array();
                         $noContriAmount = 1;
                         CRM_Price_BAO_Field::retrieve($editedFieldParams, $editedResults);
                         if (!CRM_Utils_Array::value('id', $editedResults)) {
                             $fieldParams['name'] = strtolower(CRM_Utils_String::munge("Contribution Amount", '_', 245));
                             $fieldParams['label'] = "Contribution Amount";
                         } else {
                             $fieldParams['id'] = CRM_Utils_Array::value('id', $editedResults);
                         }
                         $fieldParams['price_set_id'] = $priceSetId;
                         $fieldParams['is_active'] = 1;
                         $fieldParams['weight'] = 2;
                         if (CRM_Utils_Array::value('is_allow_other_amount', $params)) {
                             $fieldParams['is_required'] = 0;
                         } else {
                             $fieldParams['is_required'] = 1;
                         }
                         $fieldParams['html_type'] = 'Radio';
                         $fieldParams['option_label'] = $params['label'];
                         $fieldParams['option_amount'] = $params['value'];
                         foreach ($options as $value) {
                             $fieldParams['option_weight'][$value['weight']] = $value['weight'];
                         }
                         $fieldParams['default_option'] = $params['default'];
                         $priceField = CRM_Price_BAO_Field::create($fieldParams);
                     }
                     if (CRM_Utils_Array::value('is_allow_other_amount', $params) && !CRM_Utils_Array::value('price_field_other', $params)) {
                         $editedFieldParams = array('price_set_id' => $priceSetId, 'name' => 'other_amount');
                         $editedResults = array();
                         CRM_Price_BAO_Field::retrieve($editedFieldParams, $editedResults);
                         if (!($priceFieldID = CRM_Utils_Array::value('id', $editedResults))) {
                             $fieldParams = array('name' => 'other_amount', 'label' => 'Other Amount', 'price_set_id' => $priceSetId, 'html_type' => 'Text', 'is_display_amounts' => 0, 'weight' => 3);
                             $fieldParams['option_weight'][1] = 1;
                             $fieldParams['option_amount'][1] = 1;
                             if (!$noContriAmount) {
                                 $fieldParams['is_required'] = 1;
                                 $fieldParams['option_label'][1] = 'Contribution Amount';
                             } else {
                                 $fieldParams['is_required'] = 0;
                                 $fieldParams['option_label'][1] = 'Other Amount';
                             }
                             $priceField = CRM_Price_BAO_Field::create($fieldParams);
                         } else {
                             if (!CRM_Utils_Array::value('is_active', $editedResults)) {
                                 CRM_Price_BAO_Field::setIsActive($priceFieldID, '1');
                             }
                         }
                     } elseif (!CRM_Utils_Array::value('is_allow_other_amount', $params) && CRM_Utils_Array::value('price_field_other', $params)) {
                         CRM_Price_BAO_Field::setIsActive($params['price_field_other'], '0');
                     } elseif ($priceFieldID = CRM_Utils_Array::value('price_field_other', $params)) {
                         $priceFieldValueID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_FieldValue', $priceFieldID, 'id', 'price_field_id');
                         if (!$noContriAmount) {
                             CRM_Core_DAO::setFieldValue('CRM_Price_DAO_Field', $priceFieldID, 'is_required', 1);
                             CRM_Core_DAO::setFieldValue('CRM_Price_DAO_FieldValue', $priceFieldValueID, 'label', 'Contribution Amount');
                         } else {
                             CRM_Core_DAO::setFieldValue('CRM_Price_DAO_Field', $priceFieldID, 'is_required', 0);
                             CRM_Core_DAO::setFieldValue('CRM_Price_DAO_FieldValue', $priceFieldValueID, 'label', 'Other Amount');
                         }
                     }
                 }
                 if (CRM_Utils_Array::value('is_pledge_active', $params)) {
                     $deletePledgeBlk = FALSE;
                     $pledgeBlockParams = array('entity_id' => $contributionPageID, 'entity_table' => ts('civicrm_contribution_page'));
                     if ($this->_pledgeBlockID) {
                         $pledgeBlockParams['id'] = $this->_pledgeBlockID;
                     }
                     $pledgeBlock = array('pledge_frequency_unit', 'max_reminders', 'initial_reminder_day', 'additional_reminder_day');
                     foreach ($pledgeBlock as $key) {
                         $pledgeBlockParams[$key] = CRM_Utils_Array::value($key, $params);
                     }
                     $pledgeBlockParams['is_pledge_interval'] = CRM_Utils_Array::value('is_pledge_interval', $params, FALSE);
                     // create pledge block.
                     CRM_Pledge_BAO_PledgeBlock::create($pledgeBlockParams);
                 }
             }
         } else {
             if (CRM_Utils_Array::value('price_field_id', $params) || CRM_Utils_Array::value('price_field_other', $params)) {
                 $usedPriceSetId = CRM_Price_BAO_Set::getFor('civicrm_contribution_page', $this->_id, 3);
                 if ($usedPriceSetId) {
                     if (CRM_Utils_Array::value('price_field_id', $params)) {
                         CRM_Price_BAO_Field::setIsActive($params['price_field_id'], '0');
                     }
                     if (CRM_Utils_Array::value('price_field_other', $params)) {
                         CRM_Price_BAO_Field::setIsActive($params['price_field_other'], '0');
                     }
                 } else {
                     $deleteAmountBlk = TRUE;
                     $deletePriceSet = TRUE;
                 }
             }
         }
         // delete pledge block.
         if ($deletePledgeBlk) {
             CRM_Pledge_BAO_PledgeBlock::deletePledgeBlock($this->_pledgeBlockID);
         }
         // delete previous price set.
         if ($deletePriceSet) {
             CRM_Price_BAO_Set::removeFrom('civicrm_contribution_page', $contributionPageID);
         }
         if ($deleteAmountBlk) {
             $priceField = CRM_Utils_Array::value('price_field_id', $params) ? $params['price_field_id'] : CRM_Utils_Array::value('price_field_other', $params);
             if ($priceField) {
                 $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Field', $priceField, 'price_set_id');
                 CRM_Price_BAO_Set::setIsQuickConfig($priceSetID, 0);
             }
         }
     }
     parent::endPostProcess();
 }