function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE)
 {
     $contribution =& $objects['contribution'];
     $memberships =& $objects['membership'];
     if (is_numeric($memberships)) {
         $memberships = array($objects['membership']);
     }
     $participant =& $objects['participant'];
     $event =& $objects['event'];
     $changeToday = CRM_Utils_Array::value('trxn_date', $input, self::$_now);
     $recurContrib =& $objects['contributionRecur'];
     $values = array();
     if ($input['component'] == 'contribute') {
         if ($contribution->contribution_page_id) {
             CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
             $source = ts('Online Contribution') . ': ' . $values['title'];
         } elseif ($recurContrib->id) {
             $contribution->contribution_page_id = NULL;
             $values['amount'] = $recurContrib->amount;
             $values['contribution_type_id'] = $objects['contributionType']->id;
             $values['title'] = $source = ts('Offline Recurring Contribution');
             $values['is_email_receipt'] = $recurContrib->is_email_receipt;
             $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
             $values['receipt_from_name'] = $domainValues[0];
             $values['receipt_from_email'] = $domainValues[1];
         }
         $contribution->source = $source;
         if (CRM_Utils_Array::value('is_email_receipt', $values)) {
             $contribution->receipt_date = self::$_now;
         }
         if (!empty($memberships)) {
             foreach ($memberships as $membershipTypeIdKey => $membership) {
                 if ($membership) {
                     $format = '%Y%m%d';
                     $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, $membership->membership_type_id, $membership->is_test, $membership->id);
                     // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
                     // this picks up membership type changes during renewals
                     $sql = "\nSELECT    membership_type_id\nFROM      civicrm_membership_log\nWHERE     membership_id={$membership->id}\nORDER BY  id DESC\nLIMIT 1;";
                     $dao = new CRM_Core_DAO();
                     $dao->query($sql);
                     if ($dao->fetch()) {
                         if (!empty($dao->membership_type_id)) {
                             $membership->membership_type_id = $dao->membership_type_id;
                             $membership->save();
                         }
                         // else fall back to using current membership type
                     }
                     // else fall back to using current membership type
                     $dao->free();
                     if ($currentMembership) {
                         /*
                          * Fixed FOR CRM-4433
                          * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
                          * when Contribution mode is notify and membership is for renewal )
                          */
                         CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
                         $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, $changeToday);
                         $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
                     } else {
                         $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id);
                     }
                     //get the status for membership.
                     $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', TRUE);
                     $formatedParams = array('status_id' => CRM_Utils_Array::value('id', $calcStatus, 2), 'join_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $dates), $format), 'start_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $dates), $format), 'end_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $dates), $format), 'reminder_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('reminder_date', $dates), $format));
                     //we might be renewing membership,
                     //so make status override false.
                     $formatedParams['is_override'] = FALSE;
                     $membership->copyValues($formatedParams);
                     $membership->save();
                     //updating the membership log
                     $membershipLog = array();
                     $membershipLog = $formatedParams;
                     $logStartDate = $formatedParams['start_date'];
                     if (CRM_Utils_Array::value('log_start_date', $dates)) {
                         $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
                         $logStartDate = CRM_Utils_Date::isoToMysql($logStartDate);
                     }
                     $membershipLog['start_date'] = $logStartDate;
                     $membershipLog['membership_id'] = $membership->id;
                     $membershipLog['modified_id'] = $membership->contact_id;
                     $membershipLog['modified_date'] = date('Ymd');
                     $membershipLog['membership_type_id'] = $membership->membership_type_id;
                     CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
                     //update related Memberships.
                     CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams);
                     //update the membership type key of membership relatedObjects array
                     //if it has changed after membership update
                     if ($membershipTypeIdKey != $membership->membership_type_id) {
                         $memberships[$membership->membership_type_id] = $membership;
                         $contribution->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
                         unset($contribution->_relatedObjects['membership'][$membershipTypeIdKey]);
                         unset($memberships[$membershipTypeIdKey]);
                     }
                 }
             }
         }
     } else {
         // event
         $eventParams = array('id' => $objects['event']->id);
         $values['event'] = array();
         CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
         $eventParams = array('id' => $objects['event']->id);
         $values['event'] = array();
         CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
         //get location details
         $locationParams = array('entity_id' => $objects['event']->id, 'entity_table' => 'civicrm_event');
         $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
         $ufJoinParams = array('entity_table' => 'civicrm_event', 'entity_id' => $ids['event'], 'module' => 'CiviEvent');
         list($custom_pre_id, $custom_post_ids) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
         $values['custom_pre_id'] = $custom_pre_id;
         $values['custom_post_id'] = $custom_post_ids;
         $contribution->source = ts('Online Event Registration') . ': ' . $values['event']['title'];
         if ($values['event']['is_email_confirm']) {
             $contribution->receipt_date = self::$_now;
             $values['is_email_receipt'] = 1;
         }
         $participant->status_id = 1;
         $participant->save();
     }
     if (CRM_Utils_Array::value('net_amount', $input, 0) == 0 && CRM_Utils_Array::value('fee_amount', $input, 0) != 0) {
         $input['net_amount'] = $input['amount'] - $input['fee_amount'];
     }
     $addLineItems = FALSE;
     if (empty($contribution->id)) {
         $addLineItems = TRUE;
     }
     $contribution->contribution_status_id = 1;
     $contribution->is_test = $input['is_test'];
     $contribution->fee_amount = CRM_Utils_Array::value('fee_amount', $input, 0);
     $contribution->net_amount = CRM_Utils_Array::value('net_amount', $input, 0);
     $contribution->trxn_id = $input['trxn_id'];
     $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
     $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
     $contribution->cancel_date = 'null';
     if (CRM_Utils_Array::value('check_number', $input)) {
         $contribution->check_number = $input['check_number'];
     }
     if (CRM_Utils_Array::value('payment_instrument_id', $input)) {
         $contribution->payment_instrument_id = $input['payment_instrument_id'];
     }
     $contribution->save();
     //add lineitems for recurring payments
     if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id && $addLineItems) {
         $this->addrecurLineItems($objects['contributionRecur']->id, $contribution->id);
     }
     // next create the transaction record
     $paymentProcessor = '';
     if (isset($objects['paymentProcessor'])) {
         if (is_array($objects['paymentProcessor'])) {
             $paymentProcessor = $objects['paymentProcessor']['payment_processor_type'];
         } else {
             $paymentProcessor = $objects['paymentProcessor']->payment_processor_type;
         }
     }
     if ($contribution->trxn_id) {
         $trxnParams = array('contribution_id' => $contribution->id, 'trxn_date' => isset($input['trxn_date']) ? $input['trxn_date'] : self::$_now, 'trxn_type' => 'Debit', 'total_amount' => $input['amount'], 'fee_amount' => $contribution->fee_amount, 'net_amount' => $contribution->net_amount, 'currency' => $contribution->currency, 'payment_processor' => $paymentProcessor, 'trxn_id' => $contribution->trxn_id);
         $trxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
     }
     self::updateRecurLinkedPledge($contribution);
     // create an activity record
     if ($input['component'] == 'contribute') {
         //CRM-4027
         $targetContactID = NULL;
         if (CRM_Utils_Array::value('related_contact', $ids)) {
             $targetContactID = $contribution->contact_id;
             $contribution->contact_id = $ids['related_contact'];
         }
         CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
         // event
     } else {
         CRM_Activity_BAO_Activity::addActivity($participant);
     }
     CRM_Core_Error::debug_log_message("Contribution record updated successfully");
     $transaction->commit();
     // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
     // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
     if (!array_key_exists('is_email_receipt', $values) || $values['is_email_receipt'] == 1) {
         self::sendMail($input, $ids, $objects, $values, $recur, FALSE);
     }
     CRM_Core_Error::debug_log_message("Success: Database updated and mail sent");
 }
Example #2
0
 /**
  * Complete an order.
  *
  * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
  *
  * Currently overloaded to complete a transaction & repeat a transaction - fix!
  *
  * Moving it out of the BaseIPN class is just the first step.
  *
  * @param array $input
  * @param array $ids
  * @param array $objects
  * @param CRM_Core_Transaction $transaction
  * @param int $recur
  * @param CRM_Contribute_BAO_Contribution $contribution
  * @param bool $isRecurring
  *   Duplication of param needs review. Only used by AuthorizeNetIPN
  * @param int $isFirstOrLastRecurringPayment
  *   Deprecated param only used by AuthorizeNetIPN.
  */
 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment)
 {
     $primaryContributionID = isset($contribution->id) ? $contribution->id : $objects['first_contribution']->id;
     // The previous details are used when calculating line items so keep it before any code that 'does something'
     if (!empty($contribution->id)) {
         $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues(array('id' => $contribution->id), CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
     }
     $inputContributionWhiteList = array('fee_amount', 'net_amount', 'trxn_id', 'check_number', 'payment_instrument_id', 'is_test', 'campaign_id', 'receive_date');
     $contributionParams = array_merge(array('contribution_status_id' => 'Completed'), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)));
     $participant = CRM_Utils_Array::value('participant', $objects);
     $memberships = CRM_Utils_Array::value('membership', $objects);
     $recurContrib = CRM_Utils_Array::value('contributionRecur', $objects);
     if (!empty($recurContrib->id)) {
         $contributionParams['contribution_recur_id'] = $recurContrib->id;
     }
     self::repeatTransaction($contribution, $input, $contributionParams);
     if (is_numeric($memberships)) {
         $memberships = array($objects['membership']);
     }
     $changeDate = CRM_Utils_Array::value('trxn_date', $input, date('YmdHis'));
     $values = array();
     if (isset($input['is_email_receipt'])) {
         $values['is_email_receipt'] = $input['is_email_receipt'];
     }
     if ($input['component'] == 'contribute') {
         if ($contribution->contribution_page_id) {
             CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
             $contributionParams['source'] = ts('Online Contribution') . ': ' . $values['title'];
         } elseif ($recurContrib && $recurContrib->id) {
             $contributionParams['contribution_page_id'] = NULL;
             $values['amount'] = $recurContrib->amount;
             $values['financial_type_id'] = $objects['contributionType']->id;
             $values['title'] = $source = ts('Offline Recurring Contribution');
             $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
             $values['receipt_from_name'] = $domainValues[0];
             $values['receipt_from_email'] = $domainValues[1];
         }
         if ($recurContrib && $recurContrib->id && !isset($input['is_email_receipt'])) {
             //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
             // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
             $values['is_email_receipt'] = $recurContrib->is_email_receipt;
         }
         if (!empty($values['is_email_receipt'])) {
             $contributionParams['receipt_date'] = $changeDate;
         }
         if (!empty($memberships)) {
             foreach ($memberships as $membershipTypeIdKey => $membership) {
                 if ($membership) {
                     $membershipParams = array('id' => $membership->id, 'contact_id' => $membership->contact_id, 'is_test' => $membership->is_test, 'membership_type_id' => $membership->membership_type_id);
                     $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membershipParams['contact_id'], $membershipParams['membership_type_id'], $membershipParams['is_test'], $membershipParams['id']);
                     // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
                     // this picks up membership type changes during renewals
                     $sql = "\nSELECT    membership_type_id\nFROM      civicrm_membership_log\nWHERE     membership_id={$membershipParams['id']}\nORDER BY  id DESC\nLIMIT 1;";
                     $dao = CRM_Core_DAO::executeQuery($sql);
                     if ($dao->fetch()) {
                         if (!empty($dao->membership_type_id)) {
                             $membershipParams['membership_type_id'] = $dao->membership_type_id;
                         }
                     }
                     $dao->free();
                     $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType($membershipParams['membership_type_id'], $primaryContributionID);
                     $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
                     if ($currentMembership) {
                         /*
                          * Fixed FOR CRM-4433
                          * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
                          * when Contribution mode is notify and membership is for renewal )
                          */
                         CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
                         // @todo - we should pass membership_type_id instead of null here but not
                         // adding as not sure of testing
                         $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membershipParams['id'], $changeDate, NULL, $membershipParams['num_terms']);
                         $dates['join_date'] = $currentMembership['join_date'];
                     }
                     //get the status for membership.
                     $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', TRUE, $membershipParams['membership_type_id'], $membershipParams);
                     $membershipParams['status_id'] = CRM_Utils_Array::value('id', $calcStatus, 'New');
                     //we might be renewing membership,
                     //so make status override false.
                     $membershipParams['is_override'] = FALSE;
                     civicrm_api3('Membership', 'create', $membershipParams);
                     //update related Memberships.
                     CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $membershipParams);
                 }
             }
         }
     } else {
         if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
             $eventDetail = civicrm_api3('Event', 'getsingle', array('id' => $objects['event']->id));
             $contributionParams['source'] = ts('Online Event Registration') . ': ' . $eventDetail['title'];
             if ($eventDetail['is_email_confirm']) {
                 // @todo this should be set by the function that sends the mail after sending.
                 $contributionParams['receipt_date'] = $changeDate;
             }
             $participantParams['id'] = $participant->id;
             $participantParams['status_id'] = 'Registered';
             civicrm_api3('Participant', 'create', $participantParams);
         }
     }
     $contributionParams['id'] = $contribution->id;
     civicrm_api3('Contribution', 'create', $contributionParams);
     // Add new soft credit against current $contribution.
     if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id) {
         CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
     }
     $paymentProcessorId = '';
     if (isset($objects['paymentProcessor'])) {
         if (is_array($objects['paymentProcessor'])) {
             $paymentProcessorId = $objects['paymentProcessor']['id'];
         } else {
             $paymentProcessorId = $objects['paymentProcessor']->id;
         }
     }
     $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array('labelColumn' => 'name', 'flip' => 1));
     if (empty($input['prevContribution']) && $paymentProcessorId || !$input['prevContribution']->is_pay_later && $input['prevContribution']->contribution_status_id == $contributionStatuses['Pending']) {
         $input['payment_processor'] = $paymentProcessorId;
     }
     $input['contribution_status_id'] = $contributionStatuses['Completed'];
     $input['total_amount'] = $input['amount'];
     $input['contribution'] = $contribution;
     $input['financial_type_id'] = $contribution->financial_type_id;
     if (!empty($contribution->_relatedObjects['participant'])) {
         $input['contribution_mode'] = 'participant';
         $input['participant_id'] = $contribution->_relatedObjects['participant']->id;
         $input['skipLineItem'] = 1;
     } elseif (!empty($contribution->_relatedObjects['membership'])) {
         $input['skipLineItem'] = TRUE;
         $input['contribution_mode'] = 'membership';
     }
     //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
     // and subsequent payments. In this case the line items are created at
     // CRM_Contribute_BAO_ContributionRecur::addRecurLineItems
     // and since the contribution is saved prior to this line there is always a contribution-id,
     // however there is never a prevContribution (which appears to mean original contribution not previous
     // contribution - or preUpdateContributionObject most accurately)
     // so, this is always called & only appears to succeed when prevContribution exists - which appears
     // to mean "are we updating an exisitng pending contribution"
     //I was able to make the unit test complete as fataling here doesn't prevent
     // the contribution being created - but activities would not be created or emails sent
     CRM_Contribute_BAO_Contribution::recordFinancialAccounts($input, NULL);
     CRM_Core_Error::debug_log_message("Contribution record updated successfully");
     $transaction->commit();
     CRM_Contribute_BAO_ContributionRecur::updateRecurLinkedPledge($contribution);
     // create an activity record
     if ($input['component'] == 'contribute') {
         //CRM-4027
         $targetContactID = NULL;
         if (!empty($ids['related_contact'])) {
             $targetContactID = $contribution->contact_id;
             $contribution->contact_id = $ids['related_contact'];
         }
         CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
         // event
     } else {
         CRM_Activity_BAO_Activity::addActivity($participant);
     }
     // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
     // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
     if (!array_key_exists('is_email_receipt', $values) || $values['is_email_receipt'] == 1) {
         self::sendMail($input, $ids, $objects['contribution'], $values, $recur, FALSE);
         CRM_Core_Error::debug_log_message("Receipt sent");
     }
     CRM_Core_Error::debug_log_message("Success: Database updated");
     if ($isRecurring) {
         CRM_Contribute_BAO_ContributionRecur::sendRecurringStartOrEndNotification($ids, $recur, $isFirstOrLastRecurringPayment);
     }
 }
Example #3
0
 /**
  * Process the form submission.
  */
 public function postProcess()
 {
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     if ($this->_action & CRM_Core_Action::DELETE) {
         if (CRM_Utils_Array::value('delete_participant', $params) == 2) {
             $additionalId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
             $participantLinks = CRM_Event_BAO_Participant::getAdditionalParticipantUrl($additionalId);
         }
         if (CRM_Utils_Array::value('delete_participant', $params) == 1) {
             $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
             foreach ($additionalIds as $value) {
                 CRM_Event_BAO_Participant::deleteParticipant($value);
             }
         }
         CRM_Event_BAO_Participant::deleteParticipant($this->_id);
         CRM_Core_Session::setStatus(ts('Selected participant was deleted successfully.'), ts('Record Deleted'), 'success');
         if (!empty($participantLinks)) {
             $status = ts('The following participants no longer have an event fee recorded. You can edit their registration and record a replacement contribution by clicking the links below:') . '<br/>' . $participantLinks;
             CRM_Core_Session::setStatus($status, ts('Group Payment Deleted'));
         }
         return;
     }
     // When adding a single contact, the formRule prevents you from adding duplicates
     // (See above in formRule()). When adding more than one contact, the duplicates are
     // removed automatically and the user receives one notification.
     if ($this->_action & CRM_Core_Action::ADD) {
         $event_id = $this->_eventId;
         if (empty($event_id) && !empty($params['event_id'])) {
             $event_id = $params['event_id'];
         }
         if (!$this->_single && !empty($event_id)) {
             $duplicateContacts = 0;
             while (list($k, $dupeCheckContactId) = each($this->_contactIds)) {
                 // Eliminate contacts that have already been assigned to this event.
                 $dupeCheck = new CRM_Event_BAO_Participant();
                 $dupeCheck->contact_id = $dupeCheckContactId;
                 $dupeCheck->event_id = $event_id;
                 $dupeCheck->find(TRUE);
                 if (!empty($dupeCheck->id)) {
                     $duplicateContacts++;
                     unset($this->_contactIds[$k]);
                 }
             }
             if ($duplicateContacts > 0) {
                 $msg = ts("%1 contacts have already been assigned to this event. They were not added a second time.", array(1 => $duplicateContacts));
                 CRM_Core_Session::setStatus($msg);
             }
             if (count($this->_contactIds) == 0) {
                 CRM_Core_Session::setStatus(ts("No participants were added."));
                 return;
             }
             // We have to re-key $this->_contactIds so each contact has the same
             // key as their corresponding record in the $participants array that
             // will be created below.
             $this->_contactIds = array_values($this->_contactIds);
         }
     }
     $participantStatus = CRM_Event_PseudoConstant::participantStatus();
     // set the contact, when contact is selected
     if (!empty($params['contact_id'])) {
         $this->_contactId = $params['contact_id'];
     }
     if ($this->_priceSetId && ($isQuickConfig = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'is_quick_config'))) {
         $this->_quickConfig = $isQuickConfig;
     }
     if ($this->_id) {
         $params['id'] = $this->_id;
     }
     $config = CRM_Core_Config::singleton();
     if ($this->_isPaidEvent) {
         $contributionParams = array();
         $lineItem = array();
         $additionalParticipantDetails = array();
         if (CRM_Contribute_BAO_Contribution::checkContributeSettings('deferred_revenue_enabled')) {
             $eventStartDate = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $this->_eventId, 'start_date');
             if ($eventStartDate) {
                 $contributionParams['revenue_recognition_date'] = date('Ymd', strtotime($eventStartDate));
             }
         }
         if ($this->_id && $this->_action & CRM_Core_Action::UPDATE && $this->_paymentId) {
             $participantBAO = new CRM_Event_BAO_Participant();
             $participantBAO->id = $this->_id;
             $participantBAO->find(TRUE);
             $contributionParams['total_amount'] = $participantBAO->fee_amount;
             $params['discount_id'] = NULL;
             //re-enter the values for UPDATE mode
             $params['fee_level'] = $params['amount_level'] = $participantBAO->fee_level;
             $params['fee_amount'] = $participantBAO->fee_amount;
             if (isset($params['priceSetId'])) {
                 $lineItem[0] = CRM_Price_BAO_LineItem::getLineItems($this->_id);
             }
             //also add additional participant's fee level/priceset
             if (CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
                 $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
                 $hasLineItems = CRM_Utils_Array::value('priceSetId', $params, FALSE);
                 $additionalParticipantDetails = CRM_Event_BAO_Participant::getFeeDetails($additionalIds, $hasLineItems);
             }
         } else {
             //check if discount is selected
             if (!empty($params['discount_id'])) {
                 $discountId = $params['discount_id'];
             } else {
                 $discountId = $params['discount_id'] = 'null';
             }
             //lets carry currency, CRM-4453
             $params['fee_currency'] = $config->defaultCurrency;
             CRM_Price_BAO_PriceSet::processAmount($this->_values['fee'], $params, $lineItem[0]);
             //CRM-11529 for quick config backoffice transactions
             //when financial_type_id is passed in form, update the
             //lineitems with the financial type selected in form
             $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $params);
             $isPaymentRecorded = CRM_Utils_Array::value('record_contribution', $params);
             if ($isPaymentRecorded && $this->_quickConfig && $submittedFinancialType) {
                 foreach ($lineItem[0] as &$values) {
                     $values['financial_type_id'] = $submittedFinancialType;
                 }
             }
             $params['fee_level'] = $params['amount_level'];
             $contributionParams['total_amount'] = $params['amount'];
             if ($this->_quickConfig && !empty($params['total_amount']) && $params['status_id'] != array_search('Partially paid', $participantStatus)) {
                 $params['fee_amount'] = $params['total_amount'];
             } else {
                 //fix for CRM-3086
                 $params['fee_amount'] = $params['amount'];
             }
         }
         if (isset($params['priceSetId'])) {
             if (!empty($lineItem[0])) {
                 $this->set('lineItem', $lineItem);
                 $this->_lineItem = $lineItem;
                 $lineItem = array_merge($lineItem, $additionalParticipantDetails);
                 $participantCount = array();
                 foreach ($lineItem as $k) {
                     foreach ($k as $v) {
                         if (CRM_Utils_Array::value('participant_count', $v) > 0) {
                             $participantCount[] = $v['participant_count'];
                         }
                     }
                 }
             }
             if (isset($participantCount)) {
                 $this->assign('pricesetFieldsCount', $participantCount);
             }
             $this->assign('lineItem', empty($lineItem[0]) || $this->_quickConfig ? FALSE : $lineItem);
         } else {
             $this->assign('amount_level', $params['amount_level']);
         }
     }
     $this->_params = $params;
     $amountOwed = NULL;
     if (isset($params['amount'])) {
         $amountOwed = $params['amount'];
         unset($params['amount']);
     }
     $params['register_date'] = CRM_Utils_Date::processDate($params['register_date'], $params['register_date_time']);
     $params['receive_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $params), CRM_Utils_Array::value('receive_date_time', $params));
     $params['contact_id'] = $this->_contactId;
     // overwrite actual payment amount if entered
     if (!empty($params['total_amount'])) {
         $contributionParams['total_amount'] = CRM_Utils_Array::value('total_amount', $params);
     }
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     $userName = CRM_Core_Session::singleton()->getLoggedInContactDisplayName();
     if ($this->_contactId) {
         list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_contactId);
     }
     //modify params according to parameter used in create
     //participant method (addParticipant)
     $this->_params['participant_status_id'] = $params['status_id'];
     $this->_params['participant_role_id'] = is_array($params['role_id']) ? $params['role_id'] : explode(',', $params['role_id']);
     $this->_params['participant_register_date'] = $params['register_date'];
     $roleIdWithSeparator = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['participant_role_id']);
     if ($this->_mode) {
         if (!$this->_isPaidEvent) {
             CRM_Core_Error::fatal(ts('Selected Event is not Paid Event '));
         }
         $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         // set source if not set
         if (empty($params['source'])) {
             $this->_params['participant_source'] = ts('Offline Registration for Event: %2 by: %1', array(1 => $userName, 2 => $eventTitle));
         } else {
             $this->_params['participant_source'] = $params['source'];
         }
         $this->_params['description'] = $this->_params['participant_source'];
         $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode);
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields['email-Primary'] = 1;
         $params['email-Primary'] = $params["email-{$this->_bltID}"] = $this->_contributorEmail;
         $params['register_date'] = $now;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
         $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         $fields["email-{$this->_bltID}"] = 1;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $params)) {
                 $params[$name] = $params["billing_{$name}"];
                 $params['preserveDBName'] = TRUE;
             }
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactId, NULL, NULL, $ctype);
     }
     if (!empty($this->_params['participant_role_id'])) {
         $customFieldsRole = array();
         foreach ($this->_params['participant_role_id'] as $roleKey) {
             $customFieldsRole = CRM_Utils_Array::crmArrayMerge(CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, $roleKey, $this->_roleCustomDataTypeID), $customFieldsRole);
         }
         $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, CRM_Utils_Array::value('event_id', $params), $this->_eventNameCustomDataTypeID);
         $customFieldsEventType = CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, $this->_eventTypeId, $this->_eventTypeCustomDataTypeID);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole, CRM_Core_BAO_CustomField::getFields('Participant', FALSE, FALSE, NULL, NULL, TRUE));
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
         $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEventType, $customFields);
         $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->_id, 'Participant');
     }
     //do cleanup line  items if participant edit the Event Fee.
     if (($this->_lineItem || !isset($params['proceSetId'])) && !$this->_paymentId && $this->_id) {
         CRM_Price_BAO_LineItem::deleteLineItems($this->_id, 'civicrm_participant');
     }
     if ($this->_mode) {
         // add all the additional payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
         $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $params['fee_amount'];
         $this->_params['amount_level'] = $params['amount_level'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
         // at this point we've created a contact and stored its address etc
         // all the payment processors expect the name and address to be in the
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         if (!empty($this->_params['send_receipt'])) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         // The only reason for merging in the 'contact_id' rather than ensuring it is set
         // is that this patch is being done around the time of the stable release
         // so more conservative approach is called for.
         // In fact the use of $params and $this->_params & $this->_contactId vs $contactID
         // needs rationalising.
         $mapParams = array_merge(array('contact_id' => $contactID), $this->_params);
         CRM_Core_Payment_Form::mapParams($this->_bltID, $mapParams, $paymentParams, TRUE);
         $payment = $this->_paymentProcessor['object'];
         // CRM-15622: fix for incorrect contribution.fee_amount
         $paymentParams['fee_amount'] = NULL;
         $result = $payment->doPayment($paymentParams);
         if (is_a($result, 'CRM_Core_Error')) {
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&cid={$this->_contactId}&context=participant&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $this->_params['receive_date'] = $now;
         if (!empty($this->_params['send_receipt'])) {
             $this->_params['receipt_date'] = $now;
         } else {
             $this->_params['receipt_date'] = NULL;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
         $this->assign('receive_date', CRM_Utils_Date::processDate($this->_params['receive_date']));
         //add contribution record
         $this->_params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'financial_type_id');
         $this->_params['mode'] = $this->_mode;
         //add contribution record
         $contributions[] = $contribution = CRM_Event_Form_Registration_Confirm::processContribution($this, $this->_params, $result, $contactID, FALSE);
         // add participant record
         $participants = array();
         if (!empty($this->_params['role_id']) && is_array($this->_params['role_id'])) {
             $this->_params['role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_params['role_id']);
         }
         //CRM-15372 patch to fix fee amount replacing amount
         $this->_params['fee_amount'] = $this->_params['amount'];
         $participants[] = CRM_Event_Form_Registration::addParticipant($this, $contactID);
         //add custom data for participant
         CRM_Core_BAO_CustomValueTable::postProcess($this->_params, 'civicrm_participant', $participants[0]->id, 'Participant');
         //add participant payment
         $paymentParticipant = array('participant_id' => $participants[0]->id, 'contribution_id' => $contribution->id);
         $ids = array();
         CRM_Event_BAO_ParticipantPayment::create($paymentParticipant, $ids);
         $this->_contactIds[] = $this->_contactId;
     } else {
         $participants = array();
         if ($this->_single) {
             if ($params['role_id']) {
                 $params['role_id'] = $roleIdWithSeparator;
             } else {
                 $params['role_id'] = 'NULL';
             }
             $participants[] = CRM_Event_BAO_Participant::create($params);
         } else {
             foreach ($this->_contactIds as $contactID) {
                 $commonParams = $params;
                 $commonParams['contact_id'] = $contactID;
                 if ($commonParams['role_id']) {
                     $commonParams['role_id'] = $commonParams['role_id'] = str_replace(',', CRM_Core_DAO::VALUE_SEPARATOR, $params['role_id']);
                 } else {
                     $commonParams['role_id'] = 'NULL';
                 }
                 $participants[] = CRM_Event_BAO_Participant::create($commonParams);
             }
         }
         if (isset($params['event_id'])) {
             $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         }
         if ($this->_single) {
             $this->_contactIds[] = $this->_contactId;
         }
         $contributions = array();
         if (!empty($params['record_contribution'])) {
             if (!empty($params['id'])) {
                 if ($this->_onlinePendingContributionId) {
                     $ids['contribution'] = $this->_onlinePendingContributionId;
                 } else {
                     $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $params['id'], 'contribution_id', 'participant_id');
                 }
             }
             unset($params['note']);
             //build contribution params
             if (!$this->_onlinePendingContributionId) {
                 if (empty($params['source'])) {
                     $contributionParams['source'] = ts('%1 : Offline registration (by %2)', array(1 => $eventTitle, 2 => $userName));
                 } else {
                     $contributionParams['source'] = $params['source'];
                 }
             }
             $contributionParams['currency'] = $config->defaultCurrency;
             $contributionParams['non_deductible_amount'] = 'null';
             $contributionParams['receipt_date'] = !empty($params['send_receipt']) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
             $recordContribution = array('contact_id', 'financial_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'receive_date', 'check_number', 'campaign_id');
             foreach ($recordContribution as $f) {
                 $contributionParams[$f] = CRM_Utils_Array::value($f, $params);
                 if ($f == 'trxn_id') {
                     $this->assign('trxn_id', $contributionParams[$f]);
                 }
             }
             //insert financial type name in receipt.
             $this->assign('financialTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionParams['financial_type_id']));
             // legacy support
             $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $contributionParams['financial_type_id']));
             $contributionParams['skipLineItem'] = 1;
             if ($this->_id) {
                 $contributionParams['contribution_mode'] = 'participant';
                 $contributionParams['participant_id'] = $this->_id;
             }
             // Set is_pay_later flag for back-office offline Pending status contributions
             if ($contributionParams['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Pending', 'name')) {
                 $contributionParams['is_pay_later'] = 1;
             } elseif ($contributionParams['contribution_status_id'] == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
                 $contributionParams['is_pay_later'] = 0;
             }
             if ($params['status_id'] == array_search('Partially paid', $participantStatus)) {
                 if (!$amountOwed && $this->_action & CRM_Core_Action::UPDATE) {
                     $amountOwed = $params['fee_amount'];
                 }
                 // if multiple participants are link, consider contribution total amount as the amount Owed
                 if ($this->_id && CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
                     $amountOwed = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $ids['contribution'], 'total_amount');
                 }
                 // CRM-13964 partial_payment_total
                 if ($amountOwed > $params['total_amount']) {
                     // the owed amount
                     $contributionParams['partial_payment_total'] = $amountOwed;
                     // the actual amount paid
                     $contributionParams['partial_amount_pay'] = $params['total_amount'];
                 }
             }
             if (CRM_Utils_Array::value('tax_amount', $this->_params)) {
                 $contributionParams['tax_amount'] = $this->_params['tax_amount'];
             }
             if ($this->_single) {
                 if (empty($ids)) {
                     $ids = array();
                 }
                 $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
             } else {
                 $ids = array();
                 foreach ($this->_contactIds as $contactID) {
                     $contributionParams['contact_id'] = $contactID;
                     $contributions[] = CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
                 }
             }
             //insert payment record for this participation
             if (empty($ids['contribution'])) {
                 foreach ($this->_contactIds as $num => $contactID) {
                     $ppDAO = new CRM_Event_DAO_ParticipantPayment();
                     $ppDAO->participant_id = $participants[$num]->id;
                     $ppDAO->contribution_id = $contributions[$num]->id;
                     $ppDAO->save();
                 }
             }
             // next create the transaction record
             $transaction = new CRM_Core_Transaction();
             // CRM-11124
             if ($this->_params['discount_id']) {
                 CRM_Event_BAO_Participant::createDiscountTrxn($this->_eventId, $contributionParams, NULL, CRM_Price_BAO_PriceSet::parseFirstPriceSetValueIDFromParams($this->_params));
             }
             $transaction->commit();
         }
     }
     // also store lineitem stuff here
     if ($this->_lineItem & $this->_action & CRM_Core_Action::ADD || $this->_lineItem && CRM_Core_Action::UPDATE && !$this->_paymentId) {
         foreach ($this->_contactIds as $num => $contactID) {
             foreach ($this->_lineItem as $key => $value) {
                 if (is_array($value) && $value != 'skip') {
                     foreach ($value as $lineKey => $line) {
                         //10117 update the line items for participants if contribution amount is recorded
                         if ($this->_quickConfig && !empty($params['total_amount']) && $params['status_id'] != array_search('Partially paid', $participantStatus)) {
                             $line['unit_price'] = $line['line_total'] = $params['total_amount'];
                             if (!empty($params['tax_amount'])) {
                                 $line['unit_price'] = $line['unit_price'] - $params['tax_amount'];
                                 $line['line_total'] = $line['line_total'] - $params['tax_amount'];
                             }
                         }
                         $lineItem[$this->_priceSetId][$lineKey] = $line;
                     }
                     CRM_Price_BAO_LineItem::processPriceSet($participants[$num]->id, $lineItem, CRM_Utils_Array::value($num, $contributions, NULL), 'civicrm_participant');
                     CRM_Contribute_BAO_Contribution::addPayments($value, $contributions);
                 }
             }
         }
     }
     $updateStatusMsg = NULL;
     //send mail when participant status changed, CRM-4326
     if ($this->_id && $this->_statusId && $this->_statusId != CRM_Utils_Array::value('status_id', $params) && !empty($params['is_notify'])) {
         $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_id, $params['status_id'], $this->_statusId);
     }
     $sent = array();
     $notSent = array();
     if (!empty($params['send_receipt'])) {
         if (array_key_exists($params['from_email_address'], $this->_fromEmails['from_email_id'])) {
             $receiptFrom = $params['from_email_address'];
         }
         $this->assign('module', 'Event Registration');
         //use of the message template below requires variables in different format
         $event = $events = array();
         $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
         //get all event details.
         CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
         $event = $events[$params['event_id']];
         unset($event['start_date']);
         unset($event['end_date']);
         $role = CRM_Event_PseudoConstant::participantRole();
         $participantRoles = CRM_Utils_Array::value('role_id', $params);
         if (is_array($participantRoles)) {
             $selectedRoles = array();
             foreach ($participantRoles as $roleId) {
                 $selectedRoles[] = $role[$roleId];
             }
             $event['participant_role'] = implode(', ', $selectedRoles);
         } else {
             $event['participant_role'] = CRM_Utils_Array::value($participantRoles, $role);
         }
         $event['is_monetary'] = $this->_isPaidEvent;
         if ($params['receipt_text']) {
             $event['confirm_email_text'] = $params['receipt_text'];
         }
         $this->assign('isAmountzero', 1);
         $this->assign('event', $event);
         $this->assign('isShowLocation', $event['is_show_location']);
         if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
             $locationParams = array('entity_id' => $params['event_id'], 'entity_table' => 'civicrm_event');
             $location = CRM_Core_BAO_Location::getValues($locationParams, TRUE);
             $this->assign('location', $location);
         }
         $status = CRM_Event_PseudoConstant::participantStatus();
         if ($this->_isPaidEvent) {
             $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
             if (!$this->_mode) {
                 if (isset($params['payment_instrument_id'])) {
                     $this->assign('paidBy', CRM_Utils_Array::value($params['payment_instrument_id'], $paymentInstrument));
                 }
             }
             $this->assign('totalAmount', $contributionParams['total_amount']);
             if (isset($contributionParams['partial_payment_total'])) {
                 // balance amount
                 $balanceAmount = $contributionParams['partial_payment_total'] - $contributionParams['partial_amount_pay'];
                 $this->assign('balanceAmount', $balanceAmount);
             }
             $this->assign('isPrimary', 1);
             $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
         }
         if ($this->_mode) {
             if (!empty($params['billing_first_name'])) {
                 $name = $params['billing_first_name'];
             }
             if (!empty($params['billing_middle_name'])) {
                 $name .= " {$params['billing_middle_name']}";
             }
             if (!empty($params['billing_last_name'])) {
                 $name .= " {$params['billing_last_name']}";
             }
             $this->assign('billingName', $name);
             // assign the address formatted up for display
             $addressParts = array("street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "state_province-{$this->_bltID}", "country-{$this->_bltID}");
             $addressFields = array();
             foreach ($addressParts as $part) {
                 list($n, $id) = explode('-', $part);
                 if (isset($this->_params['billing_' . $part])) {
                     $addressFields[$n] = $this->_params['billing_' . $part];
                 }
             }
             $this->assign('address', CRM_Utils_Address::format($addressFields));
             $date = CRM_Utils_Date::format($params['credit_card_exp_date']);
             $date = CRM_Utils_Date::mysqlToIso($date);
             $this->assign('credit_card_exp_date', $date);
             $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($params['credit_card_number']));
             $this->assign('credit_card_type', $params['credit_card_type']);
             // The concept of contributeMode is deprecated.
             $this->assign('contributeMode', 'direct');
             $this->assign('isAmountzero', 0);
             $this->assign('is_pay_later', 0);
             $this->assign('isPrimary', 1);
         }
         $this->assign('register_date', $params['register_date']);
         if ($params['receive_date']) {
             $this->assign('receive_date', $params['receive_date']);
         }
         $participant = array(array('participant_id', '=', $participants[0]->id, 0, 0));
         // check whether its a test drive ref CRM-3075
         if (!empty($this->_defaultValues['is_test'])) {
             $participant[] = array('participant_test', '=', 1, 0, 0);
         }
         $template = CRM_Core_Smarty::singleton();
         $customGroup = array();
         //format submitted data
         foreach ($params['custom'] as $fieldID => $values) {
             foreach ($values as $fieldValue) {
                 $customFields[$fieldID]['id'] = $fieldID;
                 $formattedValue = CRM_Core_BAO_CustomField::displayValue($fieldValue['value'], $fieldID, $participants[0]->id);
                 $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
             }
         }
         foreach ($this->_contactIds as $num => $contactID) {
             // Retrieve the name and email of the contact - this will be the TO for receipt email
             list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
             $this->_contributorDisplayName = $this->_contributorDisplayName == ' ' ? $this->_contributorEmail : $this->_contributorDisplayName;
             $waitStatus = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
             if ($waitingStatus = CRM_Utils_Array::value($params['status_id'], $waitStatus)) {
                 $this->assign('isOnWaitlist', TRUE);
             }
             $this->assign('customGroup', $customGroup);
             $this->assign('contactID', $contactID);
             $this->assign('participantID', $participants[$num]->id);
             $this->_id = $participants[$num]->id;
             if ($this->_isPaidEvent) {
                 // fix amount for each of participants ( for bulk mode )
                 $eventAmount = array();
                 $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
                 $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
                 $totalTaxAmount = 0;
                 //add dataArray in the receipts in ADD and UPDATE condition
                 $dataArray = array();
                 if ($this->_action & CRM_Core_Action::ADD) {
                     $line = $lineItem[0];
                 } elseif ($this->_action & CRM_Core_Action::UPDATE) {
                     $line = $this->_values['line_items'];
                 }
                 if ($invoicing) {
                     foreach ($line as $key => $value) {
                         if (isset($value['tax_amount'])) {
                             $totalTaxAmount += $value['tax_amount'];
                             if (isset($dataArray[(string) $value['tax_rate']])) {
                                 $dataArray[(string) $value['tax_rate']] = $dataArray[(string) $value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
                             } else {
                                 $dataArray[(string) $value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
                             }
                         }
                     }
                     $this->assign('totalTaxAmount', $totalTaxAmount);
                     $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
                     $this->assign('dataArray', $dataArray);
                 }
                 if (!empty($additionalParticipantDetails)) {
                     $params['amount_level'] = preg_replace('//', '', $params['amount_level']) . ' - ' . $this->_contributorDisplayName;
                 }
                 $eventAmount[$num] = array('label' => preg_replace('//', '', $params['amount_level']), 'amount' => $params['fee_amount']);
                 //as we are using same template for online & offline registration.
                 //So we have to build amount as array.
                 $eventAmount = array_merge($eventAmount, $additionalParticipantDetails);
                 $this->assign('amount', $eventAmount);
             }
             $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'event_offline_receipt', 'contactId' => $contactID, 'isTest' => !empty($this->_defaultValues['is_test']), 'PDFFilename' => ts('confirmation') . '.pdf');
             // try to send emails only if email id is present
             // and the do-not-email option is not checked for that contact
             if ($this->_contributorEmail and !$this->_toDoNotEmail) {
                 $sendTemplateParams['from'] = $receiptFrom;
                 $sendTemplateParams['toName'] = $this->_contributorDisplayName;
                 $sendTemplateParams['toEmail'] = $this->_contributorEmail;
                 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc', $this->_fromEmails);
                 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc', $this->_fromEmails);
             }
             //send email with pdf invoice
             $template = CRM_Core_Smarty::singleton();
             $taxAmt = $template->get_template_vars('dataArray');
             $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $this->_id, 'contribution_id', 'participant_id');
             $prefixValue = Civi::settings()->get('contribution_invoice_settings');
             $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
             if (count($taxAmt) > 0 && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
                 $sendTemplateParams['isEmailPdf'] = TRUE;
                 $sendTemplateParams['contributionId'] = $contributionId;
             }
             list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
             if ($mailSent) {
                 $sent[] = $contactID;
                 foreach ($participants as $ids => $values) {
                     if ($values->contact_id == $contactID) {
                         $values->details = CRM_Utils_Array::value('receipt_text', $params);
                         CRM_Activity_BAO_Activity::addActivity($values, 'Email');
                         break;
                     }
                 }
             } else {
                 $notSent[] = $contactID;
             }
         }
     }
     // set the participant id if it is not set
     if (!$this->_id) {
         $this->_id = $participants[0]->id;
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contributorDisplayName));
         if (!empty($params['send_receipt']) && count($sent)) {
             $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', array(1 => $this->_contributorEmail));
         }
         if ($updateStatusMsg) {
             $statusMsg = "{$statusMsg} {$updateStatusMsg}";
         }
     } elseif ($this->_action & CRM_Core_Action::ADD) {
         if ($this->_single) {
             $statusMsg = ts('Event registration for %1 has been added.', array(1 => $this->_contributorDisplayName));
             if (!empty($params['send_receipt']) && count($sent)) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $this->_contributorEmail));
             }
         } else {
             $statusMsg = ts('Total Participant(s) added to event: %1.', array(1 => count($this->_contactIds)));
             if (count($notSent) > 0) {
                 $statusMsg .= ' ' . ts('Email has NOT been sent to %1 contact(s) - communication preferences specify DO NOT EMAIL OR valid Email is NOT present. ', array(1 => count($notSent)));
             } elseif (isset($params['send_receipt'])) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to ALL participants');
             }
         }
     }
     CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
     $session = CRM_Core_Session::singleton();
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $urlParams = 'reset=1&action=add&context=standalone';
             if ($this->_mode) {
                 $urlParams .= '&mode=' . $this->_mode;
             }
             if ($this->_eID) {
                 $urlParams .= '&eid=' . $this->_eID;
             }
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', $urlParams));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactId}&selectedChild=participant"));
         }
     } elseif ($buttonName == $this->getButtonName('upload', 'new')) {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&context={$this->_context}&cid={$this->_contactId}"));
     }
 }
Example #4
0
 /**
  * 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;
 }
Example #5
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;
 }
 function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = FALSE)
 {
     $contribution =& $objects['contribution'];
     $primaryContributionID = isset($contribution->id) ? $contribution->id : $objects['first_contribution']->id;
     $memberships =& $objects['membership'];
     if (is_numeric($memberships)) {
         $memberships = array($objects['membership']);
     }
     $participant =& $objects['participant'];
     $event =& $objects['event'];
     $changeToday = CRM_Utils_Array::value('trxn_date', $input, self::$_now);
     $recurContrib =& $objects['contributionRecur'];
     $values = array();
     if (isset($input['is_email_receipt'])) {
         $values['is_email_receipt'] = $input['is_email_receipt'];
     }
     $source = NULL;
     if ($input['component'] == 'contribute') {
         if ($contribution->contribution_page_id) {
             CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
             $source = ts('Online Contribution') . ': ' . $values['title'];
         } elseif ($recurContrib && $recurContrib->id) {
             $contribution->contribution_page_id = NULL;
             $values['amount'] = $recurContrib->amount;
             $values['financial_type_id'] = $objects['contributionType']->id;
             $values['title'] = $source = ts('Offline Recurring Contribution');
             $domainValues = CRM_Core_BAO_Domain::getNameAndEmail();
             $values['receipt_from_name'] = $domainValues[0];
             $values['receipt_from_email'] = $domainValues[1];
         }
         if ($recurContrib && $recurContrib->id && !isset($input['is_email_receipt'])) {
             //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
             // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
             $values['is_email_receipt'] = $recurContrib->is_email_receipt;
         }
         $contribution->source = $source;
         if (CRM_Utils_Array::value('is_email_receipt', $values)) {
             $contribution->receipt_date = self::$_now;
         }
         if (!empty($memberships)) {
             $membershipsUpdate = array();
             foreach ($memberships as $membershipTypeIdKey => $membership) {
                 if ($membership) {
                     $format = '%Y%m%d';
                     $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, $membership->membership_type_id, $membership->is_test, $membership->id);
                     // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
                     // this picks up membership type changes during renewals
                     $sql = "\nSELECT    membership_type_id\nFROM      civicrm_membership_log\nWHERE     membership_id={$membership->id}\nORDER BY  id DESC\nLIMIT 1;";
                     $dao = new CRM_Core_DAO();
                     $dao->query($sql);
                     if ($dao->fetch()) {
                         if (!empty($dao->membership_type_id)) {
                             $membership->membership_type_id = $dao->membership_type_id;
                             $membership->save();
                         }
                         // else fall back to using current membership type
                     }
                     // else fall back to using current membership type
                     $dao->free();
                     $num_terms = $contribution->getNumTermsByContributionAndMembershipType($membership->membership_type_id, $primaryContributionID);
                     if ($currentMembership) {
                         /*
                          * Fixed FOR CRM-4433
                          * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
                          * when Contribution mode is notify and membership is for renewal )
                          */
                         CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
                         // @todo - we should pass membership_type_id instead of null here but not
                         // adding as not sure of testing
                         $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, $changeToday, NULL, $num_terms);
                         $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
                     } else {
                         $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, NULL, NULL, NULL, $num_terms);
                     }
                     //get the status for membership.
                     $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', TRUE, $membership->membership_type_id, (array) $membership);
                     $formatedParams = array('status_id' => CRM_Utils_Array::value('id', $calcStatus, 2), 'join_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('join_date', $dates), $format), 'start_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('start_date', $dates), $format), 'end_date' => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('end_date', $dates), $format));
                     //we might be renewing membership,
                     //so make status override false.
                     $formatedParams['is_override'] = FALSE;
                     $membership->copyValues($formatedParams);
                     $membership->save();
                     //updating the membership log
                     $membershipLog = array();
                     $membershipLog = $formatedParams;
                     $logStartDate = $formatedParams['start_date'];
                     if (CRM_Utils_Array::value('log_start_date', $dates)) {
                         $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
                         $logStartDate = CRM_Utils_Date::isoToMysql($logStartDate);
                     }
                     $membershipLog['start_date'] = $logStartDate;
                     $membershipLog['membership_id'] = $membership->id;
                     $membershipLog['modified_id'] = $membership->contact_id;
                     $membershipLog['modified_date'] = date('Ymd');
                     $membershipLog['membership_type_id'] = $membership->membership_type_id;
                     CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
                     //update related Memberships.
                     CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams);
                     //update the membership type key of membership relatedObjects array
                     //if it has changed after membership update
                     if ($membershipTypeIdKey != $membership->membership_type_id) {
                         $membershipsUpdate[$membership->membership_type_id] = $membership;
                         $contribution->_relatedObjects['membership'][$membership->membership_type_id] = $membership;
                         unset($contribution->_relatedObjects['membership'][$membershipTypeIdKey]);
                         unset($memberships[$membershipTypeIdKey]);
                     }
                 }
             }
             //update the memberships object with updated membershipTypeId data
             //if membershipTypeId has changed after membership update
             if (!empty($membershipsUpdate)) {
                 $memberships = $memberships + $membershipsUpdate;
             }
         }
     } else {
         // event
         $eventParams = array('id' => $objects['event']->id);
         $values['event'] = array();
         CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
         //get location details
         $locationParams = array('entity_id' => $objects['event']->id, 'entity_table' => 'civicrm_event');
         $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
         $ufJoinParams = array('entity_table' => 'civicrm_event', 'entity_id' => $ids['event'], 'module' => 'CiviEvent');
         list($custom_pre_id, $custom_post_ids) = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
         $values['custom_pre_id'] = $custom_pre_id;
         $values['custom_post_id'] = $custom_post_ids;
         //for tasks 'Change Participant Status' and 'Batch Update Participants Via Profile' case
         //and cases involving status updation through ipn
         $values['totalAmount'] = $input['amount'];
         $contribution->source = ts('Online Event Registration') . ': ' . $values['event']['title'];
         if ($values['event']['is_email_confirm']) {
             $contribution->receipt_date = self::$_now;
             $values['is_email_receipt'] = 1;
         }
         if (!CRM_Utils_Array::value('skipComponentSync', $input)) {
             $participant->status_id = 1;
         }
         $participant->save();
     }
     if (CRM_Utils_Array::value('net_amount', $input, 0) == 0 && CRM_Utils_Array::value('fee_amount', $input, 0) != 0) {
         $input['net_amount'] = $input['amount'] - $input['fee_amount'];
     }
     // This complete transaction function is being overloaded to create new contributions too.
     // here we record if it is a new contribution.
     // @todo separate the 2 more appropriately.
     $isNewContribution = FALSE;
     if (empty($contribution->id)) {
         $isNewContribution = TRUE;
         if (!empty($input['amount']) && $input['amount'] != $contribution->total_amount) {
             $contribution->total_amount = $input['amount'];
             // The BAO does this stuff but we are actually kinda bypassing it here (bad code! go sit in the corner)
             // so we have to handle net_amount in this (naughty) code.
             if (isset($input['fee_amount']) && is_numeric($input['fee_amount'])) {
                 $contribution->fee_amount = $input['fee_amount'];
             }
             $contribution->net_amount = $contribution->total_amount - $contribution->fee_amount;
         }
         if (!empty($input['campaign_id'])) {
             $contribution->campaign_id = $input['campaign_id'];
         }
     }
     $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array('labelColumn' => 'name', 'flip' => 1));
     // @todo this section should call the api  in order to have hooks called &
     // because all this 'messiness' setting variables could be avoided
     // by letting the api resolve pseudoconstants & copy set values and format dates.
     $contribution->contribution_status_id = $contributionStatuses['Completed'];
     $contribution->is_test = $input['is_test'];
     // CRM-15960 If we don't have a value we 'want' for the amounts, leave it to the BAO to sort out.
     if (isset($input['net_amount'])) {
         $contribution->fee_amount = CRM_Utils_Array::value('fee_amount', $input, 0);
     }
     if (isset($input['net_amount'])) {
         $contribution->net_amount = $input['net_amount'];
     }
     $contribution->trxn_id = $input['trxn_id'];
     $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
     $contribution->thankyou_date = CRM_Utils_Date::isoToMysql($contribution->thankyou_date);
     $contribution->receipt_date = CRM_Utils_Date::isoToMysql($contribution->receipt_date);
     $contribution->cancel_date = 'null';
     if (CRM_Utils_Array::value('check_number', $input)) {
         $contribution->check_number = $input['check_number'];
     }
     if (CRM_Utils_Array::value('payment_instrument_id', $input)) {
         $contribution->payment_instrument_id = $input['payment_instrument_id'];
     }
     if (!empty($contribution->id)) {
         $contributionId['id'] = $contribution->id;
         $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues($contributionId, CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
     }
     $contribution->save();
     //add line items for recurring payments
     if (!empty($contribution->contribution_recur_id)) {
         if ($isNewContribution) {
             $input['line_item'] = $this->addRecurLineItems($contribution->contribution_recur_id, $contribution);
         } else {
             // this is just to prevent e-notices when we call recordFinancialAccounts - per comments on that line - intention is somewhat unclear
             $input['line_item'] = array();
         }
         if (!empty($memberships) && $primaryContributionID != $contribution->id) {
             foreach ($memberships as $membership) {
                 try {
                     $membershipPayment = array('membership_id' => $membership->id, 'contribution_id' => $contribution->id);
                     if (!civicrm_api3('membership_payment', 'getcount', $membershipPayment)) {
                         civicrm_api3('membership_payment', 'create', $membershipPayment);
                     }
                 } catch (CiviCRM_API3_Exception $e) {
                     echo $e->getMessage();
                     // we are catching & ignoring errors as an extra precaution since lost IPNs may be more serious that lost membership_payment data
                     // this fn is unit-tested so risk of changes elsewhere breaking it are otherwise mitigated
                 }
             }
         }
     }
     //copy initial contribution custom fields for recurring contributions
     if ($recurContrib && $recurContrib->id) {
         $this->copyCustomValues($recurContrib->id, $contribution->id);
     }
     // next create the transaction record
     $paymentProcessor = $paymentProcessorId = '';
     if (isset($objects['paymentProcessor'])) {
         if (is_array($objects['paymentProcessor'])) {
             $paymentProcessor = $objects['paymentProcessor']['payment_processor_type'];
             $paymentProcessorId = $objects['paymentProcessor']['id'];
         } else {
             $paymentProcessor = $objects['paymentProcessor']->payment_processor_type;
             $paymentProcessorId = $objects['paymentProcessor']->id;
         }
     }
     //it's hard to see how it could reach this point without a contributon id as it is saved in line 511 above
     // which raised the question as to whether this check preceded line 511 & if so whether something could be broken
     // From a lot of code reading /debugging I'm still not sure the intent WRT first & subsequent payments in this code
     // it would be good if someone added some comments or refactored this
     if ($contribution->id) {
         $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
         if (empty($input['prevContribution']) && $paymentProcessorId || !$input['prevContribution']->is_pay_later && $input['prevContribution']->contribution_status_id == array_search('Pending', $contributionStatuses)) {
             $input['payment_processor'] = $paymentProcessorId;
         }
         $input['contribution_status_id'] = array_search('Completed', $contributionStatuses);
         $input['total_amount'] = $input['amount'];
         $input['contribution'] = $contribution;
         $input['financial_type_id'] = $contribution->financial_type_id;
         if (CRM_Utils_Array::value('participant', $contribution->_relatedObjects)) {
             $input['contribution_mode'] = 'participant';
             $input['participant_id'] = $contribution->_relatedObjects['participant']->id;
             $input['skipLineItem'] = 1;
         }
         //@todo writing a unit test I was unable to create a scenario where this line did not fatal on second
         // and subsequent payments. In this case the line items are created at $this->addRecurLineItems
         // and since the contribution is saved prior to this line there is always a contribution-id,
         // however there is never a prevContribution (which appears to mean original contribution not previous
         // contribution - or preUpdateContributionObject most accurately)
         // so, this is always called & only appears to succeed when prevContribution exists - which appears
         // to mean "are we updating an exisitng pending contribution"
         //I was able to make the unit test complete as fataling here doesn't prevent
         // the contribution being created - but activities would not be created or emails sent
         CRM_Contribute_BAO_Contribution::recordFinancialAccounts($input, NULL);
     }
     self::updateRecurLinkedPledge($contribution);
     // create an activity record
     if ($input['component'] == 'contribute') {
         //CRM-4027
         $targetContactID = NULL;
         if (CRM_Utils_Array::value('related_contact', $ids)) {
             $targetContactID = $contribution->contact_id;
             $contribution->contact_id = $ids['related_contact'];
         }
         CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
         // event
     } else {
         CRM_Activity_BAO_Activity::addActivity($participant);
     }
     CRM_Core_Error::debug_log_message("Contribution record updated successfully");
     $transaction->commit();
     // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
     // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
     if (!array_key_exists('is_email_receipt', $values) || $values['is_email_receipt'] == 1) {
         self::sendMail($input, $ids, $objects, $values, $recur, FALSE);
         CRM_Core_Error::debug_log_message("Receipt sent");
     }
     CRM_Core_Error::debug_log_message("Success: Database updated");
 }
 /**
  * takes an associative array and creates a contribution object
  *
  * @param array $params (reference ) an assoc array of name/value pairs
  * @param array $ids    the array that holds all the db ids
  *
  * @return object CRM_Contribute_BAO_Contribution object
  * @access public
  * @static
  */
 static function &create(&$params, &$ids)
 {
     // FIXME: a cludgy hack to fix the dates to MySQL format
     $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
     foreach ($dateFields as $df) {
         if (isset($params[$df])) {
             $params[$df] = CRM_Utils_Date::isoToMysql($params[$df]);
         }
     }
     if (CRM_Utils_Array::value('contribution', $ids) && !CRM_Utils_Array::value('softID', $params)) {
         if ($softID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionSoft', $ids['contribution'], 'id', 'contribution_id')) {
             $params['softID'] = $softID;
         }
     }
     $transaction = new CRM_Core_Transaction();
     // delete the soft credit record if no soft credit contact ID AND no PCP is set in the form
     if (CRM_Utils_Array::value('contribution', $ids) && (!CRM_Utils_Array::value('soft_credit_to', $params) && !CRM_Utils_Array::value('pcp_made_through_id', $params)) && CRM_Utils_Array::value('softID', $params)) {
         $softCredit = new CRM_Contribute_DAO_ContributionSoft();
         $softCredit->id = $params['softID'];
         $softCredit->delete();
     }
     $contribution = self::add($params, $ids);
     if (is_a($contribution, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $contribution;
     }
     $params['contribution_id'] = $contribution->id;
     if (CRM_Utils_Array::value('custom', $params) && is_array($params['custom'])) {
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
     }
     $session = CRM_Core_Session::singleton();
     if (CRM_Utils_Array::value('note', $params)) {
         $noteParams = array('entity_table' => 'civicrm_contribution', 'note' => $params['note'], 'entity_id' => $contribution->id, 'contact_id' => $session->get('userID'), 'modified_date' => date('Ymd'));
         if (!$noteParams['contact_id']) {
             $noteParams['contact_id'] = $params['contact_id'];
         }
         CRM_Core_BAO_Note::add($noteParams, CRM_Utils_Array::value('note', $ids));
     }
     // make entry in batch entity batch table
     if (CRM_Utils_Array::value('batch_id', $params)) {
         $entityParams = array('batch_id' => $params['batch_id'], 'entity_table' => 'civicrm_contribution', 'entity_id' => $contribution->id);
         // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
         $titleFields = array('contact_id', 'total_amount', 'currency', 'contribution_type_id');
         $retrieverequired = 0;
         foreach ($titleFields as $titleField) {
             if (!isset($contribution->{$titleField})) {
                 $retrieverequired = 1;
                 break;
             }
         }
         if ($retrieverequired == 1) {
             $contribution->find(true);
         }
         CRM_Core_BAO_Batch::addBatchEntity($entityParams);
     }
     // check if activity record exist for this contribution, if
     // not add activity
     $activity = new CRM_Activity_DAO_Activity();
     $activity->source_record_id = $contribution->id;
     $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type', 'Contribution', 'name');
     if (!$activity->find()) {
         CRM_Activity_BAO_Activity::addActivity($contribution, 'Offline');
     }
     // Handle soft credit and / or link to personal campaign page
     if (CRM_Utils_Array::value('soft_credit_to', $params) || CRM_Utils_Array::value('pcp_made_through_id', $params)) {
         $csParams = array();
         if ($id = CRM_Utils_Array::value('softID', $params)) {
             $csParams['id'] = $params['softID'];
         }
         $csParams['contribution_id'] = $contribution->id;
         // If pcp_made_through_id set, we define soft_credit_to contact based on selected PCP,
         // else use passed soft_credit_to
         if (CRM_Utils_Array::value('pcp_made_through_id', $params)) {
             $csParams['pcp_display_in_roll'] = $params['pcp_display_in_roll'] ? 1 : 0;
             foreach (array('pcp_roll_nickname', 'pcp_personal_note') as $val) {
                 $csParams[$val] = $params[$val];
             }
             $csParams['pcp_id'] = CRM_Utils_Array::value('pcp_made_through_id', $params);
             $csParams['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $csParams['pcp_id'], 'contact_id');
         } else {
             $csParams['contact_id'] = $params['soft_credit_to'];
             $csParams['pcp_id'] = '';
         }
         // first stage: we register whole amount as credited to given person
         $csParams['amount'] = $contribution->total_amount;
         self::addSoftContribution($csParams);
     }
     $transaction->commit();
     // do not add to recent items for import, CRM-4399
     if (!CRM_Utils_Array::value('skipRecentView', $params)) {
         $url = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home");
         // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
         $titleFields = array('contact_id', 'total_amount', 'currency', 'contribution_type_id');
         $retrieverequired = 0;
         foreach ($titleFields as $titleField) {
             if (!isset($contribution->{$titleField})) {
                 $retrieverequired = 1;
                 break;
             }
         }
         if ($retrieverequired == 1) {
             $contribution->find(true);
         }
         $contributionTypes = CRM_Contribute_PseudoConstant::contributionType();
         $title = CRM_Contact_BAO_Contact::displayName($contribution->contact_id) . ' - (' . CRM_Utils_Money::format($contribution->total_amount, $contribution->currency) . ' ' . ' - ' . $contributionTypes[$contribution->contribution_type_id] . ')';
         $recentOther = array();
         if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) {
             $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home");
         }
         if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) {
             $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home");
         }
         // add the recently created Contribution
         CRM_Utils_Recent::add($title, $url, $contribution->id, 'Contribution', $contribution->contact_id, NULL, $recentOther);
     }
     return $contribution;
 }
Example #8
0
 function completeTransaction(&$input, &$ids, &$objects, &$transaction, $recur = false)
 {
     $contribution =& $objects['contribution'];
     $membership =& $objects['membership'];
     $participant =& $objects['participant'];
     $event =& $objects['event'];
     $values = array();
     if ($input['component'] == 'contribute') {
         require_once 'CRM/Contribute/BAO/ContributionPage.php';
         CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
         $contribution->source = ts('Online Contribution') . ': ' . $values['title'];
         if ($values['is_email_receipt']) {
             $contribution->receipt_date = self::$_now;
         }
         if ($membership) {
             $format = '%Y%m%d';
             require_once 'CRM/Member/BAO/MembershipType.php';
             require_once 'CRM/Member/BAO/Membership.php';
             $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membership->contact_id, $membership->membership_type_id, $membership->is_test, $membership->id);
             if ($currentMembership) {
                 /*
                  * Fixed FOR CRM-4433
                  * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status 
                  * when Contribution mode is notify and membership is for renewal ) 
                  */
                 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday = null);
                 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id, $changeToday = null);
                 $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
             } else {
                 $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id);
             }
             //get the status for membership.
             require_once 'CRM/Member/BAO/MembershipStatus.php';
             $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', true);
             $formatedParams = array('status_id' => CRM_Utils_Array::value('id', $calcStatus, 2), 'join_date' => CRM_Utils_Date::customFormat($dates['join_date'], $format), 'start_date' => CRM_Utils_Date::customFormat($dates['start_date'], $format), 'end_date' => CRM_Utils_Date::customFormat($dates['end_date'], $format), 'reminder_date' => CRM_Utils_Date::customFormat($dates['reminder_date'], $format));
             $membership->copyValues($formatedParams);
             $membership->save();
             //updating the membership log
             $membershipLog = array();
             $membershipLog = $formatedParams;
             $logStartDate = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
             $logStartDate = $logStartDate ? CRM_Utils_Date::isoToMysql($logStartDate) : $formatedParams['start_date'];
             $membershipLog['start_date'] = $logStartDate;
             $membershipLog['membership_id'] = $membership->id;
             $membershipLog['modified_id'] = $membership->contact_id;
             $membershipLog['modified_date'] = date('Ymd');
             require_once 'CRM/Member/BAO/MembershipLog.php';
             CRM_Member_BAO_MembershipLog::add($membershipLog, CRM_Core_DAO::$_nullArray);
             //update related Memberships.
             CRM_Member_BAO_Membership::updateRelatedMemberships($membership->id, $formatedParams);
         }
     } else {
         // event
         $eventParams = array('id' => $objects['event']->id);
         $values['event'] = array();
         require_once 'CRM/Event/BAO/Event.php';
         CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
         $eventParams = array('id' => $objects['event']->id);
         $values['event'] = array();
         require_once 'CRM/Event/BAO/Event.php';
         CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
         //get location details
         $locationParams = array('entity_id' => $objects['event']->id, 'entity_table' => 'civicrm_event');
         require_once 'CRM/Core/BAO/Location.php';
         require_once 'CRM/Event/Form/ManageEvent/Location.php';
         $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
         require_once 'CRM/Core/BAO/UFJoin.php';
         $ufJoinParams = array('entity_table' => 'civicrm_event', 'entity_id' => $ids['event'], 'weight' => 1);
         $values['custom_pre_id'] = CRM_Core_BAO_UFJoin::findUFGroupId($ufJoinParams);
         $ufJoinParams['weight'] = 2;
         $values['custom_post_id'] = CRM_Core_BAO_UFJoin::findUFGroupId($ufJoinParams);
         $contribution->source = ts('Online Event Registration') . ': ' . $values['event']['title'];
         if ($values['event']['is_email_confirm']) {
             $contribution->receipt_date = self::$_now;
         }
         $participant->status_id = 1;
         $participant->save();
     }
     if ($input['net_amount'] == 0 && $input['fee_amount'] != 0) {
         $input['net_amount'] = $input['amount'] - $input['fee_amount'];
     }
     $contribution->contribution_status_id = 1;
     $contribution->is_test = $input['is_test'];
     $contribution->fee_amount = $input['fee_amount'];
     $contribution->net_amount = $input['net_amount'];
     $contribution->trxn_id = $input['trxn_id'];
     $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
     $contribution->cancel_date = 'null';
     if (CRM_Utils_Array::value('check_number', $input)) {
         $contribution->check_number = $input['check_number'];
     }
     if (CRM_Utils_Array::value('payment_instrument_id', $input)) {
         $contribution->payment_instrument_id = $input['payment_instrument_id'];
     }
     $contribution->save();
     // next create the transaction record
     if (isset($objects['paymentProcessor'])) {
         $paymentProcessor = $objects['paymentProcessor']['payment_processor_type'];
     } else {
         $paymentProcessor = '';
     }
     if ($contribution->trxn_id) {
         $trxnParams = array('contribution_id' => $contribution->id, 'trxn_date' => isset($input['trxn_date']) ? $input['trxn_date'] : self::$_now, 'trxn_type' => 'Debit', 'total_amount' => $input['amount'], 'fee_amount' => $contribution->fee_amount, 'net_amount' => $contribution->net_amount, 'currency' => $contribution->currency, 'payment_processor' => $paymentProcessor, 'trxn_id' => $contribution->trxn_id);
         require_once 'CRM/Contribute/BAO/FinancialTrxn.php';
         $trxn =& CRM_Contribute_BAO_FinancialTrxn::create($trxnParams);
     }
     //update corresponding pledge payment record
     require_once 'CRM/Core/DAO.php';
     $returnProperties = array('id', 'pledge_id');
     if (CRM_Core_DAO::commonRetrieveAll('CRM_Pledge_DAO_Payment', 'contribution_id', $contribution->id, $paymentDetails, $returnProperties)) {
         $paymentIDs = array();
         foreach ($paymentDetails as $key => $value) {
             $paymentIDs[] = $value['id'];
             $pledgeId = $value['pledge_id'];
         }
         // update pledge and corresponding payment statuses
         require_once 'CRM/Pledge/BAO/Payment.php';
         CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($pledgeId, $paymentIDs, $contribution->contribution_status_id);
     }
     // create an activity record
     require_once "CRM/Activity/BAO/Activity.php";
     if ($input['component'] == 'contribute') {
         //CRM-4027
         $targetContactID = null;
         if (CRM_Utils_Array::value('related_contact', $ids)) {
             $targetContactID = $contribution->contact_id;
             $contribution->contact_id = $ids['related_contact'];
         }
         CRM_Activity_BAO_Activity::addActivity($contribution, null, $targetContactID);
     } else {
         // event
         CRM_Activity_BAO_Activity::addActivity($participant);
     }
     CRM_Core_Error::debug_log_message("Contribution record updated successfully");
     $transaction->commit();
     self::sendMail($input, $ids, $objects, $values, $recur, false);
     CRM_Core_Error::debug_log_message("Success: Database updated and mail sent");
 }
 /**
  * takes an associative array and creates a participant object
  *
  * @param array $params (reference ) an assoc array of name/value pairs
  * @param array $ids    the array that holds all the db ids
  *
  * @return object CRM_Event_BAO_Participant object 
  * @access public
  * @static
  */
 static function &create(&$params)
 {
     require_once 'CRM/Utils/Date.php';
     require_once 'CRM/Core/Transaction.php';
     $transaction = new CRM_Core_Transaction();
     $status = null;
     if (CRM_Utils_Array::value('id', $params)) {
         $status = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $params['id'], 'status_id');
     }
     $participant =& self::add($params);
     if (is_a($participant, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $participant;
     }
     if (!CRM_Utils_Array::value('id', $params) || $params['status_id'] != $status) {
         require_once 'CRM/Activity/BAO/Activity.php';
         CRM_Activity_BAO_Activity::addActivity($participant);
     }
     //CRM-5403
     //for update mode
     if (self::isPrimaryParticipant($participant->id) && $status) {
         self::updateParticipantStatus($participant->id, $status, $participant->status_id);
     }
     $session =& CRM_Core_Session::singleton();
     $id = $session->get('userID');
     if (!$id) {
         $id = $params['contact_id'];
     }
     // add custom field values
     if (CRM_Utils_Array::value('custom', $params) && is_array($params['custom'])) {
         require_once 'CRM/Core/BAO/CustomValueTable.php';
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_participant', $participant->id);
     }
     if (CRM_Utils_Array::value('note', $params) || CRM_Utils_Array::value('participant_note', $params)) {
         if (CRM_Utils_Array::value('note', $params)) {
             $note = CRM_Utils_Array::value('note', $params);
         } else {
             $note = CRM_Utils_Array::value('participant_note', $params);
         }
         $noteDetails = CRM_Core_BAO_Note::getNote($participant->id, 'civicrm_participant');
         $noteIDs = array();
         if (!empty($noteDetails)) {
             $noteIDs['id'] = array_pop(array_flip($noteDetails));
         }
         if ($note) {
             require_once 'CRM/Core/BAO/Note.php';
             $noteParams = array('entity_table' => 'civicrm_participant', 'note' => $note, 'entity_id' => $participant->id, 'contact_id' => $id, 'modified_date' => date('Ymd'));
             CRM_Core_BAO_Note::add($noteParams, $noteIDs);
         }
     }
     // Log the information on successful add/edit of Participant data.
     require_once 'CRM/Core/BAO/Log.php';
     $logParams = array('entity_table' => 'civicrm_participant', 'entity_id' => $participant->id, 'data' => CRM_Event_PseudoConstant::participantStatus($participant->status_id), 'modified_id' => $id, 'modified_date' => date('Ymd'));
     CRM_Core_BAO_Log::add($logParams);
     $params['participant_id'] = $participant->id;
     $transaction->commit();
     // do not add to recent items for import, CRM-4399
     if (!CRM_Utils_Array::value('skipRecentView', $params)) {
         require_once 'CRM/Utils/Recent.php';
         require_once 'CRM/Event/PseudoConstant.php';
         require_once 'CRM/Contact/BAO/Contact.php';
         $url = CRM_Utils_System::url('civicrm/contact/view/participant', "action=view&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home");
         $recentOther = array();
         if (CRM_Core_Permission::check('edit event participants')) {
             $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/participant', "action=update&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home");
         }
         if (CRM_Core_Permission::check('delete in CiviEvent')) {
             $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/participant', "action=delete&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home");
         }
         $participantRoles = CRM_Event_PseudoConstant::participantRole();
         if ($participant->role_id) {
             $role = explode(CRM_Core_DAO::VALUE_SEPARATOR, $participant->role_id);
             foreach ($role as $roleKey => $roleValue) {
                 if (isset($roles)) {
                     $roles .= ", " . $participantRoles[$roleValue];
                 } else {
                     $roles = $participantRoles[$roleValue];
                 }
             }
         }
         $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $participant->event_id, 'title');
         $title = CRM_Contact_BAO_Contact::displayName($participant->contact_id) . ' (' . $roles . ' - ' . $eventTitle . ')';
         // add the recently created Participant
         CRM_Utils_Recent::add($title, $url, $participant->id, 'Participant', $participant->contact_id, null, $recentOther);
     }
     return $participant;
 }
Example #10
0
 /** 
  * Function to process the form 
  * 
  * @access public 
  */
 public function postProcess()
 {
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     if ($this->_action & CRM_Core_Action::DELETE) {
         require_once "CRM/Event/BAO/Participant.php";
         if (CRM_Utils_Array::value('delete_participant', $params) == 2) {
             $additionalId = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
             $participantLinks = CRM_Event_BAO_Participant::getAdditionalParticipantUrl($additionalId);
         }
         if (CRM_Utils_Array::value('delete_participant', $params) == 1) {
             $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
             foreach ($additionalIds as $value) {
                 CRM_Event_BAO_Participant::deleteParticipant($value);
             }
         }
         CRM_Event_BAO_Participant::deleteParticipant($this->_id);
         if (!empty($participantLinks)) {
             $status = ts('The following participants no longer have an event fee recorded. You can edit their registration and record a replacement contribution by clicking the links below:') . '<br>' . $participantLinks;
         } else {
             $status = "Selected Participants was deleted sucessfully.";
         }
         CRM_Core_Session::setStatus($status);
         return;
     }
     // set the contact, when contact is selected
     if (CRM_Utils_Array::value('contact_select_id', $params)) {
         $this->_contactId = $params['contact_select_id'][1];
     }
     if ($this->_id) {
         $params['id'] = $this->_id;
     }
     $config = CRM_Core_Config::singleton();
     if ($this->_isPaidEvent) {
         $contributionParams = array();
         $lineItem = array();
         $additionalParticipantDetails = array();
         if ($this->_id && $this->_action & CRM_Core_Action::UPDATE && $this->_paymentId) {
             $participantBAO = new CRM_Event_BAO_Participant();
             $participantBAO->id = $this->_id;
             $participantBAO->find(true);
             $contributionParams['total_amount'] = $participantBAO->fee_amount;
             $params['discount_id'] = null;
             //re-enter the values for UPDATE mode
             $params['fee_level'] = $params['amount_level'] = $participantBAO->fee_level;
             $params['fee_amount'] = $participantBAO->fee_amount;
             if (isset($params['priceSetId'])) {
                 require_once 'CRM/Price/BAO/LineItem.php';
                 $lineItem[0] = CRM_Price_BAO_LineItem::getLineItems($this->_id);
             }
             //also add additional participant's fee level/priceset
             if (CRM_Event_BAO_Participant::isPrimaryParticipant($this->_id)) {
                 $additionalIds = CRM_Event_BAO_Participant::getAdditionalParticipantIds($this->_id);
                 $hasLineItems = CRM_Utils_Array::value('priceSetId', $params, false);
                 $additionalParticipantDetails = CRM_Event_BAO_Participant::getFeeDetails($additionalIds, $hasLineItems);
             }
         } else {
             //check if discount is selected
             if (CRM_Utils_Array::value('discount_id', $params)) {
                 $discountId = $params['discount_id'];
             } else {
                 $discountId = $params['discount_id'] = 'null';
             }
             //lets carry currency, CRM-4453
             $params['fee_currency'] = $config->defaultCurrency;
             // fix for CRM-3088
             if ($discountId && !empty($this->_values['discount'][$discountId])) {
                 $params['amount_level'] = $this->_values['discount'][$discountId][$params['amount']]['label'];
                 $params['amount'] = $this->_values['discount'][$discountId][$params['amount']]['value'];
             } else {
                 if (!isset($params['priceSetId']) && CRM_Utils_Array::value('amount', $params)) {
                     $params['amount_level'] = $this->_values['fee'][$params['amount']]['label'];
                     $params['amount'] = $this->_values['fee'][$params['amount']]['value'];
                 } else {
                     CRM_Price_BAO_Set::processAmount($this->_values['fee'], $params, $lineItem[0]);
                 }
             }
             $params['fee_level'] = $params['amount_level'];
             $contributionParams['total_amount'] = $params['amount'];
             //fix for CRM-3086
             $params['fee_amount'] = $params['amount'];
         }
         if (isset($params['priceSetId'])) {
             $this->set('lineItem', $lineItem);
             $this->_lineItem = $lineItem;
             $lineItem = array_merge($lineItem, $additionalParticipantDetails);
             $participantCount = array();
             foreach ($lineItem as $k) {
                 foreach ($k as $v) {
                     if (CRM_Utils_Array::value('participant_count', $v) > 0) {
                         $participantCount[] = $v['participant_count'];
                     }
                 }
             }
             if ($participantCount) {
                 $this->assign('pricesetFieldsCount', $participantCount);
             }
             $this->assign('lineItem', empty($lineItem[0]) ? false : $lineItem);
         } else {
             $this->assign('amount_level', $params['amount_level']);
         }
     }
     $this->_params = $params;
     unset($params['amount']);
     $params['register_date'] = CRM_Utils_Date::processDate($params['register_date'], $params['register_date_time']);
     $params['receive_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $params));
     $params['contact_id'] = $this->_contactId;
     // overwrite actual payment amount if entered
     if (CRM_Utils_Array::value('total_amount', $params)) {
         $contributionParams['total_amount'] = CRM_Utils_Array::value('total_amount', $params);
     }
     require_once 'CRM/Contact/BAO/Contact.php';
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     $session = CRM_Core_Session::singleton();
     $userID = $session->get('userID');
     list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
     require_once "CRM/Event/BAO/Participant.php";
     if ($this->_mode) {
         if (!$this->_isPaidEvent) {
             CRM_Core_Error::fatal(ts('Selected Event is not Paid Event '));
         }
         //modify params according to parameter used in create
         //participant method (addParticipant)
         $this->_params['participant_status_id'] = $params['status_id'];
         $this->_params['participant_role_id'] = $params['role_id'];
         $this->_params['participant_register_date'] = $params['register_date'];
         $this->_params['participant_source'] = $params['source'];
         require_once 'CRM/Core/BAO/PaymentProcessor.php';
         $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode);
         require_once "CRM/Contact/BAO/Contact.php";
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields["email-Primary"] = 1;
         list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_contactId);
         $params["email-Primary"] = $params["email-{$this->_bltID}"] = $this->_contributorEmail;
         $params['register_date'] = $now;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
         $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         $fields["email-{$this->_bltID}"] = 1;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $params)) {
                 $params[$name] = $params["billing_{$name}"];
                 $params['preserveDBName'] = true;
             }
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactId, null, null, $ctype);
     }
     $roleAllIds = CRM_Utils_Array::value('role_id', $params);
     if ($roleAllIds) {
         foreach ($roleAllIds as $rkey => $rvalue) {
             $customFieldsRole = CRM_Core_BAO_CustomField::getFields('Participant', false, false, $rkey, $this->_roleCustomDataTypeID);
             $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant', false, false, CRM_Utils_Array::value('event_id', $params), $this->_eventNameCustomDataTypeID);
             $customFieldsEventType = CRM_Core_BAO_CustomField::getFields('Participant', false, false, $this->_eventTypeId, $this->_eventTypeCustomDataTypeID);
             $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole, CRM_Core_BAO_CustomField::getFields('Participant', false, false, null, null, true));
             $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
             $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEventType, $customFields);
             $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_id, 'Participant');
         }
     }
     if ($this->_mode) {
         // add all the additioanl payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = $this->_params['credit_card_exp_date']['Y'];
         $this->_params['month'] = $this->_params['credit_card_exp_date']['M'];
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $params['fee_amount'];
         $this->_params['amount_level'] = $params['amount_level'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['payment_action'] = 'Sale';
         $this->_params['invoiceID'] = md5(uniqid(rand(), true));
         // at this point we've created a contact and stored its address etc
         // all the payment processors expect the name and address to be in the
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         require_once 'CRM/Core/Payment/Form.php';
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, true);
         $payment =& CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
         $result =& $payment->doDirectPayment($paymentParams);
         if (is_a($result, 'CRM_Core_Error')) {
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&cid={$this->_contactId}&context=participant&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $this->_params['receive_date'] = $now;
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $this->_params['receipt_date'] = $now;
         } else {
             $this->_params['receipt_date'] = null;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
         $this->assign('receive_date', CRM_Utils_Date::processDate($this->_params['receive_date']));
         // set source if not set
         $this->_params['description'] = ts('Submit Credit Card for Event Registration by: %1', array(1 => $userName));
         require_once 'CRM/Event/Form/Registration/Confirm.php';
         require_once 'CRM/Event/Form/Registration.php';
         //add contribution record
         $this->_params['contribution_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'contribution_type_id');
         $this->_params['mode'] = $this->_mode;
         //add contribution reocord
         $contribution = CRM_Event_Form_Registration_Confirm::processContribution($this, $this->_params, $result, $contactID, false);
         // add participant record
         $participants = array();
         if (CRM_Utils_Array::value('participant_role_id', $this->_params) && is_array($this->_params['participant_role_id'])) {
             $this->_params['participant_role_id'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, array_keys($this->_params['participant_role_id']));
         }
         $participants[] = CRM_Event_Form_Registration::addParticipant($this->_params, $contactID);
         //add custom data for participant
         require_once 'CRM/Core/BAO/CustomValueTable.php';
         CRM_Core_BAO_CustomValueTable::postProcess($this->_params, CRM_Core_DAO::$_nullArray, 'civicrm_participant', $participants[0]->id, 'Participant');
         //add participant payment
         require_once 'CRM/Event/BAO/ParticipantPayment.php';
         $paymentParticipant = array('participant_id' => $participants[0]->id, 'contribution_id' => $contribution->id);
         $ids = array();
         CRM_Event_BAO_ParticipantPayment::create($paymentParticipant, $ids);
         $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         $this->_contactIds[] = $this->_contactId;
     } else {
         $participants = array();
         // fix note if deleted
         if (!$params['note']) {
             $params['note'] = 'null';
         }
         if ($this->_single) {
             if ($params['role_id']) {
                 foreach ($params['role_id'] as $k => $v) {
                     $rolesIDS[] = $k;
                 }
                 require_once 'CRM/Core/DAO.php';
                 $seperator = CRM_Core_DAO::VALUE_SEPARATOR;
                 $params['role_id'] = implode($seperator, $rolesIDS);
             } else {
                 $params['role_id'] = 'NULL';
             }
             $participants[] = CRM_Event_BAO_Participant::create($params);
         } else {
             foreach ($this->_contactIds as $contactID) {
                 $commonParams = $params;
                 $commonParams['contact_id'] = $contactID;
                 if ($commonParams['role_id']) {
                     $rolesIDS = array();
                     foreach ($commonParams['role_id'] as $k => $v) {
                         $rolesIDS[] = $k;
                     }
                     require_once 'CRM/Core/DAO.php';
                     $seperator = CRM_Core_DAO::VALUE_SEPARATOR;
                     $commonParams['role_id'] = implode($seperator, $rolesIDS);
                     $commonParams['participant_role_id'] = implode($seperator, $rolesIDS);
                 } else {
                     $commonParams['role_id'] = 'NULL';
                 }
                 $participants[] = CRM_Event_BAO_Participant::create($commonParams);
             }
         }
         if (isset($params['event_id'])) {
             $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         }
         if ($this->_single) {
             $this->_contactIds[] = $this->_contactId;
         }
         if (CRM_Utils_Array::value('record_contribution', $params)) {
             if (CRM_Utils_Array::value('id', $params)) {
                 if ($this->_onlinePendingContributionId) {
                     $ids['contribution'] = $this->_onlinePendingContributionId;
                 } else {
                     $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $params['id'], 'contribution_id', 'participant_id');
                 }
             }
             unset($params['note']);
             //build contribution params
             if (!$this->_onlinePendingContributionId) {
                 $contributionParams['source'] = "{$eventTitle}: Offline registration (by {$userName})";
             }
             $contributionParams['currency'] = $config->defaultCurrency;
             $contributionParams['non_deductible_amount'] = 'null';
             $contributionParams['receipt_date'] = CRM_Utils_Array::value('send_receipt', $params) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
             $recordContribution = array('contact_id', 'contribution_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'receive_date', 'check_number');
             foreach ($recordContribution as $f) {
                 $contributionParams[$f] = CRM_Utils_Array::value($f, $params);
                 if ($f == 'trxn_id') {
                     $this->assign('trxn_id', $contributionParams[$f]);
                 }
             }
             //insert contribution type name in receipt.
             $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionType', $contributionParams['contribution_type_id']));
             require_once 'CRM/Contribute/BAO/Contribution.php';
             $contributions = array();
             if ($this->_single) {
                 $contributions[] =& CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
             } else {
                 $ids = array();
                 foreach ($this->_contactIds as $contactID) {
                     $contributionParams['contact_id'] = $contactID;
                     $contributions[] =& CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
                 }
             }
             //insert payment record for this participation
             if (!$ids['contribution']) {
                 require_once 'CRM/Event/DAO/ParticipantPayment.php';
                 foreach ($this->_contactIds as $num => $contactID) {
                     $ppDAO = new CRM_Event_DAO_ParticipantPayment();
                     $ppDAO->participant_id = $participants[$num]->id;
                     $ppDAO->contribution_id = $contributions[$num]->id;
                     $ppDAO->save();
                 }
             }
         }
     }
     //do cleanup line  items if participant edit the Event Fee.
     if (($this->_lineItem || !isset($params['proceSetId'])) && !$this->_paymentId) {
         require_once 'CRM/Price/BAO/LineItem.php';
         CRM_Price_BAO_LineItem::deleteLineItems($params['participant_id'], 'civicrm_participant');
     }
     // also store lineitem stuff here
     if ($this->_lineItem & $this->_action & CRM_Core_Action::ADD || $this->_lineItem && CRM_Core_Action::UPDATE && !$this->_paymentId) {
         require_once 'CRM/Price/BAO/LineItem.php';
         foreach ($this->_contactIds as $num => $contactID) {
             foreach ($this->_lineItem as $key => $value) {
                 if (is_array($value) && $value != 'skip') {
                     foreach ($value as $line) {
                         $line['entity_table'] = 'civicrm_participant';
                         $line['entity_id'] = $participants[$num]->id;
                         CRM_Price_BAO_LineItem::create($line);
                     }
                 }
             }
         }
     }
     $updateStatusMsg = null;
     //send mail when participant status changed, CRM-4326
     if ($this->_id && $this->_statusId && $this->_statusId != CRM_Utils_Array::value('status_id', $params) && CRM_Utils_Array::value('is_notify', $params)) {
         require_once "CRM/Event/BAO/Participant.php";
         $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_id, $params['status_id'], $this->_statusId);
     }
     if (CRM_Utils_Array::value('send_receipt', $params)) {
         $receiptFrom = CRM_Utils_Array::value($params['from_email_address'], $this->_fromEmails['name']);
         $this->assign('module', 'Event Registration');
         //use of the message template below requires variables in different format
         $event = $events = array();
         $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
         //get all event details.
         CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
         $event = $events[$params['event_id']];
         unset($event['start_date']);
         unset($event['end_date']);
         $role = CRM_Event_PseudoConstant::participantRole();
         if (is_array($params['role_id'])) {
             $selectedRoles = array();
             foreach (array_keys($params['role_id']) as $roleId) {
                 $selectedRoles[] = $role[$roleId];
             }
             $event['participant_role'] = implode(', ', $selectedRoles);
         } else {
             $event['participant_role'] = $role[$params['role_id']];
         }
         $event['is_monetary'] = $this->_isPaidEvent;
         if ($params['receipt_text']) {
             $event['confirm_email_text'] = $params['receipt_text'];
         }
         $this->assign('isAmountzero', 1);
         $this->assign('event', $event);
         $this->assign('isShowLocation', $event['is_show_location']);
         if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
             $locationParams = array('entity_id' => $params['event_id'], 'entity_table' => 'civicrm_event');
             require_once 'CRM/Core/BAO/Location.php';
             $location = CRM_Core_BAO_Location::getValues($locationParams, true);
             $this->assign('location', $location);
         }
         $status = CRM_Event_PseudoConstant::participantStatus();
         if ($this->_isPaidEvent) {
             $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
             if (!$this->_mode) {
                 $this->assign('paidBy', CRM_Utils_Array::value($params['payment_instrument_id'], $paymentInstrument));
             }
             $this->assign('totalAmount', $contributionParams['total_amount']);
             $this->assign('isPrimary', 1);
             $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
         }
         if ($this->_mode) {
             if (CRM_Utils_Array::value('billing_first_name', $params)) {
                 $name = $params['billing_first_name'];
             }
             if (CRM_Utils_Array::value('billing_middle_name', $params)) {
                 $name .= " {$params['billing_middle_name']}";
             }
             if (CRM_Utils_Array::value('billing_last_name', $params)) {
                 $name .= " {$params['billing_last_name']}";
             }
             $this->assign('billingName', $name);
             // assign the address formatted up for display
             $addressParts = array("street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "state_province-{$this->_bltID}", "country-{$this->_bltID}");
             $addressFields = array();
             foreach ($addressParts as $part) {
                 list($n, $id) = explode('-', $part);
                 if (isset($this->_params['billing_' . $part])) {
                     $addressFields[$n] = $this->_params['billing_' . $part];
                 }
             }
             require_once 'CRM/Utils/Address.php';
             $this->assign('address', CRM_Utils_Address::format($addressFields));
             $date = CRM_Utils_Date::format($params['credit_card_exp_date']);
             $date = CRM_Utils_Date::mysqlToIso($date);
             $this->assign('credit_card_exp_date', $date);
             $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($params['credit_card_number']));
             $this->assign('credit_card_type', $params['credit_card_type']);
             $this->assign('contributeMode', 'direct');
             $this->assign('isAmountzero', 0);
             $this->assign('is_pay_later', 0);
             $this->assign('isPrimary', 1);
         }
         $this->assign('register_date', $params['register_date']);
         if ($params['receive_date']) {
             $this->assign('receive_date', $params['receive_date']);
         }
         $participant = array(array('participant_id', '=', $participants[0]->id, 0, 0));
         // check whether its a test drive ref CRM-3075
         if (CRM_Utils_Array::value('is_test', $this->_defaultValues)) {
             $participant[] = array('participant_test', '=', 1, 0, 0);
         }
         $template = CRM_Core_Smarty::singleton();
         $customGroup = array();
         //format submitted data
         foreach ($params['custom'] as $fieldID => $values) {
             foreach ($values as $fieldValue) {
                 $customValue = array('data' => $fieldValue['value']);
                 $customFields[$fieldID]['id'] = $fieldID;
                 $formattedValue = CRM_Core_BAO_CustomGroup::formatCustomValues($customValue, $customFields[$fieldID], true);
                 $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
             }
         }
         foreach ($this->_contactIds as $num => $contactID) {
             // Retrieve the name and email of the contact - this will be the TO for receipt email
             list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
             $this->_contributorDisplayName = $this->_contributorDisplayName == ' ' ? $this->_contributorEmail : $this->_contributorDisplayName;
             $this->assign('customGroup', $customGroup);
             $this->assign('contactID', $contactID);
             $this->assign('participantID', $participants[$num]->id);
             if ($this->_isPaidEvent) {
                 // fix amount for each of participants ( for bulk mode )
                 $eventAmount = array();
                 if (!empty($additionalParticipantDetails)) {
                     $params['amount_level'] = $params['amount_level'] . ' - ' . $this->_contributorDisplayName;
                 }
                 $eventAmount[$num] = array('label' => $params['amount_level'], 'amount' => $params['fee_amount']);
                 //as we are using same template for online & offline registration.
                 //So we have to build amount as array.
                 $eventAmount = array_merge($eventAmount, $additionalParticipantDetails);
                 $this->assign('amount', $eventAmount);
             }
             $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'event_offline_receipt', 'contactId' => $contactID, 'isTest' => (bool) CRM_Utils_Array::value('is_test', $this->_defaultValues));
             // try to send emails only if email id is present
             // and the do-not-email option is not checked for that contact
             if ($this->_contributorEmail and !$this->_toDoNotEmail) {
                 $sendTemplateParams['from'] = $receiptFrom;
                 $sendTemplateParams['toName'] = $this->_contributorDisplayName;
                 $sendTemplateParams['toEmail'] = $this->_contributorEmail;
                 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc', $this->_fromEmails);
                 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc', $this->_fromEmails);
             }
             require_once 'CRM/Core/BAO/MessageTemplates.php';
             list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplates::sendTemplate($sendTemplateParams);
             if ($mailSent) {
                 $sent[] = $contactID;
                 require_once 'CRM/Activity/BAO/Activity.php';
                 foreach ($participants as $ids => $values) {
                     CRM_Activity_BAO_Activity::addActivity($values, 'Email');
                 }
             } else {
                 $notSent[] = $contactID;
             }
         }
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contributorDisplayName));
         if (CRM_Utils_Array::value('send_receipt', $params) && count($sent)) {
             $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', array(1 => $this->_contributorEmail));
         }
         if ($updateStatusMsg) {
             $statusMsg = "{$statusMsg} {$updateStatusMsg}";
         }
     } elseif ($this->_action & CRM_Core_Action::ADD) {
         if ($this->_single) {
             $statusMsg = ts('Event registration for %1 has been added.', array(1 => $this->_contributorDisplayName));
             if (CRM_Utils_Array::value('send_receipt', $params) && count($sent)) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $this->_contributorEmail));
             }
         } else {
             $statusMsg = ts('Total Participant(s) added to event: %1.', array(1 => count($this->_contactIds)));
             if (count($notSent) > 0) {
                 $statusMsg .= ' ' . ts('Email has NOT been sent to %1 contact(s) - communication preferences specify DO NOT EMAIL OR valid Email is NOT present. ', array(1 => count($notSent)));
             } elseif (isset($params['send_receipt'])) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to ALL participants');
             }
         }
     }
     require_once "CRM/Core/Session.php";
     CRM_Core_Session::setStatus("{$statusMsg}");
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactId}&selectedChild=participant"));
         }
     } else {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&context={$this->_context}&cid={$this->_contactId}"));
         }
     }
 }
Example #11
0
 /**
  * Process the contribution
  *
  * @return void
  * @access public
  */
 static function processContribution(&$form, $params, $result, $contactID, $contributionType, $deductibleMode = true, $pending = false, $online = true)
 {
     require_once 'CRM/Core/Transaction.php';
     $transaction = new CRM_Core_Transaction();
     $honorCId = $recurringContributionID = null;
     if ($online) {
         if ($form->get('honor_block_is_active')) {
             $honorCId = $form->createHonorContact();
         }
         $recurringContributionID = $form->processRecurringContribution($params, $contactID);
     } else {
         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', $premiumParams);
         if ($selectProduct && $selectProduct != 'no_thanks') {
             require_once 'CRM/Contribute/DAO/Product.php';
             $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;
     }
     // check contribution Type
     // first create the contribution record
     $contribParams = array('contact_id' => $contactID, 'contribution_type_id' => $contributionType->id, 'contribution_page_id' => $online ? $form->_id : null, 'receive_date' => $now, '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);
     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' => $result['trxn_result_code'], 'payment_processor' => $result['payment_processor']);
     }
     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;
     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;
         }
     }
     foreach (array('pcp_display_in_roll', 'pcp_roll_nickname', 'pcp_personal_note') as $val) {
         if (CRM_Utils_Array::value($val, $params)) {
             $contribSoftParams[$val] = $params[$val];
         }
     }
     require_once 'CRM/Contribute/BAO/Contribution.php';
     //create an contribution address
     if ($form->_contributeMode != 'notify' && !CRM_Utils_Array::value('is_pay_later', $params)) {
         $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
     require_once 'CRM/Utils/Money.php';
     $contribParams['non_deductible_amount'] = trim(CRM_Utils_Money::format($contribParams['non_deductible_amount'], ' '));
     $contribParams['total_amount'] = trim(CRM_Utils_Money::format($contribParams['total_amount'], ' '));
     //add contribution record
     $contribution =& CRM_Contribute_BAO_Contribution::add($contribParams, $ids);
     // process price set, CRM-5095
     if ($contribution->id && $form->_priceSetId) {
         require_once 'CRM/Contribute/Form/AdditionalInfo.php';
         CRM_Contribute_Form_AdditionalInfo::processPriceSet($contribution->id, $form->_lineItem);
     }
     //add 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)) {
         $contribSoftParams['contribution_id'] = $contribution->id;
         $contribSoftParams['amount'] = $params['amount'];
         //if its due to pcp
         if (CRM_Utils_Array::value('pcp_made_through_id', $params)) {
             $contribSoftParams['pcp_id'] = $params['pcp_made_through_id'];
             $contribSoftParams['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_PCP', $params['pcp_made_through_id'], 'contact_id');
         } else {
             $contribSoftParams['contact_id'] = CRM_Utils_Array::value('soft_credit_to', $params);
         }
         $softContribution = CRM_Contribute_BAO_Contribution::addSoftContribution($contribSoftParams);
     }
     //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
             require_once 'CRM/Pledge/BAO/Payment.php';
             foreach ($form->_params['pledge_amount'] as $paymentId => $dontCare) {
                 $pledgePaymentParams = array('id' => $paymentId, 'contribution_id' => $contribution->id, 'status_id' => $contribution->contribution_status_id);
                 CRM_Pledge_BAO_Payment::add($pledgePaymentParams);
             }
             //update pledge status according to the new payment statuses
             CRM_Pledge_BAO_Payment::updatePledgePaymentStatus($form->_values['pledge_id']);
         } else {
             //when user creating pledge record.
             $pledgeParams = array();
             $pledgeParams['contact_id'] = $contribution->contact_id;
             $pledgeParams['installment_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'];
             $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');
             require_once 'CRM/Pledge/BAO/Pledge.php';
             $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;
                 require_once 'CRM/Pledge/BAO/Pledge.php';
                 CRM_Pledge_BAO_Pledge::sendAcknowledgment($form, $pledgeParams);
             }
         }
     }
     if ($online) {
         require_once 'CRM/Core/BAO/CustomValueTable.php';
         CRM_Core_BAO_CustomValueTable::postProcess($form->_params, CRM_Core_DAO::$_nullArray, 'civicrm_contribution', $contribution->id, 'Contribution');
     } else {
         //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')) {
             require_once 'CRM/Core/BAO/CustomValueTable.php';
             CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
         }
     }
     require_once "CRM/Contribute/BAO/Contribution/Utils.php";
     if (isset($params['related_contact'])) {
         $contactID = $params['related_contact'];
     } else {
         if (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 ((!$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' => $result['trxn_result_code']);
         require_once 'CRM/Contribute/BAO/FinancialTrxn.php';
         $trxn =& CRM_Contribute_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('is_for_organization', $params)) {
         $targetContactID = $contribution->contact_id;
         $contribution->contact_id = $contactID;
     }
     // create an activity record
     require_once 'CRM/Activity/BAO/Activity.php';
     CRM_Activity_BAO_Activity::addActivity($contribution, null, $targetContactID);
     $transaction->commit();
     return $contribution;
 }
Example #12
0
 /**
  * Complete an order.
  *
  * Do not call this directly - use the contribution.completetransaction api as this function is being refactored.
  *
  * Currently overloaded to complete a transaction & repeat a transaction - fix!
  *
  * Moving it out of the BaseIPN class is just the first step.
  *
  * @param array $input
  * @param array $ids
  * @param array $objects
  * @param CRM_Core_Transaction $transaction
  * @param int $recur
  * @param CRM_Contribute_BAO_Contribution $contribution
  * @param bool $isRecurring
  *   Duplication of param needs review. Only used by AuthorizeNetIPN
  * @param int $isFirstOrLastRecurringPayment
  *   Deprecated param only used by AuthorizeNetIPN.
  */
 public static function completeOrder(&$input, &$ids, $objects, $transaction, $recur, $contribution, $isRecurring, $isFirstOrLastRecurringPayment)
 {
     $primaryContributionID = isset($contribution->id) ? $contribution->id : $objects['first_contribution']->id;
     // The previous details are used when calculating line items so keep it before any code that 'does something'
     if (!empty($contribution->id)) {
         $input['prevContribution'] = CRM_Contribute_BAO_Contribution::getValues(array('id' => $contribution->id), CRM_Core_DAO::$_nullArray, CRM_Core_DAO::$_nullArray);
     }
     $inputContributionWhiteList = array('fee_amount', 'net_amount', 'trxn_id', 'check_number', 'payment_instrument_id', 'is_test', 'campaign_id', 'receive_date', 'receipt_date', 'contribution_status_id');
     if (self::isSingleLineItem($primaryContributionID)) {
         $inputContributionWhiteList[] = 'financial_type_id';
     }
     $participant = CRM_Utils_Array::value('participant', $objects);
     $memberships = CRM_Utils_Array::value('membership', $objects);
     $recurContrib = CRM_Utils_Array::value('contributionRecur', $objects);
     $recurringContributionID = empty($recurContrib->id) ? NULL : $recurContrib->id;
     $event = CRM_Utils_Array::value('event', $objects);
     $paymentProcessorId = '';
     if (isset($objects['paymentProcessor'])) {
         if (is_array($objects['paymentProcessor'])) {
             $paymentProcessorId = $objects['paymentProcessor']['id'];
         } else {
             $paymentProcessorId = $objects['paymentProcessor']->id;
         }
     }
     $completedContributionStatusID = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
     $contributionParams = array_merge(array('contribution_status_id' => $completedContributionStatusID, 'source' => self::getRecurringContributionDescription($contribution, $event)), array_intersect_key($input, array_fill_keys($inputContributionWhiteList, 1)));
     $contributionParams['payment_processor'] = $input['payment_processor'] = $paymentProcessorId;
     if ($recurringContributionID) {
         $contributionParams['contribution_recur_id'] = $recurringContributionID;
     }
     $changeDate = CRM_Utils_Array::value('trxn_date', $input, date('YmdHis'));
     if (empty($contributionParams['receive_date']) && $changeDate) {
         $contributionParams['receive_date'] = $changeDate;
     }
     self::repeatTransaction($contribution, $input, $contributionParams, $paymentProcessorId);
     $contributionParams['financial_type_id'] = $contribution->financial_type_id;
     if (is_numeric($memberships)) {
         $memberships = array($objects['membership']);
     }
     $values = array();
     if (isset($input['is_email_receipt'])) {
         $values['is_email_receipt'] = $input['is_email_receipt'];
     }
     if ($input['component'] == 'contribute') {
         if ($contribution->contribution_page_id) {
             // Figure out what we gain from this.
             CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
         } elseif ($recurContrib && $recurringContributionID) {
             $values['amount'] = $recurContrib->amount;
             $values['financial_type_id'] = $objects['contributionType']->id;
             $values['title'] = $source = ts('Offline Recurring Contribution');
         }
         if ($recurContrib && $recurringContributionID && !isset($input['is_email_receipt'])) {
             //CRM-13273 - is_email_receipt setting on recurring contribution should take precedence over contribution page setting
             // but CRM-16124 if $input['is_email_receipt'] is set then that should not be overridden.
             $values['is_email_receipt'] = $recurContrib->is_email_receipt;
         }
         if (!empty($memberships)) {
             foreach ($memberships as $membershipTypeIdKey => $membership) {
                 if ($membership) {
                     $membershipParams = array('id' => $membership->id, 'contact_id' => $membership->contact_id, 'is_test' => $membership->is_test, 'membership_type_id' => $membership->membership_type_id);
                     $currentMembership = CRM_Member_BAO_Membership::getContactMembership($membershipParams['contact_id'], $membershipParams['membership_type_id'], $membershipParams['is_test'], $membershipParams['id']);
                     // CRM-8141 update the membership type with the value recorded in log when membership created/renewed
                     // this picks up membership type changes during renewals
                     $sql = "\nSELECT    membership_type_id\nFROM      civicrm_membership_log\nWHERE     membership_id={$membershipParams['id']}\nORDER BY  id DESC\nLIMIT 1;";
                     $dao = CRM_Core_DAO::executeQuery($sql);
                     if ($dao->fetch()) {
                         if (!empty($dao->membership_type_id)) {
                             $membershipParams['membership_type_id'] = $dao->membership_type_id;
                         }
                     }
                     $dao->free();
                     $membershipParams['num_terms'] = $contribution->getNumTermsByContributionAndMembershipType($membershipParams['membership_type_id'], $primaryContributionID);
                     $dates = array_fill_keys(array('join_date', 'start_date', 'end_date'), NULL);
                     if ($currentMembership) {
                         /*
                          * Fixed FOR CRM-4433
                          * In BAO/Membership.php(renewMembership function), we skip the extend membership date and status
                          * when Contribution mode is notify and membership is for renewal )
                          */
                         CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeDate);
                         // @todo - we should pass membership_type_id instead of null here but not
                         // adding as not sure of testing
                         $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membershipParams['id'], $changeDate, NULL, $membershipParams['num_terms']);
                         $dates['join_date'] = $currentMembership['join_date'];
                     }
                     //get the status for membership.
                     $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($dates['start_date'], $dates['end_date'], $dates['join_date'], 'today', TRUE, $membershipParams['membership_type_id'], $membershipParams);
                     $membershipParams['status_id'] = CRM_Utils_Array::value('id', $calcStatus, 'New');
                     //we might be renewing membership,
                     //so make status override false.
                     $membershipParams['is_override'] = FALSE;
                     //CRM-17723 - reset static $relatedContactIds array()
                     $var = TRUE;
                     CRM_Member_BAO_Membership::createRelatedMemberships($var, $var, TRUE);
                     civicrm_api3('Membership', 'create', $membershipParams);
                 }
             }
         }
     } else {
         if (empty($input['IAmAHorribleNastyBeyondExcusableHackInTheCRMEventFORMTaskClassThatNeedsToBERemoved'])) {
             if ($event->is_email_confirm) {
                 // @todo this should be set by the function that sends the mail after sending.
                 $contributionParams['receipt_date'] = $changeDate;
             }
             $participantParams['id'] = $participant->id;
             $participantParams['status_id'] = 'Registered';
             civicrm_api3('Participant', 'create', $participantParams);
         }
     }
     $contributionParams['id'] = $contribution->id;
     // CRM-19309 - if you update the contribution here with financial_type_id it can/will mess with $lineItem
     // unsetting it here does NOT cause any other contribution test to fail!
     unset($contributionParams['financial_type_id']);
     $contributionResult = civicrm_api3('Contribution', 'create', $contributionParams);
     // Add new soft credit against current $contribution.
     if (CRM_Utils_Array::value('contributionRecur', $objects) && $objects['contributionRecur']->id) {
         CRM_Contribute_BAO_ContributionRecur::addrecurSoftCredit($objects['contributionRecur']->id, $contribution->id);
     }
     $contributionStatuses = CRM_Core_PseudoConstant::get('CRM_Contribute_DAO_Contribution', 'contribution_status_id', array('labelColumn' => 'name', 'flip' => 1));
     if (isset($input['prevContribution']) && (!$input['prevContribution']->is_pay_later && $input['prevContribution']->contribution_status_id == $contributionStatuses['Pending'])) {
         $input['payment_processor'] = $paymentProcessorId;
     }
     if (!empty($contribution->_relatedObjects['participant'])) {
         $input['contribution_mode'] = 'participant';
         $input['participant_id'] = $contribution->_relatedObjects['participant']->id;
     } elseif (!empty($contribution->_relatedObjects['membership'])) {
         $input['contribution_mode'] = 'membership';
         $contribution->contribution_status_id = $contributionParams['contribution_status_id'];
         $contribution->trxn_id = CRM_Utils_Array::value('trxn_id', $input);
         $contribution->receive_date = CRM_Utils_Date::isoToMysql($contribution->receive_date);
     }
     CRM_Core_Error::debug_log_message("Contribution record updated successfully");
     $transaction->commit();
     CRM_Contribute_BAO_ContributionRecur::updateRecurLinkedPledge($contribution->id, $recurringContributionID, $contributionParams['contribution_status_id'], $input['amount']);
     // create an activity record
     if ($input['component'] == 'contribute') {
         //CRM-4027
         $targetContactID = NULL;
         if (!empty($ids['related_contact'])) {
             $targetContactID = $contribution->contact_id;
             $contribution->contact_id = $ids['related_contact'];
         }
         CRM_Activity_BAO_Activity::addActivity($contribution, NULL, $targetContactID);
         // event
     } else {
         CRM_Activity_BAO_Activity::addActivity($participant);
     }
     // CRM-9132 legacy behaviour was that receipts were sent out in all instances. Still sending
     // when array_key 'is_email_receipt doesn't exist in case some instances where is needs setting haven't been set
     if (!array_key_exists('is_email_receipt', $values) || $values['is_email_receipt'] == 1) {
         civicrm_api3('Contribution', 'sendconfirmation', array('id' => $contribution->id, 'payment_processor_id' => $paymentProcessorId));
         CRM_Core_Error::debug_log_message("Receipt sent");
     }
     CRM_Core_Error::debug_log_message("Success: Database updated");
     if ($isRecurring) {
         CRM_Contribute_BAO_ContributionRecur::sendRecurringStartOrEndNotification($ids, $recur, $isFirstOrLastRecurringPayment);
     }
     return $contributionResult;
 }
 /**
  * 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;
 }
Example #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;
 }
 /**
  * takes an associative array and creates a contribution object
  *
  * @param array $params (reference ) an assoc array of name/value pairs
  * @param array $ids    the array that holds all the db ids
  *
  * @return object CRM_Contribute_BAO_Contribution object 
  * @access public
  * @static
  */
 static function &create(&$params, &$ids)
 {
     require_once 'CRM/Utils/Money.php';
     require_once 'CRM/Utils/Date.php';
     require_once 'CRM/Contribute/PseudoConstant.php';
     // FIXME: a cludgy hack to fix the dates to MySQL format
     $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
     foreach ($dateFields as $df) {
         if (isset($params[$df])) {
             $params[$df] = CRM_Utils_Date::isoToMysql($params[$df]);
         }
     }
     require_once 'CRM/Core/Transaction.php';
     $transaction = new CRM_Core_Transaction();
     $contribution = self::add($params, $ids);
     if (is_a($contribution, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $contribution;
     }
     $params['contribution_id'] = $contribution->id;
     if (CRM_Utils_Array::value('custom', $params) && is_array($params['custom'])) {
         require_once 'CRM/Core/BAO/CustomValueTable.php';
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
     }
     $session =& CRM_Core_Session::singleton();
     if (CRM_Utils_Array::value('note', $params)) {
         require_once 'CRM/Core/BAO/Note.php';
         $noteParams = array('entity_table' => 'civicrm_contribution', 'note' => $params['note'], 'entity_id' => $contribution->id, 'contact_id' => $session->get('userID'), 'modified_date' => date('Ymd'));
         if (!$noteParams['contact_id']) {
             $noteParams['contact_id'] = $params['contact_id'];
         }
         CRM_Core_BAO_Note::add($noteParams, CRM_Utils_Array::value('note', $ids));
     }
     // check if activity record exist for this contribution, if
     // not add activity
     require_once "CRM/Activity/DAO/Activity.php";
     $activity = new CRM_Activity_DAO_Activity();
     $activity->source_record_id = $contribution->id;
     $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type', 'Contribution', 'name');
     if (!$activity->find()) {
         require_once "CRM/Activity/BAO/Activity.php";
         CRM_Activity_BAO_Activity::addActivity($contribution, 'Offline');
     }
     if (CRM_Utils_Array::value('soft_credit_to', $params)) {
         $csParams = array();
         if ($id = CRM_Utils_Array::value('softID', $params)) {
             $csParams['id'] = $params['softID'];
         }
         $csParams['pcp_display_in_roll'] = $params['pcp_display_in_roll'] ? 1 : 0;
         foreach (array('pcp_roll_nickname', 'pcp_personal_note') as $val) {
             if (CRM_Utils_Array::value($val, $params)) {
                 $csParams[$val] = $params[$val];
             }
         }
         $csParams['contribution_id'] = $contribution->id;
         $csParams['contact_id'] = $params['soft_credit_to'];
         // first stage: we register whole amount as credited to given person
         $csParams['amount'] = $contribution->total_amount;
         self::addSoftContribution($csParams);
     }
     $transaction->commit();
     // do not add to recent items for import, CRM-4399
     if (!CRM_Utils_Array::value('skipRecentView', $params)) {
         require_once 'CRM/Utils/Recent.php';
         require_once 'CRM/Contribute/PseudoConstant.php';
         require_once 'CRM/Contact/BAO/Contact.php';
         $url = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home");
         $contributionTypes = CRM_Contribute_PseudoConstant::contributionType();
         $title = CRM_Contact_BAO_Contact::displayName($contribution->contact_id) . ' - (' . CRM_Utils_Money::format($contribution->total_amount, $contribution->currency) . ' ' . ' - ' . $contributionTypes[$contribution->contribution_type_id] . ')';
         $recentOther = array();
         if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) {
             $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home");
         }
         if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) {
             $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home");
         }
         // add the recently created Contribution
         CRM_Utils_Recent::add($title, $url, $contribution->id, 'Contribution', $contribution->contact_id, null, $recentOther);
     }
     return $contribution;
 }
Example #16
0
 /**
  * Takes an associative array and creates a contribution object.
  *
  * @param array $params
  *   (reference ) an assoc array of name/value pairs.
  * @param array $ids
  *   The array that holds all the db ids.
  *
  * @return CRM_Contribute_BAO_Contribution
  */
 public static function create(&$params, $ids = array())
 {
     $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
     foreach ($dateFields as $df) {
         if (isset($params[$df])) {
             $params[$df] = CRM_Utils_Date::isoToMysql($params[$df]);
         }
     }
     $transaction = new CRM_Core_Transaction();
     $contribution = self::add($params, $ids);
     if (is_a($contribution, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $contribution;
     }
     $params['contribution_id'] = $contribution->id;
     if (!empty($params['custom']) && is_array($params['custom'])) {
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_contribution', $contribution->id);
     }
     $session = CRM_Core_Session::singleton();
     if (!empty($params['note'])) {
         $noteParams = array('entity_table' => 'civicrm_contribution', 'note' => $params['note'], 'entity_id' => $contribution->id, 'contact_id' => $session->get('userID'), 'modified_date' => date('Ymd'));
         if (!$noteParams['contact_id']) {
             $noteParams['contact_id'] = $params['contact_id'];
         }
         CRM_Core_BAO_Note::add($noteParams);
     }
     // make entry in batch entity batch table
     if (!empty($params['batch_id'])) {
         // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
         $titleFields = array('contact_id', 'total_amount', 'currency', 'financial_type_id');
         $retrieveRequired = 0;
         foreach ($titleFields as $titleField) {
             if (!isset($contribution->{$titleField})) {
                 $retrieveRequired = 1;
                 break;
             }
         }
         if ($retrieveRequired == 1) {
             $contribution->find(TRUE);
         }
     }
     // Handle soft credit and / or link to personal campaign page
     $softIDs = CRM_Contribute_BAO_ContributionSoft::getSoftCreditIds($contribution->id);
     $pcpId = CRM_Contribute_BAO_ContributionSoft::getSoftCreditIds($contribution->id, TRUE);
     if ($pcp = CRM_Utils_Array::value('pcp', $params)) {
         $softParams = array();
         $softParams['id'] = $pcpId ? $pcpId : NULL;
         $softParams['contribution_id'] = $contribution->id;
         $softParams['pcp_id'] = $pcp['pcp_made_through_id'];
         $softParams['contact_id'] = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $pcp['pcp_made_through_id'], 'contact_id');
         $softParams['currency'] = $contribution->currency;
         $softParams['amount'] = $contribution->total_amount;
         $softParams['pcp_display_in_roll'] = CRM_Utils_Array::value('pcp_display_in_roll', $pcp);
         $softParams['pcp_roll_nickname'] = CRM_Utils_Array::value('pcp_roll_nickname', $pcp);
         $softParams['pcp_personal_note'] = CRM_Utils_Array::value('pcp_personal_note', $pcp);
         $softParams['soft_credit_type_id'] = CRM_Core_OptionGroup::getValue('soft_credit_type', 'pcp', 'name');
         $contributionSoft = CRM_Contribute_BAO_ContributionSoft::add($softParams);
         //Send notification to owner for PCP
         if ($contributionSoft->pcp_id && empty($pcpId)) {
             CRM_Contribute_Form_Contribution_Confirm::pcpNotifyOwner($contribution, $contributionSoft);
         }
     } elseif (array_key_exists('pcp', $params) && $pcpId) {
         $deleteParams = array('id' => $pcpId);
         CRM_Contribute_BAO_ContributionSoft::del($deleteParams);
     }
     if (isset($params['soft_credit'])) {
         $softParams = $params['soft_credit'];
         foreach ($softParams as $softParam) {
             if (!empty($softIDs)) {
                 $key = key($softIDs);
                 $softParam['id'] = $softIDs[$key];
                 unset($softIDs[$key]);
             }
             $softParam['contribution_id'] = $contribution->id;
             $softParam['currency'] = $contribution->currency;
             //case during Contribution Import when we assign soft contribution amount as contribution's total_amount by default
             if (empty($softParam['amount'])) {
                 $softParam['amount'] = $contribution->total_amount;
             }
             CRM_Contribute_BAO_ContributionSoft::add($softParam);
         }
         if (!empty($softIDs)) {
             foreach ($softIDs as $softID) {
                 if (!in_array($softID, $params['soft_credit_ids'])) {
                     $deleteParams = array('id' => $softID);
                     CRM_Contribute_BAO_ContributionSoft::del($deleteParams);
                 }
             }
         }
     }
     $transaction->commit();
     // check if activity record exist for this contribution, if
     // not add activity
     $activity = new CRM_Activity_DAO_Activity();
     $activity->source_record_id = $contribution->id;
     $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type', 'Contribution', 'name');
     if (!$activity->find(TRUE)) {
         CRM_Activity_BAO_Activity::addActivity($contribution, 'Offline');
     } else {
         // CRM-13237 : if activity record found, update it with campaign id of contribution
         CRM_Core_DAO::setFieldValue('CRM_Activity_BAO_Activity', $activity->id, 'campaign_id', $contribution->campaign_id);
     }
     // do not add to recent items for import, CRM-4399
     if (empty($params['skipRecentView'])) {
         $url = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=view&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home");
         // in some update cases we need to get extra fields - ie an update that doesn't pass in all these params
         $titleFields = array('contact_id', 'total_amount', 'currency', 'financial_type_id');
         $retrieveRequired = 0;
         foreach ($titleFields as $titleField) {
             if (!isset($contribution->{$titleField})) {
                 $retrieveRequired = 1;
                 break;
             }
         }
         if ($retrieveRequired == 1) {
             $contribution->find(TRUE);
         }
         $contributionTypes = CRM_Contribute_PseudoConstant::financialType();
         $title = CRM_Contact_BAO_Contact::displayName($contribution->contact_id) . ' - (' . CRM_Utils_Money::format($contribution->total_amount, $contribution->currency) . ' ' . ' - ' . $contributionTypes[$contribution->financial_type_id] . ')';
         $recentOther = array();
         if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::UPDATE)) {
             $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=update&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home");
         }
         if (CRM_Core_Permission::checkActionPermission('CiviContribute', CRM_Core_Action::DELETE)) {
             $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/contribution', "action=delete&reset=1&id={$contribution->id}&cid={$contribution->contact_id}&context=home");
         }
         // add the recently created Contribution
         CRM_Utils_Recent::add($title, $url, $contribution->id, 'Contribution', $contribution->contact_id, NULL, $recentOther);
     }
     return $contribution;
 }
Example #17
0
 /**
  * Takes an associative array and creates a participant object.
  *
  * @param array $params
  *   (reference ) an assoc array of name/value pairs.
  *
  * @return CRM_Event_BAO_Participant
  */
 public static function create(&$params)
 {
     $transaction = new CRM_Core_Transaction();
     $status = NULL;
     if (!empty($params['id'])) {
         $status = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $params['id'], 'status_id');
     }
     $participant = self::add($params);
     if (is_a($participant, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $participant;
     }
     if (!CRM_Utils_Array::value('id', $params) || isset($params['status_id']) && $params['status_id'] != $status) {
         CRM_Activity_BAO_Activity::addActivity($participant);
     }
     //CRM-5403
     //for update mode
     if (self::isPrimaryParticipant($participant->id) && $status) {
         self::updateParticipantStatus($participant->id, $status, $participant->status_id);
     }
     $session = CRM_Core_Session::singleton();
     $id = $session->get('userID');
     if (!$id) {
         $id = CRM_Utils_Array::value('contact_id', $params);
     }
     // add custom field values
     if (!empty($params['custom']) && is_array($params['custom'])) {
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_participant', $participant->id);
     }
     //process note, CRM-7634
     $noteId = NULL;
     if (!empty($params['id'])) {
         $note = CRM_Core_BAO_Note::getNote($params['id'], 'civicrm_participant');
         $noteId = key($note);
     }
     $noteValue = NULL;
     $hasNoteField = FALSE;
     foreach (array('note', 'participant_note') as $noteFld) {
         if (array_key_exists($noteFld, $params)) {
             $noteValue = $params[$noteFld];
             $hasNoteField = TRUE;
             break;
         }
     }
     if ($noteId || $noteValue) {
         if ($noteValue) {
             $noteParams = array('entity_table' => 'civicrm_participant', 'note' => $noteValue, 'entity_id' => $participant->id, 'contact_id' => $id, 'modified_date' => date('Ymd'));
             $noteIDs = array();
             if ($noteId) {
                 $noteIDs['id'] = $noteId;
             }
             CRM_Core_BAO_Note::add($noteParams, $noteIDs);
         } elseif ($noteId && $hasNoteField) {
             CRM_Core_BAO_Note::del($noteId, FALSE);
         }
     }
     // Log the information on successful add/edit of Participant data.
     $logParams = array('entity_table' => 'civicrm_participant', 'entity_id' => $participant->id, 'data' => CRM_Event_PseudoConstant::participantStatus($participant->status_id), 'modified_id' => $id, 'modified_date' => date('Ymd'));
     CRM_Core_BAO_Log::add($logParams);
     $params['participant_id'] = $participant->id;
     $transaction->commit();
     // do not add to recent items for import, CRM-4399
     if (empty($params['skipRecentView'])) {
         $url = CRM_Utils_System::url('civicrm/contact/view/participant', "action=view&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home");
         $recentOther = array();
         if (CRM_Core_Permission::check('edit event participants')) {
             $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/participant', "action=update&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home");
         }
         if (CRM_Core_Permission::check('delete in CiviEvent')) {
             $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/participant', "action=delete&reset=1&id={$participant->id}&cid={$participant->contact_id}&context=home");
         }
         $participantRoles = CRM_Event_PseudoConstant::participantRole();
         if ($participant->role_id) {
             $role = explode(CRM_Core_DAO::VALUE_SEPARATOR, $participant->role_id);
             foreach ($role as &$roleValue) {
                 if (isset($roleValue)) {
                     $roleValue = $participantRoles[$roleValue];
                 }
             }
             $roles = implode(', ', $role);
         }
         $roleString = empty($roles) ? '' : $roles;
         $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $participant->event_id, 'title');
         $title = CRM_Contact_BAO_Contact::displayName($participant->contact_id) . ' (' . $roleString . ' - ' . $eventTitle . ')';
         // add the recently created Participant
         CRM_Utils_Recent::add($title, $url, $participant->id, 'Participant', $participant->contact_id, NULL, $recentOther);
     }
     return $participant;
 }
Example #18
0
 /**
  * takes an associative array and creates a membership object
  *
  * @param array    $params      (reference ) an assoc array of name/value pairs
  * @param array    $ids         the array that holds all the db ids
  * @param boolean  $callFromAPI Is this function called from API?
  * 
  * @return object CRM_Member_BAO_Membership object 
  * @access public
  * @static
  */
 static function &create(&$params, &$ids, $skipRedirect = false, $activityType = 'Membership Signup')
 {
     // always cal status if is_override/skipStatusCal is not true.
     // giving respect to is_override during import.  CRM-4012
     // To skip status cal we should use 'skipStatusCal'.
     // eg pay later membership, membership update cron CRM-3984
     if (!CRM_Utils_Array::value('is_override', $params) && !CRM_Utils_Array::value('skipStatusCal', $params)) {
         require_once 'CRM/Utils/Date.php';
         $startDate = $endDate = $joinDate = null;
         if (isset($params['start_date'])) {
             $startDate = CRM_Utils_Date::customFormat($params['start_date'], '%Y%m%d');
         }
         if (isset($params['end_date'])) {
             $endDate = CRM_Utils_Date::customFormat($params['end_date'], '%Y%m%d');
         }
         if (isset($params['join_date'])) {
             $joinDate = CRM_Utils_Date::customFormat($params['join_date'], '%Y%m%d');
         }
         require_once 'CRM/Member/BAO/MembershipStatus.php';
         //fix for CRM-3570, during import exclude the statuses those having is_admin = 1
         $excludeIsAdmin = CRM_Utils_Array::value('exclude_is_admin', $params, false);
         //CRM-3724 always skip is_admin if is_override != true.
         if (!$excludeIsAdmin && !CRM_Utils_Array::value('is_override', $params)) {
             $excludeIsAdmin = true;
         }
         $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin);
         if (empty($calcStatus)) {
             if (!$skipRedirect) {
                 // Redirect the form in case of error
                 CRM_Core_Session::setStatus(ts('The membership cannot be saved.') . '<br/>' . ts('No valid membership status for given dates.'));
                 return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view', "reset=1&force=1&cid={$params['contact_id']}&selectedChild=member"));
             }
             // Return the error message to the api
             $error = array();
             $error['is_error'] = ts('The membership cannot be saved. No valid membership status for given dates');
             return $error;
         }
         $params['status_id'] = $calcStatus['id'];
     }
     require_once 'CRM/Core/Transaction.php';
     $transaction = new CRM_Core_Transaction();
     $membership =& self::add($params, $ids);
     if (is_a($membership, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $membership;
     }
     // add custom field values
     if (CRM_Utils_Array::value('custom', $params) && is_array($params['custom'])) {
         require_once 'CRM/Core/BAO/CustomValueTable.php';
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_membership', $membership->id);
     }
     $params['membership_id'] = $membership->id;
     if (isset($ids['membership'])) {
         $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $ids['membership'], 'contribution_id', 'membership_id');
     }
     //record contribution for this membership
     if (CRM_Utils_Array::value('contribution_status_id', $params)) {
         $contributionParams = array();
         $config = CRM_Core_Config::singleton();
         $contributionParams['currency'] = $config->defaultCurrency;
         $contributionParams['receipt_date'] = CRM_Utils_Array::value('receipt_date', $params) ? $params['receipt_date'] : 'null';
         $contributionParams['source'] = CRM_Utils_Array::value('contribution_source', $params);
         $contributionParams['non_deductible_amount'] = 'null';
         $recordContribution = array('contact_id', 'total_amount', 'receive_date', 'contribution_type_id', 'payment_instrument_id', 'trxn_id', 'invoice_id', 'is_test', 'contribution_status_id', 'check_number');
         foreach ($recordContribution as $f) {
             $contributionParams[$f] = CRM_Utils_Array::value($f, $params);
         }
         require_once 'CRM/Contribute/BAO/Contribution.php';
         $contribution =& CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
         //insert payment record for this membership
         if (!CRM_Utils_Array::value('contribution', $ids) || CRM_Utils_Array::value('is_recur', $params)) {
             require_once 'CRM/Member/DAO/MembershipPayment.php';
             $mpDAO = new CRM_Member_DAO_MembershipPayment();
             $mpDAO->membership_id = $membership->id;
             $mpDAO->contribution_id = $contribution->id;
             if (CRM_Utils_Array::value('is_recur', $params)) {
                 $mpDAO->find();
             }
             CRM_Utils_Hook::pre('create', 'MembershipPayment', null, $mpDAO);
             $mpDAO->save();
             CRM_Utils_Hook::post('create', 'MembershipPayment', $mpDAO->id, $mpDAO);
         }
     }
     // add activity record only during create mode and renew mode
     // also add activity if status changed CRM-3984 and CRM-2521
     if (!CRM_Utils_Array::value('membership', $ids) || $activityType == 'Membership Renewal' || CRM_Utils_Array::value('createActivity', $params)) {
         if (CRM_Utils_Array::value('membership', $ids)) {
             CRM_Core_DAO::commonRetrieveAll('CRM_Member_DAO_Membership', 'id', $membership->id, $data, array('contact_id', 'membership_type_id', 'source'));
             $membership->contact_id = $data[$membership->id]['contact_id'];
             $membership->membership_type_id = $data[$membership->id]['membership_type_id'];
             $membership->source = CRM_Utils_Array::value('source', $data[$membership->id]);
         }
         // since we are going to create activity record w/
         // individual contact as a target in case of on behalf signup,
         // so get the copy of organization id, CRM-5551
         $realMembershipContactId = $membership->contact_id;
         // create activity source = individual, target = org CRM-4027
         $targetContactID = null;
         if (CRM_Utils_Array::value('is_for_organization', $params)) {
             $targetContactID = $membership->contact_id;
             $membership->contact_id = $ids['userId'];
         }
         require_once 'CRM/Activity/BAO/Activity.php';
         CRM_Activity_BAO_Activity::addActivity($membership, $activityType, $targetContactID);
         // we might created activity record w/ individual
         // contact as target so update membership object w/
         // original organization id, CRM-5551
         $membership->contact_id = $realMembershipContactId;
     }
     $transaction->commit();
     self::createRelatedMemberships($params, $membership);
     // do not add to recent items for import, CRM-4399
     if (!CRM_Utils_Array::value('skipRecentView', $params)) {
         require_once 'CRM/Utils/Recent.php';
         require_once 'CRM/Member/PseudoConstant.php';
         require_once 'CRM/Contact/BAO/Contact.php';
         $url = CRM_Utils_System::url('civicrm/contact/view/membership', "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home");
         $membershipTypes = CRM_Member_PseudoConstant::membershipType();
         $title = CRM_Contact_BAO_Contact::displayName($membership->contact_id) . ' - ' . ts('Membership Type:') . ' ' . $membershipTypes[$membership->membership_type_id];
         require_once 'CRM/Core/Permission.php';
         $recentOther = array();
         if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::UPDATE)) {
             $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership', "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home");
         }
         if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::DELETE)) {
             $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership', "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home");
         }
         // add the recently created Membership
         CRM_Utils_Recent::add($title, $url, $membership->id, 'Membership', $membership->contact_id, null, $recentOther);
     }
     return $membership;
 }
Example #19
0
 /**
  * Takes an associative array and creates a membership object.
  *
  * @param array $params
  *   (reference ) an assoc array of name/value pairs.
  * @param array $ids
  *   The array that holds all the db ids.
  * @param bool $skipRedirect
  * @param string $activityType
  *
  * @throws CRM_Core_Exception
  *
  * @return CRM_Member_BAO_Membership|CRM_Core_Error
  */
 public static function create(&$params, &$ids, $skipRedirect = FALSE, $activityType = 'Membership Signup')
 {
     // always calculate status if is_override/skipStatusCal is not true.
     // giving respect to is_override during import.  CRM-4012
     // To skip status calculation we should use 'skipStatusCal'.
     // eg pay later membership, membership update cron CRM-3984
     if (empty($params['is_override']) && empty($params['skipStatusCal'])) {
         $dates = array('start_date', 'end_date', 'join_date');
         // Declare these out of courtesy as IDEs don't pick up the setting of them below.
         $start_date = $end_date = $join_date = NULL;
         foreach ($dates as $date) {
             ${$date} = $params[$date] = CRM_Utils_Date::processDate(CRM_Utils_Array::value($date, $params), NULL, TRUE, 'Ymd');
         }
         //fix for CRM-3570, during import exclude the statuses those having is_admin = 1
         $excludeIsAdmin = CRM_Utils_Array::value('exclude_is_admin', $params, FALSE);
         //CRM-3724 always skip is_admin if is_override != true.
         if (!$excludeIsAdmin && empty($params['is_override'])) {
             $excludeIsAdmin = TRUE;
         }
         $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($start_date, $end_date, $join_date, 'today', $excludeIsAdmin, CRM_Utils_Array::value('membership_type_id', $params), $params);
         if (empty($calcStatus)) {
             // Redirect the form in case of error
             // @todo this redirect in the BAO layer is really bad & should be moved to the form layer
             // however since we have no idea how (if) this is triggered we can't safely move / remove it
             // NB I tried really hard to trigger this error from backoffice membership form in order to test it
             // and am convinced form validation is complete on that form WRT this error.
             $errorParams = array('message_title' => ts('No valid membership status for given dates.'), 'legacy_redirect_path' => 'civicrm/contact/view', 'legacy_redirect_query' => "reset=1&force=1&cid={$params['contact_id']}&selectedChild=member");
             throw new CRM_Core_Exception(ts("The membership cannot be saved because the status cannot be calculated for start_date: {$start_date} end_date {$end_date} join_date {$join_date} as at " . date('Y-m-d H:i:s')), 0, $errorParams);
         }
         $params['status_id'] = $calcStatus['id'];
     }
     // data cleanup only: all verifications on number of related memberships are done upstream in:
     // CRM_Member_BAO_Membership::createRelatedMemberships()
     // CRM_Contact_BAO_Relationship::relatedMemberships()
     if (isset($params['owner_membership_id'])) {
         unset($params['max_related']);
     } else {
         // if membership allows related, default max_related to value in membership_type
         if (!array_key_exists('max_related', $params) && !empty($params['membership_type_id'])) {
             $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($params['membership_type_id']);
             if (isset($membershipType['relationship_type_id'])) {
                 $params['max_related'] = CRM_Utils_Array::value('max_related', $membershipType);
             }
         }
     }
     $transaction = new CRM_Core_Transaction();
     $membership = self::add($params, $ids);
     if (is_a($membership, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $membership;
     }
     // add custom field values
     if (!empty($params['custom']) && is_array($params['custom'])) {
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_membership', $membership->id);
     }
     $params['membership_id'] = $membership->id;
     if (isset($ids['membership'])) {
         $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id, 'contribution_id', 'membership_id');
     }
     $params['skipLineItem'] = TRUE;
     //record contribution for this membership
     if (!empty($params['contribution_status_id']) && empty($params['relate_contribution_id'])) {
         $memInfo = array_merge($params, array('membership_id' => $membership->id));
         $params['contribution'] = self::recordMembershipContribution($memInfo, $ids);
     }
     if (!empty($params['lineItems'])) {
         $params['line_item'] = $params['lineItems'];
     }
     //do cleanup line  items if membership edit the Membership type.
     if (empty($ids['contribution']) && !empty($ids['membership'])) {
         CRM_Price_BAO_LineItem::deleteLineItems($ids['membership'], 'civicrm_membership');
     }
     if (!empty($params['line_item']) && empty($ids['contribution'])) {
         CRM_Price_BAO_LineItem::processPriceSet($membership->id, $params['line_item'], CRM_Utils_Array::value('contribution', $params));
     }
     //insert payment record for this membership
     if (!empty($params['relate_contribution_id'])) {
         CRM_Member_BAO_MembershipPayment::create(array('membership_id' => $membership->id, 'membership_type_id' => $membership->membership_type_id, 'contribution_id' => $params['relate_contribution_id']));
     }
     // add activity record only during create mode and renew mode
     // also add activity if status changed CRM-3984 and CRM-2521
     if (empty($ids['membership']) || $activityType == 'Membership Renewal' || !empty($params['createActivity'])) {
         if (!empty($ids['membership'])) {
             $data = array();
             CRM_Core_DAO::commonRetrieveAll('CRM_Member_DAO_Membership', 'id', $membership->id, $data, array('contact_id', 'membership_type_id', 'source'));
             $membership->contact_id = $data[$membership->id]['contact_id'];
             $membership->membership_type_id = $data[$membership->id]['membership_type_id'];
             $membership->source = CRM_Utils_Array::value('source', $data[$membership->id]);
         }
         // since we are going to create activity record w/
         // individual contact as a target in case of on behalf signup,
         // so get the copy of organization id, CRM-5551
         $realMembershipContactId = $membership->contact_id;
         // create activity source = individual, target = org CRM-4027
         $targetContactID = NULL;
         if (!empty($params['is_for_organization'])) {
             $targetContactID = $membership->contact_id;
             $membership->contact_id = CRM_Utils_Array::value('userId', $ids);
         }
         if (empty($membership->contact_id) && !empty($membership->owner_membership_id)) {
             $membership->contact_id = $realMembershipContactId;
         }
         if (!empty($ids['membership']) && $activityType != 'Membership Signup') {
             CRM_Activity_BAO_Activity::addActivity($membership, $activityType, $targetContactID);
         } elseif (empty($ids['membership'])) {
             CRM_Activity_BAO_Activity::addActivity($membership, $activityType, $targetContactID);
         }
         // we might created activity record w/ individual
         // contact as target so update membership object w/
         // original organization id, CRM-5551
         $membership->contact_id = $realMembershipContactId;
     }
     $transaction->commit();
     self::createRelatedMemberships($params, $membership);
     // do not add to recent items for import, CRM-4399
     if (empty($params['skipRecentView'])) {
         $url = CRM_Utils_System::url('civicrm/contact/view/membership', "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home");
         if (empty($membership->membership_type_id)) {
             // ie in an update situation.
             $membership->find(TRUE);
         }
         $membershipTypes = CRM_Member_PseudoConstant::membershipType();
         $title = CRM_Contact_BAO_Contact::displayName($membership->contact_id) . ' - ' . ts('Membership Type:') . ' ' . $membershipTypes[$membership->membership_type_id];
         $recentOther = array();
         if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::UPDATE)) {
             $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership', "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home");
         }
         if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::DELETE)) {
             $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership', "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home");
         }
         // add the recently created Membership
         CRM_Utils_Recent::add($title, $url, $membership->id, 'Membership', $membership->contact_id, NULL, $recentOther);
     }
     return $membership;
 }
 /**
  * takes an associative array and creates a membership object
  *
  * @param array    $params      (reference ) an assoc array of name/value pairs
  * @param array    $ids         the array that holds all the db ids
  * @param boolean  $callFromAPI Is this function called from API?
  *
  * @return object CRM_Member_BAO_Membership object
  * @access public
  * @static
  */
 static function &create(&$params, &$ids, $skipRedirect = FALSE, $activityType = 'Membership Signup')
 {
     // always calculate status if is_override/skipStatusCal is not true.
     // giving respect to is_override during import.  CRM-4012
     // To skip status calculation we should use 'skipStatusCal'.
     // eg pay later membership, membership update cron CRM-3984
     if (!CRM_Utils_Array::value('is_override', $params) && !CRM_Utils_Array::value('skipStatusCal', $params)) {
         $startDate = $endDate = $joinDate = NULL;
         if (isset($params['start_date'])) {
             $startDate = $params['start_date'];
         }
         if (array_key_exists('end_date', $params)) {
             $endDate = $params['end_date'];
             $params['end_date'] = CRM_Utils_Date::processDate($endDate, NULL, TRUE, 'Ymd');
         }
         if (isset($params['join_date'])) {
             $joinDate = $params['join_date'];
         }
         //fix for CRM-3570, during import exclude the statuses those having is_admin = 1
         $excludeIsAdmin = CRM_Utils_Array::value('exclude_is_admin', $params, FALSE);
         //CRM-3724 always skip is_admin if is_override != true.
         if (!$excludeIsAdmin && !CRM_Utils_Array::value('is_override', $params)) {
             $excludeIsAdmin = TRUE;
         }
         $calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($startDate, $endDate, $joinDate, 'today', $excludeIsAdmin);
         if (empty($calcStatus)) {
             if (!$skipRedirect) {
                 // Redirect the form in case of error
                 CRM_Core_Session::setStatus(ts('The membership cannot be saved.') . '<br/>' . ts('No valid membership status for given dates.'));
                 return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view', "reset=1&force=1&cid={$params['contact_id']}&selectedChild=member"));
             }
             // Return the error message to the api
             $error = array();
             $error['is_error'] = ts('The membership cannot be saved. No valid membership status for given dates. Please provide at least start_date. Optionally end_date and join_date.');
             return $error;
         }
         $params['status_id'] = $calcStatus['id'];
     }
     $transaction = new CRM_Core_Transaction();
     $membership = self::add($params, $ids);
     if (is_a($membership, 'CRM_Core_Error')) {
         $transaction->rollback();
         return $membership;
     }
     // add custom field values
     if (CRM_Utils_Array::value('custom', $params) && is_array($params['custom'])) {
         CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_membership', $membership->id);
     }
     $params['membership_id'] = $membership->id;
     if (isset($ids['membership'])) {
         $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $ids['membership'], 'contribution_id', 'membership_id');
     }
     //record contribution for this membership
     if (CRM_Utils_Array::value('contribution_status_id', $params) && !CRM_Utils_Array::value('relate_contribution_id', $params)) {
         $params['contribution'] = self::recordMembershipContribution($params, $ids, $membership->id);
     }
     if (CRM_Utils_Array::value('relate_contribution_id', $params)) {
         $mpDAO = new CRM_Member_DAO_MembershipPayment();
         $mpDAO->membership_id = $membership->id;
         $mpDAO->contribution_id = $params['relate_contribution_id'];
         if (!$mpDAO->find(TRUE)) {
             CRM_Utils_Hook::pre('create', 'MembershipPayment', NULL, $mpDAO);
             $mpDAO->save();
             CRM_Utils_Hook::post('create', 'MembershipPayment', $mpDAO->id, $mpDAO);
         }
     }
     // add activity record only during create mode and renew mode
     // also add activity if status changed CRM-3984 and CRM-2521
     if (!CRM_Utils_Array::value('membership', $ids) || $activityType == 'Membership Renewal' || CRM_Utils_Array::value('createActivity', $params)) {
         if (CRM_Utils_Array::value('membership', $ids)) {
             CRM_Core_DAO::commonRetrieveAll('CRM_Member_DAO_Membership', 'id', $membership->id, $data, array('contact_id', 'membership_type_id', 'source'));
             $membership->contact_id = $data[$membership->id]['contact_id'];
             $membership->membership_type_id = $data[$membership->id]['membership_type_id'];
             $membership->source = CRM_Utils_Array::value('source', $data[$membership->id]);
         }
         // since we are going to create activity record w/
         // individual contact as a target in case of on behalf signup,
         // so get the copy of organization id, CRM-5551
         $realMembershipContactId = $membership->contact_id;
         // create activity source = individual, target = org CRM-4027
         $targetContactID = NULL;
         if (CRM_Utils_Array::value('is_for_organization', $params)) {
             $targetContactID = $membership->contact_id;
             $membership->contact_id = CRM_Utils_Array::value('userId', $ids);
         }
         if (empty($membership->contact_id) && !empty($membership->owner_membership_id)) {
             $membership->contact_id = $realMembershipContactId;
         }
         if (CRM_Utils_Array::value('membership', $ids) && $activityType != 'Membership Signup') {
             CRM_Activity_BAO_Activity::addActivity($membership, $activityType, $targetContactID);
         } elseif (!CRM_Utils_Array::value('membership', $ids)) {
             CRM_Activity_BAO_Activity::addActivity($membership, $activityType, $targetContactID);
         }
         // we might created activity record w/ individual
         // contact as target so update membership object w/
         // original organization id, CRM-5551
         $membership->contact_id = $realMembershipContactId;
     }
     $transaction->commit();
     self::createRelatedMemberships($params, $membership);
     // do not add to recent items for import, CRM-4399
     if (!CRM_Utils_Array::value('skipRecentView', $params)) {
         $url = CRM_Utils_System::url('civicrm/contact/view/membership', "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home");
         if (empty($membership->membership_type_id)) {
             // ie in an update situation
             $membership->find(TRUE);
         }
         $membershipTypes = CRM_Member_PseudoConstant::membershipType();
         $title = CRM_Contact_BAO_Contact::displayName($membership->contact_id) . ' - ' . ts('Membership Type:') . ' ' . $membershipTypes[$membership->membership_type_id];
         $recentOther = array();
         if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::UPDATE)) {
             $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership', "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home");
         }
         if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::DELETE)) {
             $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership', "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home");
         }
         // add the recently created Membership
         CRM_Utils_Recent::add($title, $url, $membership->id, 'Membership', $membership->contact_id, NULL, $recentOther);
     }
     return $membership;
 }