/**
  * This function is the main function that is called when the page loads, it decides the which action has to be taken for the page.
  *
  * return null
  * @access public
  */
 function run()
 {
     $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
     $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
     $this->assign('action', $this->_action);
     $this->assign('context', $this->_context);
     $this->_contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
     CRM_Pledge_Page_Tab::setContext($this);
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $this->edit();
     } else {
         $pledgeId = CRM_Utils_Request::retrieve('pledgeId', 'Positive', $this);
         $paymentDetails = CRM_Pledge_BAO_PledgePayment::getPledgePayments($pledgeId);
         $this->assign('rows', $paymentDetails);
         $this->assign('pledgeId', $pledgeId);
         $this->assign('contactId', $this->_contactId);
         // check if we can process credit card contribs
         $this->assign('newCredit', CRM_Core_Config::isEnabledBackOfficeCreditCardPayments());
         // check is the user has view/edit signer permission
         $permission = 'view';
         if (CRM_Core_Permission::check('edit pledges')) {
             $permission = 'edit';
         }
         $this->assign('permission', $permission);
     }
     return parent::run();
 }
 /**
  * This function is the main function that is called when the page loads, it decides the which action has to be taken for the page.
  *
  * return null
  * @access public
  */
 function run()
 {
     $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
     $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
     $this->assign('action', $this->_action);
     $this->assign('context', $this->_context);
     $this->_contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
     CRM_Pledge_Page_Tab::setContext();
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $this->edit();
         // set page title
         CRM_Contact_Page_View::setTitle($this->_contactId);
     } else {
         $pledgeId = CRM_Utils_Request::retrieve('pledgeId', 'Positive', $this);
         $paymentDetails = CRM_Pledge_BAO_PledgePayment::getPledgePayments($pledgeId);
         $this->assign('rows', $paymentDetails);
         $this->assign('pledgeId', $pledgeId);
         $this->assign('contactId', $this->_contactId);
         // check if we can process credit card contribs
         $processors = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, "billing_mode IN ( 1, 3 )");
         if (count($processors) > 0) {
             $this->assign('newCredit', TRUE);
         } else {
             $this->assign('newCredit', FALSE);
         }
         // check is the user has view/edit signer permission
         $permission = 'view';
         if (CRM_Core_Permission::check('edit pledges')) {
             $permission = 'edit';
         }
         $this->assign('permission', $permission);
     }
     return parent::run();
 }
Beispiel #3
0
 /**
  * Function to setDefaults according to Pledge Id
  * for batch entry pledges
  */
 public function getPledgeDefaults()
 {
     $details = array();
     if (!empty($_POST['pid'])) {
         $pledgeID = CRM_Utils_Type::escape($_POST['pid'], 'Integer');
         $details = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeID);
     }
     CRM_Utils_JSON::output($details);
 }
Beispiel #4
0
 /**
  * Function to setDefaults according to Pledge Id
  * for batch entry pledges
  */
 public function getPledgeDefaults()
 {
     $details = array();
     if (!empty($_POST['pid'])) {
         $pledgeID = CRM_Utils_Type::escape($_POST['pid'], 'Integer');
         $details = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeID);
     }
     echo json_encode($details);
     CRM_Utils_System::civiExit();
 }
 /**
  * Process the contribution
  *
  * @param $form
  * @param $params
  * @param $result
  * @param $contactID
  * @param $contributionType
  * @param bool $deductibleMode
  * @param bool $pending
  * @param bool $online
  *
  * @return CRM_Contribute_DAO_Contribution
  * @access public
  */
 static function processContribution(&$form, $params, $result, $contactID, $contributionType, $deductibleMode = TRUE, $pending = FALSE, $online = TRUE)
 {
     $transaction = new CRM_Core_Transaction();
     $className = get_class($form);
     $recurringContributionID = NULL;
     // add these values for the recurringContrib function ,CRM-10188
     $params['financial_type_id'] = $contributionType->id;
     //@todo - this is being set from the form to resolve CRM-10188 - an
     // eNotice caused by it not being set @ the front end
     // however, we then get it being over-written with null for backend contributions
     // a better fix would be to set the values in the respective forms rather than require
     // a function being shared by two forms to deal with their respective values
     // moving it to the BAO & not taking the $form as a param would make sense here.
     if (!isset($params['is_email_receipt'])) {
         $params['is_email_receipt'] = CRM_Utils_Array::value('is_email_receipt', $form->_values);
     }
     $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $contributionType, $online);
     $config = CRM_Core_Config::singleton();
     // CRM-11885
     // if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep it.
     if (isset($params['non_deductible_amount']) && !empty($params['non_deductible_amount'])) {
         $nonDeductibleAmount = $params['non_deductible_amount'];
     } else {
         //if ($contributionType->is_deductible && $deductibleMode) {
         if ($contributionType->is_deductible) {
             if ($online && isset($params['selectProduct'])) {
                 $selectProduct = CRM_Utils_Array::value('selectProduct', $params);
             }
             if (!$online && isset($params['product_name'][0])) {
                 $selectProduct = $params['product_name'][0];
             }
             // if there is a product - compare the value to the contribution amount
             if (isset($selectProduct) && $selectProduct != 'no_thanks') {
                 $productDAO = new CRM_Contribute_DAO_Product();
                 $productDAO->id = $selectProduct;
                 $productDAO->find(TRUE);
                 // product value exceeds contribution amount
                 if ($params['amount'] < $productDAO->price) {
                     $nonDeductibleAmount = $params['amount'];
                 } else {
                     $nonDeductibleAmount = $productDAO->price;
                 }
             } else {
                 $nonDeductibleAmount = '0.00';
             }
         } else {
             $nonDeductibleAmount = $params['amount'];
         }
     }
     $now = date('YmdHis');
     $receiptDate = CRM_Utils_Array::value('receipt_date', $params);
     if (!empty($form->_values['is_email_receipt'])) {
         $receiptDate = $now;
     }
     //get the contrib page id.
     $campaignId = $contributionPageId = NULL;
     if ($online) {
         $contributionPageId = $form->_id;
         $campaignId = CRM_Utils_Array::value('campaign_id', $params);
         if (!array_key_exists('campaign_id', $params)) {
             $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
         }
     } else {
         //also for offline we do support - CRM-7290
         $contributionPageId = CRM_Utils_Array::value('contribution_page_id', $params);
         $campaignId = CRM_Utils_Array::value('campaign_id', $params);
     }
     // first create the contribution record
     $contribParams = array('contact_id' => $contactID, 'financial_type_id' => $contributionType->id, 'contribution_page_id' => $contributionPageId, 'receive_date' => CRM_Utils_Array::value('receive_date', $params) ? CRM_Utils_Date::processDate($params['receive_date']) : date('YmdHis'), 'non_deductible_amount' => $nonDeductibleAmount, 'total_amount' => $params['amount'], 'amount_level' => CRM_Utils_Array::value('amount_level', $params), 'invoice_id' => $params['invoiceID'], 'currency' => $params['currencyID'], 'source' => !$online || !empty($params['source']) ? CRM_Utils_Array::value('source', $params) : CRM_Utils_Array::value('description', $params), 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0), 'cancel_reason' => CRM_Utils_Array::value('cancel_reason', $params, 0), 'cancel_date' => isset($params['cancel_date']) ? CRM_Utils_Date::format($params['cancel_date']) : NULL, 'thankyou_date' => isset($params['thankyou_date']) ? CRM_Utils_Date::format($params['thankyou_date']) : NULL, 'campaign_id' => $campaignId);
     if (!$online && isset($params['thankyou_date'])) {
         $contribParams['thankyou_date'] = $params['thankyou_date'];
     }
     if (!$online || $form->_values['is_monetary']) {
         if (empty($params['is_pay_later'])) {
             $contribParams['payment_instrument_id'] = 1;
         }
     }
     if (!$pending && $result) {
         $contribParams += array('fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['amount']), 'trxn_id' => $result['trxn_id'], 'receipt_date' => $receiptDate, 'trxn_result_code' => CRM_Utils_Array::value('trxn_result_code', $result), 'payment_processor' => CRM_Utils_Array::value('payment_processor', $result));
     }
     if ($recurringContributionID) {
         $contribParams['contribution_recur_id'] = $recurringContributionID;
     }
     $contribParams['contribution_status_id'] = $pending ? 2 : 1;
     $contribParams['is_test'] = 0;
     if ($form->_mode == 'test') {
         $contribParams['is_test'] = 1;
     }
     $ids = array();
     if (isset($contribParams['invoice_id'])) {
         $contribID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contribParams['invoice_id'], 'id', 'invoice_id');
         if (isset($contribID)) {
             $ids['contribution'] = $contribID;
             $contribParams['id'] = $contribID;
         }
     }
     //create an contribution address
     if ($form->_contributeMode != 'notify' && empty($params['is_pay_later']) && !empty($form->_values['is_monetary'])) {
         $contribParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $form->_bltID);
     }
     // CRM-4038: for non-en_US locales, CRM_Contribute_BAO_Contribution::add() expects localised amounts
     $contribParams['non_deductible_amount'] = trim(CRM_Utils_Money::format($contribParams['non_deductible_amount'], ' '));
     $contribParams['total_amount'] = trim(CRM_Utils_Money::format($contribParams['total_amount'], ' '));
     // Prepare soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
     if (!empty($params['pcp_made_through_id']) || !empty($params['soft_credit_to'])) {
         // if its due to pcp
         if (!empty($params['pcp_made_through_id'])) {
             $contribSoftContactId = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $params['pcp_made_through_id'], 'contact_id');
         } else {
             $contribSoftContactId = CRM_Utils_Array::value('soft_credit_to', $params);
         }
         // Pass these details onto with the contribution to make them
         // available at hook_post_process, CRM-8908
         $contribParams['soft_credit_to'] = $params['soft_credit_to'] = $contribSoftContactId;
     }
     if (isset($params['amount'])) {
         $contribParams['line_item'] = $form->_lineItem;
         //add contribution record
         $contribution = CRM_Contribute_BAO_Contribution::add($contribParams, $ids);
         if (is_a($contribution, 'CRM_Core_Error')) {
             $message = CRM_Core_Error::getMessages($contribution);
             CRM_Core_Error::fatal($message);
         }
         // lets store it in the form variable so postProcess hook can get to this and use it
         $form->_contributionID = $contribution->id;
     }
     //CRM-13981, processing honor contact into soft-credit contribution
     CRM_Contact_Form_ProfileContact::postProcess($form);
     // process soft credit / pcp pages
     CRM_Contribute_Form_Contribution_Confirm::processPcpSoft($params, $contribution);
     //handle pledge stuff.
     if (empty($form->_params['separate_membership_payment']) && !empty($form->_values['pledge_block_id']) && (!empty($form->_params['is_pledge']) || !empty($form->_values['pledge_id']))) {
         if (!empty($form->_values['pledge_id'])) {
             //when user doing pledge payments.
             //update the schedule when payment(s) are made
             foreach ($form->_params['pledge_amount'] as $paymentId => $dontCare) {
                 $scheduledAmount = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $paymentId, 'scheduled_amount', 'id');
                 $pledgePaymentParams = array('id' => $paymentId, 'contribution_id' => $contribution->id, 'status_id' => $contribution->contribution_status_id, 'actual_amount' => $scheduledAmount);
                 CRM_Pledge_BAO_PledgePayment::add($pledgePaymentParams);
             }
             //update pledge status according to the new payment statuses
             CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($form->_values['pledge_id']);
         } else {
             //when user creating pledge record.
             $pledgeParams = array();
             $pledgeParams['contact_id'] = $contribution->contact_id;
             $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount;
             $pledgeParams['contribution_id'] = $contribution->id;
             $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id;
             $pledgeParams['financial_type_id'] = $contribution->financial_type_id;
             $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
             $pledgeParams['installments'] = $params['pledge_installments'];
             $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
             if ($pledgeParams['frequency_unit'] == 'month') {
                 $pledgeParams['frequency_day'] = intval(date("d"));
             } else {
                 $pledgeParams['frequency_day'] = 1;
             }
             $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
             $pledgeParams['status_id'] = $contribution->contribution_status_id;
             $pledgeParams['max_reminders'] = $form->_values['max_reminders'];
             $pledgeParams['initial_reminder_day'] = $form->_values['initial_reminder_day'];
             $pledgeParams['additional_reminder_day'] = $form->_values['additional_reminder_day'];
             $pledgeParams['is_test'] = $contribution->is_test;
             $pledgeParams['acknowledge_date'] = date('Ymd');
             $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount'];
             //inherit campaign from contirb page.
             $pledgeParams['campaign_id'] = $campaignId;
             $pledge = CRM_Pledge_BAO_Pledge::create($pledgeParams);
             $form->_params['pledge_id'] = $pledge->id;
             //send acknowledgment email. only when pledge is created
             if ($pledge->id) {
                 //build params to send acknowledgment.
                 $pledgeParams['id'] = $pledge->id;
                 $pledgeParams['receipt_from_name'] = $form->_values['receipt_from_name'];
                 $pledgeParams['receipt_from_email'] = $form->_values['receipt_from_email'];
                 //scheduled amount will be same as installment_amount.
                 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
                 //get total pledge amount.
                 $pledgeParams['total_pledge_amount'] = $pledge->amount;
                 CRM_Pledge_BAO_Pledge::sendAcknowledgment($form, $pledgeParams);
             }
         }
     }
     if ($online && $contribution) {
         CRM_Core_BAO_CustomValueTable::postProcess($form->_params, CRM_Core_DAO::$_nullArray, 'civicrm_contribution', $contribution->id, 'Contribution');
     } elseif ($contribution) {
         //handle custom data.
         $params['contribution_id'] = $contribution->id;
         if (!empty($params['custom']) && is_array($params['custom']) && !is_a($contribution, 'CRM_Core_Error')) {
             CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
         }
     }
     // Save note
     if ($contribution && !empty($params['contribution_note'])) {
         $noteParams = array('entity_table' => 'civicrm_contribution', 'note' => $params['contribution_note'], 'entity_id' => $contribution->id, 'contact_id' => $contribution->contact_id, 'modified_date' => date('Ymd'));
         CRM_Core_BAO_Note::add($noteParams, array());
     }
     if (isset($params['related_contact'])) {
         $contactID = $params['related_contact'];
     } elseif (isset($params['cms_contactID'])) {
         $contactID = $params['cms_contactID'];
     }
     //create contribution activity w/ individual and target
     //activity w/ organisation contact id when onbelf, CRM-4027
     $targetContactID = NULL;
     if (!empty($params['hidden_onbehalf_profile'])) {
         $targetContactID = $contribution->contact_id;
         $contribution->contact_id = $contactID;
     }
     // create an activity record
     if ($contribution) {
         CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
     }
     $transaction->commit();
     // CRM-13074 - create the CMSUser after the transaction is completed as it
     // is not appropriate to delete a valid contribution if a user create problem occurs
     CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params, $contactID, 'email-' . $form->_bltID);
     return $contribution;
 }
Beispiel #6
0
 /**
  * Process pledge payments.
  *
  * @param array $formatted
  *
  * @return int
  */
 public function processPledgePayments(&$formatted)
 {
     if (!empty($formatted['pledge_payment_id']) && !empty($formatted['pledge_id'])) {
         //get completed status
         $completeStatusID = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
         //need to update payment record to map contribution_id
         CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $formatted['pledge_payment_id'], 'contribution_id', $formatted['contribution_id']);
         CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($formatted['pledge_id'], array($formatted['pledge_payment_id']), $completeStatusID, NULL, $formatted['total_amount']);
         return CRM_Contribute_Import_Parser::PLEDGE_PAYMENT;
     }
 }
Beispiel #7
0
 /**
  * Process the form submission.
  *
  *
  * @return void
  */
 public function postProcess()
 {
     //get the submitted form values.
     $formValues = $this->controller->exportValues($this->_name);
     $params = array();
     $formValues['scheduled_date'] = CRM_Utils_Date::processDate($formValues['scheduled_date']);
     $params['scheduled_date'] = CRM_Utils_Date::format($formValues['scheduled_date']);
     $params['currency'] = CRM_Utils_Array::value('currency', $formValues);
     $now = date('Ymd');
     $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     if (CRM_Utils_Date::overdue(CRM_Utils_Date::customFormat($params['scheduled_date'], '%Y%m%d'), $now)) {
         $params['status_id'] = array_search('Overdue', $contributionStatus);
     } else {
         $params['status_id'] = array_search('Pending', $contributionStatus);
     }
     $params['id'] = $this->_id;
     $pledgeId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $params['id'], 'pledge_id');
     CRM_Pledge_BAO_PledgePayment::add($params);
     $adjustTotalAmount = FALSE;
     if (CRM_Utils_Array::value('option_type', $formValues) == 2) {
         $adjustTotalAmount = TRUE;
     }
     $pledgeScheduledAmount = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $params['id'], 'scheduled_amount', 'id');
     $oldestPaymentAmount = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId, 2);
     if ($oldestPaymentAmount['count'] != 1 && $oldestPaymentAmount['id'] == $params['id']) {
         $oldestPaymentAmount = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
     }
     if ($formValues['scheduled_amount'] - $pledgeScheduledAmount >= $oldestPaymentAmount['amount']) {
         $adjustTotalAmount = TRUE;
     }
     //update pledge status
     CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, array($params['id']), $params['status_id'], NULL, $formValues['scheduled_amount'], $adjustTotalAmount);
     $statusMsg = ts('Pledge Payment Schedule has been updated.');
     CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
 }
Beispiel #8
0
 /**
  * Update related pledge payment payments.
  *
  * This function has been refactored out of the back office contribution form and may
  * still overlap with other functions.
  *
  * @param string $action
  * @param int $pledgePaymentID
  * @param int $contributionID
  * @param bool $adjustTotalAmount
  * @param float $total_amount
  * @param float $original_total_amount
  * @param int $contribution_status_id
  * @param int $original_contribution_status_id
  */
 public static function updateRelatedPledge($action, $pledgePaymentID, $contributionID, $adjustTotalAmount, $total_amount, $original_total_amount, $contribution_status_id, $original_contribution_status_id)
 {
     if (!$pledgePaymentID || $action & CRM_Core_Action::ADD && !$contributionID) {
         return;
     }
     if ($pledgePaymentID) {
         //store contribution id in payment record.
         CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentID, 'contribution_id', $contributionID);
     } else {
         $pledgePaymentID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $contributionID, 'id', 'contribution_id');
     }
     $pledgeID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $contributionID, 'pledge_id', 'contribution_id');
     $updatePledgePaymentStatus = FALSE;
     // If either the status or the amount has changed we update the pledge status.
     if ($action & CRM_Core_Action::ADD) {
         $updatePledgePaymentStatus = TRUE;
     } elseif ($action & CRM_Core_Action::UPDATE && ($original_contribution_status_id != $contribution_status_id || $original_total_amount != $total_amount)) {
         $updatePledgePaymentStatus = TRUE;
     }
     if ($updatePledgePaymentStatus) {
         CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, array($pledgePaymentID), $contribution_status_id, NULL, $total_amount, $adjustTotalAmount);
     }
 }
Beispiel #9
0
 public function updatePledgeStatus($sendReminders = FALSE)
 {
     // *** Uncomment the next line if you want automated reminders to be sent
     // $sendReminders = true;
     require_once 'CRM/Contribute/PseudoConstant.php';
     $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     //unset statues that we never use for pledges
     foreach (array('Completed', 'Cancelled', 'Failed') as $statusKey) {
         if ($key = CRM_Utils_Array::key($statusKey, $allStatus)) {
             unset($allStatus[$key]);
         }
     }
     $statusIds = implode(',', array_keys($allStatus));
     $updateCnt = 0;
     $query = "\nSELECT  pledge.contact_id              as contact_id,\n        pledge.id                      as pledge_id,\n        pledge.amount                  as amount,\n        payment.scheduled_date         as scheduled_date,\n        pledge.create_date             as create_date,\n        payment.id                     as payment_id,\n        pledge.contribution_page_id    as contribution_page_id,\n        payment.reminder_count         as reminder_count,\n        pledge.max_reminders           as max_reminders,\n        payment.reminder_date          as reminder_date,\n        pledge.initial_reminder_day    as initial_reminder_day,\n        pledge.additional_reminder_day as additional_reminder_day,\n        pledge.status_id               as pledge_status,\n        payment.status_id              as payment_status,\n        pledge.is_test                 as is_test,\n        pledge.campaign_id             as campaign_id,\n        SUM(payment.scheduled_amount)  as amount_due,\n        ( SELECT sum(civicrm_pledge_payment.actual_amount)\n        FROM civicrm_pledge_payment\n        WHERE civicrm_pledge_payment.status_id = 1\n        AND  civicrm_pledge_payment.pledge_id = pledge.id\n        ) as amount_paid\n        FROM      civicrm_pledge pledge, civicrm_pledge_payment payment\n        WHERE     pledge.id = payment.pledge_id\n        AND     payment.status_id IN ( {$statusIds} ) AND pledge.status_id IN ( {$statusIds} )\n        GROUP By  payment.id\n        ";
     $dao = CRM_Core_DAO::executeQuery($query);
     require_once 'CRM/Contact/BAO/Contact/Utils.php';
     require_once 'CRM/Utils/Date.php';
     $now = date('Ymd');
     $pledgeDetails = $contactIds = $pledgePayments = $pledgeStatus = array();
     while ($dao->fetch()) {
         $checksumValue = CRM_Contact_BAO_Contact_Utils::generateChecksum($dao->contact_id);
         $pledgeDetails[$dao->payment_id] = array('scheduled_date' => $dao->scheduled_date, 'amount_due' => $dao->amount_due, 'amount' => $dao->amount, 'amount_paid' => $dao->amount_paid, 'create_date' => $dao->create_date, 'contact_id' => $dao->contact_id, 'pledge_id' => $dao->pledge_id, 'checksumValue' => $checksumValue, 'contribution_page_id' => $dao->contribution_page_id, 'reminder_count' => $dao->reminder_count, 'max_reminders' => $dao->max_reminders, 'reminder_date' => $dao->reminder_date, 'initial_reminder_day' => $dao->initial_reminder_day, 'additional_reminder_day' => $dao->additional_reminder_day, 'pledge_status' => $dao->pledge_status, 'payment_status' => $dao->payment_status, 'is_test' => $dao->is_test, 'campaign_id' => $dao->campaign_id);
         $contactIds[$dao->contact_id] = $dao->contact_id;
         $pledgeStatus[$dao->pledge_id] = $dao->pledge_status;
         if (CRM_Utils_Date::overdue(CRM_Utils_Date::customFormat($dao->scheduled_date, '%Y%m%d'), $now) && $dao->payment_status != array_search('Overdue', $allStatus)) {
             $pledgePayments[$dao->pledge_id][$dao->payment_id] = $dao->payment_id;
         }
     }
     require_once 'CRM/Pledge/BAO/PledgePayment.php';
     // process the updating script...
     foreach ($pledgePayments as $pledgeId => $paymentIds) {
         // 1. update the pledge /pledge payment status. returns new status when an update happens
         echo "<br />Checking if status update is needed for Pledge Id: {$pledgeId} (current status is {$allStatus[$pledgeStatus[$pledgeId]]})";
         $newStatus = CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIds, array_search('Overdue', $allStatus), NULL, 0, FALSE, TRUE);
         if ($newStatus != $pledgeStatus[$pledgeId]) {
             echo "<br />- status updated to: {$allStatus[$newStatus]}";
             $updateCnt += 1;
         }
     }
     if ($sendReminders) {
         // retrieve domain tokens
         require_once 'CRM/Core/BAO/Domain.php';
         require_once 'CRM/Core/SelectValues.php';
         $domain = CRM_Core_BAO_Domain::getDomain();
         $tokens = array('domain' => array('name', 'phone', 'address', 'email'), 'contact' => CRM_Core_SelectValues::contactTokens());
         require_once 'CRM/Utils/Token.php';
         $domainValues = array();
         foreach ($tokens['domain'] as $token) {
             $domainValues[$token] = CRM_Utils_Token::getDomainTokenReplacement($token, $domain);
         }
         //get the domain email address, since we don't carry w/ object.
         require_once 'CRM/Core/BAO/Domain.php';
         $domainValue = CRM_Core_BAO_Domain::getNameAndEmail();
         $domainValues['email'] = $domainValue[1];
         // retrieve contact tokens
         // this function does NOT return Deceased contacts since we don't want to send them email
         require_once 'CRM/Utils/Token.php';
         list($contactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, NULL, FALSE, FALSE, NULL, $tokens, 'CRM_UpdatePledgeRecord');
         // assign domain values to template
         $template = CRM_Core_Smarty::singleton();
         $template->assign('domain', $domainValues);
         //set receipt from
         $receiptFrom = '"' . $domainValues['name'] . '" <' . $domainValues['email'] . '>';
         foreach ($pledgeDetails as $paymentId => $details) {
             if (array_key_exists($details['contact_id'], $contactDetails)) {
                 $contactId = $details['contact_id'];
                 $pledgerName = $contactDetails[$contactId]['display_name'];
             } else {
                 continue;
             }
             if (empty($details['reminder_date'])) {
                 $nextReminderDate = new DateTime($details['scheduled_date']);
                 $nextReminderDate->modify("-" . $details['initial_reminder_day'] . "day");
                 $nextReminderDate = $nextReminderDate->format("Ymd");
             } else {
                 $nextReminderDate = new DateTime($details['reminder_date']);
                 $nextReminderDate->modify("+" . $details['additional_reminder_day'] . "day");
                 $nextReminderDate = $nextReminderDate->format("Ymd");
             }
             if ($details['reminder_count'] < $details['max_reminders'] && $nextReminderDate <= $now) {
                 $toEmail = $doNotEmail = $onHold = NULL;
                 if (!empty($contactDetails[$contactId]['email'])) {
                     $toEmail = $contactDetails[$contactId]['email'];
                 }
                 if (!empty($contactDetails[$contactId]['do_not_email'])) {
                     $doNotEmail = $contactDetails[$contactId]['do_not_email'];
                 }
                 if (!empty($contactDetails[$contactId]['on_hold'])) {
                     $onHold = $contactDetails[$contactId]['on_hold'];
                 }
                 // 2. send acknowledgement mail
                 if ($toEmail && !($doNotEmail || $onHold)) {
                     //assign value to template
                     $template->assign('amount_paid', $details['amount_paid'] ? $details['amount_paid'] : 0);
                     $template->assign('contact', $contactDetails[$contactId]);
                     $template->assign('next_payment', $details['scheduled_date']);
                     $template->assign('amount_due', $details['amount_due']);
                     $template->assign('checksumValue', $details['checksumValue']);
                     $template->assign('contribution_page_id', $details['contribution_page_id']);
                     $template->assign('pledge_id', $details['pledge_id']);
                     $template->assign('scheduled_payment_date', $details['scheduled_date']);
                     $template->assign('amount', $details['amount']);
                     $template->assign('create_date', $details['create_date']);
                     require_once 'CRM/Core/BAO/MessageTemplate.php';
                     list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_pledge', 'valueName' => 'pledge_reminder', 'contactId' => $contactId, 'from' => $receiptFrom, 'toName' => $pledgerName, 'toEmail' => $toEmail));
                     // 3. update pledge payment details
                     if ($mailSent) {
                         CRM_Pledge_BAO_PledgePayment::updateReminderDetails($paymentId);
                         $activityType = 'Pledge Reminder';
                         $activityParams = array('subject' => $subject, 'source_contact_id' => $contactId, 'source_record_id' => $paymentId, 'assignee_contact_id' => $contactId, 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', $activityType, 'name'), 'activity_date_time' => CRM_Utils_Date::isoToMysql($now), 'due_date_time' => CRM_Utils_Date::isoToMysql($details['scheduled_date']), 'is_test' => $details['is_test'], 'status_id' => 2, 'campaign_id' => $details['campaign_id']);
                         if (is_a(civicrm_api('activity', 'create', $activityParams), 'CRM_Core_Error')) {
                             CRM_Core_Error::fatal("Failed creating Activity for acknowledgment");
                         }
                         echo "<br />Payment reminder sent to: {$pledgerName} - {$toEmail}";
                     }
                 }
             }
         }
         // end foreach on $pledgeDetails
     }
     // end if ( $sendReminders )
     echo "<br />{$updateCnt} records updated.";
 }
 public function preProcessPledge()
 {
     //get the payment values associated with given pledge payment id OR check for payments due.
     $this->_pledgeValues = array();
     if ($this->_ppID) {
         $payParams = array('id' => $this->_ppID);
         CRM_Pledge_BAO_PledgePayment::retrieve($payParams, $this->_pledgeValues['pledgePayment']);
         $this->_pledgeID = CRM_Utils_Array::value('pledge_id', $this->_pledgeValues['pledgePayment']);
         $paymentStatusID = CRM_Utils_Array::value('status_id', $this->_pledgeValues['pledgePayment']);
         $this->_id = CRM_Utils_Array::value('contribution_id', $this->_pledgeValues['pledgePayment']);
         //get all status
         $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
         if (!($paymentStatusID == array_search('Pending', $allStatus) || $paymentStatusID == array_search('Overdue', $allStatus))) {
             CRM_Core_Error::fatal(ts("Pledge payment status should be 'Pending' or  'Overdue'."));
         }
         //get the pledge values associated with given pledge payment.
         $ids = array();
         $pledgeParams = array('id' => $this->_pledgeID);
         CRM_Pledge_BAO_Pledge::getValues($pledgeParams, $this->_pledgeValues, $ids);
         $this->assign('ppID', $this->_ppID);
     } else {
         // Not making a pledge payment, so if adding a new contribution we should check if pledge payment(s) are due for this contact so we can alert the user. CRM-5206
         if (isset($this->_contactID)) {
             $contactPledges = CRM_Pledge_BAO_Pledge::getContactPledges($this->_contactID);
             if (!empty($contactPledges)) {
                 $payments = $paymentsDue = NULL;
                 $multipleDue = FALSE;
                 foreach ($contactPledges as $key => $pledgeId) {
                     $payments = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
                     if ($payments) {
                         if ($paymentsDue) {
                             $multipleDue = TRUE;
                             break;
                         } else {
                             $paymentsDue = $payments;
                         }
                     }
                 }
                 if ($multipleDue) {
                     // Show link to pledge tab since more than one pledge has a payment due
                     $pledgeTab = CRM_Utils_System::url('civicrm/contact/view', "reset=1&force=1&cid={$this->_contactID}&selectedChild=pledge");
                     CRM_Core_Session::setStatus(ts('This contact has pending or overdue pledge payments. <a href="%1">Click here to view their Pledges tab</a> and verify whether this contribution should be applied as a pledge payment.', array(1 => $pledgeTab)), ts('Notice'), 'alert');
                 } elseif ($paymentsDue) {
                     // Show user link to oldest Pending or Overdue pledge payment
                     $ppAmountDue = CRM_Utils_Money::format($payments['amount'], $payments['currency']);
                     $ppSchedDate = CRM_Utils_Date::customFormat(CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $payments['id'], 'scheduled_date'));
                     if ($this->_mode) {
                         $ppUrl = CRM_Utils_System::url('civicrm/contact/view/contribution', "reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge&mode=live");
                     } else {
                         $ppUrl = CRM_Utils_System::url('civicrm/contact/view/contribution', "reset=1&action=add&cid={$this->_contactID}&ppid={$payments['id']}&context=pledge");
                     }
                     CRM_Core_Session::setStatus(ts('This contact has a pending or overdue pledge payment of %2 which is scheduled for %3. <a href="%1">Click here to enter a pledge payment</a>.', array(1 => $ppUrl, 2 => $ppAmountDue, 3 => $ppSchedDate)), ts('Notice'), 'alert');
                 }
             }
         }
     }
 }
 /**
  * Function to process the form
  *
  * @access public
  *
  * @return None
  */
 public function postProcess()
 {
     $session = CRM_Core_Session::singleton();
     if ($this->_action & CRM_Core_Action::DELETE) {
         CRM_Contribute_BAO_Contribution::deleteContribution($this->_id);
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=contribute"));
         return;
     }
     // get the submitted form values.
     $submittedValues = $this->controller->exportValues($this->_name);
     if (CRM_Utils_Array::value('price_set_id', $submittedValues) && $this->_action & CRM_Core_Action::UPDATE) {
         $line = CRM_Price_BAO_LineItem::getLineItems($this->_id, 'contribution');
         $lineID = key($line);
         $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Field', CRM_Utils_Array::value('price_field_id', $line[$lineID]), 'price_set_id');
         $quickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', $priceSetId, 'is_quick_config');
         if ($quickConfig) {
             CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_contribution');
         }
     }
     // process price set and get total amount and line items.
     $lineItem = array();
     $priceSetId = $pId = NULL;
     $priceSetId = CRM_Utils_Array::value('price_set_id', $submittedValues);
     if (empty($priceSetId) && !$this->_id) {
         $this->_priceSetId = $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', 'default_contribution_amount', 'id', 'name');
         $this->_priceSet = current(CRM_Price_BAO_Set::getSetDetail($priceSetId));
         $fieldID = key($this->_priceSet['fields']);
         $fieldValueId = key($this->_priceSet['fields'][$fieldID]['options']);
         $this->_priceSet['fields'][$fieldID]['options'][$fieldValueId]['amount'] = $submittedValues['total_amount'];
         $submittedValues['price_' . $fieldID] = 1;
     }
     if ($priceSetId) {
         CRM_Price_BAO_Set::processAmount($this->_priceSet['fields'], $submittedValues, $lineItem[$priceSetId]);
         $submittedValues['total_amount'] = CRM_Utils_Array::value('amount', $submittedValues);
     }
     if (!$priceSetId && CRM_Utils_Array::value('total_amount', $submittedValues) && $this->_id) {
         // 10117 update th line items for participants
         $pId = $this->_compId && $this->_context == 'participant' ? $this->_compId : CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'participant_id', 'contribution_id');
         //CRM-10964
         if ($pId) {
             $entityTable = 'participant';
             $entityID = $pId;
             $participantParams = array('fee_amount' => $submittedValues['total_amount'], 'id' => $entityID);
             CRM_Event_BAO_Participant::add($participantParams);
             if (empty($this->_lineItems)) {
                 $this->_lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, 'participant', 1);
             }
         } else {
             $entityTable = 'contribution';
             $entityID = $this->_id;
         }
         $lineItems = CRM_Price_BAO_LineItem::getLineItems($entityID, $entityTable);
         $itemId = key($lineItems);
         $fieldType = NULL;
         if ($itemId && CRM_Utils_Array::value('price_field_id', $lineItems[$itemId])) {
             $fieldType = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Field', $lineItems[$itemId]['price_field_id'], 'html_type');
         }
         $lineItems[$itemId]['unit_price'] = $lineItems[$itemId]['line_total'] = CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value('total_amount', $submittedValues));
         $lineItems[$itemId]['id'] = $itemId;
         // 10117 update th line items for participants
         $this->_priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Field', $lineItems[$itemId]['price_field_id'], 'price_set_id');
         $lineItem[$this->_priceSetId] = $lineItems;
     }
     $isQuickConfig = 0;
     if ($this->_priceSetId && CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', $this->_priceSetId, 'is_quick_config')) {
         $isQuickConfig = 1;
     }
     if (!CRM_Utils_Array::value('total_amount', $submittedValues)) {
         $submittedValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_values);
     }
     $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
     if (CRM_Utils_Array::value('soft_credit_to', $submittedValues)) {
         $submittedValues['soft_credit_to'] = $submittedValues['soft_contact_id'];
     }
     // set the contact, when contact is selected
     if (CRM_Utils_Array::value('contact_select_id', $submittedValues)) {
         $this->_contactID = $submittedValues['contact_select_id'][1];
     }
     $config = CRM_Core_Config::singleton();
     //Credit Card Contribution.
     if ($this->_mode) {
         $unsetParams = array('trxn_id', 'payment_instrument_id', 'contribution_status_id', 'cancel_date', 'cancel_reason');
         foreach ($unsetParams as $key) {
             if (isset($submittedValues[$key])) {
                 unset($submittedValues[$key]);
             }
         }
         //Get the rquire fields value only.
         $params = $this->_params = $submittedValues;
         $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode);
         //get the payment processor id as per mode.
         $params['payment_processor_id'] = $this->_params['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor['id'];
         $now = date('YmdHis');
         $fields = array();
         // we need to retrieve email address
         if ($this->_context == 'standalone' && CRM_Utils_Array::value('is_email_receipt', $submittedValues)) {
             list($this->userDisplayName, $this->userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
             $this->assign('displayName', $this->userDisplayName);
         }
         //set email for primary location.
         $fields['email-Primary'] = 1;
         $params['email-Primary'] = $this->userEmail;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
         $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $params)) {
                 $params[$name] = $params["billing_{$name}"];
                 $params['preserveDBName'] = TRUE;
             }
         }
         if (CRM_Utils_Array::value('source', $params)) {
             unset($params['source']);
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactID, NULL, NULL, $ctype);
         // add all the additioanl payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         if ($this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_CREDIT_CARD) {
             $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
             $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
         }
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $this->_params['total_amount'];
         $this->_params['amount_level'] = 0;
         $this->_params['currencyID'] = CRM_Utils_Array::value('currency', $this->_params, $config->defaultCurrency);
         $this->_params['payment_action'] = 'Sale';
         if (CRM_Utils_Array::value('receive_date', $this->_params)) {
             $this->_params['receive_date'] = CRM_Utils_Date::processDate($this->_params['receive_date'], $this->_params['receive_date_time']);
         }
         if (CRM_Utils_Array::value('soft_credit_to', $params)) {
             $this->_params['soft_credit_to'] = $params['soft_credit_to'];
             $this->_params['pcp_made_through_id'] = $params['pcp_made_through_id'];
         }
         $this->_params['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $params);
         $this->_params['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $params);
         $this->_params['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $params);
         //Add common data to formatted params
         CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params);
         if (empty($this->_params['invoice_id'])) {
             $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
         } else {
             $this->_params['invoiceID'] = $this->_params['invoice_id'];
         }
         // at this point we've created a contact and stored its address etc
         // all the payment processors expect the name and address to be in the
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         $paymentParams['contactID'] = $this->_contactID;
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
         $contributionType = new CRM_Contribute_DAO_ContributionType();
         $contributionType->id = $params['contribution_type_id'];
         if (!$contributionType->find(TRUE)) {
             CRM_Core_Error::fatal('Could not find a system table');
         }
         // add some contribution type details to the params list
         // if folks need to use it
         $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $contributionType->name;
         $paymentParams['contributionType_accounting_code'] = $this->_params['contributionType_accounting_code'] = $contributionType->accounting_code;
         $paymentParams['contributionPageID'] = NULL;
         if (CRM_Utils_Array::value('is_email_receipt', $this->_params)) {
             $paymentParams['email'] = $this->userEmail;
             $paymentParams['is_email_receipt'] = 1;
         } else {
             $paymentParams['is_email_receipt'] = 0;
             $this->_params['is_email_receipt'] = 0;
         }
         if (CRM_Utils_Array::value('receive_date', $this->_params)) {
             $paymentParams['receive_date'] = $this->_params['receive_date'];
         }
         if (CRM_Utils_Array::value('receive_date', $this->_params)) {
             $paymentParams['receive_date'] = $this->_params['receive_date'];
         }
         $result = NULL;
         // For recurring contribution, create Contribution Record first.
         // Contribution ID, Recurring ID and Contact ID needed
         // When we get a callback from the payment processor, CRM-7115
         if (CRM_Utils_Array::value('is_recur', $paymentParams)) {
             $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $this->_params, $result, $this->_contactID, $contributionType, FALSE, TRUE, FALSE);
             $paymentParams['contributionID'] = $contribution->id;
             $paymentParams['contributionTypeID'] = $contribution->contribution_type_id;
             $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
             $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
         }
         if ($paymentParams['amount'] > 0.0) {
             // force a reget of the payment processor in case the form changed it, CRM-7179
             $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this, TRUE);
             $result = $payment->doDirectPayment($paymentParams);
         }
         if (is_a($result, 'CRM_Core_Error')) {
             //make sure to cleanup db for recurring case.
             if (CRM_Utils_Array::value('contributionID', $paymentParams)) {
                 CRM_Core_Error::debug_log_message(CRM_Core_Error::getMessages($result) . "contact id={$this->_contactID} (deleting contribution {$paymentParams['contributionID']}");
                 CRM_Contribute_BAO_Contribution::deleteContribution($paymentParams['contributionID']);
             }
             if (CRM_Utils_Array::value('contributionRecurID', $paymentParams)) {
                 CRM_Core_Error::debug_log_message(CRM_Core_Error::getMessages($result) . "contact id={$this->_contactID} (deleting recurring contribution {$paymentParams['contributionRecurID']}");
                 CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
             }
             //set the contribution mode.
             $urlParams = "action=add&cid={$this->_contactID}";
             if ($this->_mode) {
                 $urlParams .= "&mode={$this->_mode}";
             }
             if (!empty($this->_ppID)) {
                 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
             }
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/contribution', $urlParams));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $this->_params['receive_date'] = $now;
         if (CRM_Utils_Array::value('is_email_receipt', $this->_params)) {
             $this->_params['receipt_date'] = $now;
         } else {
             $this->_params['receipt_date'] = CRM_Utils_Date::processDate($this->_params['receipt_date'], $params['receipt_date_time'], TRUE);
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
         $this->assign('receive_date', $this->_params['receive_date']);
         // result has all the stuff we need
         // lets archive it to a financial transaction
         if ($contributionType->is_deductible) {
             $this->assign('is_deductible', TRUE);
             $this->set('is_deductible', TRUE);
         }
         // set source if not set
         if (empty($this->_params['source'])) {
             $userID = $session->get('userID');
             $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID, 'sort_name');
             $this->_params['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
         }
         // build custom data getFields array
         $customFieldsContributionType = CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE, CRM_Utils_Array::value('contribution_type_id', $params));
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsContributionType, CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE, NULL, NULL, TRUE));
         $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_id, 'Contribution');
         if (!CRM_Utils_Array::value('is_recur', $paymentParams)) {
             $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $this->_params, $result, $this->_contactID, $contributionType, FALSE, FALSE, FALSE);
         }
         if ($this->_context != 'participant' && !$pId) {
             $entityID = $contribution->id;
             $entityTable = 'contribution';
         }
         // process line items, until no previous line items.
         if (empty($this->_lineItems) && $entityID && !empty($lineItem)) {
             CRM_Contribute_Form_AdditionalInfo::processPriceSet($entityID, $lineItem, 'civicrm_' . $entityTable);
         }
         //send receipt mail.
         if ($contribution->id && CRM_Utils_Array::value('is_email_receipt', $this->_params)) {
             $this->_params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
             $this->_params['contact_id'] = $this->_contactID;
             $this->_params['contribution_id'] = $contribution->id;
             $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $this->_params, TRUE);
         }
         //process the note
         if ($contribution->id && isset($params['note'])) {
             CRM_Contribute_Form_AdditionalInfo::processNote($params, $contactID, $contribution->id, NULL);
         }
         //process premium
         if ($contribution->id && isset($params['product_name'][0])) {
             CRM_Contribute_Form_AdditionalInfo::processPremium($params, $contribution->id, NULL, $this->_options);
         }
         //update pledge payment status.
         if ($this->_ppID && $contribution->id) {
             //store contribution id in payment record.
             CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID, 'contribution_id', $contribution->id);
             CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_pledgeID, array($this->_ppID), $contribution->contribution_status_id, NULL, $contribution->total_amount);
         }
         if ($contribution->id) {
             $statusMsg = ts('The contribution record has been processed.');
             if (CRM_Utils_Array::value('is_email_receipt', $this->_params) && $sendReceipt) {
                 $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
             }
             CRM_Core_Session::setStatus($statusMsg);
         }
         //submit credit card contribution ends.
     } else {
         //Offline Contribution.
         $unsetParams = array('payment_processor_id', "email-{$this->_bltID}", 'hidden_buildCreditCard', 'hidden_buildDirectDebit', 'billing_first_name', 'billing_middle_name', 'billing_last_name', 'street_address-5', "city-{$this->_bltID}", "state_province_id-{$this->_bltID}", "postal_code-{$this->_bltID}", "country_id-{$this->_bltID}", 'credit_card_number', 'cvv2', 'credit_card_exp_date', 'credit_card_type');
         foreach ($unsetParams as $key) {
             if (isset($submittedValues[$key])) {
                 unset($submittedValues[$key]);
             }
         }
         // get the required field value only.
         $formValues = $submittedValues;
         $params = $ids = array();
         $params['contact_id'] = $this->_contactID;
         // get current currency from DB or use default currency
         $currentCurrency = CRM_Utils_Array::value('currency', $this->_values, $config->defaultCurrency);
         // use submitted currency if present else use current currency
         $params['currency'] = CRM_Utils_Array::value('currency', $submittedValues, $currentCurrency);
         $fields = array('contribution_type_id', 'contribution_status_id', 'payment_instrument_id', 'cancel_reason', 'source', 'check_number', 'soft_credit_to', 'pcp_made_through_id', 'pcp_display_in_roll', 'pcp_roll_nickname', 'pcp_personal_note');
         foreach ($fields as $f) {
             $params[$f] = CRM_Utils_Array::value($f, $formValues);
         }
         if ($softID = CRM_Utils_Array::value('softID', $this->_values)) {
             $params['softID'] = $softID;
         }
         //if priceset is used, no need to cleanup money
         //CRM-5740
         if ($priceSetId) {
             $params['skipCleanMoney'] = 1;
         }
         $dates = array('receive_date', 'receipt_date', 'cancel_date');
         foreach ($dates as $d) {
             $params[$d] = CRM_Utils_Date::processDate($formValues[$d], $formValues[$d . '_time'], TRUE);
         }
         if (CRM_Utils_Array::value('is_email_receipt', $formValues)) {
             $params['receipt_date'] = date("Y-m-d");
         }
         if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Cancelled', 'name')) {
             if (CRM_Utils_System::isNull(CRM_Utils_Array::value('cancel_date', $params))) {
                 $params['cancel_date'] = date("Y-m-d");
             }
         } else {
             $params['cancel_date'] = $params['cancel_reason'] = 'null';
         }
         // Set is_pay_later flag for back-office offline Pending status contributions CRM-8996
         if ($params['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
             $params['is_pay_later'] = 1;
         }
         $ids['contribution'] = $params['id'] = $this->_id;
         //Add Additional common information  to formatted params
         CRM_Contribute_Form_AdditionalInfo::postProcessCommon($formValues, $params);
         //create contribution.
         $contribution = CRM_Contribute_BAO_Contribution::create($params, $ids);
         // 10117 update th line items for participants
         if ($this->_context != 'participant' && !$pId) {
             $entityID = $contribution->id;
             $entityTable = 'contribution';
         }
         // process line items, until no previous line items.
         if (empty($this->_lineItems) && $entityID && !empty($lineItem)) {
             CRM_Contribute_Form_AdditionalInfo::processPriceSet($entityID, $lineItem, 'civicrm_' . $entityTable);
         }
         // process associated membership / participant, CRM-4395
         $relatedComponentStatusMsg = NULL;
         if ($contribution->id && $this->_action & CRM_Core_Action::UPDATE) {
             $relatedComponentStatusMsg = $this->updateRelatedComponent($contribution->id, $contribution->contribution_status_id, CRM_Utils_Array::value('contribution_status_id', $this->_values));
         }
         //process  note
         if ($contribution->id && isset($formValues['note'])) {
             CRM_Contribute_Form_AdditionalInfo::processNote($formValues, $this->_contactID, $contribution->id, $this->_noteID);
         }
         //process premium
         if ($contribution->id && isset($formValues['product_name'][0])) {
             CRM_Contribute_Form_AdditionalInfo::processPremium($formValues, $contribution->id, $this->_premiumID, $this->_options);
         }
         //send receipt mail.
         if ($contribution->id && CRM_Utils_Array::value('is_email_receipt', $formValues)) {
             $formValues['contact_id'] = $this->_contactID;
             $formValues['contribution_id'] = $contribution->id;
             // to get 'from email id' for send receipt
             $this->fromEmailId = $formValues['from_email_address'];
             $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $formValues);
         }
         $pledgePaymentId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $contribution->id, 'id', 'contribution_id');
         //update pledge payment status.
         if ($this->_ppID && $contribution->id && $this->_action & CRM_Core_Action::ADD || $pledgePaymentId && $this->_action & CRM_Core_Action::UPDATE) {
             if ($this->_ppID) {
                 //store contribution id in payment record.
                 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID, 'contribution_id', $contribution->id);
             } else {
                 $this->_ppID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $contribution->id, 'id', 'contribution_id');
                 $this->_pledgeID = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $contribution->id, 'pledge_id', 'contribution_id');
             }
             $adjustTotalAmount = FALSE;
             if (CRM_Utils_Array::value('option_type', $formValues) == 2) {
                 $adjustTotalAmount = TRUE;
             }
             CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_pledgeID, array($this->_ppID), $contribution->contribution_status_id, NULL, $contribution->total_amount, $adjustTotalAmount);
         }
         $statusMsg = ts('The contribution record has been saved.');
         if (CRM_Utils_Array::value('is_email_receipt', $formValues) && $sendReceipt) {
             $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
         }
         if ($relatedComponentStatusMsg) {
             $statusMsg .= ' ' . $relatedComponentStatusMsg;
         }
         CRM_Core_Session::setStatus($statusMsg, FALSE);
         //Offline Contribution ends.
     }
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contribute/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=contribute"));
         }
     } elseif ($this->_context == 'contribution' && $this->_mode && $buttonName == $this->getButtonName('upload', 'new')) {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution', "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}&mode={$this->_mode}"));
     } elseif ($buttonName == $this->getButtonName('upload', 'new')) {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/contribution', "reset=1&action=add&context={$this->_context}&cid={$this->_contactID}"));
     }
 }
 /**
  *  Test calculateNextScheduledDate - no date provided
  */
 function testcalculateNextScheduledDateYearDateProvided()
 {
     $params = array('scheduled_date' => '20110510', 'frequency_unit' => 'year', 'frequency_day' => 15, 'frequency_interval' => 2);
     $date = CRM_Pledge_BAO_PledgePayment::calculateNextScheduledDate($params, 3, '20080510');
     $this->assertEquals('20140510000000', $date);
 }
 function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = false)
 {
     if ($loadAll) {
         $ids = array_merge($this->getComponentDetails($this->id), $ids);
         if (empty($ids['contact']) && isset($this->contact_id)) {
             $ids['contact'] = $this->contact_id;
         }
     }
     if (empty($this->_component)) {
         if (!empty($ids['event'])) {
             $this->_component = 'event';
         } else {
             $this->_component = strtolower(CRM_Utils_Array::value('component', $input, 'contribute'));
         }
     }
     $paymentProcessorID = CRM_Utils_Array::value('paymentProcessor', $ids);
     $contributionType = new CRM_Financial_BAO_FinancialType();
     $contributionType->id = $this->financial_type_id;
     if (!$contributionType->find(TRUE)) {
         throw new Exception("Could not find financial type record: " . $this->financial_type_id);
     }
     if (!empty($ids['contact'])) {
         $this->_relatedObjects['contact'] = new CRM_Contact_BAO_Contact();
         $this->_relatedObjects['contact']->id = $ids['contact'];
         $this->_relatedObjects['contact']->find(TRUE);
     }
     $this->_relatedObjects['contributionType'] = $contributionType;
     if ($this->_component == 'contribute') {
         // retrieve the other optional objects first so
         // stuff down the line can use this info and do things
         // CRM-6056
         //in any case get the memberships associated with the contribution
         //because we now support multiple memberships w/ price set
         // see if there are any other memberships to be considered for same contribution.
         $query = "\n            SELECT membership_id\n            FROM   civicrm_membership_payment\nWHERE  contribution_id = %1 ";
         $params = array(1 => array($this->id, 'Integer'));
         $dao = CRM_Core_DAO::executeQuery($query, $params);
         while ($dao->fetch()) {
             if ($dao->membership_id) {
                 if (!is_array($ids['membership'])) {
                     $ids['membership'] = array();
                 }
                 $ids['membership'][] = $dao->membership_id;
             }
         }
         if (array_key_exists('membership', $ids) && is_array($ids['membership'])) {
             foreach ($ids['membership'] as $id) {
                 if (!empty($id)) {
                     $membership = new CRM_Member_BAO_Membership();
                     $membership->id = $id;
                     if (!$membership->find(TRUE)) {
                         throw new Exception("Could not find membership record: {$id}");
                     }
                     $membership->join_date = CRM_Utils_Date::isoToMysql($membership->join_date);
                     $membership->start_date = CRM_Utils_Date::isoToMysql($membership->start_date);
                     $membership->end_date = CRM_Utils_Date::isoToMysql($membership->end_date);
                     $this->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
                     $membership->free();
                 }
             }
         }
         if (!empty($ids['pledge_payment'])) {
             foreach ($ids['pledge_payment'] as $key => $paymentID) {
                 if (empty($paymentID)) {
                     continue;
                 }
                 $payment = new CRM_Pledge_BAO_PledgePayment();
                 $payment->id = $paymentID;
                 if (!$payment->find(TRUE)) {
                     throw new Exception("Could not find pledge payment record: " . $paymentID);
                 }
                 $this->_relatedObjects['pledge_payment'][] = $payment;
             }
         }
         if (!empty($ids['contributionRecur'])) {
             $recur = new CRM_Contribute_BAO_ContributionRecur();
             $recur->id = $ids['contributionRecur'];
             if (!$recur->find(TRUE)) {
                 throw new Exception("Could not find recur record: " . $ids['contributionRecur']);
             }
             $this->_relatedObjects['contributionRecur'] =& $recur;
             //get payment processor id from recur object.
             $paymentProcessorID = $recur->payment_processor_id;
         }
         //for normal contribution get the payment processor id.
         if (!$paymentProcessorID) {
             if ($this->contribution_page_id) {
                 // get the payment processor id from contribution page
                 $paymentProcessorID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $this->contribution_page_id, 'payment_processor');
             } elseif (!CRM_Utils_Array::value('pledge_payment', $ids)) {
                 $loadObjectSuccess = TRUE;
                 if ($required) {
                     throw new Exception("Could not find contribution page for contribution record: " . $this->id);
                 }
                 return $loadObjectSuccess;
             }
         }
     } else {
         // we are in event mode
         // make sure event exists and is valid
         $event = new CRM_Event_BAO_Event();
         $event->id = $ids['event'];
         if ($ids['event'] && !$event->find(TRUE)) {
             throw new Exception("Could not find event: " . $ids['event']);
         }
         $this->_relatedObjects['event'] =& $event;
         $participant = new CRM_Event_BAO_Participant();
         $participant->id = $ids['participant'];
         if ($ids['participant'] && !$participant->find(TRUE)) {
             throw new Exception("Could not find participant: " . $ids['participant']);
         }
         $participant->register_date = CRM_Utils_Date::isoToMysql($participant->register_date);
         $this->_relatedObjects['participant'] =& $participant;
         if (!$paymentProcessorID) {
             $paymentProcessorID = $this->_relatedObjects['event']->payment_processor;
         }
     }
     $loadObjectSuccess = TRUE;
     if ($paymentProcessorID) {
         $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($paymentProcessorID, $this->is_test ? 'test' : 'live');
         $ids['paymentProcessor'] = $paymentProcessorID;
         $this->_relatedObjects['paymentProcessor'] =& $paymentProcessor;
     } elseif ($required) {
         $loadObjectSuccess = FALSE;
         throw new Exception("Could not find payment processor for contribution record: " . $this->id);
     }
     return $loadObjectSuccess;
 }
Beispiel #14
0
 /**
  * Process the contribution.
  *
  * @param CRM_Core_Form $form
  * @param array $params
  * @param array $result
  * @param int $contactID
  * @param CRM_Financial_DAO_FinancialType $financialType
  * @param bool $pending
  * @param bool $online
  *
  * @param bool $isTest
  * @param array $lineItems
  *
  * @param int $billingLocationID
  *   ID of billing location type.
  *
  * @return \CRM_Contribute_DAO_Contribution
  * @throws \Exception
  */
 public static function processFormContribution(&$form, $params, $result, $contactID, $financialType, $pending, $online, $isTest, $lineItems, $billingLocationID)
 {
     $transaction = new CRM_Core_Transaction();
     $contribSoftContactId = $addressID = NULL;
     $contributeMode = $form->_contributeMode;
     $isMonetary = !empty($form->_values['is_monetary']);
     $isEmailReceipt = !empty($form->_values['is_email_receipt']);
     // How do these vary from params? These are currently passed to
     // - custom data function....
     $formParams = $form->_params;
     $isSeparateMembershipPayment = empty($formParams['separate_membership_payment']) ? FALSE : TRUE;
     $pledgeID = empty($formParams['pledge_id']) ? NULL : $formParams['pledge_id'];
     if (!$isSeparateMembershipPayment && !empty($form->_values['pledge_block_id']) && (!empty($formParams['is_pledge']) || $pledgeID)) {
         $isPledge = TRUE;
     } else {
         $isPledge = FALSE;
     }
     // add these values for the recurringContrib function ,CRM-10188
     $params['financial_type_id'] = $financialType->id;
     //create an contribution address
     if ($contributeMode != 'notify' && empty($params['is_pay_later']) && $isMonetary) {
         $addressID = CRM_Contribute_BAO_Contribution::createAddress($params, $billingLocationID);
     }
     //@todo - this is being set from the form to resolve CRM-10188 - an
     // eNotice caused by it not being set @ the front end
     // however, we then get it being over-written with null for backend contributions
     // a better fix would be to set the values in the respective forms rather than require
     // a function being shared by two forms to deal with their respective values
     // moving it to the BAO & not taking the $form as a param would make sense here.
     if (!isset($params['is_email_receipt']) && $isEmailReceipt) {
         $params['is_email_receipt'] = $isEmailReceipt;
     }
     $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $financialType, $online);
     $nonDeductibleAmount = self::getNonDeductibleAmount($params, $financialType, $online);
     $now = date('YmdHis');
     $receiptDate = CRM_Utils_Array::value('receipt_date', $params);
     if ($isEmailReceipt) {
         $receiptDate = $now;
     }
     //get the contrib page id.
     $contributionPageId = NULL;
     if ($online) {
         $contributionPageId = $form->_id;
         $campaignId = CRM_Utils_Array::value('campaign_id', $params);
         if (!array_key_exists('campaign_id', $params)) {
             $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
         }
     } else {
         //also for offline we do support - CRM-7290
         $contributionPageId = CRM_Utils_Array::value('contribution_page_id', $params);
         $campaignId = CRM_Utils_Array::value('campaign_id', $params);
     }
     // Prepare soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
     if (!empty($params['pcp_made_through_id']) || !empty($params['soft_credit_to'])) {
         // if its due to pcp
         if (!empty($params['pcp_made_through_id'])) {
             $contribSoftContactId = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $params['pcp_made_through_id'], 'contact_id');
         } else {
             $contribSoftContactId = CRM_Utils_Array::value('soft_credit_to', $params);
         }
         // Pass these details onto with the contribution to make them
         // available at hook_post_process, CRM-8908
         $params['soft_credit_to'] = $contribSoftContactId;
     }
     if (isset($params['amount'])) {
         $contribParams = self::getContributionParams($params, $contactID, $financialType->id, $online, $contributionPageId, $nonDeductibleAmount, $campaignId, $isMonetary, $pending, $result, $receiptDate, $recurringContributionID, $isTest, $addressID, $contribSoftContactId, $lineItems);
         $contribution = CRM_Contribute_BAO_Contribution::add($contribParams);
         $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
         $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
         if ($invoicing) {
             $dataArray = array();
             foreach ($form->_lineItem as $lineItemKey => $lineItemValue) {
                 foreach ($lineItemValue as $key => $value) {
                     if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
                         if (isset($dataArray[$value['tax_rate']])) {
                             $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
                         } else {
                             $dataArray[$value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
                         }
                     }
                 }
             }
             $smarty = CRM_Core_Smarty::singleton();
             $smarty->assign('dataArray', $dataArray);
             $smarty->assign('totalTaxAmount', $params['tax_amount']);
         }
         if (is_a($contribution, 'CRM_Core_Error')) {
             $message = CRM_Core_Error::getMessages($contribution);
             CRM_Core_Error::fatal($message);
         }
         // lets store it in the form variable so postProcess hook can get to this and use it
         $form->_contributionID = $contribution->id;
     }
     //CRM-13981, processing honor contact into soft-credit contribution
     CRM_Contact_Form_ProfileContact::postProcess($form);
     // process soft credit / pcp pages
     CRM_Contribute_Form_Contribution_Confirm::processPcpSoft($params, $contribution);
     //handle pledge stuff.
     if ($isPledge) {
         if ($pledgeID) {
             //when user doing pledge payments.
             //update the schedule when payment(s) are made
             foreach ($form->_params['pledge_amount'] as $paymentId => $dontCare) {
                 $scheduledAmount = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $paymentId, 'scheduled_amount', 'id');
                 $pledgePaymentParams = array('id' => $paymentId, 'contribution_id' => $contribution->id, 'status_id' => $contribution->contribution_status_id, 'actual_amount' => $scheduledAmount);
                 CRM_Pledge_BAO_PledgePayment::add($pledgePaymentParams);
             }
             //update pledge status according to the new payment statuses
             CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID);
         } else {
             //when user creating pledge record.
             $pledgeParams = array();
             $pledgeParams['contact_id'] = $contribution->contact_id;
             $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount;
             $pledgeParams['contribution_id'] = $contribution->id;
             $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id;
             $pledgeParams['financial_type_id'] = $contribution->financial_type_id;
             $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
             $pledgeParams['installments'] = $params['pledge_installments'];
             $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
             if ($pledgeParams['frequency_unit'] == 'month') {
                 $pledgeParams['frequency_day'] = intval(date("d"));
             } else {
                 $pledgeParams['frequency_day'] = 1;
             }
             $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
             $pledgeParams['status_id'] = $contribution->contribution_status_id;
             $pledgeParams['max_reminders'] = $form->_values['max_reminders'];
             $pledgeParams['initial_reminder_day'] = $form->_values['initial_reminder_day'];
             $pledgeParams['additional_reminder_day'] = $form->_values['additional_reminder_day'];
             $pledgeParams['is_test'] = $contribution->is_test;
             $pledgeParams['acknowledge_date'] = date('Ymd');
             $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount'];
             //inherit campaign from contirb page.
             $pledgeParams['campaign_id'] = $campaignId;
             $pledge = CRM_Pledge_BAO_Pledge::create($pledgeParams);
             $form->_params['pledge_id'] = $pledge->id;
             //send acknowledgment email. only when pledge is created
             if ($pledge->id) {
                 //build params to send acknowledgment.
                 $pledgeParams['id'] = $pledge->id;
                 $pledgeParams['receipt_from_name'] = $form->_values['receipt_from_name'];
                 $pledgeParams['receipt_from_email'] = $form->_values['receipt_from_email'];
                 //scheduled amount will be same as installment_amount.
                 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
                 //get total pledge amount.
                 $pledgeParams['total_pledge_amount'] = $pledge->amount;
                 CRM_Pledge_BAO_Pledge::sendAcknowledgment($form, $pledgeParams);
             }
         }
     }
     if ($online && $contribution) {
         CRM_Core_BAO_CustomValueTable::postProcess($form->_params, 'civicrm_contribution', $contribution->id, 'Contribution');
     } elseif ($contribution) {
         //handle custom data.
         $params['contribution_id'] = $contribution->id;
         if (!empty($params['custom']) && is_array($params['custom']) && !is_a($contribution, 'CRM_Core_Error')) {
             CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
         }
     }
     // Save note
     if ($contribution && !empty($params['contribution_note'])) {
         $noteParams = array('entity_table' => 'civicrm_contribution', 'note' => $params['contribution_note'], 'entity_id' => $contribution->id, 'contact_id' => $contribution->contact_id, 'modified_date' => date('Ymd'));
         CRM_Core_BAO_Note::add($noteParams, array());
     }
     if (isset($params['related_contact'])) {
         $contactID = $params['related_contact'];
     } elseif (isset($params['cms_contactID'])) {
         $contactID = $params['cms_contactID'];
     }
     //create contribution activity w/ individual and target
     //activity w/ organisation contact id when onbelf, CRM-4027
     $targetContactID = NULL;
     if (!empty($params['hidden_onbehalf_profile'])) {
         $targetContactID = $contribution->contact_id;
         $contribution->contact_id = $contactID;
     }
     // create an activity record
     if ($contribution) {
         CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
     }
     $transaction->commit();
     // CRM-13074 - create the CMSUser after the transaction is completed as it
     // is not appropriate to delete a valid contribution if a user create problem occurs
     CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params, $contactID, 'email-' . $billingLocationID);
     return $contribution;
 }
Beispiel #15
0
 /**
  * Function used to build form element for soft credit block.
  *
  * @param CRM_Core_Form $form
  *
  * @return void
  */
 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::formatMultilingualHonorParams($ufJoinDAO->module_data, TRUE);
             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']);
         }
     }
     // CRM-7368 allow user to set or edit PCP link for contributions
     $siteHasPCPs = CRM_Contribute_PseudoConstant::pcPage();
     if (!CRM_Utils_Array::crmIsEmptyArray($siteHasPCPs)) {
         $form->assign('siteHasPCPs', 1);
         // Fixme: Not a true entityRef field. Relies on PCP.js.tpl
         $form->add('text', 'pcp_made_through_id', ts('Credit to a Personal Campaign Page'), array('class' => 'twenty', 'placeholder' => ts('- select -')));
         // stores the label
         $form->add('hidden', 'pcp_made_through');
         $form->addElement('checkbox', 'pcp_display_in_roll', ts('Display in Honor Roll?'), NULL);
         $form->addElement('text', 'pcp_roll_nickname', ts('Name (for Honor Roll)'));
         $form->addElement('textarea', 'pcp_personal_note', ts('Personal Note (for Honor Roll)'));
     }
     $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'));
 }
Beispiel #16
0
 /**
  * Mark a pledge (and any outstanding payments) as cancelled.
  *
  * @param int $pledgeID
  */
 public static function cancel($pledgeID)
 {
     $paymentIDs = self::findCancelablePayments($pledgeID);
     $status = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     $cancelled = array_search('Cancelled', $status);
     CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $paymentIDs, NULL, $cancelled, 0, FALSE, TRUE);
 }
/**
 * Add or update a plege payment
 *
 * @param  array   $params           (reference ) input parameters
 *
 * @return array (reference )        pledge_id of created or updated record
 * @static void
 * @access public
 */
function &civicrm_pledge_payment_create(&$params)
{
    _civicrm_initialize();
    //GAP - update doesn't recalculate payment dates on existing payment schedule  - not the sure the code is in Civi to leverage
    if (empty($params)) {
        return civicrm_create_error(ts('No input parameters present'));
    }
    if (!is_array($params)) {
        return civicrm_create_error(ts('Input parameters is not an array'));
    }
    $error = _civicrm_pledgepayment_check_params($params);
    if (civicrm_error($error)) {
        return $error;
    }
    $values = array();
    require_once 'CRM/Pledge/BAO/PledgePayment.php';
    $error = _civicrm_pledgepayment_format_params($params, $values);
    if (civicrm_error($error)) {
        return $error;
    }
    $pledge = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($params['pledge_id']);
    $params['id'] = $pledge['id'];
    //params ID needs to be pledge payment ID
    // pledge payment isn't retrieved if only one exists - the status is not set correctly causing this so let's get it for now as a cludgey make it work
    // copied from getOldestPayment function
    if (!$params['id']) {
        $query = "\nSELECT civicrm_pledge_payment.id id, civicrm_pledge_payment.scheduled_amount amount\nFROM civicrm_pledge, civicrm_pledge_payment\nWHERE civicrm_pledge.id = civicrm_pledge_payment.pledge_id\n  AND civicrm_pledge.id = %1\nLIMIT 0, 1  \n";
        $params[1] = array($params['pledge_id'], 'Integer');
        $payment = CRM_Core_DAO::executeQuery($query, $params);
        $paymentDetails = NULL;
        if ($payment->fetch()) {
            $params['id'] = $payment->id;
        }
    }
    CRM_Pledge_BAO_PledgePayment::add($params);
    //update pledge status
    CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($params['pledge_id']);
    return $errors;
}
 /**
  * Function used to build form element for soft credit block
  *
  * @param object   $form form object
  * @access public
  *
  * @return void
  */
 static function buildQuickForm(&$form)
 {
     if ($form->_mode == 'live' && !empty($form->_values['honor_block_is_active'])) {
         $ufJoinDAO = new CRM_Core_DAO_UFJoin();
         $ufJoinDAO->module = 'soft_credit';
         $ufJoinDAO->entity_id = $form->_id;
         if ($ufJoinDAO->find(TRUE)) {
             $jsonData = json_decode($ufJoinDAO->module_data);
             if ($jsonData) {
                 $form->assign('honor_block_title', $jsonData->soft_credit->honor_block_title);
                 $form->assign('honor_block_text', $jsonData->soft_credit->honor_block_text);
                 $softCreditTypes = CRM_Core_OptionGroup::values("soft_credit_type", FALSE);
                 $extraOption = array('onclick' => "enableHonorType();");
                 // radio button for Honor Type
                 foreach ($jsonData->soft_credit->soft_credit_types as $value) {
                     $honorTypes[$value] = $form->createElement('radio', NULL, NULL, $softCreditTypes[$value], $value, $extraOption);
                 }
                 $form->addGroup($honorTypes, 'soft_credit_type_id', NULL);
             }
         }
         return $form;
     }
     $prefix = 'soft_credit_';
     // by default generate 5 blocks
     $item_count = 6;
     $showSoftCreditRow = 2;
     $showCreateNew = TRUE;
     if ($form->_action & CRM_Core_Action::UPDATE) {
         $form->_softCreditInfo = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($form->_id, TRUE);
     } elseif ($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++;
             $showCreateNew = FALSE;
         }
     }
     for ($rowNumber = 1; $rowNumber <= $item_count; $rowNumber++) {
         CRM_Contact_Form_NewContact::buildQuickForm($form, $rowNumber, NULL, FALSE, $prefix);
         $form->addMoney("{$prefix}amount[{$rowNumber}]", ts('Amount'), FALSE, NULL, FALSE);
         $form->add('select', "{$prefix}type[{$rowNumber}]", ts('Soft Credit Type'), array('' => ts('- select -')) + CRM_Core_OptionGroup::values("{$prefix}type", FALSE));
         if (!empty($form->_softCreditInfo['soft_credit'][$rowNumber]['soft_credit_id'])) {
             $form->add('hidden', "{$prefix}id[{$rowNumber}]", $form->_softCreditInfo['soft_credit'][$rowNumber]['soft_credit_id']);
         }
     }
     // CRM-7368 allow user to set or edit PCP link for contributions
     $siteHasPCPs = CRM_Contribute_PseudoConstant::pcPage();
     if (!CRM_Utils_Array::crmIsEmptyArray($siteHasPCPs)) {
         $form->assign('siteHasPCPs', 1);
         $pcpDataUrl = CRM_Utils_System::url('civicrm/ajax/rest', 'className=CRM_Contact_Page_AJAX&fnName=getPCPList&json=1&context=contact&reset=1', FALSE, NULL, FALSE);
         $form->assign('pcpDataUrl', $pcpDataUrl);
         $form->addElement('text', 'pcp_made_through', ts('Credit to a Personal Campaign Page'));
         $form->addElement('hidden', 'pcp_made_through_id', '', array('id' => 'pcp_made_through_id'));
         $form->addElement('checkbox', 'pcp_display_in_roll', ts('Display in Honor Roll?'), NULL);
         $form->addElement('text', 'pcp_roll_nickname', ts('Name (for Honor Roll)'));
         $form->addElement('textarea', 'pcp_personal_note', ts('Personal Note (for Honor Roll)'));
     }
     $form->assign('showSoftCreditRow', $showSoftCreditRow);
     $form->assign('rowCount', $item_count);
     $form->assign('showCreateNew', $showCreateNew);
     $form->addElement('hidden', 'sct_default_id', CRM_Core_OptionGroup::getDefaultValue("{$prefix}type"), array('id' => 'sct_default_id'));
     // Tell tpl to hide soft credit field if contribution is linked directly to a PCP Page
     if (!empty($form->_values['pcp_made_through_id'])) {
         $form->assign('pcpLinked', 1);
     }
 }
Beispiel #19
0
 /**
  * Process contribution records.
  *
  * @param array $params
  *   Associated array of submitted values.
  *
  *
  * @return void
  */
 private function processContribution(&$params)
 {
     $dates = array('receive_date', 'receipt_date', 'thankyou_date', 'cancel_date');
     // get the price set associated with offline contribution record.
     $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
     $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
     $priceFieldID = CRM_Price_BAO_PriceSet::getOnlyPriceFieldID($this->_priceSet);
     $priceFieldValueID = CRM_Price_BAO_PriceSet::getOnlyPriceFieldValueID($this->_priceSet);
     if (isset($params['field'])) {
         foreach ($params['field'] as $key => $value) {
             // if contact is not selected we should skip the row
             if (empty($params['primary_contact_id'][$key])) {
                 continue;
             }
             $value['contact_id'] = CRM_Utils_Array::value($key, $params['primary_contact_id']);
             // update contact information
             $this->updateContactInfo($value);
             //build soft credit params
             if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
                 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
                 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
                 //CRM-15350: if soft-credit-type profile field is disabled or removed then
                 //we choose configured SCT default value
                 if (!empty($params['soft_credit_type'][$key])) {
                     $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
                 } else {
                     $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_OptionGroup::getDefaultValue("soft_credit_type");
                 }
             }
             $value['custom'] = CRM_Core_BAO_CustomField::postProcess($value, NULL, 'Contribution');
             foreach ($dates as $val) {
                 if (!empty($value[$val])) {
                     $value[$val] = CRM_Utils_Date::processDate($value[$val], $value[$val . '_time'], TRUE);
                 }
             }
             if (!empty($value['send_receipt'])) {
                 $value['receipt_date'] = date('Y-m-d His');
             }
             // these translations & date handling are required because we are calling BAO directly rather than the api
             $fieldTranslations = array('financial_type' => 'financial_type_id', 'payment_instrument' => 'payment_instrument_id', 'contribution_source' => 'source', 'contribution_note' => 'note');
             foreach ($fieldTranslations as $formField => $baoField) {
                 if (isset($value[$formField])) {
                     $value[$baoField] = $value[$formField];
                 }
                 unset($value[$formField]);
             }
             $params['actualBatchTotal'] += $value['total_amount'];
             $value['batch_id'] = $this->_batchId;
             $value['skipRecentView'] = TRUE;
             // build line item params
             $this->_priceSet['fields'][$priceFieldID]['options'][$priceFieldValueID]['amount'] = $value['total_amount'];
             $value['price_' . $priceFieldID] = 1;
             $lineItem = array();
             CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $value, $lineItem[$priceSetId]);
             //unset amount level since we always use quick config price set
             unset($value['amount_level']);
             //CRM-11529 for back office transactions
             //when financial_type_id is passed in form, update the
             //line items with the financial type selected in form
             if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
                 foreach ($lineItem[$priceSetId] as &$values) {
                     $values['financial_type_id'] = $value['financial_type_id'];
                 }
             }
             $value['line_item'] = $lineItem;
             //finally call contribution create for all the magic
             $contribution = CRM_Contribute_BAO_Contribution::create($value, CRM_Core_DAO::$_nullArray);
             $batchTypes = CRM_Core_Pseudoconstant::get('CRM_Batch_DAO_Batch', 'type_id', array('flip' => 1), 'validate');
             if (!empty($this->_batchInfo['type_id']) && $this->_batchInfo['type_id'] == $batchTypes['Pledge Payment']) {
                 $adjustTotalAmount = FALSE;
                 if (isset($params['option_type'][$key])) {
                     if ($params['option_type'][$key] == 2) {
                         $adjustTotalAmount = TRUE;
                     }
                 }
                 $pledgeId = $params['open_pledges'][$key];
                 if (is_numeric($pledgeId)) {
                     $result = CRM_Pledge_BAO_PledgePayment::getPledgePayments($pledgeId);
                     $pledgePaymentId = 0;
                     foreach ($result as $key => $values) {
                         if ($values['status'] != 'Completed') {
                             $pledgePaymentId = $values['id'];
                             break;
                         }
                     }
                     CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentId, 'contribution_id', $contribution->id);
                     CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, array($pledgePaymentId), $contribution->contribution_status_id, NULL, $contribution->total_amount, $adjustTotalAmount);
                 }
             }
             //process premiums
             if (!empty($value['product_name'])) {
                 if ($value['product_name'][0] > 0) {
                     list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
                     $value['hidden_Premium'] = 1;
                     $value['product_option'] = CRM_Utils_Array::value($value['product_name'][1], $options[$value['product_name'][0]]);
                     $premiumParams = array('product_id' => $value['product_name'][0], 'contribution_id' => $contribution->id, 'product_option' => $value['product_option'], 'quantity' => 1);
                     CRM_Contribute_BAO_Contribution::addPremium($premiumParams);
                 }
             }
             // end of premium
             //send receipt mail.
             if ($contribution->id && !empty($value['send_receipt'])) {
                 // add the domain email id
                 $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
                 $domainEmail = "{$domainEmail['0']} <{$domainEmail['1']}>";
                 $value['from_email_address'] = $domainEmail;
                 $value['contribution_id'] = $contribution->id;
                 CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $value);
             }
         }
     }
     return TRUE;
 }
Beispiel #20
0
 /**
  * @param CRM_Core_Form $form
  */
 public static function buildSearchForm(&$form)
 {
     // pledge related dates
     CRM_Core_Form_Date::buildDateRange($form, 'pledge_start_date', 1, '_low', '_high', ts('From'), FALSE);
     CRM_Core_Form_Date::buildDateRange($form, 'pledge_end_date', 1, '_low', '_high', ts('From'), FALSE);
     CRM_Core_Form_Date::buildDateRange($form, 'pledge_create_date', 1, '_low', '_high', ts('From'), FALSE);
     // pledge payment related dates
     CRM_Core_Form_Date::buildDateRange($form, 'pledge_payment_date', 1, '_low', '_high', ts('From'), FALSE);
     $form->addYesNo('pledge_test', ts('Pledge is a Test?'), TRUE);
     $form->add('text', 'pledge_amount_low', ts('From'), array('size' => 8, 'maxlength' => 8));
     $form->addRule('pledge_amount_low', ts('Please enter a valid money value (e.g. %1).', array(1 => CRM_Utils_Money::format('9.99', ' '))), 'money');
     $form->add('text', 'pledge_amount_high', ts('To'), array('size' => 8, 'maxlength' => 8));
     $form->addRule('pledge_amount_high', ts('Please enter a valid money value (e.g. %1).', array(1 => CRM_Utils_Money::format('99.99', ' '))), 'money');
     $form->add('select', 'pledge_status_id', ts('Pledge Status'), CRM_Pledge_BAO_Pledge::buildOptions('status_id'), FALSE, array('class' => 'crm-select2', 'multiple' => 'multiple'));
     $form->addYesNo('pledge_acknowledge_date_is_not_null', ts('Acknowledgement sent?'), TRUE);
     $form->add('text', 'pledge_installments_low', ts('From'), array('size' => 8, 'maxlength' => 8));
     $form->addRule('pledge_installments_low', ts('Please enter a number'), 'integer');
     $form->add('text', 'pledge_installments_high', ts('To'), array('size' => 8, 'maxlength' => 8));
     $form->addRule('pledge_installments_high', ts('Please enter number.'), 'integer');
     $form->add('select', 'pledge_payment_status_id', ts('Pledge Payment Status'), CRM_Pledge_BAO_PledgePayment::buildOptions('status_id'), FALSE, array('class' => 'crm-select2', 'multiple' => 'multiple'));
     $form->add('select', 'pledge_financial_type_id', ts('Financial Type'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::financialType(), FALSE, array('class' => 'crm-select2'));
     $form->add('select', 'pledge_contribution_page_id', ts('Contribution Page'), array('' => ts('- any -')) + CRM_Contribute_PseudoConstant::contributionPage(), FALSE, array('class' => 'crm-select2'));
     // add fields for pledge frequency
     $form->add('text', 'pledge_frequency_interval', ts('Every'), array('size' => 8, 'maxlength' => 8));
     $form->addRule('pledge_frequency_interval', ts('Please enter valid Pledge Frequency Interval'), 'integer');
     $frequencies = CRM_Core_OptionGroup::values('recur_frequency_units');
     foreach ($frequencies as $val => $label) {
         $freqUnitsDisplay["'{$val}'"] = ts('%1(s)', array(1 => $label));
     }
     $form->add('select', 'pledge_frequency_unit', ts('Pledge Frequency'), array('' => ts('- any -')) + $freqUnitsDisplay);
     // add all the custom  searchable fields
     $pledge = array('Pledge');
     $groupDetails = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, TRUE, $pledge);
     if ($groupDetails) {
         $form->assign('pledgeGroupTree', $groupDetails);
         foreach ($groupDetails as $group) {
             foreach ($group['fields'] as $field) {
                 $fieldId = $field['id'];
                 $elementName = 'custom_' . $fieldId;
                 CRM_Core_BAO_CustomField::addQuickFormElement($form, $elementName, $fieldId, FALSE, TRUE);
             }
         }
     }
     CRM_Campaign_BAO_Campaign::addCampaignInComponentSearch($form, 'pledge_campaign_id');
     $form->assign('validCiviPledge', TRUE);
     $form->setDefaults(array('pledge_test' => 0));
 }
 /**
  * Retrieve DB object based on input parameters.
  *
  * It also stores all the retrieved values in the default array.
  *
  * @param array $params
  *   (reference ) an assoc array of name/value pairs.
  * @param array $defaults
  *   (reference ) an assoc array to hold the flattened values.
  *
  * @return CRM_Pledge_BAO_PledgePayment
  */
 public static function retrieve(&$params, &$defaults)
 {
     $payment = new CRM_Pledge_BAO_PledgePayment();
     $payment->copyValues($params);
     if ($payment->find(TRUE)) {
         CRM_Core_DAO::storeValues($payment, $defaults);
         return $payment;
     }
     return NULL;
 }
Beispiel #22
0
 /**
  * Set the default values.
  */
 public function setDefaultValues()
 {
     // check if the user is registered and we have a contact ID
     $contactID = $this->getContactID();
     if (!empty($contactID)) {
         $fields = array();
         $removeCustomFieldTypes = array('Contribution', 'Membership');
         $contribFields = CRM_Contribute_BAO_Contribution::getContributionFields();
         // remove component related fields
         foreach ($this->_fields as $name => $dontCare) {
             //don't set custom data Used for Contribution (CRM-1344)
             if (substr($name, 0, 7) == 'custom_') {
                 $id = substr($name, 7);
                 if (!CRM_Core_BAO_CustomGroup::checkCustomField($id, $removeCustomFieldTypes)) {
                     continue;
                 }
                 // ignore component fields
             } elseif (array_key_exists($name, $contribFields) || substr($name, 0, 11) == 'membership_' || substr($name, 0, 13) == 'contribution_') {
                 continue;
             }
             $fields[$name] = 1;
         }
         if (!empty($fields)) {
             CRM_Core_BAO_UFGroup::setProfileDefaults($contactID, $fields, $this->_defaults);
         }
         $billingDefaults = $this->getProfileDefaults('Billing', $contactID);
         $this->_defaults = array_merge($this->_defaults, $billingDefaults);
     }
     if (!empty($this->_ccid) && !empty($this->_pendingAmount)) {
         $this->_defaults['total_amount'] = CRM_Utils_Money::format($this->_pendingAmount, NULL, '%a');
     }
     /*
      * hack to simplify credit card entry for testing
      *
      * $this->_defaults['credit_card_type']     = 'Visa';
      *         $this->_defaults['amount']               = 168;
      *         $this->_defaults['credit_card_number']   = '4111111111111111';
      *         $this->_defaults['cvv2']                 = '000';
      *         $this->_defaults['credit_card_exp_date'] = array('Y' => date('Y')+1, 'M' => '05');
      *         // hack to simplify direct debit entry for testing
      *         $this->_defaults['account_holder'] = 'Max Müller';
      *         $this->_defaults['bank_account_number'] = '12345678';
      *         $this->_defaults['bank_identification_number'] = '12030000';
      *         $this->_defaults['bank_name'] = 'Bankname';
      */
     //build set default for pledge overdue payment.
     if (!empty($this->_values['pledge_id'])) {
         //used to record completed pledge payment ids used later for honor default
         $completedContributionIds = array();
         $pledgePayments = CRM_Pledge_BAO_PledgePayment::getPledgePayments($this->_values['pledge_id']);
         $paymentAmount = 0;
         $duePayment = FALSE;
         foreach ($pledgePayments as $payId => $value) {
             if ($value['status'] == 'Overdue') {
                 $this->_defaults['pledge_amount'][$payId] = 1;
                 $paymentAmount += $value['scheduled_amount'];
             } elseif (!$duePayment && $value['status'] == 'Pending') {
                 $this->_defaults['pledge_amount'][$payId] = 1;
                 $paymentAmount += $value['scheduled_amount'];
                 $duePayment = TRUE;
             } elseif ($value['status'] == 'Completed' && $value['contribution_id']) {
                 $completedContributionIds[] = $value['contribution_id'];
             }
         }
         $this->_defaults['price_' . $this->_priceSetId] = $paymentAmount;
         if (count($completedContributionIds)) {
             $softCredit = array();
             foreach ($completedContributionIds as $id) {
                 $softCredit = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($id);
             }
             if (isset($softCredit['soft_credit'])) {
                 $this->_defaults['soft_credit_type_id'] = $softCredit['soft_credit'][1]['soft_credit_type'];
                 //since honoree profile fieldname of fields are prefixed with 'honor'
                 //we need to reformat the fieldname to append prefix during setting default values
                 CRM_Core_BAO_UFGroup::setProfileDefaults($softCredit['soft_credit'][1]['contact_id'], CRM_Core_BAO_UFGroup::getFields($this->_honoreeProfileId), $defaults);
                 foreach ($defaults as $fieldName => $value) {
                     $this->_defaults['honor[' . $fieldName . ']'] = $value;
                 }
             }
         }
     } elseif (!empty($this->_values['pledge_block_id'])) {
         //set default to one time contribution.
         $this->_defaults['is_pledge'] = 0;
     }
     // to process Custom data that are appended to URL
     $getDefaults = CRM_Core_BAO_CustomGroup::extractGetParams($this, "'Contact', 'Individual', 'Contribution'");
     $this->_defaults = array_merge($this->_defaults, $getDefaults);
     $config = CRM_Core_Config::singleton();
     // set default country from config if no country set
     if (empty($this->_defaults["billing_country_id-{$this->_bltID}"])) {
         $this->_defaults["billing_country_id-{$this->_bltID}"] = $config->defaultContactCountry;
     }
     // set default state/province from config if no state/province set
     if (empty($this->_defaults["billing_state_province_id-{$this->_bltID}"])) {
         $this->_defaults["billing_state_province_id-{$this->_bltID}"] = $config->defaultContactStateProvince;
     }
     $entityId = $memtypeID = NULL;
     if ($this->_priceSetId) {
         if ($this->_useForMember && !empty($this->_currentMemberships) || $this->_defaultMemTypeId) {
             $selectedCurrentMemTypes = array();
             foreach ($this->_priceSet['fields'] as $key => $val) {
                 foreach ($val['options'] as $keys => $values) {
                     $opMemTypeId = CRM_Utils_Array::value('membership_type_id', $values);
                     $priceFieldName = 'price_' . $values['price_field_id'];
                     $priceFieldValue = CRM_Price_BAO_PriceSet::getPriceFieldValueFromURL($this, $priceFieldName);
                     if (!empty($priceFieldValue)) {
                         CRM_Price_BAO_PriceSet::setDefaultPriceSetField($priceFieldName, $priceFieldValue, $val['html_type'], $this->_defaults);
                         // break here to prevent overwriting of default due to 'is_default'
                         // option configuration or setting of current membership or
                         // membership for related organization.
                         // The value sent via URL get's higher priority.
                         break;
                     } elseif ($opMemTypeId && in_array($opMemTypeId, $this->_currentMemberships) && !in_array($opMemTypeId, $selectedCurrentMemTypes)) {
                         CRM_Price_BAO_PriceSet::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $this->_defaults);
                         $memtypeID = $selectedCurrentMemTypes[] = $values['membership_type_id'];
                     } elseif (!empty($values['is_default']) && !$opMemTypeId && (!isset($this->_defaults[$priceFieldName]) || $val['html_type'] == 'CheckBox' && !isset($this->_defaults[$priceFieldName][$keys]))) {
                         CRM_Price_BAO_PriceSet::setDefaultPriceSetField($priceFieldName, $keys, $val['html_type'], $this->_defaults);
                         $memtypeID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceFieldValue', $this->_defaults[$priceFieldName], 'membership_type_id');
                     }
                 }
             }
             $entityId = CRM_Utils_Array::value('id', CRM_Member_BAO_Membership::getContactMembership($contactID, $memtypeID, NULL));
         } else {
             CRM_Price_BAO_PriceSet::setDefaultPriceSet($this, $this->_defaults);
         }
     }
     //set custom field defaults set by admin if value is not set
     if (!empty($this->_fields)) {
         //load default campaign from page.
         if (array_key_exists('contribution_campaign_id', $this->_fields)) {
             $this->_defaults['contribution_campaign_id'] = CRM_Utils_Array::value('campaign_id', $this->_values);
         }
         //set custom field defaults
         foreach ($this->_fields as $name => $field) {
             if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($name)) {
                 if (!isset($this->_defaults[$name])) {
                     CRM_Core_BAO_CustomField::setProfileDefaults($customFieldID, $name, $this->_defaults, $entityId, CRM_Profile_Form::MODE_REGISTER);
                 }
             }
         }
     }
     if (!empty($this->_paymentProcessors)) {
         foreach ($this->_paymentProcessors as $pid => $value) {
             if (!empty($value['is_default'])) {
                 $this->_defaults['payment_processor_id'] = $pid;
             }
         }
     }
     return $this->_defaults;
 }
Beispiel #23
0
/**
 * Delete a pledge Payment - Note this deletes the contribution not just the link.
 *
 * @param array $params
 *   Input parameters.
 *
 * @return array
 *   API result
 */
function civicrm_api3_pledge_payment_delete($params)
{
    if (CRM_Pledge_BAO_PledgePayment::del($params['id'])) {
        return civicrm_api3_create_success(array('id' => $params['id']), $params, 'PledgePayment', 'delete');
    } else {
        return civicrm_api3_create_error('Could not delete payment');
    }
}
 /**
  * This function is the main function that is called when the page loads, it decides the which action has to be taken for the page.
  *
  * return null
  * @access public
  */
 function run()
 {
     $this->preProcess();
     // check if we can process credit card registration
     $processors = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, "billing_mode IN ( 1, 3 )");
     if (count($processors) > 0) {
         $this->assign('newCredit', TRUE);
     } else {
         $this->assign('newCredit', FALSE);
     }
     $this->setContext();
     if ($this->_action & CRM_Core_Action::VIEW) {
         $this->view();
     } elseif ($this->_action & (CRM_Core_Action::UPDATE | CRM_Core_Action::ADD | CRM_Core_Action::DELETE)) {
         $this->edit();
     } elseif ($this->_action & CRM_Core_Action::DETACH) {
         CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_id, NULL, NULL, array_search('Cancelled', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')));
         $session = CRM_Core_Session::singleton();
         $session->setStatus(ts('Pledge has been Cancelled and all scheduled (not completed) payments have been cancelled.<br />'));
         CRM_Utils_System::redirect($session->popUserContext());
     } else {
         $this->browse();
     }
     return parent::run();
 }
Beispiel #25
0
 /**
  * Process the contribution.
  *
  * @param CRM_Core_Form $form
  * @param array $params
  * @param array $result
  * @param array $contributionParams
  *   Parameters to be passed to contribution create action.
  *   This differs from params in that we are currently adding params to it and 1) ensuring they are being
  *   passed consistently & 2) documenting them here.
  *   - contact_id
  *   - line_item
  *   - is_test
  *   - campaign_id
  *   - contribution_page_id
  *   - source
  *   - payment_type_id
  *   - thankyou_date (not all forms will set this)
  *
  * @param CRM_Financial_DAO_FinancialType $financialType
  * @param bool $online
  *   Is the form a front end form? If so set a bunch of unpredictable things that should be passed in from the form.
  *
  * @param int $billingLocationID
  *   ID of billing location type.
  * @param bool $isRecur
  *   Is this recurring?
  *
  * @return \CRM_Contribute_DAO_Contribution
  * @throws \Exception
  */
 public static function processFormContribution(&$form, $params, $result, $contributionParams, $financialType, $online, $billingLocationID, $isRecur)
 {
     $transaction = new CRM_Core_Transaction();
     $contactID = $contributionParams['contact_id'];
     $isEmailReceipt = !empty($form->_values['is_email_receipt']);
     $isSeparateMembershipPayment = empty($params['separate_membership_payment']) ? FALSE : TRUE;
     $pledgeID = !empty($params['pledge_id']) ? $params['pledge_id'] : CRM_Utils_Array::value('pledge_id', $form->_values);
     if (!$isSeparateMembershipPayment && !empty($form->_values['pledge_block_id']) && (!empty($params['is_pledge']) || $pledgeID)) {
         $isPledge = TRUE;
     } else {
         $isPledge = FALSE;
     }
     // add these values for the recurringContrib function ,CRM-10188
     $params['financial_type_id'] = $financialType->id;
     $contributionParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $billingLocationID);
     //@todo - this is being set from the form to resolve CRM-10188 - an
     // eNotice caused by it not being set @ the front end
     // however, we then get it being over-written with null for backend contributions
     // a better fix would be to set the values in the respective forms rather than require
     // a function being shared by two forms to deal with their respective values
     // moving it to the BAO & not taking the $form as a param would make sense here.
     if (!isset($params['is_email_receipt']) && $isEmailReceipt) {
         $params['is_email_receipt'] = $isEmailReceipt;
     }
     $params['is_recur'] = $isRecur;
     $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $financialType);
     $nonDeductibleAmount = self::getNonDeductibleAmount($params, $financialType, $online);
     $now = date('YmdHis');
     $receiptDate = CRM_Utils_Array::value('receipt_date', $params);
     if ($isEmailReceipt) {
         $receiptDate = $now;
     }
     if (isset($params['amount'])) {
         $contributionParams = array_merge(self::getContributionParams($params, $financialType->id, $nonDeductibleAmount, TRUE, $result, $receiptDate, $recurringContributionID), $contributionParams);
         $contribution = CRM_Contribute_BAO_Contribution::add($contributionParams);
         $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
         $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
         if ($invoicing) {
             $dataArray = array();
             // @todo - interrogate the line items passed in on the params array.
             // No reason to assume line items will be set on the form.
             foreach ($form->_lineItem as $lineItemKey => $lineItemValue) {
                 foreach ($lineItemValue as $key => $value) {
                     if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
                         if (isset($dataArray[$value['tax_rate']])) {
                             $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
                         } else {
                             $dataArray[$value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
                         }
                     }
                 }
             }
             $smarty = CRM_Core_Smarty::singleton();
             $smarty->assign('dataArray', $dataArray);
             $smarty->assign('totalTaxAmount', $params['tax_amount']);
         }
         if (is_a($contribution, 'CRM_Core_Error')) {
             $message = CRM_Core_Error::getMessages($contribution);
             CRM_Core_Error::fatal($message);
         }
         // lets store it in the form variable so postProcess hook can get to this and use it
         $form->_contributionID = $contribution->id;
     }
     // process soft credit / pcp params first
     CRM_Contribute_BAO_ContributionSoft::formatSoftCreditParams($params, $form);
     //CRM-13981, processing honor contact into soft-credit contribution
     CRM_Contribute_BAO_ContributionSoft::processSoftContribution($params, $contribution);
     //handle pledge stuff.
     if ($isPledge) {
         if ($pledgeID) {
             //when user doing pledge payments.
             //update the schedule when payment(s) are made
             $amount = $params['amount'];
             $pledgePaymentParams = array();
             foreach ($params['pledge_amount'] as $paymentId => $dontCare) {
                 $scheduledAmount = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $paymentId, 'scheduled_amount', 'id');
                 $pledgePayment = $amount >= $scheduledAmount ? $scheduledAmount : $amount;
                 if ($pledgePayment > 0) {
                     $pledgePaymentParams[] = array('id' => $paymentId, 'contribution_id' => $contribution->id, 'status_id' => $contribution->contribution_status_id, 'actual_amount' => $pledgePayment);
                     $amount -= $pledgePayment;
                 }
             }
             if ($amount > 0 && count($pledgePaymentParams)) {
                 $pledgePaymentParams[count($pledgePaymentParams) - 1]['actual_amount'] += $amount;
             }
             foreach ($pledgePaymentParams as $p) {
                 CRM_Pledge_BAO_PledgePayment::add($p);
             }
             //update pledge status according to the new payment statuses
             CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID);
         } else {
             //when user creating pledge record.
             $pledgeParams = array();
             $pledgeParams['contact_id'] = $contribution->contact_id;
             $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount;
             $pledgeParams['contribution_id'] = $contribution->id;
             $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id;
             $pledgeParams['financial_type_id'] = $contribution->financial_type_id;
             $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
             $pledgeParams['installments'] = $params['pledge_installments'];
             $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
             if ($pledgeParams['frequency_unit'] == 'month') {
                 $pledgeParams['frequency_day'] = intval(date("d"));
             } else {
                 $pledgeParams['frequency_day'] = 1;
             }
             $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
             $pledgeParams['status_id'] = $contribution->contribution_status_id;
             $pledgeParams['max_reminders'] = $form->_values['max_reminders'];
             $pledgeParams['initial_reminder_day'] = $form->_values['initial_reminder_day'];
             $pledgeParams['additional_reminder_day'] = $form->_values['additional_reminder_day'];
             $pledgeParams['is_test'] = $contribution->is_test;
             $pledgeParams['acknowledge_date'] = date('Ymd');
             $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount'];
             //inherit campaign from contirb page.
             $pledgeParams['campaign_id'] = CRM_Utils_Array::value('campaign_id', $contributionParams);
             $pledge = CRM_Pledge_BAO_Pledge::create($pledgeParams);
             $form->_params['pledge_id'] = $pledge->id;
             //send acknowledgment email. only when pledge is created
             if ($pledge->id) {
                 //build params to send acknowledgment.
                 $pledgeParams['id'] = $pledge->id;
                 $pledgeParams['receipt_from_name'] = $form->_values['receipt_from_name'];
                 $pledgeParams['receipt_from_email'] = $form->_values['receipt_from_email'];
                 //scheduled amount will be same as installment_amount.
                 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
                 //get total pledge amount.
                 $pledgeParams['total_pledge_amount'] = $pledge->amount;
                 CRM_Pledge_BAO_Pledge::sendAcknowledgment($form, $pledgeParams);
             }
         }
     }
     if ($online && $contribution) {
         CRM_Core_BAO_CustomValueTable::postProcess($params, 'civicrm_contribution', $contribution->id, 'Contribution');
     } elseif ($contribution) {
         //handle custom data.
         $params['contribution_id'] = $contribution->id;
         if (!empty($params['custom']) && is_array($params['custom']) && !is_a($contribution, 'CRM_Core_Error')) {
             CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
         }
     }
     // Save note
     if ($contribution && !empty($params['contribution_note'])) {
         $noteParams = array('entity_table' => 'civicrm_contribution', 'note' => $params['contribution_note'], 'entity_id' => $contribution->id, 'contact_id' => $contribution->contact_id, 'modified_date' => date('Ymd'));
         CRM_Core_BAO_Note::add($noteParams, array());
     }
     if (isset($params['related_contact'])) {
         $contactID = $params['related_contact'];
     } elseif (isset($params['cms_contactID'])) {
         $contactID = $params['cms_contactID'];
     }
     //create contribution activity w/ individual and target
     //activity w/ organisation contact id when onbelf, CRM-4027
     $targetContactID = NULL;
     if (!empty($params['hidden_onbehalf_profile'])) {
         $targetContactID = $contribution->contact_id;
         $contribution->contact_id = $contactID;
     }
     // create an activity record
     if ($contribution) {
         CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
     }
     $transaction->commit();
     // CRM-13074 - create the CMSUser after the transaction is completed as it
     // is not appropriate to delete a valid contribution if a user create problem occurs
     CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params, $contactID, 'email-' . $billingLocationID);
     return $contribution;
 }
 /**
  * Process credit card payment.
  *
  * @param array $submittedValues
  * @param array $lineItem
  *
  * @throws CRM_Core_Exception
  */
 protected function processCreditCard($submittedValues, $lineItem)
 {
     $sendReceipt = $contribution = FALSE;
     $unsetParams = array('trxn_id', 'payment_instrument_id', 'contribution_status_id', 'cancel_date', 'cancel_reason');
     foreach ($unsetParams as $key) {
         if (isset($submittedValues[$key])) {
             unset($submittedValues[$key]);
         }
     }
     $isTest = $this->_mode == 'test' ? 1 : 0;
     // CRM-12680 set $_lineItem if its not set
     if (empty($this->_lineItem) && !empty($lineItem)) {
         $this->_lineItem = $lineItem;
     }
     //Get the require fields value only.
     $params = $this->_params = $submittedValues;
     $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode);
     // Get the payment processor id as per mode.
     $this->_params['payment_processor'] = $params['payment_processor_id'] = $this->_params['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor['id'];
     $now = date('YmdHis');
     $fields = array();
     // we need to retrieve email address
     if ($this->_context == 'standalone' && !empty($submittedValues['is_email_receipt'])) {
         list($this->userDisplayName, $this->userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactID);
         $this->assign('displayName', $this->userDisplayName);
     }
     // Set email for primary location.
     $fields['email-Primary'] = 1;
     $params['email-Primary'] = $this->userEmail;
     // now set the values for the billing location.
     foreach (array_keys($this->_fields) as $name) {
         $fields[$name] = 1;
     }
     // also add location name to the array
     $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
     $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
     $fields["address_name-{$this->_bltID}"] = 1;
     $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
     $nameFields = array('first_name', 'middle_name', 'last_name');
     foreach ($nameFields as $name) {
         $fields[$name] = 1;
         if (array_key_exists("billing_{$name}", $params)) {
             $params[$name] = $params["billing_{$name}"];
             $params['preserveDBName'] = TRUE;
         }
     }
     if (!empty($params['source'])) {
         unset($params['source']);
     }
     $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactID, NULL, NULL, $ctype);
     // add all the additional payment params we need
     if (!empty($this->_params["billing_state_province_id-{$this->_bltID}"])) {
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
     }
     if (!empty($this->_params["billing_country_id-{$this->_bltID}"])) {
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
     }
     $legacyCreditCardExpiryCheck = FALSE;
     if ($this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_CREDIT_CARD && !isset($this->_paymentFields)) {
         $legacyCreditCardExpiryCheck = TRUE;
     }
     if ($legacyCreditCardExpiryCheck || in_array('credit_card_exp_date', array_keys($this->_paymentFields))) {
         $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
         $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
     }
     $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
     $this->_params['amount'] = $this->_params['total_amount'];
     $this->_params['amount_level'] = 0;
     $this->_params['description'] = ts('Office Credit Card contribution');
     $this->_params['currencyID'] = CRM_Utils_Array::value('currency', $this->_params, CRM_Core_Config::singleton()->defaultCurrency);
     $this->_params['payment_action'] = 'Sale';
     if (!empty($this->_params['receive_date'])) {
         $this->_params['receive_date'] = CRM_Utils_Date::processDate($this->_params['receive_date'], $this->_params['receive_date_time']);
     }
     if (!empty($params['soft_credit_to'])) {
         $this->_params['soft_credit_to'] = $params['soft_credit_to'];
         $this->_params['pcp_made_through_id'] = $params['pcp_made_through_id'];
     }
     $this->_params['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $params);
     $this->_params['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $params);
     $this->_params['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $params);
     //Add common data to formatted params
     CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this);
     if (empty($this->_params['invoice_id'])) {
         $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
     } else {
         $this->_params['invoiceID'] = $this->_params['invoice_id'];
     }
     // At this point we've created a contact and stored its address etc
     // all the payment processors expect the name and address to be in the
     // so we copy stuff over to first_name etc.
     $paymentParams = $this->_params;
     $paymentParams['contactID'] = $this->_contactID;
     CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
     $contributionType = new CRM_Financial_DAO_FinancialType();
     $contributionType->id = $params['financial_type_id'];
     // Add some financial type details to the params list
     // if folks need to use it.
     $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $contributionType->name;
     $paymentParams['contributionPageID'] = NULL;
     if (!empty($this->_params['is_email_receipt'])) {
         $paymentParams['email'] = $this->userEmail;
         $paymentParams['is_email_receipt'] = 1;
     } else {
         $paymentParams['is_email_receipt'] = 0;
         $this->_params['is_email_receipt'] = 0;
     }
     if (!empty($this->_params['receive_date'])) {
         $paymentParams['receive_date'] = $this->_params['receive_date'];
     }
     // For recurring contribution, create Contribution Record first.
     // Contribution ID, Recurring ID and Contact ID needed
     // When we get a callback from the payment processor, CRM-7115
     if (!empty($paymentParams['is_recur'])) {
         $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $this->_params, NULL, $this->_contactID, $contributionType, TRUE, FALSE, $isTest, $this->_lineItem);
         $paymentParams['contributionID'] = $contribution->id;
         $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
         $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
         $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
     }
     $result = array();
     if ($paymentParams['amount'] > 0.0) {
         // force a re-get of the payment processor in case the form changed it, CRM-7179
         $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this, TRUE);
         try {
             $result = $payment->doPayment($paymentParams, 'contribute');
         } catch (CRM_Core_Exception $e) {
             $message = ts("Payment Processor Error message") . $e->getMessage();
             $this->cleanupDBAfterPaymentFailure($paymentParams, $message);
             // Set the contribution mode.
             $urlParams = "action=add&cid={$this->_contactID}";
             if ($this->_mode) {
                 $urlParams .= "&mode={$this->_mode}";
             }
             if (!empty($this->_ppID)) {
                 $urlParams .= "&context=pledge&ppid={$this->_ppID}";
             }
             CRM_Core_Error::statusBounce($message, $urlParams, ts('Payment Processor Error'));
         }
     }
     $this->_params = array_merge($this->_params, $result);
     $this->_params['receive_date'] = $now;
     if (!empty($this->_params['is_email_receipt'])) {
         $this->_params['receipt_date'] = $now;
     } else {
         $this->_params['receipt_date'] = CRM_Utils_Date::processDate($this->_params['receipt_date'], $params['receipt_date_time'], TRUE);
     }
     $this->set('params', $this->_params);
     $this->assign('trxn_id', $result['trxn_id']);
     $this->assign('receive_date', $this->_params['receive_date']);
     // Result has all the stuff we need
     // lets archive it to a financial transaction
     if ($contributionType->is_deductible) {
         $this->assign('is_deductible', TRUE);
         $this->set('is_deductible', TRUE);
     }
     // Set source if not set
     if (empty($this->_params['source'])) {
         $userID = CRM_Core_Session::singleton()->get('userID');
         $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID, 'sort_name');
         $this->_params['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
     }
     // Build custom data getFields array
     $customFieldsContributionType = CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE, CRM_Utils_Array::value('financial_type_id', $params));
     $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsContributionType, CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE, NULL, NULL, TRUE));
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_id, 'Contribution');
     if (empty($paymentParams['is_recur'])) {
         $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($this, $this->_params, $result, $this->_contactID, $contributionType, FALSE, FALSE, $isTest, $this->_lineItem);
     }
     // Send receipt mail.
     if ($contribution->id && !empty($this->_params['is_email_receipt'])) {
         $this->_params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
         $this->_params['contact_id'] = $this->_contactID;
         $this->_params['contribution_id'] = $contribution->id;
         $sendReceipt = CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $this->_params, TRUE);
     }
     //process the note
     if ($contribution->id && isset($params['note'])) {
         CRM_Contribute_Form_AdditionalInfo::processNote($params, $contactID, $contribution->id, NULL);
     }
     //process premium
     if ($contribution->id && isset($params['product_name'][0])) {
         CRM_Contribute_Form_AdditionalInfo::processPremium($params, $contribution->id, NULL, $this->_options);
     }
     //update pledge payment status.
     if ($this->_ppID && $contribution->id) {
         // Store contribution id in payment record.
         CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $this->_ppID, 'contribution_id', $contribution->id);
         CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($this->_pledgeID, array($this->_ppID), $contribution->contribution_status_id, NULL, $contribution->total_amount);
     }
     if ($contribution->id) {
         $statusMsg = ts('The contribution record has been processed.');
         if (!empty($this->_params['is_email_receipt']) && $sendReceipt) {
             $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
         }
         CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
     }
 }
Beispiel #27
0
 /**
  * Mark a pledge (and any outstanding payments) as cancelled.
  *
  * @param int $pledgeID
  */
 public static function cancel($pledgeID)
 {
     $statuses = array_flip(CRM_Contribute_PseudoConstant::contributionStatus());
     $paymentIDs = self::findCancelablePayments($pledgeID);
     CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeID, $paymentIDs, NULL, $statuses['Cancelled'], 0, FALSE, TRUE);
 }
 /**
  * Process the contribution
  *
  * @return void
  * @access public
  */
 static function processContribution(&$form, $params, $result, $contactID, $contributionType, $deductibleMode = TRUE, $pending = FALSE, $online = TRUE)
 {
     $transaction = new CRM_Core_Transaction();
     $className = get_class($form);
     $honorCId = $recurringContributionID = NULL;
     if ($online && $form->get('honor_block_is_active')) {
         $honorCId = $form->createHonorContact();
     }
     // add these values for the recurringContrib function ,CRM-10188
     $params['contribution_type_id'] = $contributionType->id;
     $params['is_email_receipt'] = CRM_Utils_Array::value('is_email_receipt', $form->_values);
     $recurringContributionID = self::processRecurringContribution($form, $params, $contactID, $contributionType, $online);
     if (!$online && isset($params['honor_contact_id'])) {
         $honorCId = $params['honor_contact_id'];
     }
     $config = CRM_Core_Config::singleton();
     if (!$online && isset($params['non_deductible_amount'])) {
         $nonDeductibleAmount = $params['non_deductible_amount'];
     } else {
         $nonDeductibleAmount = $params['amount'];
     }
     if ($online && $contributionType->is_deductible && $deductibleMode) {
         $selectProduct = CRM_Utils_Array::value('selectProduct', $params);
         if ($selectProduct && $selectProduct != 'no_thanks') {
             $productDAO = new CRM_Contribute_DAO_Product();
             $productDAO->id = $selectProduct;
             $productDAO->find(TRUE);
             if ($params['amount'] < $productDAO->price) {
                 $nonDeductibleAmount = $params['amount'];
             } else {
                 $nonDeductibleAmount = $productDAO->price;
             }
         } else {
             $nonDeductibleAmount = '0.00';
         }
     }
     $now = date('YmdHis');
     $receiptDate = CRM_Utils_Array::value('receipt_date', $params);
     if (CRM_Utils_Array::value('is_email_receipt', $form->_values)) {
         $receiptDate = $now;
     }
     //get the contrib page id.
     $campaignId = $contributionPageId = NULL;
     if ($online) {
         $contributionPageId = $form->_id;
         $campaignId = CRM_Utils_Array::value('campaign_id', $params);
         if (!array_key_exists('campaign_id', $params)) {
             $campaignId = CRM_Utils_Array::value('campaign_id', $form->_values);
         }
     } else {
         //also for offline we do support - CRM-7290
         $contributionPageId = CRM_Utils_Array::value('contribution_page_id', $params);
         $campaignId = CRM_Utils_Array::value('campaign_id', $params);
     }
     // first create the contribution record
     $contribParams = array('contact_id' => $contactID, 'contribution_type_id' => $contributionType->id, 'contribution_page_id' => $contributionPageId, 'receive_date' => CRM_Utils_Array::value('receive_date', $params) ? CRM_Utils_Date::processDate($params['receive_date']) : date('YmdHis'), 'non_deductible_amount' => $nonDeductibleAmount, 'total_amount' => $params['amount'], 'amount_level' => CRM_Utils_Array::value('amount_level', $params), 'invoice_id' => $params['invoiceID'], 'currency' => $params['currencyID'], 'source' => !$online || CRM_Utils_Array::value('source', $params) ? CRM_Utils_Array::value('source', $params) : CRM_Utils_Array::value('description', $params), 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0), 'cancel_reason' => CRM_Utils_Array::value('cancel_reason', $params, 0), 'cancel_date' => isset($params['cancel_date']) ? CRM_Utils_Date::format($params['cancel_date']) : NULL, 'thankyou_date' => isset($params['thankyou_date']) ? CRM_Utils_Date::format($params['thankyou_date']) : NULL, 'campaign_id' => $campaignId);
     if (!$online && isset($params['thankyou_date'])) {
         $contribParams['thankyou_date'] = $params['thankyou_date'];
     }
     if (!$online || $form->_values['is_monetary']) {
         if (!CRM_Utils_Array::value('is_pay_later', $params)) {
             $contribParams['payment_instrument_id'] = 1;
         }
     }
     if (!$pending && $result) {
         $contribParams += array('fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['amount']), 'trxn_id' => $result['trxn_id'], 'receipt_date' => $receiptDate, 'trxn_result_code' => CRM_Utils_Array::value('trxn_result_code', $result), 'payment_processor' => CRM_Utils_Array::value('payment_processor', $result));
     }
     if (isset($honorCId)) {
         $contribParams['honor_contact_id'] = $honorCId;
         $contribParams['honor_type_id'] = $params['honor_type_id'];
     }
     if ($recurringContributionID) {
         $contribParams['contribution_recur_id'] = $recurringContributionID;
     }
     $contribParams['contribution_status_id'] = $pending ? 2 : 1;
     $contribParams['is_test'] = 0;
     if ($form->_mode == 'test') {
         $contribParams['is_test'] = 1;
     }
     $ids = array();
     if (isset($contribParams['invoice_id'])) {
         $contribID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contribParams['invoice_id'], 'id', 'invoice_id');
         if (isset($contribID)) {
             $ids['contribution'] = $contribID;
             $contribParams['id'] = $contribID;
         }
     }
     //create an contribution address
     if ($form->_contributeMode != 'notify' && !CRM_Utils_Array::value('is_pay_later', $params) && CRM_Utils_Array::value('is_monetary', $form->_values)) {
         $contribParams['address_id'] = CRM_Contribute_BAO_Contribution::createAddress($params, $form->_bltID);
     }
     // CRM-4038: for non-en_US locales, CRM_Contribute_BAO_Contribution::add() expects localised amounts
     $contribParams['non_deductible_amount'] = trim(CRM_Utils_Money::format($contribParams['non_deductible_amount'], ' '));
     $contribParams['total_amount'] = trim(CRM_Utils_Money::format($contribParams['total_amount'], ' '));
     // Prepare soft contribution due to pcp or Submit Credit / Debit Card Contribution by admin.
     if (CRM_Utils_Array::value('pcp_made_through_id', $params) || CRM_Utils_Array::value('soft_credit_to', $params)) {
         // if its due to pcp
         if (CRM_Utils_Array::value('pcp_made_through_id', $params)) {
             $contribSoftContactId = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $params['pcp_made_through_id'], 'contact_id');
         } else {
             $contribSoftContactId = CRM_Utils_Array::value('soft_credit_to', $params);
         }
         // Pass these details onto with the contribution to make them
         // available at hook_post_process, CRM-8908
         $contribParams['soft_credit_to'] = $params['soft_credit_to'] = $contribSoftContactId;
     }
     if ($params['amount']) {
         //add contribution record
         $contribution =& CRM_Contribute_BAO_Contribution::add($contribParams, $ids);
     }
     // process soft credit / pcp pages
     CRM_Contribute_Form_Contribution_Confirm::processPcpSoft($params, $contribution);
     // process price set, CRM-5095
     if ($contribution && $contribution->id && $form->_priceSetId) {
         if (CRM_Utils_Array::value('is_quick_config', $form->_params)) {
             $temp = array();
             foreach ($form->_lineItem as $key => $val) {
                 foreach ($val as $k => $v) {
                     if (CRM_Utils_Money::format($v['line_total']) == CRM_Utils_Money::format($contribution->total_amount)) {
                         $temp[$key][$k] = $form->_lineItem[$key][$k];
                         CRM_Contribute_Form_AdditionalInfo::processPriceSet($contribution->id, $temp);
                     }
                 }
             }
         } elseif (!CRM_Utils_Array::value('is_quick_config', $form->_params)) {
             CRM_Contribute_Form_AdditionalInfo::processPriceSet($contribution->id, $form->_lineItem);
         }
         if (!$form->_separateMembershipPayment && CRM_Utils_Array::value('is_quick_config', $form->_params)) {
             $form->_lineItem = null;
         }
     }
     //handle pledge stuff.
     if (!CRM_Utils_Array::value('separate_membership_payment', $form->_params) && CRM_Utils_Array::value('pledge_block_id', $form->_values) && (CRM_Utils_Array::value('is_pledge', $form->_params) || CRM_Utils_Array::value('pledge_id', $form->_values))) {
         if (CRM_Utils_Array::value('pledge_id', $form->_values)) {
             //when user doing pledge payments.
             //update the schedule when payment(s) are made
             foreach ($form->_params['pledge_amount'] as $paymentId => $dontCare) {
                 $scheduledAmount = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $paymentId, 'scheduled_amount', 'id');
                 $pledgePaymentParams = array('id' => $paymentId, 'contribution_id' => $contribution->id, 'status_id' => $contribution->contribution_status_id, 'actual_amount' => $scheduledAmount);
                 CRM_Pledge_BAO_PledgePayment::add($pledgePaymentParams);
             }
             //update pledge status according to the new payment statuses
             CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($form->_values['pledge_id']);
         } else {
             //when user creating pledge record.
             $pledgeParams = array();
             $pledgeParams['contact_id'] = $contribution->contact_id;
             $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount;
             $pledgeParams['contribution_id'] = $contribution->id;
             $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id;
             $pledgeParams['contribution_type_id'] = $contribution->contribution_type_id;
             $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
             $pledgeParams['installments'] = $params['pledge_installments'];
             $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
             if ($pledgeParams['frequency_unit'] == 'month') {
                 $pledgeParams['frequency_day'] = intval(date("d"));
             } else {
                 $pledgeParams['frequency_day'] = 1;
             }
             $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
             $pledgeParams['status_id'] = $contribution->contribution_status_id;
             $pledgeParams['max_reminders'] = $form->_values['max_reminders'];
             $pledgeParams['initial_reminder_day'] = $form->_values['initial_reminder_day'];
             $pledgeParams['additional_reminder_day'] = $form->_values['additional_reminder_day'];
             $pledgeParams['is_test'] = $contribution->is_test;
             $pledgeParams['acknowledge_date'] = date('Ymd');
             $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount'];
             //inherit campaign from contirb page.
             $pledgeParams['campaign_id'] = $campaignId;
             $pledge = CRM_Pledge_BAO_Pledge::create($pledgeParams);
             $form->_params['pledge_id'] = $pledge->id;
             //send acknowledgment email. only when pledge is created
             if ($pledge->id) {
                 //build params to send acknowledgment.
                 $pledgeParams['id'] = $pledge->id;
                 $pledgeParams['receipt_from_name'] = $form->_values['receipt_from_name'];
                 $pledgeParams['receipt_from_email'] = $form->_values['receipt_from_email'];
                 //scheduled amount will be same as installment_amount.
                 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
                 //get total pledge amount.
                 $pledgeParams['total_pledge_amount'] = $pledge->amount;
                 CRM_Pledge_BAO_Pledge::sendAcknowledgment($form, $pledgeParams);
             }
         }
     }
     if ($online && $contribution) {
         CRM_Core_BAO_CustomValueTable::postProcess($form->_params, CRM_Core_DAO::$_nullArray, 'civicrm_contribution', $contribution->id, 'Contribution');
     } elseif ($contribution) {
         //handle custom data.
         $params['contribution_id'] = $contribution->id;
         if (CRM_Utils_Array::value('custom', $params) && is_array($params['custom']) && !is_a($contribution, 'CRM_Core_Error')) {
             CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
         }
     }
     if (isset($params['related_contact'])) {
         $contactID = $params['related_contact'];
     } elseif (isset($params['cms_contactID'])) {
         $contactID = $params['cms_contactID'];
     }
     CRM_Contribute_BAO_Contribution_Utils::createCMSUser($params, $contactID, 'email-' . $form->_bltID);
     // return if pending
     if ($pending) {
         return $contribution;
     }
     // next create the transaction record
     if ($contribution && (!$online || $form->_values['is_monetary']) && $result['trxn_id']) {
         $trxnParams = array('contribution_id' => $contribution->id, 'trxn_date' => $now, 'trxn_type' => 'Debit', 'total_amount' => $params['amount'], 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $params['amount']), 'currency' => $params['currencyID'], 'payment_processor' => $form->_paymentProcessor['payment_processor_type'], 'trxn_id' => $result['trxn_id'], 'trxn_result_code' => isset($result['trxn_result_code']) ? $result['trxn_result_code'] : FALSE);
         $trxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
     }
     //create contribution activity w/ individual and target
     //activity w/ organisation contact id when onbelf, CRM-4027
     $targetContactID = NULL;
     if (CRM_Utils_Array::value('hidden_onbehalf_profile', $params)) {
         $targetContactID = $contribution->contact_id;
         $contribution->contact_id = $contactID;
     }
     // create an activity record
     if ($contribution) {
         CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
     }
     $transaction->commit();
     return $contribution;
 }
 function updateRecurLinkedPledge(&$contribution)
 {
     $returnProperties = array('id', 'pledge_id');
     $paymentDetails = $paymentIDs = array();
     if (CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $contribution->id, $paymentDetails, $returnProperties)) {
         foreach ($paymentDetails as $key => $value) {
             $paymentIDs[] = $value['id'];
             $pledgeId = $value['pledge_id'];
         }
     } else {
         //payment is not already linked - if it is linked with a pledge we need to create a link.
         // return if it is not recurring contribution
         if (!$contribution->contribution_recur_id) {
             return;
         }
         $relatedContributions = new CRM_Contribute_DAO_Contribution();
         $relatedContributions->contribution_recur_id = $contribution->contribution_recur_id;
         $relatedContributions->find();
         while ($relatedContributions->fetch()) {
             CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_PledgePayment', 'contribution_id', $relatedContributions->id, $paymentDetails, $returnProperties);
         }
         if (empty($paymentDetails)) {
             // payment is not linked with a pledge and neither are any other contributions on this
             return;
         }
         foreach ($paymentDetails as $key => $value) {
             $pledgeId = $value['pledge_id'];
         }
         // we have a pledge now we need to get the oldest unpaid payment
         $paymentDetails = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
         if (empty($paymentDetails['id'])) {
             // we can assume this pledge is now completed
             // return now so we don't create a core error & roll back
             return;
         }
         $paymentDetails['contribution_id'] = $contribution->id;
         $paymentDetails['status_id'] = $contribution->contribution_status_id;
         $paymentDetails['actual_amount'] = $contribution->total_amount;
         // put contribution against it
         $payment = CRM_Pledge_BAO_PledgePayment::add($paymentDetails);
         $paymentIDs[] = $payment->id;
     }
     // update pledge and corresponding payment statuses
     CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contribution->contribution_status_id, NULL, $contribution->total_amount);
 }
/**
 * take the input parameter list as specified in the data model and
 * convert it into the same format that we use in QF and BAO object
 *
 * @param array $params
 *   Associative array of property name/value.
 *                             pairs to insert in new contact.
 * @param array $values
 *   The reformatted properties that we can use internally.
 *                            '
 *
 * @param bool $create
 * @param null $onDuplicate
 *
 * @return array|CRM_Error
 */
function _civicrm_api3_deprecated_formatted_param($params, &$values, $create = FALSE, $onDuplicate = NULL)
{
    // copy all the contribution fields as is
    $fields = CRM_Contribute_DAO_Contribution::fields();
    _civicrm_api3_store_values($fields, $params, $values);
    require_once 'CRM/Core/OptionGroup.php';
    $customFields = CRM_Core_BAO_CustomField::getFields('Contribution', FALSE, FALSE, NULL, NULL, FALSE, FALSE, FALSE);
    foreach ($params as $key => $value) {
        // ignore empty values or empty arrays etc
        if (CRM_Utils_System::isNull($value)) {
            continue;
        }
        // Handling Custom Data
        if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) {
            $values[$key] = $value;
            $type = $customFields[$customFieldID]['html_type'];
            if ($type == 'CheckBox' || $type == 'Multi-Select') {
                $mulValues = explode(',', $value);
                $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
                $values[$key] = array();
                foreach ($mulValues as $v1) {
                    foreach ($customOption as $customValueID => $customLabel) {
                        $customValue = $customLabel['value'];
                        if (strtolower($customLabel['label']) == strtolower(trim($v1)) || strtolower($customValue) == strtolower(trim($v1))) {
                            if ($type == 'CheckBox') {
                                $values[$key][$customValue] = 1;
                            } else {
                                $values[$key][] = $customValue;
                            }
                        }
                    }
                }
            } elseif ($type == 'Select' || $type == 'Radio' || $type == 'Autocomplete-Select' && $customFields[$customFieldID]['data_type'] == 'String') {
                $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, TRUE);
                foreach ($customOption as $customFldID => $customValue) {
                    $val = CRM_Utils_Array::value('value', $customValue);
                    $label = CRM_Utils_Array::value('label', $customValue);
                    $label = strtolower($label);
                    $value = strtolower(trim($value));
                    if ($value == $label || $value == strtolower($val)) {
                        $values[$key] = $val;
                    }
                }
            }
        }
        switch ($key) {
            case 'contribution_contact_id':
                if (!CRM_Utils_Rule::integer($value)) {
                    return civicrm_api3_create_error("contact_id not valid: {$value}");
                }
                $dao = new CRM_Core_DAO();
                $qParams = array();
                $svq = $dao->singleValueQuery("SELECT is_deleted FROM civicrm_contact WHERE id = {$value}", $qParams);
                if (!isset($svq)) {
                    return civicrm_api3_create_error("Invalid Contact ID: There is no contact record with contact_id = {$value}.");
                } elseif ($svq == 1) {
                    return civicrm_api3_create_error("Invalid Contact ID: contact_id {$value} is a soft-deleted contact.");
                }
                $values['contact_id'] = $values['contribution_contact_id'];
                unset($values['contribution_contact_id']);
                break;
            case 'contact_type':
                // import contribution record according to select contact type
                require_once 'CRM/Contact/DAO/Contact.php';
                $contactType = new CRM_Contact_DAO_Contact();
                // when insert mode check contact id or external identifier
                if (!empty($params['contribution_contact_id']) || !empty($params['external_identifier'])) {
                    if (!empty($params['contribution_contact_id'])) {
                        $contactType->id = CRM_Utils_Array::value('contribution_contact_id', $params);
                    } elseif (!empty($params['external_identifier'])) {
                        $contactType->external_identifier = $params['external_identifier'];
                    }
                    if ($contactType->find(TRUE)) {
                        if ($params['contact_type'] != $contactType->contact_type) {
                            return civicrm_api3_create_error("Contact Type is wrong: {$contactType->contact_type}");
                        }
                    }
                } elseif (!empty($params['contribution_id']) || !empty($params['trxn_id']) || !empty($params['invoice_id'])) {
                    // when update mode check contribution id or trxn id or
                    // invoice id
                    $contactId = new CRM_Contribute_DAO_Contribution();
                    if (!empty($params['contribution_id'])) {
                        $contactId->id = $params['contribution_id'];
                    } elseif (!empty($params['trxn_id'])) {
                        $contactId->trxn_id = $params['trxn_id'];
                    } elseif (!empty($params['invoice_id'])) {
                        $contactId->invoice_id = $params['invoice_id'];
                    }
                    if ($contactId->find(TRUE)) {
                        $contactType->id = $contactId->contact_id;
                        if ($contactType->find(TRUE)) {
                            if ($params['contact_type'] != $contactType->contact_type) {
                                return civicrm_api3_create_error("Contact Type is wrong: {$contactType->contact_type}");
                            }
                        }
                    }
                } else {
                    if ($onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE) {
                        return civicrm_api3_create_error("Empty Contribution and Invoice and Transaction ID. Row was skipped.");
                    } else {
                        return civicrm_api3_create_error("Empty Contact and External ID. Row was skipped.");
                    }
                }
                break;
            case 'receive_date':
            case 'cancel_date':
            case 'receipt_date':
            case 'thankyou_date':
                if (!CRM_Utils_Rule::dateTime($value)) {
                    return civicrm_api3_create_error("{$key} not a valid date: {$value}");
                }
                break;
            case 'non_deductible_amount':
            case 'total_amount':
            case 'fee_amount':
            case 'net_amount':
                if (!CRM_Utils_Rule::money($value)) {
                    return civicrm_api3_create_error("{$key} not a valid amount: {$value}");
                }
                break;
            case 'currency':
                if (!CRM_Utils_Rule::currencyCode($value)) {
                    return civicrm_api3_create_error("currency not a valid code: {$value}");
                }
                break;
            case 'financial_type':
                require_once 'CRM/Contribute/PseudoConstant.php';
                $contriTypes = CRM_Contribute_PseudoConstant::financialType();
                foreach ($contriTypes as $val => $type) {
                    if (strtolower($value) == strtolower($type)) {
                        $values['financial_type_id'] = $val;
                        break;
                    }
                }
                if (empty($values['financial_type_id'])) {
                    return civicrm_api3_create_error("Financial Type is not valid: {$value}");
                }
                break;
            case 'payment_instrument':
                require_once 'CRM/Core/OptionGroup.php';
                $values['payment_instrument_id'] = CRM_Core_OptionGroup::getValue('payment_instrument', $value);
                if (empty($values['payment_instrument_id'])) {
                    return civicrm_api3_create_error("Payment Instrument is not valid: {$value}");
                }
                break;
            case 'contribution_status_id':
                require_once 'CRM/Core/OptionGroup.php';
                if (!($values['contribution_status_id'] = CRM_Core_OptionGroup::getValue('contribution_status', $value))) {
                    return civicrm_api3_create_error("Contribution Status is not valid: {$value}");
                }
                break;
            case 'soft_credit':
                // import contribution record according to select contact type
                // validate contact id and external identifier.
                $value[$key] = $mismatchContactType = $softCreditContactIds = '';
                if (isset($params[$key]) && is_array($params[$key])) {
                    foreach ($params[$key] as $softKey => $softParam) {
                        $contactId = CRM_Utils_Array::value('contact_id', $softParam);
                        $externalId = CRM_Utils_Array::value('external_identifier', $softParam);
                        $email = CRM_Utils_Array::value('email', $softParam);
                        if ($contactId || $externalId) {
                            require_once 'CRM/Contact/DAO/Contact.php';
                            $contact = new CRM_Contact_DAO_Contact();
                            $contact->id = $contactId;
                            $contact->external_identifier = $externalId;
                            $errorMsg = NULL;
                            if (!$contact->find(TRUE)) {
                                $field = $contactId ? ts('Contact ID') : ts('External ID');
                                $errorMsg = ts("Soft Credit %1 - %2 doesn't exist. Row was skipped.", array(1 => $field, 2 => $contactId ? $contactId : $externalId));
                            }
                            if ($errorMsg) {
                                return civicrm_api3_create_error($errorMsg, $value[$key]);
                            }
                            // finally get soft credit contact id.
                            $values[$key][$softKey] = $softParam;
                            $values[$key][$softKey]['contact_id'] = $contact->id;
                        } elseif ($email) {
                            if (!CRM_Utils_Rule::email($email)) {
                                return civicrm_api3_create_error("Invalid email address {$email} provided for Soft Credit. Row was skipped");
                            }
                            // get the contact id from duplicate contact rule, if more than one contact is returned
                            // we should return error, since current interface allows only one-one mapping
                            $emailParams = array('email' => $email, 'contact_type' => $params['contact_type']);
                            $checkDedupe = _civicrm_api3_deprecated_duplicate_formatted_contact($emailParams);
                            if (!$checkDedupe['is_error']) {
                                return civicrm_api3_create_error("Invalid email address(doesn't exist) {$email} for Soft Credit. Row was skipped");
                            } else {
                                $matchingContactIds = explode(',', $checkDedupe['error_message']['params'][0]);
                                if (count($matchingContactIds) > 1) {
                                    return civicrm_api3_create_error("Invalid email address(duplicate) {$email} for Soft Credit. Row was skipped");
                                } elseif (count($matchingContactIds) == 1) {
                                    $contactId = $matchingContactIds[0];
                                    unset($softParam['email']);
                                    $values[$key][$softKey] = $softParam + array('contact_id' => $contactId);
                                }
                            }
                        }
                    }
                }
                break;
            case 'pledge_payment':
            case 'pledge_id':
                // giving respect to pledge_payment flag.
                if (empty($params['pledge_payment'])) {
                    continue;
                }
                // get total amount of from import fields
                $totalAmount = CRM_Utils_Array::value('total_amount', $params);
                $onDuplicate = CRM_Utils_Array::value('onDuplicate', $params);
                // we need to get contact id $contributionContactID to
                // retrieve pledge details as well as to validate pledge ID
                // first need to check for update mode
                if ($onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE && ($params['contribution_id'] || $params['trxn_id'] || $params['invoice_id'])) {
                    $contribution = new CRM_Contribute_DAO_Contribution();
                    if ($params['contribution_id']) {
                        $contribution->id = $params['contribution_id'];
                    } elseif ($params['trxn_id']) {
                        $contribution->trxn_id = $params['trxn_id'];
                    } elseif ($params['invoice_id']) {
                        $contribution->invoice_id = $params['invoice_id'];
                    }
                    if ($contribution->find(TRUE)) {
                        $contributionContactID = $contribution->contact_id;
                        if (!$totalAmount) {
                            $totalAmount = $contribution->total_amount;
                        }
                    } else {
                        return civicrm_api3_create_error('No match found for specified contact in contribution data. Row was skipped.', 'pledge_payment');
                    }
                } else {
                    // first get the contact id for given contribution record.
                    if (!empty($params['contribution_contact_id'])) {
                        $contributionContactID = $params['contribution_contact_id'];
                    } elseif (!empty($params['external_identifier'])) {
                        require_once 'CRM/Contact/DAO/Contact.php';
                        $contact = new CRM_Contact_DAO_Contact();
                        $contact->external_identifier = $params['external_identifier'];
                        if ($contact->find(TRUE)) {
                            $contributionContactID = $params['contribution_contact_id'] = $values['contribution_contact_id'] = $contact->id;
                        } else {
                            return civicrm_api3_create_error('No match found for specified contact in contribution data. Row was skipped.', 'pledge_payment');
                        }
                    } else {
                        // we need to get contribution contact using de dupe
                        $error = _civicrm_api3_deprecated_check_contact_dedupe($params);
                        if (isset($error['error_message']['params'][0])) {
                            $matchedIDs = explode(',', $error['error_message']['params'][0]);
                            // check if only one contact is found
                            if (count($matchedIDs) > 1) {
                                return civicrm_api3_create_error($error['error_message']['message'], 'pledge_payment');
                            } else {
                                $contributionContactID = $params['contribution_contact_id'] = $values['contribution_contact_id'] = $matchedIDs[0];
                            }
                        } else {
                            return civicrm_api3_create_error('No match found for specified contact in contribution data. Row was skipped.', 'pledge_payment');
                        }
                    }
                }
                if (!empty($params['pledge_id'])) {
                    if (CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge', $params['pledge_id'], 'contact_id') != $contributionContactID) {
                        return civicrm_api3_create_error('Invalid Pledge ID provided. Contribution row was skipped.', 'pledge_payment');
                    }
                    $values['pledge_id'] = $params['pledge_id'];
                } else {
                    // check if there are any pledge related to this contact, with payments pending or in progress
                    require_once 'CRM/Pledge/BAO/Pledge.php';
                    $pledgeDetails = CRM_Pledge_BAO_Pledge::getContactPledges($contributionContactID);
                    if (empty($pledgeDetails)) {
                        return civicrm_api3_create_error('No open pledges found for this contact. Contribution row was skipped.', 'pledge_payment');
                    } elseif (count($pledgeDetails) > 1) {
                        return civicrm_api3_create_error('This contact has more than one open pledge. Unable to determine which pledge to apply the contribution to. Contribution row was skipped.', 'pledge_payment');
                    }
                    // this mean we have only one pending / in progress pledge
                    $values['pledge_id'] = $pledgeDetails[0];
                }
                // we need to check if oldest payment amount equal to contribution amount
                require_once 'CRM/Pledge/BAO/PledgePayment.php';
                $pledgePaymentDetails = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($values['pledge_id']);
                if ($pledgePaymentDetails['amount'] == $totalAmount) {
                    $values['pledge_payment_id'] = $pledgePaymentDetails['id'];
                } else {
                    return civicrm_api3_create_error('Contribution and Pledge Payment amount mismatch for this record. Contribution row was skipped.', 'pledge_payment');
                }
                break;
            default:
                break;
        }
    }
    if (array_key_exists('note', $params)) {
        $values['note'] = $params['note'];
    }
    if ($create) {
        // CRM_Contribute_BAO_Contribution::add() handles contribution_source
        // So, if $values contains contribution_source, convert it to source
        $changes = array('contribution_source' => 'source');
        foreach ($changes as $orgVal => $changeVal) {
            if (isset($values[$orgVal])) {
                $values[$changeVal] = $values[$orgVal];
                unset($values[$orgVal]);
            }
        }
    }
    return NULL;
}