Example #1
0
 /**
  * Set the parameters to be passed to contribution create function
  *
  * @param array $params
  * @param integer $contactID
  * @param $financialTypeID
  * @param $online
  * @param $contributionPageId
  * @param $nonDeductibleAmount
  * @param $campaignId
  *
  * @param $isMonetary
  *
  * @param $pending
  * @param $paymentProcessorOutcome
  * @param $receiptDate
  *
  * @param $recurringContributionID
  * @param $isTest
  *
  * @param $addressID
  *
  * @param $softCreditToID
  *
  * @param $lineItems
  *
  * @internal param $financialType
  * @return array
  */
 public static function getContributionParams($params, $contactID, $financialTypeID, $online, $contributionPageId, $nonDeductibleAmount, $campaignId, $isMonetary, $pending, $paymentProcessorOutcome, $receiptDate, $recurringContributionID, $isTest, $addressID, $softCreditToID, $lineItems)
 {
     $contributionParams = array('contact_id' => $contactID, 'financial_type_id' => $financialTypeID, '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, 'is_test' => $isTest, 'address_id' => $addressID, 'soft_credit_to' => $softCreditToID, 'line_item' => $lineItems, 'skipLineItem' => CRM_Utils_Array::value('skipLineItem', $params, 0));
     if (!$online && isset($params['thankyou_date'])) {
         $contributionParam['thankyou_date'] = $params['thankyou_date'];
     }
     if (!$online || $isMonetary) {
         if (empty($params['is_pay_later'])) {
             $contributionParams['payment_instrument_id'] = 1;
         }
     }
     if (!$pending && $paymentProcessorOutcome) {
         $contributionParams += array('fee_amount' => CRM_Utils_Array::value('fee_amount', $paymentProcessorOutcome), 'net_amount' => CRM_Utils_Array::value('net_amount', $paymentProcessorOutcome, $params['amount']), 'trxn_id' => $paymentProcessorOutcome['trxn_id'], 'receipt_date' => $receiptDate, 'trxn_result_code' => CRM_Utils_Array::value('trxn_result_code', $paymentProcessorOutcome), 'payment_processor' => CRM_Utils_Array::value('payment_processor', $paymentProcessorOutcome));
     }
     // CRM-4038: for non-en_US locales, CRM_Contribute_BAO_Contribution::add() expects localised amounts
     $contributionParams['non_deductible_amount'] = trim(CRM_Utils_Money::format($contributionParams['non_deductible_amount'], ' '));
     $contributionParams['total_amount'] = trim(CRM_Utils_Money::format($contributionParams['total_amount'], ' '));
     if ($recurringContributionID) {
         $contributionParams['contribution_recur_id'] = $recurringContributionID;
     }
     $contributionParams['contribution_status_id'] = $pending ? 2 : 1;
     if (isset($contributionParams['invoice_id'])) {
         $contributionParams['id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionParams['invoice_id'], 'id', 'invoice_id');
     }
     return $contributionParams;
 }
Example #2
0
 /**
  * Form rule to validate the date selector and/or if we should deliver
  * immediately.
  *
  * Warning: if you make changes here, be sure to also make them in
  * Retry.php
  * 
  * @param array $params     The form values
  * @return boolean          True if either we deliver immediately, or the
  *                          date is properly set.
  * @static
  */
 function &formRule(&$params)
 {
     if ($params['now']) {
         return true;
     }
     if (!CRM_Utils_Rule::qfDate($params['start_date'])) {
         return array('start_date' => ts('Start date is not valid.'));
     }
     if (CRM_Utils_Date::format($params['start_date']) < date('YmdHi00')) {
         return array('start_date' => ts('Start date cannot be earlier than the current time.'));
     }
     return true;
 }
Example #3
0
 /** 
  * Heart of the viewing process. The runner gets all the meta data for 
  * the contact and calls the appropriate type of page to view. 
  * 
  * @return void 
  * @access public 
  * 
  */
 function preProcess()
 {
     CRM_Utils_System::setTitle(ts('CiviContribute'));
     $startToDate = array();
     $yearToDate = array();
     $monthToDate = array();
     $status = array('Valid', 'Cancelled');
     $startDate = null;
     $config =& CRM_Core_Config::singleton();
     $currentMonth = date('m');
     $currentDay = date('d');
     if ((int) $config->fiscalYearStart['M'] > $currentMonth || (int) $config->fiscalYearStart['M'] == $currentMonth && (int) $config->fiscalYearStart['d'] > $currentDay) {
         $year = date('Y') - 1;
     } else {
         $year = date('Y');
     }
     $year = array('Y' => $year);
     $yearDate = $config->fiscalYearStart;
     $yearDate = array_merge($year, $yearDate);
     $yearDate = CRM_Utils_Date::format($yearDate);
     $monthDate = date('Ym') . '01000000';
     $prefixes = array('start', 'month', 'year');
     $status = array('Valid', 'Cancelled');
     $yearNow = $yearDate + 10000;
     $yearNow .= '000000';
     $yearDate = $yearDate . '000000';
     // we are specific since we want all information till this second
     $now = date('YmdHis');
     require_once 'CRM/Contribute/BAO/Contribution.php';
     foreach ($prefixes as $prefix) {
         $aName = $prefix . 'ToDate';
         $dName = $prefix . 'Date';
         if ($prefix == 'year') {
             $now = $yearNow;
         }
         foreach ($status as $s) {
             ${$aName}[$s] = CRM_Contribute_BAO_Contribution::getTotalAmountAndCount($s, ${$dName}, $now);
             ${$aName}[$s]['url'] = CRM_Utils_System::url('civicrm/contribute/search', "reset=1&force=1&status=1&start={${$dName}}&end={$now}&test=0");
         }
         $this->assign($aName, ${$aName});
     }
     // Check for admin permission to see if we should include the Manage Contribution Pages action link
     $isAdmin = 0;
     require_once 'CRM/Core/Permission.php';
     if (CRM_Core_Permission::check('administer CiviCRM')) {
         $isAdmin = 1;
     }
     $this->assign('isAdmin', $isAdmin);
 }
Example #4
0
 /** 
  * Heart of the viewing process. The runner gets all the meta data for 
  * the contact and calls the appropriate type of page to view. 
  * 
  * @return void 
  * @access public 
  * 
  */
 function preProcess()
 {
     CRM_Utils_System::setTitle(ts('CiviPledge'));
     $startToDate = array();
     $yearToDate = array();
     $monthToDate = array();
     $previousToDate = array();
     $prefixes = array('start', 'month', 'year', 'previous');
     $status = array('Completed', 'Cancelled', 'Pending', 'In Progress', 'Overdue');
     // cumulative (since inception) - prefix = 'start'
     $startDate = null;
     $startDateEnd = null;
     // current year - prefix = 'year'
     $config =& CRM_Core_Config::singleton();
     $yearDate = $config->fiscalYearStart;
     $year = array('Y' => date('Y'));
     $this->assign('curYear', $year['Y']);
     $yearDate = array_merge($year, $yearDate);
     $yearDate = CRM_Utils_Date::format($yearDate);
     $yearDate = $yearDate . '000000';
     $yearDateEnd = $year['Y'] . '1231235959';
     // current month - prefix = 'month'
     $currentMonth = date("F Y", mktime(0, 0, 0, date("m"), 01, date("Y")));
     $this->assign('currentMonthYear', $currentMonth);
     $monthDate = date('Ym') . '01000000';
     $monthDateEnd = CRM_Utils_Date::customFormat(date("Y-m-t", mktime(0, 0, 0, date("m"), 01, date("Y"))), '%Y%m%d') . '235959';
     // previous month - prefix = 'previous'
     $previousDate = CRM_Utils_Date::customFormat(date("Y-m-d", mktime(0, 0, 0, date("m") - 1, 01, date("Y"))), '%Y%m%d') . '000000';
     $previousDateEnd = CRM_Utils_Date::customFormat(date("Y-m-t", mktime(0, 0, 0, date("m") - 1, 01, date("Y"))), '%Y%m%d') . '235959';
     $previousMonth = date("F Y", mktime(0, 0, 0, date("m") - 1, 01, date("Y")));
     $this->assign('previousMonthYear', $previousMonth);
     require_once 'CRM/Pledge/BAO/Pledge.php';
     foreach ($prefixes as $prefix) {
         $aName = $prefix . 'ToDate';
         $startName = $prefix . 'Date';
         $endName = $prefix . 'DateEnd';
         foreach ($status as $s) {
             ${$aName}[str_replace(" ", "", $s)] = CRM_Pledge_BAO_Pledge::getTotalAmountAndCount($s, ${$startName}, ${$endName});
         }
         $this->assign($aName, ${$aName});
     }
 }
Example #5
0
 /**
  * Set the parameters to be passed to contribution create function.
  *
  * @param array $params
  * @param int $financialTypeID
  * @param float $nonDeductibleAmount
  * @param bool $pending
  * @param array $paymentProcessorOutcome
  * @param string $receiptDate
  * @param int $recurringContributionID
  *
  * @return array
  */
 public static function getContributionParams($params, $financialTypeID, $nonDeductibleAmount, $pending, $paymentProcessorOutcome, $receiptDate, $recurringContributionID)
 {
     $contributionParams = array('financial_type_id' => $financialTypeID, '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'], 'tax_amount' => CRM_Utils_Array::value('tax_amount', $params), 'amount_level' => CRM_Utils_Array::value('amount_level', $params), 'invoice_id' => $params['invoiceID'], 'currency' => $params['currencyID'], '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, 'skipLineItem' => CRM_Utils_Array::value('skipLineItem', $params, 0));
     if ($paymentProcessorOutcome) {
         $contributionParams['payment_processor'] = CRM_Utils_Array::value('payment_processor', $paymentProcessorOutcome);
     }
     if (!$pending && $paymentProcessorOutcome) {
         $contributionParams += array('fee_amount' => CRM_Utils_Array::value('fee_amount', $paymentProcessorOutcome), 'net_amount' => CRM_Utils_Array::value('net_amount', $paymentProcessorOutcome, $params['amount']), 'trxn_id' => $paymentProcessorOutcome['trxn_id'], 'receipt_date' => $receiptDate, 'trxn_result_code' => CRM_Utils_Array::value('trxn_result_code', $paymentProcessorOutcome));
     }
     // CRM-4038: for non-en_US locales, CRM_Contribute_BAO_Contribution::add() expects localised amounts
     $contributionParams['non_deductible_amount'] = trim(CRM_Utils_Money::format($contributionParams['non_deductible_amount'], ' '));
     $contributionParams['total_amount'] = trim(CRM_Utils_Money::format($contributionParams['total_amount'], ' '));
     if ($recurringContributionID) {
         $contributionParams['contribution_recur_id'] = $recurringContributionID;
     }
     $contributionParams['contribution_status_id'] = $pending ? 2 : 1;
     if (isset($contributionParams['invoice_id'])) {
         $contributionParams['id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionParams['invoice_id'], 'id', 'invoice_id');
     }
     return $contributionParams;
 }
 /**
  * takes an associative array and creates a contact object
  *
  * the function extract all the params it needs to initialize the create a
  * contact object. the params array could contain additional unused name/value
  * pairs
  *
  * @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_Contact_BAO_Individual object
  * @access public
  * @static
  */
 function add(&$params, &$ids)
 {
     if (!CRM_Contact_BAO_Individual::dataExists($params, $ids)) {
         return;
     }
     $individual =& new CRM_Contact_BAO_Individual();
     $individual->copyValues($params);
     $date = CRM_Utils_Array::value('birth_date', $params);
     if (is_array($date)) {
         $individual->birth_date = CRM_Utils_Date::format($date);
     } else {
         $individual->birth_date = preg_replace('/[^0-9]/', '', $date);
     }
     $individual->middle_name = CRM_Utils_Array::value('middle_name', $params);
     // hack to make db_do save a null value to a field
     if (!$individual->birth_date) {
         $individual->birth_date = 'NULL';
     }
     if (!array_key_exists('is_deceased', $params)) {
         $individual->is_deceased = 0;
     }
     $individual->id = CRM_Utils_Array::value('individual', $ids);
     return $individual->save();
 }
Example #7
0
 /**
  * Form rule to validate the date selector and/or if we should deliver
  * immediately.
  *
  * Warning: if you make changes here, be sure to also make them in
  * Retry.php
  *
  * @param array $params
  *   The form values.
  *
  * @param $files
  * @param $self
  *
  * @return bool
  *   True if either we deliver immediately, or the date is properly
  *   set.
  */
 public static function formRule($params, $files, $self)
 {
     if (!empty($params['_qf_Schedule_submit'])) {
         CRM_Core_Session::setStatus(ts("Your Mass SMS has been saved. Click the 'Continue' action to resume working on it."), ts('Saved'), 'success');
         $url = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1&sms=1');
         CRM_Utils_System::redirect($url);
     }
     if (isset($params['now']) || CRM_Utils_Array::value('_qf_Schedule_back', $params) == ts('Previous')) {
         return TRUE;
     }
     if (CRM_Utils_Date::format(CRM_Utils_Date::processDate($params['start_date'], $params['start_date_time'])) < CRM_Utils_Date::format(date('YmdHi00'))) {
         return array('start_date' => ts('Start date cannot be earlier than the current time.'));
     }
     return TRUE;
 }
 /**
  * global validation rules for the form
  *
  * @param array $fields posted values of the form
  *
  * @return array list of errors to be posted back to the form
  * @static
  * @access public
  */
 static function formRule($fields)
 {
     $errors = array();
     if (!empty($fields['is_active']) && CRM_Utils_System::isNull($fields['subject'])) {
         $errors['subject'] = ts('Subject is a required field.');
     }
     if (!CRM_Utils_System::isNull($fields['absolute_date'])) {
         if (CRM_Utils_Date::format(CRM_Utils_Date::processDate($fields['absolute_date'], NULL)) < CRM_Utils_Date::format(date('YmdHi00'))) {
             $errors['absolute_date'] = ts('Absolute date cannot be earlier than the current time.');
         }
     }
     if (!empty($errors)) {
         return $errors;
     }
     return empty($errors) ? TRUE : $errors;
 }
 function getContributionDates()
 {
     $config = CRM_Core_Config::singleton();
     $currentMonth = date('m');
     $currentDay = date('d');
     if ((int) $config->fiscalYearStart['M'] > $currentMonth || (int) $config->fiscalYearStart['M'] == $currentMonth && (int) $config->fiscalYearStart['d'] > $currentDay) {
         $year = date('Y') - 1;
     } else {
         $year = date('Y');
     }
     $year = array('Y' => $year);
     $yearDate = $config->fiscalYearStart;
     $yearDate = array_merge($year, $yearDate);
     $yearDate = CRM_Utils_Date::format($yearDate);
     $monthDate = date('Ym') . '01';
     $now = date('Ymd');
     return array('now' => $now, 'yearDate' => $yearDate, 'monthDate' => $monthDate);
 }
Example #10
0
 /**
  * assign the minimal set of variables to the template
  *
  * @return void
  * @access public
  */
 function assignToTemplate()
 {
     $name = CRM_Utils_Array::value('billing_first_name', $this->_params);
     if (CRM_Utils_Array::value('billing_middle_name', $this->_params)) {
         $name .= " {$this->_params['billing_middle_name']}";
     }
     $name .= ' ' . CRM_Utils_Array::value('billing_last_name', $this->_params);
     $name = trim($name);
     $this->assign('billingName', $name);
     $this->set('name', $name);
     $this->assign('paymentProcessor', $this->_paymentProcessor);
     $vars = array('amount', 'currencyID', 'credit_card_type', 'trxn_id', 'amount_level');
     $config = CRM_Core_Config::singleton();
     if (isset($this->_values['is_recur']) && CRM_Utils_Array::value('is_recur', $this->_paymentProcessor)) {
         $this->assign('is_recur_enabled', 1);
         $vars = array_merge($vars, array('is_recur', 'frequency_interval', 'frequency_unit', 'installments'));
     }
     if (in_array('CiviPledge', $config->enableComponents) && CRM_Utils_Array::value('is_pledge', $this->_params) == 1) {
         $this->assign('pledge_enabled', 1);
         $vars = array_merge($vars, array('is_pledge', 'pledge_frequency_interval', 'pledge_frequency_unit', 'pledge_installments'));
     }
     if (isset($this->_params['amount_other']) || isset($this->_params['selectMembership'])) {
         $this->_params['amount_level'] = '';
     }
     foreach ($vars as $v) {
         if (isset($this->_params[$v])) {
             if ($v == 'frequency_unit' || $v == 'pledge_frequency_unit') {
                 $frequencyUnits = CRM_Core_OptionGroup::values('recur_frequency_units');
                 if (array_key_exists($this->_params[$v], $frequencyUnits)) {
                     $this->_params[$v] = $frequencyUnits[$this->_params[$v]];
                 }
             }
             if ($v == "amount" && $this->_params[$v] === 0) {
                 $this->_params[$v] = CRM_Utils_Money::format($this->_params[$v], NULL, NULL, TRUE);
             }
             $this->assign($v, $this->_params[$v]);
         }
     }
     // 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);
         $addressFields[$n] = CRM_Utils_Array::value('billing_' . $part, $this->_params);
     }
     $this->assign('address', CRM_Utils_Address::format($addressFields));
     if (CRM_Utils_Array::value('hidden_onbehalf_profile', $this->_params)) {
         $this->assign('onBehalfName', $this->_params['organization_name']);
         $locTypeId = array_keys($this->_params['onbehalf_location']['email']);
         $this->assign('onBehalfEmail', $this->_params['onbehalf_location']['email'][$locTypeId[0]]['email']);
     }
     //fix for CRM-3767
     $assignCCInfo = FALSE;
     if ($this->_amount > 0.0) {
         $assignCCInfo = TRUE;
     } elseif (CRM_Utils_array::value('selectMembership', $this->_params)) {
         $memFee = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_params['selectMembership'], 'minimum_fee');
         if ($memFee > 0.0) {
             $assignCCInfo = TRUE;
         }
     }
     if ($this->_contributeMode == 'direct' && $assignCCInfo) {
         if ($this->_paymentProcessor && $this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_DIRECT_DEBIT) {
             $this->assign('payment_type', $this->_paymentProcessor['payment_type']);
             $this->assign('account_holder', $this->_params['account_holder']);
             $this->assign('bank_identification_number', $this->_params['bank_identification_number']);
             $this->assign('bank_name', $this->_params['bank_name']);
             $this->assign('bank_account_number', $this->_params['bank_account_number']);
         } else {
             $date = CRM_Utils_Date::format(CRM_Utils_array::value('credit_card_exp_date', $this->_params));
             $date = CRM_Utils_Date::mysqlToIso($date);
             $this->assign('credit_card_exp_date', $date);
             $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard(CRM_Utils_array::value('credit_card_number', $this->_params)));
         }
     }
     $this->assign('email', $this->controller->exportValue('Main', "email-{$this->_bltID}"));
     // also assign the receipt_text
     if (isset($this->_values['receipt_text'])) {
         $this->assign('receipt_text', $this->_values['receipt_text']);
     }
 }
Example #11
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}"));
     }
 }
 /**
  * Get the values for pseudoconstants for name->value and reverse.
  *
  * @param array $defaults
  *   (reference) the default values, some of which need to be resolved.
  * @param bool $reverse
  *   True if we want to resolve the values in the reverse direction (value -> name).
  */
 public static function resolveDefaults(&$defaults, $reverse = FALSE)
 {
     // Hack for birth_date.
     if (!empty($defaults['birth_date'])) {
         if (is_array($defaults['birth_date'])) {
             $defaults['birth_date'] = CRM_Utils_Date::format($defaults['birth_date'], '-');
         }
     }
     CRM_Utils_Array::lookupValue($defaults, 'prefix', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id'), $reverse);
     CRM_Utils_Array::lookupValue($defaults, 'suffix', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'suffix_id'), $reverse);
     CRM_Utils_Array::lookupValue($defaults, 'gender', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'), $reverse);
     CRM_Utils_Array::lookupValue($defaults, 'communication_style', CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'communication_style_id'), $reverse);
     //lookup value of email/postal greeting, addressee, CRM-4575
     foreach (self::$_greetingTypes as $greeting) {
         $filterCondition = array('contact_type' => CRM_Utils_Array::value('contact_type', $defaults), 'greeting_type' => $greeting);
         CRM_Utils_Array::lookupValue($defaults, $greeting, CRM_Core_PseudoConstant::greeting($filterCondition), $reverse);
     }
     $blocks = array('address', 'im', 'phone');
     foreach ($blocks as $name) {
         if (!array_key_exists($name, $defaults) || !is_array($defaults[$name])) {
             continue;
         }
         foreach ($defaults[$name] as $count => &$values) {
             //get location type id.
             CRM_Utils_Array::lookupValue($values, 'location_type', CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'), $reverse);
             if ($name == 'address') {
                 // FIXME: lookupValue doesn't work for vcard_name
                 if (!empty($values['location_type_id'])) {
                     $vcardNames = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id', array('labelColumn' => 'vcard_name'));
                     $values['vcard_name'] = $vcardNames[$values['location_type_id']];
                 }
                 if (!CRM_Utils_Array::lookupValue($values, 'country', CRM_Core_PseudoConstant::country(), $reverse) && $reverse) {
                     CRM_Utils_Array::lookupValue($values, 'country', CRM_Core_PseudoConstant::countryIsoCode(), $reverse);
                 }
                 // CRM-7597
                 // if we find a country id above, we need to restrict it to that country
                 // rather than the list of all countries
                 if (!empty($values['country_id'])) {
                     $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceForCountry($values['country_id']);
                 } else {
                     $stateProvinceList = CRM_Core_PseudoConstant::stateProvince();
                 }
                 if (!CRM_Utils_Array::lookupValue($values, 'state_province', $stateProvinceList, $reverse) && $reverse) {
                     if (!empty($values['country_id'])) {
                         $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceForCountry($values['country_id'], 'abbreviation');
                     } else {
                         $stateProvinceList = CRM_Core_PseudoConstant::stateProvinceAbbreviation();
                     }
                     CRM_Utils_Array::lookupValue($values, 'state_province', $stateProvinceList, $reverse);
                 }
                 if (!empty($values['state_province_id'])) {
                     $countyList = CRM_Core_PseudoConstant::countyForState($values['state_province_id']);
                 } else {
                     $countyList = CRM_Core_PseudoConstant::county();
                 }
                 CRM_Utils_Array::lookupValue($values, 'county', $countyList, $reverse);
             }
             if ($name == 'im') {
                 CRM_Utils_Array::lookupValue($values, 'provider', CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'), $reverse);
             }
             if ($name == 'phone') {
                 CRM_Utils_Array::lookupValue($values, 'phone_type', CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'), $reverse);
             }
             // Kill the reference.
             unset($values);
         }
     }
 }
 /**
  * Form rule to validate the date selector and/or if we should deliver
  * immediately.
  *
  * Warning: if you make changes here, be sure to also make them in
  * Retry.php
  *
  * @param array $params     The form values
  *
  * @return boolean          True if either we deliver immediately, or the
  *                          date is properly set.
  * @static
  */
 public static function formRule($params, $files, $self)
 {
     if (!empty($params['_qf_Schedule_submit'])) {
         //when user perform mailing from search context
         //redirect it to search result CRM-3711.
         $ssID = $self->get('ssID');
         if ($ssID && $self->_searchBasedMailing) {
             if ($self->_action == CRM_Core_Action::BASIC) {
                 $fragment = 'search';
             } elseif ($self->_action == CRM_Core_Action::PROFILE) {
                 $fragment = 'search/builder';
             } elseif ($self->_action == CRM_Core_Action::ADVANCED) {
                 $fragment = 'search/advanced';
             } else {
                 $fragment = 'search/custom';
             }
             $draftURL = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1');
             $status = ts("Your mailing has been saved. You can continue later by clicking the 'Continue' action to resume working on it.<br /> From <a href='%1'>Draft and Unscheduled Mailings</a>.", array(1 => $draftURL));
             CRM_Core_Session::setStatus($status);
             //replace user context to search.
             $context = $self->get('context');
             if (!CRM_Contact_Form_Search::isSearchContext($context)) {
                 $context = 'search';
             }
             $urlParams = "force=1&reset=1&ssID={$ssID}&context={$context}";
             $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this);
             if (CRM_Utils_Rule::qfKey($qfKey)) {
                 $urlParams .= "&qfKey={$qfKey}";
             }
             $url = CRM_Utils_System::url('civicrm/contact/' . $fragment, "force=1&reset=1&ssID={$ssID}");
             CRM_Utils_System::redirect($url);
         } else {
             CRM_Core_Session::setStatus(ts("Your mailing has been saved. Click the 'Continue' action to resume working on it."));
             $url = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1');
             CRM_Utils_System::redirect($url);
         }
     }
     if (isset($params['now']) || CRM_Utils_Array::value('_qf_Schedule_back', $params) == '<< Previous') {
         return TRUE;
     }
     if (CRM_Utils_Date::format(CRM_Utils_Date::processDate($params['start_date'], $params['start_date_time'])) < CRM_Utils_Date::format(date('YmdHi00'))) {
         return array('start_date' => ts('Start date cannot be earlier than the current time.'));
     }
     return TRUE;
 }
 /**
  * Where clause for a single field.
  *
  * @param $values
  * @param $query
  *
  * @return void
  */
 public static function whereClauseSingle(&$values, &$query)
 {
     list($name, $op, $value, $grouping, $wildcard) = $values;
     $val = $names = array();
     switch ($name) {
         case 'case_type_id':
         case 'case_type':
         case 'case_status':
         case 'case_status_id':
         case 'case_id':
             if (strpos($name, 'type')) {
                 $name = 'case_type_id';
                 $label = 'Case Type(s)';
             } elseif (strpos($name, 'status')) {
                 $name = 'status_id';
                 $label = 'Case Status(s)';
             } else {
                 $name = 'id';
                 $label = 'Case ID';
             }
             $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_case.{$name}", $op, $value, "Integer");
             list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Case_DAO_Case', $name, $value, $op);
             $query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $label, 2 => $op, 3 => $value));
             $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
             return;
         case 'case_owner':
         case 'case_mycases':
             if (!empty($value)) {
                 if ($value == 2) {
                     $session = CRM_Core_Session::singleton();
                     $userID = $session->get('userID');
                     $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_relationship.contact_id_b", $op, $userID, 'Int');
                     $query->_qill[$grouping][] = ts('Case %1 My Cases', array(1 => $op));
                     $query->_tables['case_relationship'] = $query->_whereTables['case_relationship'] = 1;
                 } elseif ($value == 1) {
                     $query->_qill[$grouping][] = ts('Case %1 All Cases', array(1 => $op));
                     $query->_where[$grouping][] = "civicrm_case_contact.contact_id = contact_a.id";
                 }
                 $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
                 $query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
             }
             return;
         case 'case_deleted':
             $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_case.is_deleted", $op, $value, 'Boolean');
             if ($value) {
                 $query->_qill[$grouping][] = ts("Find Deleted Cases");
             }
             $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
             return;
         case 'case_activity_subject':
             $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_activity.subject", $op, $value, 'String');
             $query->_qill[$grouping][] = ts("Activity Subject %1 '%2'", array(1 => $op, 2 => $value));
             $query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1;
             $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
             $query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
             return;
         case 'case_subject':
             $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_case.subject", $op, $value, 'String');
             $query->_qill[$grouping][] = ts("Case Subject %1 '%2'", array(1 => $op, 2 => $value));
             $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
             $query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
             return;
         case 'case_source_contact_id':
             $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_case_reporter.sort_name", $op, $value, 'String');
             $query->_qill[$grouping][] = ts("Activity Reporter %1 '%2'", array(1 => $op, 2 => $value));
             $query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1;
             $query->_tables['civicrm_case_reporter'] = $query->_whereTables['civicrm_case_reporter'] = 1;
             $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
             $query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
             return;
         case 'case_recent_activity_date':
             $date = CRM_Utils_Date::format($value);
             $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_activity.activity_date_time", $op, $date, 'Date');
             if ($date) {
                 $date = CRM_Utils_Date::customFormat($date);
                 $query->_qill[$grouping][] = ts("Activity Actual Date %1 %2", array(1 => $op, 2 => $date));
             }
             $query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1;
             $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
             $query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
             return;
         case 'case_scheduled_activity_date':
             $date = CRM_Utils_Date::format($value);
             $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_activity.activity_date_time", $op, $date, 'Date');
             if ($date) {
                 $date = CRM_Utils_Date::customFormat($date);
                 $query->_qill[$grouping][] = ts("Activity Schedule Date %1 %2", array(1 => $op, 2 => $date));
             }
             $query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1;
             $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
             $query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
             return;
         case 'case_recent_activity_type':
             $names = $value;
             if ($activityType = CRM_Core_OptionGroup::getLabel('activity_type', $value, 'value')) {
                 $names = $activityType;
             }
             $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_activity.activity_type_id", $op, $value, 'Int');
             $query->_qill[$grouping][] = ts("Activity Type %1 %2", array(1 => $op, 2 => $names));
             $query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1;
             $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
             $query->_tables['case_activity_type'] = 1;
             $query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
             return;
         case 'case_activity_status_id':
             $names = $value;
             if ($activityStatus = CRM_Core_OptionGroup::getLabel('activity_status', $value, 'value')) {
                 $names = $activityStatus;
             }
             $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_activity.status_id", $op, $value, 'Int');
             $query->_qill[$grouping][] = ts("Activity Type %1 %2", array(1 => $op, 2 => $names));
             $query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1;
             $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
             $query->_tables['case_activity_status'] = 1;
             $query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
             return;
         case 'case_activity_duration':
             $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_activity.duration", $op, $value, 'Int');
             $query->_qill[$grouping][] = ts("Activity Duration %1 %2", array(1 => $op, 2 => $value));
             $query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1;
             $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
             $query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
             return;
         case 'case_activity_medium_id':
             $names = $value;
             if ($activityMedium = CRM_Core_OptionGroup::getLabel('encounter_medium', $value, 'value')) {
                 $names = $activityMedium;
             }
             $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_activity.medium_id", $op, $value, 'Int');
             $query->_qill[$grouping][] = ts("Activity Medium %1 %2", array(1 => $op, 2 => $names));
             $query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1;
             $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
             $query->_tables['case_activity_medium'] = 1;
             $query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
             return;
         case 'case_activity_details':
             $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_activity.details", $op, $value, 'String');
             $query->_qill[$grouping][] = ts("Activity Details %1 '%2'", array(1 => $op, 2 => $value));
             $query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1;
             $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
             $query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
             return;
         case 'case_activity_is_auto':
             $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_activity.is_auto", $op, $value, 'Boolean');
             $query->_qill[$grouping][] = ts("Activity Auto Genrated %1 '%2'", array(1 => $op, 2 => $value));
             $query->_tables['case_activity'] = $query->_whereTables['case_activity'] = 1;
             $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
             $query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
             return;
             // adding where clause for case_role
         // adding where clause for case_role
         case 'case_role':
             $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("case_relation_type.name_b_a", $op, $value, 'String');
             $query->_qill[$grouping][] = ts("Role in Case  %1 '%2'", array(1 => $op, 2 => $value));
             $query->_tables['case_relation_type'] = $query->_whereTables['case_relationship_type'] = 1;
             $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
             $query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
             return;
         case 'case_from_start_date_low':
         case 'case_from_start_date_high':
             $query->dateQueryBuilder($values, 'civicrm_case', 'case_from_start_date', 'start_date', 'Start Date');
             return;
         case 'case_to_end_date_low':
         case 'case_to_end_date_high':
             $query->dateQueryBuilder($values, 'civicrm_case', 'case_to_end_date', 'end_date', 'End Date');
             return;
         case 'case_start_date':
             $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_case.start_date", $op, $value, 'Int');
             $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
             return;
         case 'case_end_date':
             $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_case.end_date", $op, $value, 'Int');
             $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
             return;
         case 'case_taglist':
             $taglist = $value;
             $value = array();
             foreach ($taglist as $val) {
                 if ($val) {
                     $val = explode(',', $val);
                     foreach ($val as $tId) {
                         if (is_numeric($tId)) {
                             $value[$tId] = 1;
                         }
                     }
                 }
             }
         case 'case_tags':
             $tags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
             if (is_array($value)) {
                 foreach ($value as $k => $v) {
                     if ($v) {
                         $val[$k] = $k;
                         $names[] = $tags[$k];
                     }
                 }
             }
             $query->_where[$grouping][] = " civicrm_case_tag.tag_id IN (" . implode(',', $val) . " )";
             $query->_qill[$grouping][] = ts('Case Tags %1', array(1 => $op)) . ' ' . implode(' ' . ts('or') . ' ', $names);
             $query->_tables['civicrm_case'] = $query->_whereTables['civicrm_case'] = 1;
             $query->_tables['civicrm_case_contact'] = $query->_whereTables['civicrm_case_contact'] = 1;
             $query->_tables['civicrm_case_tag'] = $query->_whereTables['civicrm_case_tag'] = 1;
             return;
     }
 }
Example #15
0
 /** 
  * Function to process the form 
  * 
  * @access public 
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         require_once "CRM/Event/BAO/Participant.php";
         CRM_Event_BAO_Participant::deleteParticipant($this->_participantId);
         return;
     }
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     // set the contact, when contact is selected
     if (CRM_Utils_Array::value('contact_select_id', $params)) {
         $this->_contactID = CRM_Utils_Array::value('contact_select_id', $params);
     }
     $config =& CRM_Core_Config::singleton();
     //check if discount is selected
     if (CRM_Utils_Array::value('discount_id', $params)) {
         $discountId = $params['discount_id'];
     } else {
         $params['discount_id'] = 'null';
         $discountId = null;
     }
     if ($this->_isPaidEvent) {
         //lets carry currency, CRM-4453
         $params['fee_currency'] = $config->defaultCurrency;
         // fix for CRM-3088
         if ($discountId && !empty($this->_values['discount'][$discountId])) {
             $params['amount_level'] = $this->_values['discount'][$discountId][$params['amount']]['label'];
             $params['amount'] = $this->_values['discount'][$discountId][$params['amount']]['value'];
             $this->assign('amount_level', $params['amount_level']);
         } else {
             if (!isset($params['priceSetId'])) {
                 $params['amount_level'] = $this->_values['fee'][$params['amount']]['label'];
                 $params['amount'] = $this->_values['fee'][$params['amount']]['value'];
                 $this->assign('amount_level', $params['amount_level']);
             } else {
                 if (!$this->_online) {
                     $lineItem = array();
                     CRM_Price_BAO_Set::processAmount($this->_values['fee']['fields'], $params, $lineItem[0]);
                     $this->set('lineItem', $lineItem);
                     $this->assign('lineItem', $lineItem);
                     $this->_lineItem = $lineItem;
                 }
             }
         }
         $params['fee_level'] = $params['amount_level'];
         $contributionParams = array();
         $contributionParams['total_amount'] = $params['amount'];
     }
     //fix for CRM-3086
     $params['fee_amount'] = $params['amount'];
     $this->_params = $params;
     unset($params['amount']);
     $params['register_date'] = CRM_Utils_Date::processDate($params['register_date'], $params['register_date_time']);
     $params['receive_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $params));
     $params['contact_id'] = $this->_contactID;
     if ($this->_participantId) {
         $params['id'] = $this->_participantId;
     }
     $status = null;
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $participantBAO =& new CRM_Event_BAO_Participant();
         $participantBAO->id = $this->_participantId;
         $participantBAO->find();
         while ($participantBAO->fetch()) {
             $status = $participantBAO->status_id;
             $contributionParams['total_amount'] = $participantBAO->fee_amount;
         }
         $params['discount_id'] = null;
         //re-enter the values for UPDATE mode
         $params['fee_level'] = $params['amount_level'] = $participantBAO->fee_level;
         $params['fee_amount'] = $participantBAO->fee_amount;
     }
     require_once 'CRM/Contact/BAO/Contact.php';
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     $session =& CRM_Core_Session::singleton();
     $userID = $session->get('userID');
     list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
     require_once "CRM/Event/BAO/Participant.php";
     if ($this->_mode) {
         if (!$this->_isPaidEvent) {
             CRM_Core_Error::fatal(ts('Selected Event is not Paid Event '));
         }
         //modify params according to parameter used in create
         //participant method (addParticipant)
         $params['participant_status_id'] = $params['status_id'];
         $params['participant_role_id'] = $params['role_id'];
         $params['participant_register_date'] = $params['register_date'];
         $params['participant_source'] = $params['source'];
         require_once 'CRM/Core/BAO/PaymentProcessor.php';
         $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode);
         require_once "CRM/Contact/BAO/Contact.php";
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields["email-Primary"] = 1;
         $params["email-Primary"] = $params["email-{$this->_bltID}"] = $this->_contributorEmail;
         $params['register_date'] = $now;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
         $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         $fields["email-{$this->_bltID}"] = 1;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $params)) {
                 $params[$name] = $params["billing_{$name}"];
                 $params['preserveDBName'] = true;
             }
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactID, null, null, $ctype);
     }
     // build custom data getFields array
     $customFieldsRole = CRM_Core_BAO_CustomField::getFields('Participant', false, false, CRM_Utils_Array::value('role_id', $params), $this->_roleCustomDataTypeID);
     $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant', false, false, CRM_Utils_Array::value('event_id', $params), $this->_eventNameCustomDataTypeID);
     $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole, CRM_Core_BAO_CustomField::getFields('Participant', false, false, null, null, true));
     $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_participantId, 'Participant');
     if ($this->_mode) {
         // add all the additioanl payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = $this->_params['credit_card_exp_date']['Y'];
         $this->_params['month'] = $this->_params['credit_card_exp_date']['M'];
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $params['fee_amount'];
         $this->_params['amount_level'] = $params['amount_level'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['payment_action'] = 'Sale';
         $this->_params['invoiceID'] = md5(uniqid(rand(), true));
         // at this point we've created a contact and stored its address etc
         // all the payment processors expect the name and address to be in the
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         require_once 'CRM/Core/Payment/Form.php';
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, true);
         $payment =& CRM_Core_Payment::singleton($this->_mode, 'Event', $this->_paymentProcessor, $this);
         $result =& $payment->doDirectPayment($paymentParams);
         if (is_a($result, 'CRM_Core_Error')) {
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&cid={$this->_contactID}&context=participant&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $this->_params['receive_date'] = $now;
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $this->_params['receipt_date'] = $now;
         } else {
             $this->_params['receipt_date'] = null;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
         $this->assign('receive_date', CRM_Utils_Date::processDate($this->_params['receive_date']));
         // set source if not set
         $this->_params['description'] = ts('Submit Credit Card for Event Registration by: %1', array(1 => $userName));
         require_once 'CRM/Event/Form/Registration/Confirm.php';
         require_once 'CRM/Event/Form/Registration.php';
         //add contribution record
         $this->_params['contribution_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'contribution_type_id');
         $this->_params['mode'] = $this->_mode;
         //add contribution reocord
         $contribution = CRM_Event_Form_Registration_Confirm::processContribution($this, $this->_params, $result, $contactID, false);
         // add participant record
         $participants = array();
         $participants[] = CRM_Event_Form_Registration::addParticipant($this->_params, $contactID);
         //add custom data for participant
         require_once 'CRM/Core/BAO/CustomValueTable.php';
         CRM_Core_BAO_CustomValueTable::postProcess($this->_params, CRM_Core_DAO::$_nullArray, 'civicrm_participant', $participants[0]->id, 'Participant');
         //add participant payment
         require_once 'CRM/Event/BAO/ParticipantPayment.php';
         $paymentParticipant = array('participant_id' => $participants[0]->id, 'contribution_id' => $contribution->id);
         $ids = array();
         CRM_Event_BAO_ParticipantPayment::create($paymentParticipant, $ids);
         $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         $this->_contactIds[] = $this->_contactID;
     } else {
         $participants = array();
         // fix note if deleted
         if (!$params['note']) {
             $params['note'] = 'null';
         }
         if ($this->_single) {
             $participants[] = CRM_Event_BAO_Participant::create($params);
         } else {
             foreach ($this->_contactIds as $contactID) {
                 $commonParams = $params;
                 $commonParams['contact_id'] = $contactID;
                 $participants[] = CRM_Event_BAO_Participant::create($commonParams);
             }
         }
         if (isset($params['event_id'])) {
             $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         }
         if ($this->_single) {
             $this->_contactIds[] = $this->_contactID;
         }
         if (CRM_Utils_Array::value('record_contribution', $params)) {
             if (CRM_Utils_Array::value('id', $params)) {
                 if ($this->_onlinePendingContributionId) {
                     $ids['contribution'] = $this->_onlinePendingContributionId;
                 } else {
                     $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $params['id'], 'contribution_id', 'participant_id');
                 }
             }
             unset($params['note']);
             //build contribution params
             if (!$this->_onlinePendingContributionId) {
                 $contributionParams['source'] = "{$eventTitle}: Offline registration (by {$userName})";
             }
             $contributionParams['currency'] = $config->defaultCurrency;
             $contributionParams['non_deductible_amount'] = 'null';
             $contributionParams['receipt_date'] = CRM_Utils_Array::value('send_receipt', $params) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
             $recordContribution = array('contact_id', 'contribution_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'receive_date', 'check_number');
             foreach ($recordContribution as $f) {
                 $contributionParams[$f] = CRM_Utils_Array::value($f, $params);
                 if ($f == 'trxn_id') {
                     $this->assign('trxn_id', $contributionParams[$f]);
                 }
             }
             //insert contribution type name in receipt.
             $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionType', $contributionParams['contribution_type_id']));
             require_once 'CRM/Contribute/BAO/Contribution.php';
             $contributions = array();
             if ($this->_single) {
                 $contributions[] =& CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
             } else {
                 $ids = array();
                 foreach ($this->_contactIds as $contactID) {
                     $contributionParams['contact_id'] = $contactID;
                     $contributions[] =& CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
                 }
             }
             //insert payment record for this participation
             if (!$ids['contribution']) {
                 require_once 'CRM/Event/DAO/ParticipantPayment.php';
                 foreach ($this->_contactIds as $num => $contactID) {
                     $ppDAO =& new CRM_Event_DAO_ParticipantPayment();
                     $ppDAO->participant_id = $participants[$num]->id;
                     $ppDAO->contribution_id = $contributions[$num]->id;
                     $ppDAO->save();
                 }
             }
         }
     }
     // also store lineitem stuff here
     if ($this->_lineItem) {
         require_once 'CRM/Price/BAO/LineItem.php';
         foreach ($this->_contactIds as $num => $contactID) {
             foreach ($this->_lineItem as $key => $value) {
                 if (is_array($value) && $value != 'skip') {
                     foreach ($value as $line) {
                         $line['entity_table'] = 'civicrm_participant';
                         $line['entity_id'] = $participants[$num]->id;
                         CRM_Price_BAO_LineItem::create($line);
                     }
                 }
             }
         }
     }
     $updateStatusMsg = null;
     //send mail when participant status changed, CRM-4326
     if ($this->_participantId && $this->_statusId && $this->_statusId != CRM_Utils_Array::value('status_id', $params) && CRM_Utils_Array::value('is_notify', $params)) {
         require_once "CRM/Event/BAO/Participant.php";
         $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_participantId, $params['status_id'], $this->_statusId);
     }
     if (CRM_Utils_Array::value('send_receipt', $params)) {
         $receiptFrom = "{$userName} <{$userEmail}>";
         $this->assign('module', 'Event Registration');
         //use of the message template below requires variables in different format
         $event = $events = array();
         $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
         //get all event details.
         CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
         $event = $events[$params['event_id']];
         unset($event['start_date']);
         unset($event['end_date']);
         $role = CRM_Event_PseudoConstant::participantRole();
         $event['participant_role'] = $role[$params['role_id']];
         $event['is_monetary'] = $this->_isPaidEvent;
         if ($params['receipt_text']) {
             $event['confirm_email_text'] = $params['receipt_text'];
         }
         $this->assign('isAmountzero', 1);
         $this->assign('event', $event);
         $this->assign('isShowLocation', $event['is_show_location']);
         if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
             $locationParams = array('entity_id' => $params['event_id'], 'entity_table' => 'civicrm_event');
             require_once 'CRM/Core/BAO/Location.php';
             $location = CRM_Core_BAO_Location::getValues($locationParams, true);
             $this->assign('location', $location);
         }
         $status = CRM_Event_PseudoConstant::participantStatus();
         if ($this->_isPaidEvent) {
             $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
             if (!$this->_mode) {
                 $this->assign('paidBy', CRM_Utils_Array::value($params['payment_instrument_id'], $paymentInstrument));
             }
             $this->assign('totalAmount', $contributionParams['total_amount']);
             $this->assign('isPrimary', 1);
             $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
         }
         if ($this->_mode) {
             if (CRM_Utils_Array::value('billing_first_name', $params)) {
                 $name = $params['billing_first_name'];
             }
             if (CRM_Utils_Array::value('billing_middle_name', $params)) {
                 $name .= " {$params['billing_middle_name']}";
             }
             if (CRM_Utils_Array::value('billing_last_name', $params)) {
                 $name .= " {$params['billing_last_name']}";
             }
             $this->assign('billingName', $name);
             // assign the address formatted up for display
             $addressParts = array("street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "state_province-{$this->_bltID}", "country-{$this->_bltID}");
             $addressFields = array();
             foreach ($addressParts as $part) {
                 list($n, $id) = explode('-', $part);
                 if (isset($this->_params['billing_' . $part])) {
                     $addressFields[$n] = $this->_params['billing_' . $part];
                 }
             }
             require_once 'CRM/Utils/Address.php';
             $this->assign('address', CRM_Utils_Address::format($addressFields));
             $date = CRM_Utils_Date::format($params['credit_card_exp_date']);
             $date = CRM_Utils_Date::mysqlToIso($date);
             $this->assign('credit_card_exp_date', $date);
             $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($params['credit_card_number']));
             $this->assign('credit_card_type', $params['credit_card_type']);
             $this->assign('contributeMode', 'direct');
             $this->assign('isAmountzero', 0);
             $this->assign('is_pay_later', 0);
             $this->assign('isPrimary', 1);
         }
         $this->assign('register_date', $params['register_date']);
         if ($params['receive_date']) {
             $this->assign('receive_date', $params['receive_date']);
         }
         $participant = array(array('participant_id', '=', $participants[0]->id, 0, 0));
         // check whether its a test drive ref CRM-3075
         if (CRM_Utils_Array::value('is_test', $this->_defaultValues)) {
             $participant[] = array('participant_test', '=', 1, 0, 0);
         }
         $template =& CRM_Core_Smarty::singleton();
         $customGroup = array();
         //format submitted data
         foreach ($params['custom'] as $fieldID => $values) {
             foreach ($values as $fieldValue) {
                 $customValue = array('data' => $fieldValue['value']);
                 $customFields[$fieldID]['id'] = $fieldID;
                 $formattedValue = CRM_Core_BAO_CustomGroup::formatCustomValues($customValue, $customFields[$fieldID]);
                 $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
             }
         }
         foreach ($this->_contactIds as $num => $contactID) {
             // Retrieve the name and email of the contact - this will be the TO for receipt email
             list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
             $this->_contributorDisplayName = $this->_contributorDisplayName == ' ' ? $this->_contributorEmail : $this->_contributorDisplayName;
             $this->assign('customGroup', $customGroup);
             $this->assign('contactID', $contactID);
             $this->assign('participantID', $participants[$num]->id);
             if ($this->_isPaidEvent) {
                 // fix amount for each of participants ( for bulk mode )
                 $eventAmount = array();
                 $eventAmount[$num] = array('label' => $params['amount_level'], 'amount' => $params['fee_amount']);
                 //as we are using same template for online & offline registration.
                 //So we have to build amount as array.
                 $this->assign('amount', $eventAmount);
             }
             $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'event_offline_receipt', 'contactId' => $contactID, 'isTest' => (bool) CRM_Utils_Array::value('is_test', $this->_defaultValues));
             // try to send emails only if email id is present
             // and the do-not-email option is not checked for that contact
             if ($this->_contributorEmail and !$this->_toDoNotEmail) {
                 $sendTemplateParams['from'] = $receiptFrom;
                 $sendTemplateParams['toName'] = $this->_contributorDisplayName;
                 $sendTemplateParams['toEmail'] = $this->_contributorEmail;
             }
             require_once 'CRM/Core/BAO/MessageTemplates.php';
             list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplates::sendTemplate($sendTemplateParams);
             if ($mailSent) {
                 $sent[] = $contactID;
             } else {
                 $notSent[] = $contactID;
             }
         }
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contributorDisplayName));
         if ($params['send_receipt'] && count($sent)) {
             $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', array(1 => $this->_contributorEmail));
         }
         if ($updateStatusMsg) {
             $statusMsg = "{$statusMsg} {$updateStatusMsg}";
         }
     } elseif ($this->_action & CRM_Core_Action::ADD) {
         if ($this->_single) {
             $statusMsg = ts('Event registration for %1 has been added.', array(1 => $this->_contributorDisplayName));
             if (CRM_Utils_Array::value('send_receipt', $params) && count($sent)) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $this->_contributorEmail));
             }
         } else {
             $statusMsg = ts('Total Participant(s) added to event: %1.', array(1 => count($this->_contactIds)));
             if (count($notSent) > 0) {
                 $statusMsg .= ' ' . ts('Email has NOT been sent to %1 contact - communication preferences specify DO NOT EMAIL OR valid Email is NOT present. ', array(1 => count($notSent)));
             } elseif (isset($params['send_receipt'])) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to ALL participants');
             }
         }
     }
     require_once "CRM/Core/Session.php";
     CRM_Core_Session::setStatus("{$statusMsg}");
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=participant"));
         }
     } else {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&context=participant&cid={$this->_contactID}"));
         }
     }
 }
 /**
  * Global form rule.
  *
  * @param array $fields
  *   The input form values.
  * @param array $files
  * @param CRM_Admin_Form_ScheduleReminders $self
  *
  * @return array|bool
  *   True if no errors, else array of errors
  */
 public static function formRule($fields, $files, $self)
 {
     $errors = array();
     if (array_key_exists(1, $fields['entity']) && $fields['entity'][1][0] === 0 || array_key_exists(2, $fields['entity']) && $fields['entity'][2][0] == 0) {
         $errors['entity'] = ts('Please select appropriate value');
     }
     if (!empty($fields['is_active']) && CRM_Utils_System::isNull($fields['subject'])) {
         $errors['subject'] = ts('Subject is a required field.');
     }
     if (!empty($fields['is_active']) && CRM_Utils_System::isNull(trim(strip_tags($fields['html_message'])))) {
         $errors['html_message'] = ts('The HTML message is a required field.');
     }
     if (empty($self->_context) && CRM_Utils_System::isNull(CRM_Utils_Array::value(1, $fields['entity']))) {
         $errors['entity'] = ts('Please select entity value');
     }
     if (!CRM_Utils_System::isNull($fields['absolute_date'])) {
         if (CRM_Utils_Date::format(CRM_Utils_Date::processDate($fields['absolute_date'], NULL)) < CRM_Utils_Date::format(date('Ymd'))) {
             $errors['absolute_date'] = ts('Absolute date cannot be earlier than the current time.');
         }
     }
     $recipientKind = array('participant_role' => array('name' => 'participant role', 'target_id' => 'recipient_listing'), 'manual' => array('name' => 'recipient', 'target_id' => 'recipient_manual_id'));
     if ($fields['limit_to'] != '' && array_key_exists($fields['recipient'], $recipientKind) && empty($fields[$recipientKind[$fields['recipient']]['target_id']])) {
         $errors[$recipientKind[$fields['recipient']]['target_id']] = ts('If "Also include" or "Limit to" are selected, you must specify at least one %1', array(1 => $recipientKind[$fields['recipient']]['name']));
     }
     $actionSchedule = $self->parseActionSchedule($fields);
     if ($actionSchedule->mapping_id) {
         $mapping = CRM_Core_BAO_ActionSchedule::getMapping($actionSchedule->mapping_id);
         CRM_Utils_Array::extend($errors, $mapping->validateSchedule($actionSchedule));
     }
     if (!empty($errors)) {
         return $errors;
     }
     return empty($errors) ? TRUE : $errors;
 }
Example #17
0
 /**  
  * Function to build the array for display the profile fields
  *  
  * @param array $params key value. 
  * @param int $gid profile Id
  * @param array $groupTitle Profile Group Title.
  * @param array $values formatted array of key value
  *
  * @return None  
  * @access public  
  */
 function displayProfile(&$params, $gid, &$groupTitle, &$values)
 {
     if ($gid) {
         require_once 'CRM/Core/BAO/UFGroup.php';
         require_once 'CRM/Profile/Form.php';
         require_once 'CRM/Event/PseudoConstant.php';
         $session = CRM_Core_Session::singleton();
         $contactID = $session->get('userID');
         if ($contactID) {
             if (CRM_Core_BAO_UFGroup::filterUFGroups($gid, $contactID)) {
                 $fields = CRM_Core_BAO_UFGroup::getFields($gid, false, CRM_Core_Action::VIEW);
             }
         } else {
             $fields = CRM_Core_BAO_UFGroup::getFields($gid, false, CRM_Core_Action::ADD);
         }
         if (is_array($fields)) {
             // unset any email-* fields since we already collect it, CRM-2888
             foreach (array_keys($fields) as $fieldName) {
                 if (substr($fieldName, 0, 6) == 'email-') {
                     unset($fields[$fieldName]);
                 }
             }
         }
         foreach ($fields as $v) {
             if (CRM_Utils_Array::value('groupTitle', $v)) {
                 $groupTitle['groupTitle'] = $v["groupTitle"];
                 break;
             }
         }
         $config = CRM_Core_Config::singleton();
         require_once 'CRM/Core/PseudoConstant.php';
         $locationTypes = $imProviders = array();
         $locationTypes = CRM_Core_PseudoConstant::locationType();
         $imProviders = CRM_Core_PseudoConstant::IMProvider();
         //start of code to set the default values
         foreach ($fields as $name => $field) {
             $index = $field['title'];
             $customFieldName = null;
             if ($name === 'organization_name') {
                 $values[$index] = $params[$name];
             }
             if ('state_province' == substr($name, 0, 14)) {
                 if ($params[$name]) {
                     $values[$index] = CRM_Core_PseudoConstant::stateProvince($params[$name]);
                 } else {
                     $values[$index] = '';
                 }
             } else {
                 if ('country' == substr($name, 0, 7)) {
                     if ($params[$name]) {
                         $values[$index] = CRM_Core_PseudoConstant::country($params[$name]);
                     } else {
                         $values[$index] = '';
                     }
                 } else {
                     if ('county' == substr($name, 0, 6)) {
                         if ($params[$name]) {
                             $values[$index] = CRM_Core_PseudoConstant::county($params[$name]);
                         } else {
                             $values[$index] = '';
                         }
                     } else {
                         if ('gender' == substr($name, 0, 6)) {
                             $gender = CRM_Core_PseudoConstant::gender();
                             $values[$index] = $gender[$params[$name]];
                         } else {
                             if ('individual_prefix' == substr($name, 0, 17)) {
                                 $prefix = CRM_Core_PseudoConstant::individualPrefix();
                                 $values[$index] = $prefix[$params[$name]];
                             } else {
                                 if ('individual_suffix' == substr($name, 0, 17)) {
                                     $suffix = CRM_Core_PseudoConstant::individualSuffix();
                                     $values[$index] = $suffix[$params[$name]];
                                 } else {
                                     if (in_array($name, array('addressee', 'email_greeting', 'postal_greeting'))) {
                                         $filterCondition = array('greeting_type' => $name);
                                         $greeting =& CRM_Core_PseudoConstant::greeting($filterCondition);
                                         $values[$index] = $greeting[$params[$name]];
                                     } else {
                                         if ($name === 'preferred_communication_method') {
                                             $communicationFields = CRM_Core_PseudoConstant::pcm();
                                             $pref = array();
                                             $compref = array();
                                             $pref = $params[$name];
                                             if (is_array($pref)) {
                                                 foreach ($pref as $k => $v) {
                                                     if ($v) {
                                                         $compref[] = $communicationFields[$k];
                                                     }
                                                 }
                                             }
                                             $values[$index] = implode(",", $compref);
                                         } else {
                                             if ($name == 'group') {
                                                 require_once 'CRM/Contact/BAO/GroupContact.php';
                                                 $groups = CRM_Contact_BAO_GroupContact::getGroupList();
                                                 $title = array();
                                                 foreach ($params[$name] as $gId => $dontCare) {
                                                     if ($dontCare) {
                                                         $title[] = $groups[$gId];
                                                     }
                                                 }
                                                 $values[$index] = implode(', ', $title);
                                             } else {
                                                 if ($name == 'tag') {
                                                     require_once 'CRM/Core/BAO/EntityTag.php';
                                                     $entityTags = $params[$name];
                                                     $allTags =& CRM_Core_PseudoConstant::tag();
                                                     $title = array();
                                                     if (is_array($entityTags)) {
                                                         foreach ($entityTags as $tagId => $dontCare) {
                                                             $title[] = $allTags[$tagId];
                                                         }
                                                     }
                                                     $values[$index] = implode(', ', $title);
                                                 } else {
                                                     if ('participant_role_id' == $name) {
                                                         $roles = CRM_Event_PseudoConstant::participantRole();
                                                         $values[$index] = $roles[$params[$name]];
                                                     } else {
                                                         if ('participant_status_id' == $name) {
                                                             $status = CRM_Event_PseudoConstant::participantStatus();
                                                             $values[$index] = $status[$params[$name]];
                                                         } else {
                                                             if (strpos($name, '-') !== false) {
                                                                 list($fieldName, $id) = CRM_Utils_System::explode('-', $name, 2);
                                                                 $detailName = str_replace(' ', '_', $name);
                                                                 if (in_array($fieldName, array('state_province', 'country', 'county'))) {
                                                                     $values[$index] = $params[$detailName];
                                                                     $idx = $detailName . '_id';
                                                                     $values[$index] = $params[$idx];
                                                                 } else {
                                                                     if ($fieldName == 'im') {
                                                                         $providerName = null;
                                                                         if ($providerId = $detailName . '-provider_id') {
                                                                             $providerName = CRM_Utils_Array::value($params[$providerId], $imProviders);
                                                                         }
                                                                         if ($providerName) {
                                                                             $values[$index] = $params[$detailName] . " (" . $providerName . ")";
                                                                         } else {
                                                                             $values[$index] = $params[$detailName];
                                                                         }
                                                                     } else {
                                                                         $values[$index] = $params[$detailName];
                                                                     }
                                                                 }
                                                             } else {
                                                                 if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') {
                                                                     if ($params[$name]) {
                                                                         $values[$index] = '[ x ]';
                                                                     }
                                                                 } else {
                                                                     require_once 'CRM/Core/BAO/CustomField.php';
                                                                     if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) {
                                                                         $query = "\nSELECT html_type, data_type\nFROM   civicrm_custom_field\nWHERE  id = {$cfID}\n";
                                                                         $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
                                                                         $dao->fetch();
                                                                         $htmlType = $dao->html_type;
                                                                         $dataType = $dao->data_type;
                                                                         if ($htmlType == 'File') {
                                                                             //$fileURL = CRM_Core_BAO_CustomField::getFileURL( $contactID, $cfID );
                                                                             //$params[$index] = $values[$index] = $fileURL['file_url'];
                                                                             $values[$index] = $params[$index];
                                                                         } else {
                                                                             if ($dao->data_type == 'Int' || $dao->data_type == 'Boolean') {
                                                                                 $customVal = (int) $params[$name];
                                                                             } else {
                                                                                 if ($dao->data_type == 'Float') {
                                                                                     $customVal = (double) $params[$name];
                                                                                 } else {
                                                                                     if ($dao->data_type == 'Date') {
                                                                                         $date = CRM_Utils_Date::format($params[$name], null, 'invalidDate');
                                                                                         if ($date != 'invalidDate') {
                                                                                             $customVal = $date;
                                                                                         }
                                                                                     } else {
                                                                                         $customVal = $params[$name];
                                                                                     }
                                                                                 }
                                                                             }
                                                                             //take the custom field options
                                                                             $returnProperties = array($name => 1);
                                                                             require_once 'CRM/Contact/BAO/Query.php';
                                                                             $query = new CRM_Contact_BAO_Query($params, $returnProperties, $fields);
                                                                             $options =& $query->_options;
                                                                             $displayValue = CRM_Core_BAO_CustomField::getDisplayValue($customVal, $cfID, $options);
                                                                             //Hack since we dont have function to check empty.
                                                                             //FIXME in 2.3 using crmIsEmptyArray()
                                                                             $customValue = true;
                                                                             if (is_array($customVal) && is_array($displayValue)) {
                                                                                 $customValue = array_diff($customVal, $displayValue);
                                                                             }
                                                                             //use difference of arrays
                                                                             if (empty($customValue) || !$customValue) {
                                                                                 $values[$index] = '';
                                                                             } else {
                                                                                 $values[$index] = $displayValue;
                                                                             }
                                                                             if (CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $cfID, 'is_search_range')) {
                                                                                 $customFieldName = "{$name}_from";
                                                                             }
                                                                         }
                                                                     } else {
                                                                         if ($name == 'home_URL' && !empty($params[$name])) {
                                                                             $url = CRM_Utils_System::fixURL($params[$name]);
                                                                             $values[$index] = "<a href=\"{$url}\">{$params[$name]}</a>";
                                                                         } else {
                                                                             if (in_array($name, array('birth_date', 'deceased_date', 'participant_register_date'))) {
                                                                                 require_once 'CRM/Utils/Date.php';
                                                                                 $values[$index] = CRM_Utils_Date::customFormat(CRM_Utils_Date::format($params[$name]));
                                                                             } else {
                                                                                 $values[$index] = $params[$name];
                                                                             }
                                                                         }
                                                                     }
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
 }
Example #18
0
 /**
  * Process the form submission.
  *
  *
  * @return void
  */
 public function postProcess()
 {
     //get the submitted form values.
     $formValues = $this->controller->exportValues($this->_name);
     $params = array();
     $formValues['scheduled_date'] = CRM_Utils_Date::processDate($formValues['scheduled_date']);
     $params['scheduled_date'] = CRM_Utils_Date::format($formValues['scheduled_date']);
     $params['currency'] = CRM_Utils_Array::value('currency', $formValues);
     $now = date('Ymd');
     $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     if (CRM_Utils_Date::overdue(CRM_Utils_Date::customFormat($params['scheduled_date'], '%Y%m%d'), $now)) {
         $params['status_id'] = array_search('Overdue', $contributionStatus);
     } else {
         $params['status_id'] = array_search('Pending', $contributionStatus);
     }
     $params['id'] = $this->_id;
     $pledgeId = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $params['id'], 'pledge_id');
     CRM_Pledge_BAO_PledgePayment::add($params);
     $adjustTotalAmount = FALSE;
     if (CRM_Utils_Array::value('option_type', $formValues) == 2) {
         $adjustTotalAmount = TRUE;
     }
     $pledgeScheduledAmount = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $params['id'], 'scheduled_amount', 'id');
     $oldestPaymentAmount = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId, 2);
     if ($oldestPaymentAmount['count'] != 1 && $oldestPaymentAmount['id'] == $params['id']) {
         $oldestPaymentAmount = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeId);
     }
     if ($formValues['scheduled_amount'] - $pledgeScheduledAmount >= $oldestPaymentAmount['amount']) {
         $adjustTotalAmount = TRUE;
     }
     //update pledge status
     CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId, array($params['id']), $params['status_id'], NULL, $formValues['scheduled_amount'], $adjustTotalAmount);
     $statusMsg = ts('Pledge Payment Schedule has been updated.');
     CRM_Core_Session::setStatus($statusMsg, ts('Saved'), 'success');
 }
 /**
  * global form rule
  *
  * @param array $fields  the input form values
  *
  * @return true if no errors, else array of errors
  * @access public
  * @static
  */
 static function formRule($fields)
 {
     $errors = array();
     if (array_key_exists(1, $fields['entity']) && $fields['entity'][1][0] == 0 || array_key_exists(2, $fields['entity']) && $fields['entity'][2][0] == 0) {
         $errors['entity'] = ts('Please select appropriate value');
     }
     if (CRM_Utils_Array::value('is_active', $fields) && CRM_Utils_System::isNull($fields['subject'])) {
         $errors['subject'] = ts('Subject is a required field.');
     }
     if (!CRM_Utils_System::isNull($fields['absolute_date'])) {
         if (CRM_Utils_Date::format(CRM_Utils_Date::processDate($fields['absolute_date'], NULL)) < CRM_Utils_Date::format(date('YmdHi00'))) {
             $errors['absolute_date'] = ts('Absolute date cannot be earlier than the current time.');
         }
     }
     if (!empty($errors)) {
         return $errors;
     }
     return empty($errors) ? TRUE : $errors;
 }
Example #20
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 #21
0
 /**
  * Function to process the form
  *
  * @access public
  *
  * @return None
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::VIEW) {
         return;
     } elseif ($this->_action & CRM_Core_Action::DELETE) {
         CRM_Auction_BAO_Auction::del($this->_id);
         return;
     }
     $params = $this->controller->exportValues($this->_name);
     $params['id'] = $this->_id;
     // format date params
     foreach ($this->_dates as $name => $title) {
         $params[$name] = CRM_Utils_Date::format($params[$name]);
     }
     // format checkboxes
     foreach ($this->_checkboxes as $name => $title) {
         $params[$name] = CRM_Utils_Array::value($name, $params, FALSE);
     }
     CRM_Auction_BAO_Auction::add($params);
 }
Example #22
0
 /**
  * Function to build the array for display the profile fields
  *
  * @param array $params key value.
  * @param int $gid profile Id
  * @param array $groupTitle Profile Group Title.
  * @param array $values formatted array of key value
  *
  * @param array $profileFields
  *
  * @return void
  * @access public
  * @static
  */
 static function displayProfile(&$params, $gid, &$groupTitle, &$values, &$profileFields = array())
 {
     if ($gid) {
         $config = CRM_Core_Config::singleton();
         $session = CRM_Core_Session::singleton();
         $contactID = $session->get('userID');
         if ($contactID) {
             if (CRM_Core_BAO_UFGroup::filterUFGroups($gid, $contactID)) {
                 $fields = CRM_Core_BAO_UFGroup::getFields($gid, FALSE, CRM_Core_Action::VIEW);
             }
         } else {
             $fields = CRM_Core_BAO_UFGroup::getFields($gid, FALSE, CRM_Core_Action::ADD);
         }
         foreach ($fields as $v) {
             if (!empty($v['groupTitle'])) {
                 $groupTitle['groupTitle'] = $v['groupTitle'];
                 break;
             }
         }
         $customVal = '';
         $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
         //start of code to set the default values
         foreach ($fields as $name => $field) {
             $skip = FALSE;
             // skip fields that should not be displayed separately
             if ($field['skipDisplay']) {
                 continue;
             }
             $index = $field['title'];
             if ($name === 'organization_name') {
                 $values[$index] = $params[$name];
             }
             if ('state_province' == substr($name, 0, 14)) {
                 if ($params[$name]) {
                     $values[$index] = CRM_Core_PseudoConstant::stateProvince($params[$name]);
                 } else {
                     $values[$index] = '';
                 }
             } elseif ('date' == substr($name, -4)) {
                 $values[$index] = CRM_Utils_Date::customFormat(CRM_Utils_Date::processDate($params[$name]), $config->dateformatFull);
             } elseif ('country' == substr($name, 0, 7)) {
                 if ($params[$name]) {
                     $values[$index] = CRM_Core_PseudoConstant::country($params[$name]);
                 } else {
                     $values[$index] = '';
                 }
             } elseif ('county' == substr($name, 0, 6)) {
                 if ($params[$name]) {
                     $values[$index] = CRM_Core_PseudoConstant::county($params[$name]);
                 } else {
                     $values[$index] = '';
                 }
             } elseif (in_array(substr($name, 0, -3), array('gender', 'prefix', 'suffix', 'communication_style'))) {
                 $values[$index] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', $name, $params[$name]);
             } elseif (in_array($name, array('addressee', 'email_greeting', 'postal_greeting'))) {
                 $filterCondition = array('greeting_type' => $name);
                 $greeting = CRM_Core_PseudoConstant::greeting($filterCondition);
                 $values[$index] = $greeting[$params[$name]];
             } elseif ($name === 'preferred_communication_method') {
                 $communicationFields = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
                 $compref = array();
                 $pref = $params[$name];
                 if (is_array($pref)) {
                     foreach ($pref as $k => $v) {
                         if ($v) {
                             $compref[] = $communicationFields[$k];
                         }
                     }
                 }
                 $values[$index] = implode(',', $compref);
             } elseif ($name == 'contact_sub_type') {
                 $values[$index] = implode(', ', $params[$name]);
             } elseif ($name == 'group') {
                 $groups = CRM_Contact_BAO_GroupContact::getGroupList();
                 $title = array();
                 foreach ($params[$name] as $gId => $dontCare) {
                     if ($dontCare) {
                         $title[] = $groups[$gId];
                     }
                 }
                 $values[$index] = implode(', ', $title);
             } elseif ($name == 'tag') {
                 $entityTags = $params[$name];
                 $allTags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
                 $title = array();
                 if (is_array($entityTags)) {
                     foreach ($entityTags as $tagId => $dontCare) {
                         $title[] = $allTags[$tagId];
                     }
                 }
                 $values[$index] = implode(', ', $title);
             } elseif ('participant_role_id' == $name or 'participant_role' == $name) {
                 $roles = CRM_Event_PseudoConstant::participantRole();
                 $values[$index] = $roles[$params[$name]];
             } elseif ('participant_status_id' == $name or 'participant_status' == $name) {
                 $status = CRM_Event_PseudoConstant::participantStatus();
                 $values[$index] = $status[$params[$name]];
             } elseif (substr($name, -11) == 'campaign_id') {
                 $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($params[$name]);
                 $values[$index] = CRM_Utils_Array::value($params[$name], $campaigns);
             } elseif (strpos($name, '-') !== FALSE) {
                 list($fieldName, $id) = CRM_Utils_System::explode('-', $name, 2);
                 $detailName = str_replace(' ', '_', $name);
                 if (in_array($fieldName, array('state_province', 'country', 'county'))) {
                     $values[$index] = $params[$detailName];
                     $idx = $detailName . '_id';
                     $values[$index] = $params[$idx];
                 } elseif ($fieldName == 'im') {
                     $providerName = NULL;
                     if ($providerId = $detailName . '-provider_id') {
                         $providerName = CRM_Utils_Array::value($params[$providerId], $imProviders);
                     }
                     if ($providerName) {
                         $values[$index] = $params[$detailName] . " (" . $providerName . ")";
                     } else {
                         $values[$index] = $params[$detailName];
                     }
                 } elseif ($fieldName == 'phone') {
                     $phoneExtField = str_replace('phone', 'phone_ext', $detailName);
                     if (isset($params[$phoneExtField])) {
                         $values[$index] = $params[$detailName] . " (" . $params[$phoneExtField] . ")";
                     } else {
                         $values[$index] = $params[$detailName];
                     }
                 } else {
                     $values[$index] = $params[$detailName];
                 }
             } else {
                 if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') {
                     if ($params[$name]) {
                         $values[$index] = '[ x ]';
                     }
                 } else {
                     if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) {
                         $query = "\nSELECT html_type, data_type\nFROM   civicrm_custom_field\nWHERE  id = {$cfID}\n";
                         $dao = CRM_Core_DAO::executeQuery($query);
                         $dao->fetch();
                         $htmlType = $dao->html_type;
                         if ($htmlType == 'File') {
                             $values[$index] = $params[$index];
                         } else {
                             if ($dao->data_type == 'Int' || $dao->data_type == 'Boolean') {
                                 $v = $params[$name];
                                 if (!CRM_Utils_System::isNull($v)) {
                                     $customVal = (int) $v;
                                 }
                             } elseif ($dao->data_type == 'Float') {
                                 $customVal = (double) $params[$name];
                             } elseif ($dao->data_type == 'Date') {
                                 //@todo note the currently we are using default date time formatting. Since you can select/set
                                 // different date and time format specific to custom field we should consider fixing this
                                 // sometime in the future
                                 $customVal = $displayValue = CRM_Utils_Date::customFormat(CRM_Utils_Date::processDate($params[$name]), $config->dateformatFull);
                                 if (!empty($params[$name . '_time'])) {
                                     $customVal = $displayValue = CRM_Utils_Date::customFormat(CRM_Utils_Date::processDate($params[$name], $params[$name . '_time']), $config->dateformatDatetime);
                                 }
                                 $skip = TRUE;
                             } else {
                                 $customVal = $params[$name];
                             }
                             //take the custom field options
                             $returnProperties = array($name => 1);
                             $query = new CRM_Contact_BAO_Query($params, $returnProperties, $fields);
                             $options =& $query->_options;
                             if (!$skip) {
                                 $displayValue = CRM_Core_BAO_CustomField::getDisplayValue($customVal, $cfID, $options);
                             }
                             //Hack since we dont have function to check empty.
                             //FIXME in 2.3 using crmIsEmptyArray()
                             $customValue = TRUE;
                             if (is_array($customVal) && is_array($displayValue)) {
                                 $customValue = array_diff($customVal, $displayValue);
                             }
                             //use difference of arrays
                             if (empty($customValue) || !$customValue) {
                                 $values[$index] = '';
                             } else {
                                 $values[$index] = $displayValue;
                             }
                         }
                     } elseif ($name == 'home_URL' && !empty($params[$name])) {
                         $url = CRM_Utils_System::fixURL($params[$name]);
                         $values[$index] = "<a href=\"{$url}\">{$params[$name]}</a>";
                     } elseif (in_array($name, array('birth_date', 'deceased_date', 'participant_register_date'))) {
                         $values[$index] = CRM_Utils_Date::customFormat(CRM_Utils_Date::format($params[$name]));
                     } else {
                         $values[$index] = $params[$name];
                     }
                 }
             }
             $profileFields[$name] = $field;
         }
     }
 }
Example #23
0
 /**
  * Send email receipt.
  *
  * @param CRM_Core_Form $form
  *   Form object.
  * @param array $formValues
  * @param object $membership
  *   Object.
  *
  * @return bool
  *   true if mail was sent successfully
  */
 public static function emailReceipt(&$form, &$formValues, &$membership)
 {
     // retrieve 'from email id' for acknowledgement
     $receiptFrom = $formValues['from_email_address'];
     if (!empty($formValues['payment_instrument_id'])) {
         $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
         $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
     }
     // retrieve custom data
     $customFields = $customValues = array();
     if (property_exists($form, '_groupTree') && !empty($form->_groupTree)) {
         foreach ($form->_groupTree as $groupID => $group) {
             if ($groupID == 'info') {
                 continue;
             }
             foreach ($group['fields'] as $k => $field) {
                 $field['title'] = $field['label'];
                 $customFields["custom_{$k}"] = $field;
             }
         }
     }
     $members = array(array('member_id', '=', $membership->id, 0, 0));
     // check whether its a test drive
     if ($form->_mode == 'test') {
         $members[] = array('member_test', '=', 1, 0, 0);
     }
     CRM_Core_BAO_UFGroup::getValues($formValues['contact_id'], $customFields, $customValues, FALSE, $members);
     if ($form->_mode) {
         if (!empty($form->_params['billing_first_name'])) {
             $name = $form->_params['billing_first_name'];
         }
         if (!empty($form->_params['billing_middle_name'])) {
             $name .= " {$form->_params['billing_middle_name']}";
         }
         if (!empty($form->_params['billing_last_name'])) {
             $name .= " {$form->_params['billing_last_name']}";
         }
         $form->assign('billingName', $name);
         // assign the address formatted up for display
         $addressParts = array("street_address-{$form->_bltID}", "city-{$form->_bltID}", "postal_code-{$form->_bltID}", "state_province-{$form->_bltID}", "country-{$form->_bltID}");
         $addressFields = array();
         foreach ($addressParts as $part) {
             list($n, $id) = explode('-', $part);
             if (isset($form->_params['billing_' . $part])) {
                 $addressFields[$n] = $form->_params['billing_' . $part];
             }
         }
         $form->assign('address', CRM_Utils_Address::format($addressFields));
         $date = CRM_Utils_Date::format($form->_params['credit_card_exp_date']);
         $date = CRM_Utils_Date::mysqlToIso($date);
         $form->assign('credit_card_exp_date', $date);
         $form->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($form->_params['credit_card_number']));
         $form->assign('credit_card_type', $form->_params['credit_card_type']);
         $form->assign('contributeMode', 'direct');
         $form->assign('isAmountzero', 0);
         $form->assign('is_pay_later', 0);
         $form->assign('isPrimary', 1);
     }
     $form->assign('module', 'Membership');
     $form->assign('contactID', $formValues['contact_id']);
     $form->assign('membershipID', CRM_Utils_Array::value('membership_id', $form->_params, CRM_Utils_Array::value('membership_id', $form->_defaultValues)));
     if (!empty($formValues['contribution_id'])) {
         $form->assign('contributionID', $formValues['contribution_id']);
     } elseif (isset($form->_onlinePendingContributionId)) {
         $form->assign('contributionID', $form->_onlinePendingContributionId);
     }
     if (!empty($formValues['contribution_status_id'])) {
         $form->assign('contributionStatusID', $formValues['contribution_status_id']);
         $form->assign('contributionStatus', CRM_Contribute_PseudoConstant::contributionStatus($formValues['contribution_status_id'], 'name'));
     }
     if (!empty($formValues['is_renew'])) {
         $form->assign('receiptType', 'membership renewal');
     } else {
         $form->assign('receiptType', 'membership signup');
     }
     $form->assign('receive_date', CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $formValues)));
     $form->assign('formValues', $formValues);
     if (empty($lineItem)) {
         $form->assign('mem_start_date', CRM_Utils_Date::customFormat($membership->start_date, '%B %E%f, %Y'));
         if (!CRM_Utils_System::isNull($membership->end_date)) {
             $form->assign('mem_end_date', CRM_Utils_Date::customFormat($membership->end_date, '%B %E%f, %Y'));
         }
         $form->assign('membership_name', CRM_Member_PseudoConstant::membershipType($membership->membership_type_id));
     }
     $form->assign('customValues', $customValues);
     $isBatchProcess = is_a($form, 'CRM_Batch_Form_Entry');
     if (empty($form->_contributorDisplayName) || empty($form->_contributorEmail) || $isBatchProcess) {
         // in this case the form is being called statically from the batch editing screen
         // having one class in the form layer call another statically is not greate
         // & we should aim to move this function to the BAO layer in future.
         // however, we can assume that the contact_id passed in by the batch
         // function will be the recipient
         list($form->_contributorDisplayName, $form->_contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($formValues['contact_id']);
         if (empty($form->_receiptContactId) || $isBatchProcess) {
             $form->_receiptContactId = $formValues['contact_id'];
         }
     }
     $template = CRM_Core_Smarty::singleton();
     $taxAmt = $template->get_template_vars('dataArray');
     $eventTaxAmt = $template->get_template_vars('totalTaxAmount');
     $prefixValue = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
     $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
     if ((!empty($taxAmt) || isset($eventTaxAmt)) && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
         $isEmailPdf = TRUE;
     } else {
         $isEmailPdf = FALSE;
     }
     list($mailSend, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_membership', 'valueName' => 'membership_offline_receipt', 'contactId' => $form->_receiptContactId, 'from' => $receiptFrom, 'toName' => $form->_contributorDisplayName, 'toEmail' => $form->_contributorEmail, 'PDFFilename' => ts('receipt') . '.pdf', 'isEmailPdf' => $isEmailPdf, 'contributionId' => $formValues['contribution_id'], 'isTest' => (bool) ($form->_action & CRM_Core_Action::PREVIEW)));
     return TRUE;
 }
Example #24
0
 /**
  * @param int $pledgeID
  * @param $actualAmount
  * @param $pledgeScheduledAmount
  * @param int $paymentContributionId
  * @param int $pPaymentId
  * @param int $paymentStatusID
  */
 public static function adjustPledgePayment($pledgeID, $actualAmount, $pledgeScheduledAmount, $paymentContributionId = NULL, $pPaymentId = NULL, $paymentStatusID = NULL)
 {
     $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
     if ($paymentStatusID == array_search('Cancelled', $allStatus) || $paymentStatusID == array_search('Refunded', $allStatus)) {
         $query = "\nSELECT civicrm_pledge_payment.id id\nFROM  civicrm_pledge_payment\nWHERE civicrm_pledge_payment.contribution_id = {$paymentContributionId}\n";
         $paymentsAffected = CRM_Core_DAO::executeQuery($query);
         $paymentIDs = array();
         while ($paymentsAffected->fetch()) {
             $paymentIDs[] = $paymentsAffected->id;
         }
         // Reset the affected values by the amount paid more than the scheduled amount
         foreach ($paymentIDs as $key => $value) {
             $payment = new CRM_Pledge_DAO_PledgePayment();
             $payment->id = $value;
             if ($payment->find(TRUE)) {
                 $payment->contribution_id = 'null';
                 $payment->status_id = array_search('Pending', $allStatus);
                 $payment->scheduled_date = NULL;
                 $payment->reminder_date = NULL;
                 $payment->scheduled_amount = $pledgeScheduledAmount;
                 $payment->actual_amount = 'null';
                 $payment->save();
             }
         }
         // Cancel the initial paid amount
         CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', reset($paymentIDs), 'status_id', $paymentStatusID, 'id');
         CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', reset($paymentIDs), 'actual_amount', $actualAmount, 'id');
         // Add new payment after the last payment for the pledge
         $allPayments = self::getPledgePayments($pledgeID);
         $lastPayment = array_pop($allPayments);
         $pledgeFrequencyUnit = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge', $pledgeID, 'frequency_unit', 'id');
         $pledgeFrequencyInterval = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge', $pledgeID, 'frequency_interval', 'id');
         $pledgeScheduledDate = $lastPayment['scheduled_date'];
         $scheduled_date = CRM_Utils_Date::processDate($pledgeScheduledDate);
         $date['year'] = (int) substr($scheduled_date, 0, 4);
         $date['month'] = (int) substr($scheduled_date, 4, 2);
         $date['day'] = (int) substr($scheduled_date, 6, 2);
         $newDate = date('YmdHis', mktime(0, 0, 0, $date['month'], $date['day'], $date['year']));
         $ScheduledDate = CRM_Utils_Date::format(CRM_Utils_Date::intervalAdd($pledgeFrequencyUnit, $pledgeFrequencyInterval, $newDate));
         $pledgeParams = array('status_id' => array_search('Pending', $allStatus), 'pledge_id' => $pledgeID, 'scheduled_amount' => $pledgeScheduledAmount, 'scheduled_date' => $ScheduledDate);
         $payment = self::add($pledgeParams);
     } else {
         $oldestPayment = self::getOldestPledgePayment($pledgeID);
         if (!$paymentContributionId) {
             // means we are editing payment scheduled payment, so get the second pending to update.
             $oldestPayment = self::getOldestPledgePayment($pledgeID, 2);
             if ($oldestPayment['count'] != 1 && $oldestPayment['id'] == $pPaymentId) {
                 $oldestPayment = self::getOldestPledgePayment($pledgeID);
             }
         }
         if ($oldestPayment) {
             // not the last scheduled payment and the actual amount is less than the expected , add it to oldest pending.
             if ($actualAmount != $pledgeScheduledAmount && ($actualAmount < $pledgeScheduledAmount || $actualAmount - $pledgeScheduledAmount < $oldestPayment['amount'])) {
                 $oldScheduledAmount = $oldestPayment['amount'];
                 $newScheduledAmount = $oldScheduledAmount + ($pledgeScheduledAmount - $actualAmount);
                 // store new amount in oldest pending payment record.
                 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $oldestPayment['id'], 'scheduled_amount', $newScheduledAmount);
                 if (CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_PledgePayment', $oldestPayment['id'], 'contribution_id', 'id')) {
                     CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $oldestPayment['id'], 'contribution_id', $paymentContributionId);
                 }
             } elseif ($actualAmount > $pledgeScheduledAmount && $actualAmount - $pledgeScheduledAmount >= $oldestPayment['amount']) {
                 // here the actual amount is greater than expected and also greater than the next installment amount, so update the next installment as complete and again add it to next subsequent pending payment
                 // set the actual amount of the next pending to '0', set contribution Id to current contribution Id and status as completed
                 $paymentId = array($oldestPayment['id']);
                 self::updatePledgePayments($pledgeID, array_search('Completed', $allStatus), $paymentId, 0, $paymentContributionId);
                 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $oldestPayment['id'], 'scheduled_amount', 0, 'id');
                 $oldestPayment = self::getOldestPledgePayment($pledgeID);
                 if (!$paymentContributionId) {
                     // means we are editing payment scheduled payment.
                     $oldestPaymentAmount = self::getOldestPledgePayment($pledgeID, 2);
                 }
                 $newActualAmount = $actualAmount - $pledgeScheduledAmount;
                 $newPledgeScheduledAmount = $oldestPayment['amount'];
                 if (!$paymentContributionId) {
                     $newActualAmount = $actualAmount - $pledgeScheduledAmount;
                     $newPledgeScheduledAmount = $oldestPaymentAmount['amount'];
                     // means we are editing payment scheduled payment, so update scheduled amount.
                     CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $oldestPaymentAmount['id'], 'scheduled_amount', $newActualAmount);
                 }
                 if ($newActualAmount > 0) {
                     self::adjustPledgePayment($pledgeID, $newActualAmount, $newPledgeScheduledAmount, $paymentContributionId);
                 }
             }
         }
     }
 }
Example #25
0
 /**
  * Generate where for a single parameter.
  *
  * @param array $values
  * @param CRM_Contact_BAO_Query $query
  */
 public static function whereClauseSingle(&$values, &$query)
 {
     list($name, $op, $value, $grouping) = $values;
     switch ($name) {
         case 'member_join_date_low':
         case 'member_join_date_high':
             $query->dateQueryBuilder($values, 'civicrm_membership', 'member_join_date', 'join_date', 'Member Since');
             return;
         case 'member_start_date_low':
         case 'member_start_date_high':
             $query->dateQueryBuilder($values, 'civicrm_membership', 'member_start_date', 'start_date', 'Start Date');
             return;
         case 'member_end_date_low':
         case 'member_end_date_high':
             $query->dateQueryBuilder($values, 'civicrm_membership', 'member_end_date', 'end_date', 'End Date');
             return;
         case 'member_join_date':
             $op = '>=';
             $date = CRM_Utils_Date::format($value);
             if ($date) {
                 $query->_where[$grouping][] = "civicrm_membership.join_date {$op} {$date}";
                 $format = CRM_Utils_Date::customFormat(CRM_Utils_Date::format(array_reverse($value), '-'));
                 $query->_qill[$grouping][] = ts('Member Since %2 %1', array(1 => $format, 2 => $op));
             }
             return;
         case 'member_source':
             $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
             $value = $strtolower(CRM_Core_DAO::escapeString(trim($value)));
             $query->_where[$grouping][] = "civicrm_membership.source {$op} '{$value}'";
             $query->_qill[$grouping][] = ts('Source %2 %1', array(1 => $value, 2 => $op));
             $query->_tables['civicrm_membership'] = $query->_whereTables['civicrm_membership'] = 1;
             return;
             // CRM-17011 These 2 variants appear in some smart groups saved at some time prior to 4.6.6.
         // CRM-17011 These 2 variants appear in some smart groups saved at some time prior to 4.6.6.
         case 'member_status_id':
         case 'member_membership_type_id':
             if (is_array($value)) {
                 $op = 'IN';
                 $value = array_keys($value);
             }
         case 'membership_type_id':
             // CRM-17075 we are specifically handling the possibility we are dealing with the entity reference field
             // for membership_type_id here (although status would be handled if converted). The unhandled pathway at the moment
             // is from groupContactCache::load and this is a small fix to get the entity reference field to work.
             // However, it would seem the larger fix would be to NOT invoke the form formValues for
             // the load function. The where clause and the whereTables are saved so they should suffice to generate the query
             // to get a contact list. But, better to deal with in 4.8 now...
             if (is_string($value) && strpos($value, ',') && $op == '=') {
                 $value = array('IN' => explode(',', $value));
             }
         case 'membership_status':
         case 'membership_status_id':
         case 'membership_type':
         case 'member_id':
             if (strstr($name, 'status') && is_string($value) && !is_numeric($value)) {
                 $value = CRM_Core_PseudoConstant::getKey('CRM_Member_BAO_Membership', 'status_id', $value);
             }
             if (strpos($name, 'status') !== FALSE) {
                 $name = 'status_id';
                 $qillName = 'Membership Status(s)';
             } elseif ($name == 'member_id') {
                 $name = 'id';
                 $qillName = 'Membership ID';
             } else {
                 $name = 'membership_type_id';
                 $qillName = 'Membership Type(s)';
             }
             $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_membership.{$name}", $op, $value, "Integer");
             list($op, $value) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Member_DAO_Membership', $name, $value, $op);
             $query->_qill[$grouping][] = ts('%1 %2 %3', array(1 => $qillName, 2 => $op, 3 => $value));
             $query->_tables['civicrm_membership'] = $query->_whereTables['civicrm_membership'] = 1;
             return;
         case 'member_test':
             // We dont want to include all tests for sql OR CRM-7827
             if (!$value || $query->getOperator() != 'OR') {
                 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_membership.is_test", $op, $value, "Boolean");
                 if ($value) {
                     $query->_qill[$grouping][] = ts('Membership is a Test');
                 }
             }
             $query->_tables['civicrm_membership'] = $query->_whereTables['civicrm_membership'] = 1;
             return;
         case 'member_auto_renew':
             $op = "!=";
             if ($value) {
                 $query->_where[$grouping][] = " civicrm_membership.contribution_recur_id IS NOT NULL";
                 $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("ccr.contribution_status_id", $op, array_search('Cancelled', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name')), "Integer");
                 $query->_qill[$grouping][] = ts("Membership is Auto-Renew");
             } else {
                 $query->_where[$grouping][] = " civicrm_membership.contribution_recur_id IS NULL";
                 $query->_qill[$grouping][] = ts("Membership is NOT Auto-Renew");
             }
             $query->_tables['civicrm_membership'] = $query->_whereTables['civicrm_membership'] = 1;
             return;
         case 'member_pay_later':
             $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_membership.is_pay_later", $op, $value, "Integer");
             if ($value) {
                 $query->_qill[$grouping][] = ts("Membership is Pay Later");
             } else {
                 $query->_qill[$grouping][] = ts("Membership is NOT Pay Later");
             }
             $query->_tables['civicrm_membership'] = $query->_whereTables['civicrm_membership'] = 1;
             return;
         case 'member_is_primary':
             if ($value) {
                 $query->_where[$grouping][] = " civicrm_membership.owner_membership_id IS NULL";
                 $query->_qill[$grouping][] = ts("Primary Members Only");
             } else {
                 $query->_where[$grouping][] = " civicrm_membership.owner_membership_id IS NOT NULL";
                 $query->_qill[$grouping][] = ts("Related Members Only");
             }
             $query->_tables['civicrm_membership'] = $query->_whereTables['civicrm_membership'] = 1;
             return;
         case 'member_is_override':
             $query->_where[$grouping][] = CRM_Contact_BAO_Query::buildClause("civicrm_membership.is_override", $op, $value, "Boolean");
             $query->_qill[$grouping][] = $value ? ts("Is Membership Status overriden? Yes") : ts("Is Membership Status overriden? No");
             $query->_tables['civicrm_membership'] = $query->_whereTables['civicrm_membership'] = 1;
             return;
         case 'member_campaign_id':
             if (CRM_Utils_Array::value($op, $value)) {
                 $value = $value[$op];
             }
             $campParams = array('op' => $op, 'campaign' => $value, 'grouping' => $grouping, 'tableName' => 'civicrm_membership');
             CRM_Campaign_BAO_Query::componentSearchClause($campParams, $query);
             return;
     }
 }
 /**
  * global form rule
  *
  * @param array $fields  the input form values
  *
  * @return true if no errors, else array of errors
  * @access public
  * @static
  */
 static function formRule($fields)
 {
     $errors = array();
     if (array_key_exists(1, $fields['entity']) && $fields['entity'][1][0] === 0 || array_key_exists(2, $fields['entity']) && $fields['entity'][2][0] == 0) {
         $errors['entity'] = ts('Please select appropriate value');
     }
     if (array_key_exists(1, $fields['entity']) && !is_numeric($fields['entity'][1][0])) {
         if (count($fields['entity'][1]) > 1) {
             $errors['entity'] = ts('You may only select one contact field per reminder');
         } elseif (!(array_key_exists(2, $fields['entity']) && $fields['entity'][2][0] > 0)) {
             $errors['entity'] = ts('Please select whether the reminder is sent each year.');
         }
     }
     if (!empty($fields['is_active']) && CRM_Utils_System::isNull($fields['subject'])) {
         $errors['subject'] = ts('Subject is a required field.');
     }
     if (CRM_Utils_System::isNull(CRM_Utils_Array::value(1, $fields['entity']))) {
         $errors['entity'] = ts('Please select entity value');
     }
     if (!CRM_Utils_System::isNull($fields['absolute_date'])) {
         if (CRM_Utils_Date::format(CRM_Utils_Date::processDate($fields['absolute_date'], NULL)) < CRM_Utils_Date::format(date('Ymd'))) {
             $errors['absolute_date'] = ts('Absolute date cannot be earlier than the current time.');
         }
     }
     if (!empty($errors)) {
         return $errors;
     }
     return empty($errors) ? TRUE : $errors;
 }
 /**
  * Process the form after the input has been submitted and validated.
  */
 public function postProcess()
 {
     $config = CRM_Core_Config::singleton();
     $chartType = 'bvg';
     if ($this->_chartType) {
         $chartType = $this->_chartType;
     }
     $selectedYear = date('Y');
     if ($this->_year) {
         $selectedYear = $this->_year;
     }
     //take contribution information monthly
     $chartInfoMonthly = CRM_Contribute_BAO_Contribution_Utils::contributionChartMonthly($selectedYear);
     $chartData = $abbrMonthNames = array();
     if (is_array($chartInfoMonthly)) {
         for ($i = 1; $i <= 12; $i++) {
             $abbrMonthNames[$i] = strftime('%b', mktime(0, 0, 0, $i, 10, 1970));
         }
         foreach ($abbrMonthNames as $monthKey => $monthName) {
             $val = CRM_Utils_Array::value($monthKey, $chartInfoMonthly['By Month'], 0);
             // don't include zero value month.
             if (!$val && $chartType != 'bvg') {
                 continue;
             }
             //build the params for chart.
             $chartData['by_month']['values'][$monthName] = $val;
         }
         $chartData['by_month']['legend'] = 'By Month' . ' - ' . $selectedYear;
         // handle onclick event.
         $chartData['by_month']['on_click_fun_name'] = 'byMonthOnClick';
         $chartData['by_month']['yname'] = ts('Contribution');
     }
     //take contribution information by yearly
     $chartInfoYearly = CRM_Contribute_BAO_Contribution_Utils::contributionChartYearly();
     //get the years.
     $this->_years = $chartInfoYearly['By Year'];
     $hasContributions = FALSE;
     if (is_array($chartInfoYearly)) {
         $hasContributions = TRUE;
         $chartData['by_year']['legend'] = 'By Year';
         $chartData['by_year']['values'] = $chartInfoYearly['By Year'];
         // handle onclick event.
         $chartData['by_year']['on_click_fun_name'] = 'byYearOnClick';
         $chartData['by_year']['yname'] = ts('Total Amount');
     }
     $this->assign('hasContributions', $hasContributions);
     // process the data.
     $chartCnt = 1;
     $monthlyChart = $yearlyChart = FALSE;
     foreach ($chartData as $chartKey => &$values) {
         $chartValues = CRM_Utils_Array::value('values', $values);
         if (!is_array($chartValues) || empty($chartValues)) {
             continue;
         }
         if ($chartKey == 'by_year') {
             $yearlyChart = TRUE;
             if (!empty($config->fiscalYearStart) && ($config->fiscalYearStart['M'] !== 1 || $config->fiscalYearStart['d'] !== 1)) {
                 $values['xLabelAngle'] = 45;
             } else {
                 $values['xLabelAngle'] = 0;
             }
         }
         if ($chartKey == 'by_month') {
             $monthlyChart = TRUE;
         }
         $values['divName'] = "open_flash_chart_{$chartKey}";
         $funName = $chartType == 'bvg' ? 'barChart' : 'pieChart';
         // build the chart objects.
         $values['object'] = CRM_Utils_OpenFlashChart::$funName($values);
         //build the urls.
         $urlCnt = 0;
         foreach ($chartValues as $index => $val) {
             $urlParams = NULL;
             if ($chartKey == 'by_month') {
                 $monthPosition = array_search($index, $abbrMonthNames);
                 $startDate = CRM_Utils_Date::format(array('Y' => $selectedYear, 'M' => $monthPosition));
                 $endDate = date('Ymd', mktime(0, 0, 0, $monthPosition + 1, 0, $selectedYear));
                 $urlParams = "reset=1&force=1&status=1&start={$startDate}&end={$endDate}&test=0";
             } elseif ($chartKey == 'by_year') {
                 if (!empty($config->fiscalYearStart) && ($config->fiscalYearStart['M'] != 1 || $config->fiscalYearStart['d'] != 1)) {
                     $startDate = date('Ymd', mktime(0, 0, 0, $config->fiscalYearStart['M'], $config->fiscalYearStart['d'], substr($index, 0, 4)));
                     $endDate = date('Ymd', mktime(0, 0, 0, $config->fiscalYearStart['M'], $config->fiscalYearStart['d'], substr($index, 0, 4) + 1));
                 } else {
                     $startDate = CRM_Utils_Date::format(array('Y' => substr($index, 0, 4)));
                     $endDate = date('Ymd', mktime(0, 0, 0, 13, 0, substr($index, 0, 4)));
                 }
                 $urlParams = "reset=1&force=1&status=1&start={$startDate}&end={$endDate}&test=0";
             }
             if ($urlParams) {
                 $values['on_click_urls']["url_" . $urlCnt++] = CRM_Utils_System::url('civicrm/contribute/search', $urlParams, TRUE, FALSE, FALSE);
             }
         }
         // calculate chart size.
         $xSize = 400;
         $ySize = 300;
         if ($chartType == 'bvg') {
             $ySize = 250;
             $xSize = 60 * count($chartValues);
             // reduce x size by 100 for by_month
             if ($chartKey == 'by_month') {
                 $xSize -= 100;
             }
             //hack to show tooltip.
             if ($xSize < 150) {
                 $xSize = 150;
             }
         }
         $values['size'] = array('xSize' => $xSize, 'ySize' => $ySize);
     }
     // finally assign this chart data to template.
     $this->assign('hasYearlyChart', $yearlyChart);
     $this->assign('hasByMonthChart', $monthlyChart);
     $this->assign('hasOpenFlashChart', empty($chartData) ? FALSE : TRUE);
     $this->assign('openFlashChartData', json_encode($chartData));
 }
 /**
  * function for date validation
  *
  * @param array $params (reference ) an assoc array of name/value pairs
  *
  * @return mixed true or array of errors
  * @access public
  * @static
  */
 function dateRule(&$params)
 {
     $errors = array();
     // check start and end date
     if (CRM_Utils_Array::value('start_date', $params) && CRM_Utils_Array::value('end_date', $params)) {
         $start_date = CRM_Utils_Date::format(CRM_Utils_Array::value('start_date', $params));
         $end_date = CRM_Utils_Date::format(CRM_Utils_Array::value('end_date', $params));
         if ($start_date && $end_date && (int) $end_date < (int) $start_date) {
             $errors['end_date'] = ts('The relationship end date cannot be prior to the start date.');
         }
     }
     return empty($errors) ? true : $errors;
 }
Example #29
0
 /**
  * Process the participant.
  *
  * @param CRM_Core_Form $form
  * @param int $contactID
  *
  * @return \CRM_Event_BAO_Participant
  */
 public static function addParticipant(&$form, $contactID)
 {
     if (empty($form->_params)) {
         return NULL;
     }
     $params = $form->_params;
     $transaction = new CRM_Core_Transaction();
     $groupName = 'participant_role';
     $query = "\nSELECT  v.label as label ,v.value as value\nFROM   civicrm_option_value v,\n       civicrm_option_group g\nWHERE  v.option_group_id = g.id\n  AND  g.name            = %1\n  AND  v.is_active       = 1\n  AND  g.is_active       = 1\n";
     $p = array(1 => array($groupName, 'String'));
     $dao = CRM_Core_DAO::executeQuery($query, $p);
     if ($dao->fetch()) {
         $roleID = $dao->value;
     }
     // handle register date CRM-4320
     $registerDate = NULL;
     if (!empty($form->_allowConfirmation) && $form->_participantId) {
         $registerDate = $params['participant_register_date'];
     } elseif (!empty($params['participant_register_date']) && is_array($params['participant_register_date']) && !empty($params['participant_register_date'])) {
         $registerDate = CRM_Utils_Date::format($params['participant_register_date']);
     }
     $participantFields = CRM_Event_DAO_Participant::fields();
     $participantParams = array('id' => CRM_Utils_Array::value('participant_id', $params), 'contact_id' => $contactID, 'event_id' => $form->_eventId ? $form->_eventId : $params['event_id'], 'status_id' => CRM_Utils_Array::value('participant_status', $params, 1), 'role_id' => CRM_Utils_Array::value('participant_role_id', $params, $roleID), 'register_date' => $registerDate ? $registerDate : date('YmdHis'), 'source' => CRM_Utils_String::ellipsify(isset($params['participant_source']) ? CRM_Utils_Array::value('participant_source', $params) : CRM_Utils_Array::value('description', $params), $participantFields['participant_source']['maxlength']), 'fee_level' => CRM_Utils_Array::value('amount_level', $params), 'is_pay_later' => CRM_Utils_Array::value('is_pay_later', $params, 0), 'fee_amount' => CRM_Utils_Array::value('fee_amount', $params), 'registered_by_id' => CRM_Utils_Array::value('registered_by_id', $params), 'discount_id' => CRM_Utils_Array::value('discount_id', $params), 'fee_currency' => CRM_Utils_Array::value('currencyID', $params), 'campaign_id' => CRM_Utils_Array::value('campaign_id', $params));
     if ($form->_action & CRM_Core_Action::PREVIEW || CRM_Utils_Array::value('mode', $params) == 'test') {
         $participantParams['is_test'] = 1;
     } else {
         $participantParams['is_test'] = 0;
     }
     if (!empty($form->_params['note'])) {
         $participantParams['note'] = $form->_params['note'];
     } elseif (!empty($form->_params['participant_note'])) {
         $participantParams['note'] = $form->_params['participant_note'];
     }
     // reuse id if one already exists for this one (can happen
     // with back button being hit etc)
     if (!$participantParams['id'] && !empty($params['contributionID'])) {
         $pID = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $params['contributionID'], 'participant_id', 'contribution_id');
         $participantParams['id'] = $pID;
     }
     $participantParams['discount_id'] = CRM_Core_BAO_Discount::findSet($form->_eventId, 'civicrm_event');
     if (!$participantParams['discount_id']) {
         $participantParams['discount_id'] = "null";
     }
     $participant = CRM_Event_BAO_Participant::create($participantParams);
     $transaction->commit();
     return $participant;
 }
Example #30
0
 /**
  * Create / update / delete membership for related contacts.
  *
  * This function will create/update/delete membership for related
  * contact based on 1) contact have active membership 2) that
  * membership is is extedned by the same relationship type to that
  * of the existing relationship.
  *
  * @param int $contactId
  *   contact id.
  * @param array $params
  *   array of values submitted by POST.
  * @param array $ids
  *   array of ids.
  * @param \const|int $action which action called this function
  *
  * @param bool $active
  *
  * @throws \CRM_Core_Exception
  */
 public static function relatedMemberships($contactId, &$params, $ids, $action = CRM_Core_Action::ADD, $active = TRUE)
 {
     // Check the end date and set the status of the relationship
     // accordingly.
     $status = self::CURRENT;
     $targetContact = $targetContact = CRM_Utils_Array::value('contact_check', $params, array());
     $today = date('Ymd');
     // If a relationship hasn't yet started, just return for now
     // TODO: handle edge-case of updating start_date of an existing relationship
     if (!empty($params['start_date'])) {
         $startDate = substr(CRM_Utils_Date::format($params['start_date']), 0, 8);
         if ($today < $startDate) {
             return;
         }
     }
     if (!empty($params['end_date'])) {
         $endDate = substr(CRM_Utils_Date::format($params['end_date']), 0, 8);
         if ($today > $endDate) {
             $status = self::PAST;
         }
     }
     if ($action & CRM_Core_Action::ADD && $status & self::PAST) {
         // If relationship is PAST and action is ADD, do nothing.
         return;
     }
     $rel = explode('_', $params['relationship_type_id']);
     $relTypeId = $rel[0];
     if (!empty($rel[1])) {
         $relDirection = "_{$rel[1]}_{$rel[2]}";
     } else {
         // this call is coming from somewhere where the direction was resolved early on (e.g an api call)
         // so we can assume _a_b
         $relDirection = "_a_b";
         $targetContact = array($params['contact_id_b'] => 1);
     }
     if ($action & CRM_Core_Action::ADD || $action & CRM_Core_Action::DELETE) {
         $contact = $contactId;
     } elseif ($action & CRM_Core_Action::UPDATE) {
         $contact = $ids['contact'];
         $targetContact = array($ids['contactTarget'] => 1);
     }
     // Build the 'values' array for
     // 1. ContactA
     // 2. ContactB
     // This will allow us to check if either of the contacts in
     // relationship have active memberships.
     $values = array();
     // 1. ContactA
     $values[$contact] = array('relatedContacts' => $targetContact, 'relationshipTypeId' => $relTypeId, 'relationshipTypeDirection' => $relDirection);
     // 2. ContactB
     if (!empty($targetContact)) {
         foreach ($targetContact as $cid => $donCare) {
             $values[$cid] = array('relatedContacts' => array($contact => 1), 'relationshipTypeId' => $relTypeId);
             $relTypeParams = array('id' => $relTypeId);
             $relTypeValues = array();
             CRM_Contact_BAO_RelationshipType::retrieve($relTypeParams, $relTypeValues);
             if (CRM_Utils_Array::value('name_a_b', $relTypeValues) == CRM_Utils_Array::value('name_b_a', $relTypeValues)) {
                 $values[$cid]['relationshipTypeDirection'] = '_a_b';
             } else {
                 $values[$cid]['relationshipTypeDirection'] = $relDirection == '_a_b' ? '_b_a' : '_a_b';
             }
         }
     }
     // CRM-15829 UPDATES
     // If we're looking for active memberships we must consider pending (id: 5) ones too.
     // Hence we can't just call CRM_Member_BAO_Membership::getValues below with the active flag, is it would completely miss pending relatioships.
     // As suggested by @davecivicrm, the pending status id is fetched using the CRM_Member_PseudoConstant::membershipStatus() class and method, since these ids differ from system to system.
     $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant::membershipStatus());
     $query = 'SELECT * FROM `civicrm_membership_status`';
     if ($active) {
         $query .= ' WHERE `is_current_member` = 1 OR `id` = %1 ';
     }
     $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($pendingStatusId, 'Integer')));
     while ($dao->fetch()) {
         $membershipStatusRecordIds[$dao->id] = $dao->id;
     }
     // Now get the active memberships for all the contacts.
     // If contact have any valid membership(s), then add it to
     // 'values' array.
     foreach ($values as $cid => $subValues) {
         $memParams = array('contact_id' => $cid);
         $memberships = array();
         // CRM-15829 UPDATES
         // Since we want PENDING memberships as well, the $active flag needs to be set to false so that this will return all memberships and we can then filter the memberships based on the status IDs recieved above.
         CRM_Member_BAO_Membership::getValues($memParams, $memberships, FALSE, TRUE);
         // CRM-15829 UPDATES
         // filter out the memberships returned by CRM_Member_BAO_Membership::getValues based on the status IDs fetched on line ~1462
         foreach ($memberships as $key => $membership) {
             if (!isset($memberships[$key]['status_id'])) {
                 continue;
             }
             $membershipStatusId = $memberships[$key]['status_id'];
             if (!isset($membershipStatusRecordIds[$membershipStatusId])) {
                 unset($memberships[$key]);
             }
         }
         if (empty($memberships)) {
             continue;
         }
         //get ownerMembershipIds for related Membership
         //this is to handle memberships being deleted and recreated
         if (!empty($memberships['owner_membership_ids'])) {
             $ownerMemIds[$cid] = $memberships['owner_membership_ids'];
             unset($memberships['owner_membership_ids']);
         }
         $values[$cid]['memberships'] = $memberships;
     }
     $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant::membershipStatus());
     // done with 'values' array.
     // Finally add / edit / delete memberships for the related contacts
     foreach ($values as $cid => $details) {
         if (!array_key_exists('memberships', $details)) {
             continue;
         }
         $relatedContacts = array_keys(CRM_Utils_Array::value('relatedContacts', $details, array()));
         $mainRelatedContactId = reset($relatedContacts);
         foreach ($details['memberships'] as $membershipId => $membershipValues) {
             $relTypeIds = array();
             if ($action & CRM_Core_Action::DELETE) {
                 // Delete memberships of the related contacts only if relationship type exists for membership type
                 $query = "\nSELECT relationship_type_id, relationship_direction\n  FROM civicrm_membership_type\n WHERE id = {$membershipValues['membership_type_id']}";
                 $dao = CRM_Core_DAO::executeQuery($query);
                 $relTypeDirs = array();
                 while ($dao->fetch()) {
                     $relTypeId = $dao->relationship_type_id;
                     $relDirection = $dao->relationship_direction;
                 }
                 $relTypeIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $relTypeId);
                 if (in_array($values[$cid]['relationshipTypeId'], $relTypeIds) && !empty($membershipValues['owner_membership_id']) && !empty($values[$mainRelatedContactId]['memberships'][$membershipValues['owner_membership_id']])) {
                     CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipValues['owner_membership_id'], $membershipValues['membership_contact_id']);
                 }
                 continue;
             }
             if ($action & CRM_Core_Action::UPDATE && $status & self::PAST && $membershipValues['owner_membership_id']) {
                 // If relationship is PAST and action is UPDATE
                 // then delete the RELATED membership
                 CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipValues['owner_membership_id'], $membershipValues['membership_contact_id']);
                 continue;
             }
             // add / edit the memberships for related
             // contacts.
             // Get the Membership Type Details.
             $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypeDetails($membershipValues['membership_type_id']);
             // Check if contact's relationship type exists in membership type
             $relTypeDirs = array();
             if (!empty($membershipType['relationship_type_id'])) {
                 $relTypeIds = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_type_id']);
             }
             if (!empty($membershipType['relationship_direction'])) {
                 $relDirections = explode(CRM_Core_DAO::VALUE_SEPARATOR, $membershipType['relationship_direction']);
             }
             foreach ($relTypeIds as $key => $value) {
                 $relTypeDirs[] = $value . '_' . $relDirections[$key];
             }
             $relTypeDir = $details['relationshipTypeId'] . $details['relationshipTypeDirection'];
             if (in_array($relTypeDir, $relTypeDirs)) {
                 // Check if relationship being created/updated is
                 // similar to that of membership type's
                 // relationship.
                 $membershipValues['owner_membership_id'] = $membershipId;
                 unset($membershipValues['id']);
                 unset($membershipValues['membership_contact_id']);
                 unset($membershipValues['contact_id']);
                 unset($membershipValues['membership_id']);
                 foreach ($details['relatedContacts'] as $relatedContactId => $donCare) {
                     $membershipValues['contact_id'] = $relatedContactId;
                     if ($deceasedStatusId && CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $relatedContactId, 'is_deceased')) {
                         $membershipValues['status_id'] = $deceasedStatusId;
                         $membershipValues['skipStatusCal'] = TRUE;
                     }
                     foreach (array('join_date', 'start_date', 'end_date') as $dateField) {
                         if (!empty($membershipValues[$dateField])) {
                             $membershipValues[$dateField] = CRM_Utils_Date::processDate($membershipValues[$dateField]);
                         }
                     }
                     if ($action & CRM_Core_Action::UPDATE) {
                         //if updated relationship is already related to contact don't delete existing inherited membership
                         if (in_array($relTypeId, $relTypeIds) && !empty($values[$relatedContactId]['memberships']) && !empty($ownerMemIds) && in_array($membershipValues['owner_membership_id'], $ownerMemIds[$relatedContactId])) {
                             continue;
                         }
                         //delete the membership record for related
                         //contact before creating new membership record.
                         CRM_Member_BAO_Membership::deleteRelatedMemberships($membershipId, $relatedContactId);
                     }
                     // check whether we have some related memberships still available
                     $query = "\nSELECT count(*)\n  FROM civicrm_membership\n    LEFT JOIN civicrm_membership_status ON (civicrm_membership_status.id = civicrm_membership.status_id)\n WHERE membership_type_id = {$membershipValues['membership_type_id']} AND owner_membership_id = {$membershipValues['owner_membership_id']}\n    AND is_current_member = 1";
                     $result = CRM_Core_DAO::singleValueQuery($query);
                     if ($result < CRM_Utils_Array::value('max_related', $membershipValues, PHP_INT_MAX)) {
                         CRM_Member_BAO_Membership::create($membershipValues, CRM_Core_DAO::$_nullArray);
                     }
                 }
             } elseif ($action & CRM_Core_Action::UPDATE) {
                 // if action is update and updated relationship do
                 // not match with the existing
                 // membership=>relationship then we need to
                 // change the status of the membership record to expired for
                 // previous relationship -- CRM-12078.
                 // CRM-16087 we need to pass ownerMembershipId to isRelatedMembershipExpired function
                 if (empty($params['relationship_ids']) && !empty($params['id'])) {
                     $relIds = array($params['id']);
                 } else {
                     $relIds = CRM_Utils_Array::value('relationship_ids', $params);
                 }
                 if (self::isRelatedMembershipExpired($relTypeIds, $contactId, $mainRelatedContactId, $relTypeId, $relIds) && !empty($membershipValues['owner_membership_id']) && !empty($values[$mainRelatedContactId]['memberships'][$membershipValues['owner_membership_id']])) {
                     $membershipValues['status_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', 'Expired', 'id', 'label');
                     $type = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $membershipValues['membership_type_id'], 'name', 'id');
                     CRM_Member_BAO_Membership::add($membershipValues);
                     CRM_Core_Session::setStatus(ts("Inherited membership {$type} status was changed to Expired due to the change in relationship type."), ts('Record Updated'), 'alert');
                 }
             }
         }
     }
 }