コード例 #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;
 }
 public function postProcess()
 {
     $params = $this->_submitValues;
     $batchDetailsSql = " UPDATE civicrm_batch SET ";
     $batchDetailsSql .= "    title = %1 ";
     $batchDetailsSql .= " ,  description = %2 ";
     $batchDetailsSql .= " ,  banking_account = %3 ";
     $batchDetailsSql .= " ,  banking_date  = %4 ";
     $batchDetailsSql .= " ,  exclude_from_posting = %5 ";
     $batchDetailsSql .= " ,  contribution_type_id = %6 ";
     $batchDetailsSql .= " ,  payment_instrument_id = %7 ";
     $batchDetailsSql .= " WHERE id = %8 ";
     $bankingDate = CRM_Utils_Date::processDate($params['banking_date']);
     $sqlParams = array();
     $sqlParams[1] = array((string) $params['batch_title'], 'String');
     $sqlParams[2] = array((string) $params['description'], 'String');
     $sqlParams[3] = array((string) $params['banking_account'], 'String');
     $sqlParams[4] = array((string) $bankingDate, 'String');
     $sqlParams[5] = array((string) $params['exclude_from_posting'], 'String');
     $sqlParams[6] = array((string) $params['contribution_type_id'], 'String');
     $sqlParams[7] = array((string) $params['payment_instrument_id'], 'String');
     $sqlParams[8] = array((int) $params['id'], 'Integer');
     CRM_Core_DAO::executeQuery($batchDetailsSql, $sqlParams);
     drupal_goto('civicrm/batch/process', array('query' => array('bid' => $params['id'], 'reset' => '1')));
     CRM_Utils_System::civiExit();
 }
コード例 #3
0
 /**
  * Takes an associative array and creates a discount item
  *
  * This function extracts all the params it needs to initialize the created
  * discount item. The params array could contain additional unused name/value
  * pairs
  *
  * @param array $params (reference ) an assoc array of name/value pairs
  *
  * @return object CRM_CiviDiscount_BAO_Item object
  * @access public
  * @static
  */
 static function add(&$params)
 {
     $item = new CRM_CiviDiscount_DAO_Item();
     $item->code = $params['code'];
     $item->description = $params['description'];
     $item->amount = $params['amount'];
     $item->amount_type = $params['amount_type'];
     $item->discount_term = $params['discount_term'];
     $item->count_max = $params['count_max'];
     $item->discount_msg = $params['discount_msg'];
     $item->filters = json_encode($params['filters']);
     $item->autodiscount = json_encode($params['autodiscount']);
     foreach ($params['multi_valued'] as $mv => $dontCare) {
         if (!empty($params[$mv])) {
             $item->{$mv} = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, array_values($params[$mv])) . CRM_Core_DAO::VALUE_SEPARATOR;
         } else {
             $item->{$mv} = 'null';
         }
     }
     if (!empty($params['id'])) {
         $item->id = $params['id'];
     }
     $item->is_active = CRM_Utils_Array::value('is_active', $params) ? 1 : 0;
     $item->discount_msg_enabled = CRM_Utils_Array::value('discount_msg_enabled', $params) ? 1 : 0;
     if (!empty($params['active_on'])) {
         $item->active_on = CRM_Utils_Date::processDate($params['active_on']);
     } else {
         $item->active_on = 'null';
     }
     if (!empty($params['expire_on'])) {
         $item->expire_on = CRM_Utils_Date::processDate($params['expire_on']);
     } else {
         $item->expire_on = 'null';
     }
     if (!empty($params['organization_id'])) {
         $item->organization_id = $params['organization_id'];
     } else {
         $item->organization_id = 'null';
     }
     $id = empty($params['id']) ? NULL : $params['id'];
     $op = $id ? 'edit' : 'create';
     CRM_Utils_Hook::pre($op, 'CiviDiscount', $id, $params);
     $item->save();
     CRM_Utils_Hook::post($op, 'CiviDiscount', $item->id, $item);
     return $item;
 }
コード例 #4
0
ファイル: Search.php プロジェクト: ksecor/civicrm
 function postProcess()
 {
     $params = $this->controller->exportValues($this->_name);
     $parent = $this->controller->getParent();
     if (!empty($params)) {
         $fields = array('mailing_name', 'mailing_from', 'mailing_to', 'sort_name');
         foreach ($fields as $field) {
             if (isset($params[$field]) && !CRM_Utils_System::isNull($params[$field])) {
                 if (substr($field, 7) != 'name') {
                     $parent->set($field, CRM_Utils_Date::unformat(CRM_Utils_Date::processDate($params[$field]), ''));
                 } else {
                     $parent->set($field, $params[$field]);
                 }
             } else {
                 $parent->set($field, null);
             }
         }
     }
 }
コード例 #5
0
 function __construct(&$formValues)
 {
     $this->_formValues = $formValues;
     $this->_columns = array(ts('Contact Id') => 'contact_id', ts('Name') => 'display_name', ts('Donation Count') => 'donation_count', ts('Donation Amount') => 'donation_amount');
     $this->_amounts = array('min_amount_1' => ts('Min Amount One'), 'max_amount_1' => ts('Max Amount One'), 'min_amount_2' => ts('Min Amount Two'), 'max_amount_2' => ts('Max Amount Two'), 'exclude_min_amount' => ts('Exclusion Min Amount'), 'exclude_max_amount' => ts('Exclusion Max Amount'));
     $this->_dates = array('start_date_1' => ts('Start Date One'), 'end_date_1' => ts('End Date One'), 'start_date_2' => ts('Start Date Two'), 'end_date_2' => ts('End Date Two'), 'exclude_start_date' => ts('Exclusion Start Date'), 'exclude_end_date' => ts('Exclusion End Date'));
     $this->_checkboxes = array('is_first_amount' => ts('First Donation?'));
     foreach ($this->_amounts as $name => $title) {
         $this->{$name} = CRM_Utils_Array::value($name, $this->_formValues);
     }
     foreach ($this->_checkboxes as $name => $title) {
         $this->{$name} = CRM_Utils_Array::value($name, $this->_formValues, FALSE);
     }
     foreach ($this->_dates as $name => $title) {
         if (CRM_Utils_Array::value($name, $this->_formValues)) {
             $this->{$name} = CRM_Utils_Date::processDate($this->_formValues[$name]);
         }
     }
 }
コード例 #6
0
 /**
  * takes an associative array and creates a cancellation object
  *
  * the function extract all the params it needs to initialize the create a
  * resource 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_Booking_BAO_Cancellation object
  * @access public
  * @static
  */
 static function create(&$values)
 {
     $bookingID = CRM_Utils_Array::value('booking_id', $values);
     if (!$bookingID) {
         return;
     } else {
         $transaction = new CRM_Core_Transaction();
         try {
             $params = array('option_group_name' => CRM_Booking_Utils_Constants::OPTION_BOOKING_STATUS, 'name' => CRM_Booking_Utils_Constants::OPTION_VALUE_CANCELLED);
             $result = civicrm_api3('OptionValue', 'get', $params);
             $params = array();
             $params['id'] = $bookingID;
             $params['status_id'] = CRM_Utils_Array::value('value', CRM_Utils_Array::value($result['id'], $result['values']));
             $booking = CRM_Booking_BAO_Booking::create($params);
             $params = array();
             $params['booking_id'] = $bookingID;
             $percentage = CRM_Utils_Array::value('cancellation_percentage', $values);
             $bookingTotal = CRM_Utils_Array::value('booking_total', $values);
             $cancellationFee = $bookingTotal * $percentage / 100;
             $additionalCharge = CRM_Utils_Array::value('additional_charge', $values);
             if (is_numeric($additionalCharge)) {
                 $cancellationFee += $additionalCharge;
                 $params['additional_fee'] = $additionalCharge;
             }
             $params['cancellation_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('cancellation_date', $values));
             $params['comment'] = CRM_Utils_Array::value('comment', $values);
             $params['cancellation_fee'] = $cancellationFee;
             self::add($params);
             $slots = CRM_Booking_BAO_Slot::getBookingSlot($bookingID);
             foreach ($slots as $slotId => $slots) {
                 $subSlots = CRM_Booking_BAO_SubSlot::getSubSlotSlot($slotId);
                 foreach ($subSlots as $subSlotId => $subSlot) {
                     CRM_Booking_BAO_SubSlot::cancel($subSlotId);
                 }
                 CRM_Booking_BAO_Slot::cancel($slotId);
             }
             // return TRUE;
         } catch (Exception $e) {
             $transaction->rollback();
             CRM_Core_Error::fatal($e->getMessage());
         }
     }
 }
コード例 #7
0
 function postProcess()
 {
     $params = $this->controller->exportValues($this->_name);
     $startDate = CRM_Utils_Date::processDate($params['start_date'], null, false, 'Ymd');
     $endDate = CRM_Utils_Date::processDate($params['end_date'], null, false, 'Ymd');
     $includeMorning = CRM_Utils_Array::value('include_morning', $params, false);
     $showDetails = CRM_Utils_Array::value('show_details', $params, false);
     $notSignedOut = CRM_Utils_Array::value('not_signed_out', $params, false);
     $showBalances = CRM_Utils_Array::value('show_balances', $params, false);
     require_once 'SFS/Utils/ExtendedCare.php';
     if ($showBalances) {
         $showDetails = false;
         $summary =& SFS_Utils_ExtendedCare::balanceDetails();
     } else {
         $summary =& SFS_Utils_ExtendedCare::signoutDetails($startDate, $endDate, $includeMorning, $showDetails, $notSignedOut, $params['student_id']);
     }
     $this->assign('summary', $summary);
     $this->assign('showBalances', $showBalances);
     $this->assign('showDetails', $showDetails);
 }
コード例 #8
0
ファイル: DayView.php プロジェクト: sushantpaste/civibooking
 function run()
 {
     //get date value from url through get method
     $date = CRM_Utils_Request::retrieve('date', 'Positive', $this, FALSE, 0);
     //convert javascript.getTime() to PHP date format
     $date = date('m/d/Y', round($date / 1000));
     //get resources information by selected date
     $from = CRM_Utils_Date::processDate($date);
     $resources = CRM_Booking_BAO_Slot::getSlotDetailsOrderByResourceBetweenDate($from, $from);
     $values = array();
     //put resources result to values, being ready to display.
     $values['resources'] = $resources;
     //Convert date to compile with crmDate
     $values['dayview_select_date'] = DateTime::createFromFormat('m/d/Y', $date)->format('Y-m-d');
     //assign variables for use in a template
     $this->assign($values);
     // Example: Set the page-title dynamically; alternatively, declare a static title in xml/Menu/*.xml
     CRM_Utils_System::setTitle(ts('DayViewPrint'));
     parent::run();
 }
コード例 #9
0
ファイル: SearchEvent.php プロジェクト: ksecor/civicrm
 function postProcess()
 {
     $params = $this->controller->exportValues($this->_name);
     $parent = $this->controller->getParent();
     $parent->set('searchResult', 1);
     if (!empty($params)) {
         $fields = array('title', 'event_type_id', 'start_date', 'end_date', 'eventsByDates');
         foreach ($fields as $field) {
             if (isset($params[$field]) && !CRM_Utils_System::isNull($params[$field])) {
                 if (substr($field, -4) == 'date') {
                     $parent->set($field, CRM_Utils_Date::unformat(CRM_Utils_Date::processDate($params[$field]), ''));
                 } else {
                     $parent->set($field, $params[$field]);
                 }
             } else {
                 $parent->set($field, null);
             }
         }
     }
 }
コード例 #10
0
ファイル: DayView.php プロジェクト: sushantpaste/civibooking
 function postProcess()
 {
     $values = $this->exportValues();
     $selectedDate = CRM_Utils_Array::value('dayview_select_date', $values);
     //get booking slots from selected date
     $from = CRM_Utils_Date::processDate($selectedDate);
     $resources = CRM_Booking_BAO_Slot::getSlotDetailsOrderByResourceBetweenDate($from, $from);
     //put resources result to values, being ready to display.
     $values['resources'] = $resources;
     if (empty($resources)) {
         //check empty result
         //Convert date to show on no match found view
         $values['dayview_select_date'] = DateTime::createFromFormat('m/d/Y', $selectedDate)->format('d/m/Y');
     } else {
         //Convert date to compile with crmDate
         $values['dayview_select_date'] = DateTime::createFromFormat('m/d/Y', $selectedDate)->format('Y-m-d');
     }
     //assign values to show on template
     $this->assign($values);
     //parent::postProcess();
 }
コード例 #11
0
 function postProcess()
 {
     $params = $this->controller->exportValues($this->_name);
     CRM_Contact_BAO_Query::fixDateValues($params["mailing_relative"], $params['mailing_from'], $params['mailing_to']);
     $parent = $this->controller->getParent();
     if (!empty($params)) {
         $fields = array('mailing_name', 'mailing_from', 'mailing_to', 'sort_name', 'campaign_id', 'mailing_status', 'sms');
         foreach ($fields as $field) {
             if (isset($params[$field]) && !CRM_Utils_System::isNull($params[$field])) {
                 if (in_array($field, array('mailing_from', 'mailing_to')) && !$params["mailing_relative"]) {
                     $time = $field == 'mailing_to' ? '235959' : NULL;
                     $parent->set($field, CRM_Utils_Date::processDate($params[$field], $time));
                 } else {
                     $parent->set($field, $params[$field]);
                 }
             } else {
                 $parent->set($field, NULL);
             }
         }
     }
 }
コード例 #12
0
ファイル: SearchEvent.php プロジェクト: agloa/tournament
 public function postProcess()
 {
     $params = $this->controller->exportValues($this->_name);
     $parent = $this->controller->getParent();
     $parent->set('searchResult', 1);
     if (!empty($params)) {
         $fields = array('title', 'event_type_id', 'start_date', 'end_date', 'eventsByDates', 'campaign_id');
         foreach ($fields as $field) {
             if (isset($params[$field]) && !CRM_Utils_System::isNull($params[$field])) {
                 if (substr($field, -4) == 'date') {
                     $time = $field == 'end_date' ? '235959' : NULL;
                     $parent->set($field, CRM_Utils_Date::processDate($params[$field], $time));
                 } else {
                     $parent->set($field, $params[$field]);
                 }
             } else {
                 $parent->set($field, NULL);
             }
         }
     }
 }
コード例 #13
0
ファイル: Confirm.php プロジェクト: hyebahi/civicrm-core
 /**
  * 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;
 }
コード例 #14
0
 function postProcess()
 {
     $current_status_ids = array();
     $dao = CRM_Core_DAO::executeQuery("SELECT id from civicrm_membership_status where is_current_member = 1");
     while ($dao->fetch()) {
         $current_status_ids[] = $dao->id;
     }
     $formValues = $this->exportValues();
     if (!isset($formValues['member_status_id'])) {
         $formValues['member_status_id'] = array();
     }
     $birth_date_from = CRM_Utils_Date::processDate($formValues['birth_date_from']);
     $birth_date_to = CRM_Utils_Date::processDate($formValues['birth_date_to']);
     $selector = new CRM_Rood_UpgradeSelector();
     $original_where = $selector->getWhere();
     $selector->setData($formValues['rood_mtype'], array_keys($formValues['member_status_id']), $birth_date_from, $birth_date_to);
     $selector->store();
     $where = $selector->getWhere();
     $count = CRM_Core_DAO::singleValueQuery("SELECT COUNT(*)\n      FROM civicrm_membership\n      INNER JOIN civicrm_contact ON civicrm_membership.contact_id = civicrm_contact.id\n      LEFT JOIN civicrm_membership sp_membership ON civicrm_contact.id = sp_membership.contact_id AND sp_membership.membership_type_id = '{$formValues['sp_mtype']}' AND sp_membership.status_id IN (" . implode(', ', $current_status_ids) . ")\n      " . $where . " AND sp_membership.id is null");
     $this->assign('found', $count);
     if ($where == $original_where && isset($_POST['continue']) && !empty($_POST['continue'])) {
         $queue = CRM_Queue_Service::singleton()->create(array('type' => 'Sql', 'name' => 'nl.sp.rood.upgrade', 'reset' => TRUE));
         $dao = CRM_Core_DAO::executeQuery("SELECT civicrm_membership.id\n       FROM civicrm_membership\n      INNER JOIN civicrm_contact ON civicrm_membership.contact_id = civicrm_contact.id\n      LEFT JOIN civicrm_membership sp_membership ON civicrm_contact.id = sp_membership.contact_id AND sp_membership.membership_type_id = '{$formValues['sp_mtype']}' AND sp_membership.status_id IN (" . implode(', ', $current_status_ids) . ")\n      " . $where . " AND sp_membership.id is null\n      ");
         $i = 1;
         while ($dao->fetch()) {
             $title = ts('Upgrade Rood lidmaatschappen %1 van %2', array(1 => $i, 2 => $count));
             //create a task without parameters
             $task = new CRM_Queue_Task(array('CRM_Rood_MembershipUpgrade', 'UpgradeFromQueue'), array($dao->id, $formValues), $title);
             //now add this task to the queue
             $queue->createItem($task);
             $i++;
         }
         $runner = new CRM_Queue_Runner(array('title' => ts('Upgrade rood lidmaatschappen'), 'queue' => $queue, 'errorMode' => CRM_Queue_Runner::ERROR_ABORT, 'onEnd' => array('CRM_Rood_Form_UpgradeRoodMembership', 'onEnd'), 'onEndUrl' => CRM_Utils_System::url('civicrm/member/upgrade_rood', 'reset=1')));
         $runner->runAllViaWeb();
         // does not return
     }
 }
 function preProcess()
 {
     parent::preProcess();
     //    	if(!empty($values['range_from']) && !empty($values['range_from'])) {
     //    		$from = CRM_Utils_Date::processDate($values['range_from'], null, null, 'Y-m-d');
     //    		$to = CRM_Utils_Date::processDate($values['range_to'], null, null, 'Y-m-d');
     //
     //    		$this->set('range_from', $from);
     //    		$this->set('range_to', $to);
     //    	}
     $values = array('range_from' => CRM_Utils_Request::retrieve('range_from', 'String', $this, false, null, 'POST'), 'range_to' => CRM_Utils_Request::retrieve('range_to', 'String', $this, false, null, 'POST'));
     if (!empty($values['range_from']) && !empty($values['range_from'])) {
         $from = CRM_Utils_Date::processDate($values['range_from'], null, null, 'Y-m-d');
         $to = CRM_Utils_Date::processDate($values['range_to'], null, null, 'Y-m-d');
         $fromDate = new DateTime($from);
         $toDate = new DateTime($to);
         $diff = $fromDate->diff($toDate);
         $days = $diff->days;
         //https://bugs.php.net/bug.php?id=51184
         if ($days == 6015) {
             $y1 = $fromDate->format('Y');
             $y2 = $toDate->format('Y');
             $z1 = $fromDate->format('z');
             $z2 = $toDate->format('z');
             $days = intval($y1 * 365.2425 + $z1) - intval($y2 * 365.2425 + $z2);
         }
         if ($days > 93 || $diff->m >= 3) {
             $this->setElementError('range_to', "Date range can't exceed 3 months");
             $this->set('range_from', null);
             $this->set('range_to', null);
         } else {
             $this->set('range_from', $from);
             $this->set('range_to', $to);
             $this->renderPayments();
         }
     }
 }
 /**
  * @param $formValues
  */
 public function __construct(&$formValues)
 {
     $this->_formValues = $formValues;
     $clauses = array();
     $clauses[] = "contrib.total_amount != contrib_recur.amount";
     $clauses[] = "contrib.is_test = 0";
     $clauses[] = "(contrib.contribution_status_id = 1 OR contrib.contribution_status_id = 8)";
     $value = isset($this->_formValues['start_date']) ? $this->_formValues['start_date'] : '';
     if ($changeDate = CRM_Utils_Date::processDate($value)) {
         $clauses[] = "contrib.receive_date >= {$changeDate}";
     }
     $whereClause = implode(' AND ', $clauses);
     $this->tableName = 'civicrm_temp_custom_recurring_change_search';
     if (CRM_Core_DAO::checkTableExists($this->tableName)) {
         $query = "DROP TABLE {$this->tableName}";
         CRM_Core_DAO::executeQuery($query);
     }
     $creatSql = "CREATE TABLE {$this->tableName}\n       SELECT contrib.id as contribution_id, contact_a.id as contact_id,\n       contact_a.sort_name as sort_name,\n       contrib_recur.amount as new_amount,\n       CONCAT(contrib_recur.frequency_interval, ' ', contrib_recur.frequency_unit) as frequency,\n       contrib.receive_date as change_date,\n       contrib.total_amount AS old_amount\n       FROM civicrm_contact contact_a \n       INNER JOIN civicrm_contribution_recur contrib_recur ON (contrib_recur.contact_id = contact_a.id AND (contrib_recur.end_date IS NULL OR contrib_recur.end_date >= NOW()) AND (contrib_recur.cancel_date IS NULL OR contrib_recur.cancel_date >= NOW()) )\n       INNER JOIN civicrm_contribution contrib ON contrib.contribution_recur_id = contrib_recur.id\n       WHERE {$whereClause}";
     CRM_Core_DAO::executeQuery($creatSql);
     // Define the columns for search result rows
     $this->_columns = array(ts('Name') => 'sort_name', ts('Old Amount') => 'old_amount', ts('Changed Since') => 'change_date', ts('New Amount') => 'new_amount', ts('Frequency') => 'frequency');
     // define component access permission needed
     $this->_permissionedComponent = 'CiviContribute';
 }
コード例 #17
0
ファイル: Registration.php プロジェクト: nyimbi/civicrm-core
 /**
  * Check if event is valid.
  *
  * @todo - combine this with CRM_Event_BAO_Event::validRegistrationRequest
  * (probably extract relevant values here & call that with them & handle bounces & redirects here -as
  * those belong in the form layer)
  *
  * @param string $redirect
  */
 public function checkValidEvent($redirect = NULL)
 {
     // is the event active (enabled)?
     if (!$this->_values['event']['is_active']) {
         // form is inactive, die a fatal death
         CRM_Core_Error::statusBounce(ts('The event you requested is currently unavailable (contact the site administrator for assistance).'));
     }
     // is online registration is enabled?
     if (!$this->_values['event']['is_online_registration']) {
         CRM_Core_Error::statusBounce(ts('Online registration is not currently available for this event (contact the site administrator for assistance).'), $redirect);
     }
     // is this an event template ?
     if (!empty($this->_values['event']['is_template'])) {
         CRM_Core_Error::statusBounce(ts('Event templates are not meant to be registered.'), $redirect);
     }
     $now = date('YmdHis');
     $startDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('registration_start_date', $this->_values['event']));
     if ($startDate && $startDate >= $now) {
         CRM_Core_Error::statusBounce(ts('Registration for this event begins on %1', array(1 => CRM_Utils_Date::customFormat(CRM_Utils_Array::value('registration_start_date', $this->_values['event'])))), $redirect);
     }
     $regEndDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('registration_end_date', $this->_values['event']));
     $eventEndDate = CRM_Utils_Date::processDate(CRM_Utils_Array::value('event_end_date', $this->_values['event']));
     if ($regEndDate && $regEndDate < $now || empty($regEndDate) && !empty($eventEndDate) && $eventEndDate < $now) {
         $endDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('registration_end_date', $this->_values['event']));
         if (empty($regEndDate)) {
             $endDate = CRM_Utils_Date::customFormat(CRM_Utils_Array::value('event_end_date', $this->_values['event']));
         }
         CRM_Core_Error::statusBounce(ts('Registration for this event ended on %1', array(1 => $endDate)), $redirect);
     }
 }
コード例 #18
0
ファイル: Membership.php プロジェクト: konadave/civicrm-core
 /**
  * Method to fix membership status of stale membership.
  *
  * This method first checks if the membership is stale. If it is,
  * then status will be updated based on existing start and end
  * dates and log will be added for the status change.
  *
  * @param array $currentMembership
  *   Reference to the array.
  *   containing all values of
  *   the current membership
  * @param array $changeToday
  *   Array of month, day, year.
  *   values in case today needs
  *   to be customised, null otherwise
  */
 public static function fixMembershipStatusBeforeRenew(&$currentMembership, $changeToday)
 {
     $today = NULL;
     if ($changeToday) {
         $today = CRM_Utils_Date::processDate($changeToday, NULL, FALSE, 'Y-m-d');
     }
     $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate(CRM_Utils_Array::value('start_date', $currentMembership), CRM_Utils_Array::value('end_date', $currentMembership), CRM_Utils_Array::value('join_date', $currentMembership), $today, TRUE, $currentMembership['membership_type_id'], $currentMembership);
     if (empty($status) || empty($status['id'])) {
         CRM_Core_Error::fatal(ts('Oops, it looks like there is no valid membership status corresponding to the membership start and end dates for this membership. Contact the site administrator for assistance.'));
     }
     $currentMembership['today_date'] = $today;
     if ($status['id'] !== $currentMembership['status_id']) {
         $memberDAO = new CRM_Member_DAO_Membership();
         $memberDAO->id = $currentMembership['id'];
         $memberDAO->find(TRUE);
         $memberDAO->status_id = $status['id'];
         $memberDAO->join_date = CRM_Utils_Date::isoToMysql($memberDAO->join_date);
         $memberDAO->start_date = CRM_Utils_Date::isoToMysql($memberDAO->start_date);
         $memberDAO->end_date = CRM_Utils_Date::isoToMysql($memberDAO->end_date);
         $memberDAO->save();
         CRM_Core_DAO::storeValues($memberDAO, $currentMembership);
         $memberDAO->free();
         $currentMembership['is_current_member'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $currentMembership['status_id'], 'is_current_member');
         $format = '%Y%m%d';
         $logParams = array('membership_id' => $currentMembership['id'], 'status_id' => $status['id'], 'start_date' => CRM_Utils_Date::customFormat($currentMembership['start_date'], $format), 'end_date' => CRM_Utils_Date::customFormat($currentMembership['end_date'], $format), 'modified_date' => CRM_Utils_Date::customFormat($currentMembership['today_date'], $format), 'membership_type_id' => $currentMembership['membership_type_id'], 'max_related' => CRM_Utils_Array::value('max_related', $currentMembership, 0));
         $session = CRM_Core_Session::singleton();
         // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
         if ($session->get('userID')) {
             $logParams['modified_id'] = $session->get('userID');
         } else {
             $logParams['modified_id'] = $currentMembership['contact_id'];
         }
         CRM_Member_BAO_MembershipLog::add($logParams, CRM_Core_DAO::$_nullArray);
     }
 }
コード例 #19
0
ファイル: Schedule.php プロジェクト: kcristiano/civicrm-core
 /**
  * Process the posted form values.  Create and schedule a Mass SMS.
  */
 public function postProcess()
 {
     $params = array();
     $params['mailing_id'] = $ids['mailing_id'] = $this->_mailingID;
     if (empty($params['mailing_id'])) {
         CRM_Core_Error::fatal(ts('Could not find a mailing id'));
     }
     foreach (array('now', 'start_date', 'start_date_time') as $parameter) {
         $params[$parameter] = $this->controller->exportValue($this->_name, $parameter);
     }
     if ($params['now']) {
         $params['scheduled_date'] = date('YmdHis');
     } else {
         $params['scheduled_date'] = CRM_Utils_Date::processDate($params['start_date'] . ' ' . $params['start_date_time']);
     }
     $session = CRM_Core_Session::singleton();
     // set the scheduled_id
     $params['scheduled_id'] = $session->get('userID');
     $params['scheduled_date'] = date('YmdHis');
     // set approval details if workflow is not enabled
     if (!CRM_Mailing_Info::workflowEnabled()) {
         $params['approver_id'] = $session->get('userID');
         $params['approval_date'] = date('YmdHis');
         $params['approval_status_id'] = 1;
     }
     if ($params['now']) {
         $params['scheduled_date'] = date('YmdHis');
     } else {
         $params['scheduled_date'] = CRM_Utils_Date::processDate($params['start_date'] . ' ' . $params['start_date_time']);
     }
     // Build the mailing object.
     CRM_Mailing_BAO_Mailing::create($params, $ids);
     $session = CRM_Core_Session::singleton();
     $session->pushUserContext(CRM_Utils_System::url('civicrm/mailing/browse/scheduled', 'reset=1&scheduled=true&sms=1'));
 }
コード例 #20
0
ファイル: Fee.php プロジェクト: saurabhbatra96/civicrm-core
 /**
  * Process the form.
  */
 public function postProcess()
 {
     $eventTitle = '';
     $params = $this->exportValues();
     $this->set('discountSection', 0);
     if (!empty($_POST['_qf_Fee_submit'])) {
         $this->buildAmountLabel();
         $this->set('discountSection', 2);
         return;
     }
     if (!empty($params['payment_processor'])) {
         $params['payment_processor'] = str_replace(',', CRM_Core_DAO::VALUE_SEPARATOR, $params['payment_processor']);
     } else {
         $params['payment_processor'] = 'null';
     }
     $params['is_pay_later'] = CRM_Utils_Array::value('is_pay_later', $params, 0);
     $params['is_billing_required'] = CRM_Utils_Array::value('is_billing_required', $params, 0);
     if ($this->_id) {
         // delete all the prior label values or discounts in the custom options table
         // and delete a price set if one exists
         //@todo note that this removes the reference from existing participants -
         // even where there is not change - redress?
         // note that a more tentative form of this is invoked by passing price_set_id as an array
         // to event.create see CRM-14069
         // @todo get all of this logic out of form layer (currently partially in BAO/api layer)
         if (CRM_Price_BAO_PriceSet::removeFrom('civicrm_event', $this->_id)) {
             CRM_Core_BAO_Discount::del($this->_id, 'civicrm_event');
         }
     }
     if ($params['is_monetary']) {
         if (!empty($params['price_set_id'])) {
             //@todo this is now being done in the event BAO if passed price_set_id as an array
             // per notes on that fn - looking at the api converting to an array
             // so calling via the api may cause this to be done in the api
             CRM_Price_BAO_PriceSet::addTo('civicrm_event', $this->_id, $params['price_set_id']);
             if (!empty($params['price_field_id'])) {
                 $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
                 CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
             }
         } else {
             // if there are label / values, create custom options for them
             $labels = CRM_Utils_Array::value('label', $params);
             $values = CRM_Utils_Array::value('value', $params);
             $default = CRM_Utils_Array::value('default', $params);
             $options = array();
             if (!CRM_Utils_System::isNull($labels) && !CRM_Utils_System::isNull($values)) {
                 for ($i = 1; $i < self::NUM_OPTION; $i++) {
                     if (!empty($labels[$i]) && !CRM_Utils_System::isNull($values[$i])) {
                         $options[] = array('label' => trim($labels[$i]), 'value' => CRM_Utils_Rule::cleanMoney(trim($values[$i])), 'weight' => $i, 'is_active' => 1, 'is_default' => $default == $i);
                     }
                 }
                 if (!empty($options)) {
                     $params['default_fee_id'] = NULL;
                     if (empty($params['price_set_id'])) {
                         if (empty($params['price_field_id'])) {
                             $setParams['title'] = $eventTitle = $this->_isTemplate ? $this->_defaultValues['template_title'] : $this->_defaultValues['title'];
                             $eventTitle = strtolower(CRM_Utils_String::munge($eventTitle, '_', 245));
                             if (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceSet', $eventTitle, 'id', 'name')) {
                                 $setParams['name'] = $eventTitle;
                             } elseif (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceSet', $eventTitle . '_' . $this->_id, 'id', 'name')) {
                                 $setParams['name'] = $eventTitle . '_' . $this->_id;
                             } else {
                                 $timeSec = explode('.', microtime(TRUE));
                                 $setParams['name'] = $eventTitle . '_' . date('is', $timeSec[0]) . $timeSec[1];
                             }
                             $setParams['is_quick_config'] = 1;
                             $setParams['financial_type_id'] = $params['financial_type_id'];
                             $setParams['extends'] = CRM_Core_Component::getComponentID('CiviEvent');
                             $priceSet = CRM_Price_BAO_PriceSet::create($setParams);
                             $fieldParams['name'] = strtolower(CRM_Utils_String::munge($params['fee_label'], '_', 245));
                             $fieldParams['price_set_id'] = $priceSet->id;
                         } else {
                             foreach ($params['price_field_value'] as $arrayID => $fieldValueID) {
                                 if (empty($params['label'][$arrayID]) && empty($params['value'][$arrayID]) && !empty($fieldValueID)) {
                                     CRM_Price_BAO_PriceFieldValue::setIsActive($fieldValueID, '0');
                                     unset($params['price_field_value'][$arrayID]);
                                 }
                             }
                             $fieldParams['id'] = CRM_Utils_Array::value('price_field_id', $params);
                             $fieldParams['option_id'] = $params['price_field_value'];
                             $priceSet = new CRM_Price_BAO_PriceSet();
                             $priceSet->id = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', CRM_Utils_Array::value('price_field_id', $params), 'price_set_id');
                             if ($this->_defaultValues['financial_type_id'] != $params['financial_type_id']) {
                                 CRM_Core_DAO::setFieldValue('CRM_Price_DAO_PriceSet', $priceSet->id, 'financial_type_id', $params['financial_type_id']);
                             }
                         }
                         $fieldParams['label'] = $params['fee_label'];
                         $fieldParams['html_type'] = 'Radio';
                         CRM_Price_BAO_PriceSet::addTo('civicrm_event', $this->_id, $priceSet->id);
                         $fieldParams['option_label'] = $params['label'];
                         $fieldParams['option_amount'] = $params['value'];
                         $fieldParams['financial_type_id'] = $params['financial_type_id'];
                         foreach ($options as $value) {
                             $fieldParams['option_weight'][$value['weight']] = $value['weight'];
                         }
                         $fieldParams['default_option'] = $params['default'];
                         $priceField = CRM_Price_BAO_PriceField::create($fieldParams);
                     }
                 }
             }
             $discountPriceSets = !empty($this->_defaultValues['discount_price_set']) ? $this->_defaultValues['discount_price_set'] : array();
             $discountFieldIDs = !empty($this->_defaultValues['discount_option_id']) ? $this->_defaultValues['discount_option_id'] : array();
             if (CRM_Utils_Array::value('is_discount', $params) == 1) {
                 // if there are discounted set of label / values,
                 // create custom options for them
                 $labels = CRM_Utils_Array::value('discounted_label', $params);
                 $values = CRM_Utils_Array::value('discounted_value', $params);
                 $default = CRM_Utils_Array::value('discounted_default', $params);
                 if (!CRM_Utils_System::isNull($labels) && !CRM_Utils_System::isNull($values)) {
                     for ($j = 1; $j <= self::NUM_DISCOUNT; $j++) {
                         $discountOptions = array();
                         for ($i = 1; $i < self::NUM_OPTION; $i++) {
                             if (!empty($labels[$i]) && !CRM_Utils_System::isNull(CRM_Utils_Array::value($j, $values[$i]))) {
                                 $discountOptions[] = array('label' => trim($labels[$i]), 'value' => CRM_Utils_Rule::cleanMoney(trim($values[$i][$j])), 'weight' => $i, 'is_active' => 1, 'is_default' => $default == $i);
                             }
                         }
                         if (!empty($discountOptions)) {
                             $fieldParams = array();
                             $params['default_discount_fee_id'] = NULL;
                             $keyCheck = $j - 1;
                             $setParams = array();
                             if (empty($discountPriceSets[$keyCheck])) {
                                 if (!$eventTitle) {
                                     $eventTitle = strtolower(CRM_Utils_String::munge($this->_defaultValues['title'], '_', 200));
                                 }
                                 $setParams['title'] = $params['discount_name'][$j];
                                 if (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceSet', $eventTitle . '_' . $params['discount_name'][$j], 'id', 'name')) {
                                     $setParams['name'] = $eventTitle . '_' . $params['discount_name'][$j];
                                 } elseif (!CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceSet', $eventTitle . '_' . $params['discount_name'][$j] . '_' . $this->_id, 'id', 'name')) {
                                     $setParams['name'] = $eventTitle . '_' . $params['discount_name'][$j] . '_' . $this->_id;
                                 } else {
                                     $timeSec = explode('.', microtime(TRUE));
                                     $setParams['name'] = $eventTitle . '_' . $params['discount_name'][$j] . '_' . date('is', $timeSec[0]) . $timeSec[1];
                                 }
                                 $setParams['is_quick_config'] = 1;
                                 $setParams['financial_type_id'] = $params['financial_type_id'];
                                 $setParams['extends'] = CRM_Core_Component::getComponentID('CiviEvent');
                                 $priceSet = CRM_Price_BAO_PriceSet::create($setParams);
                                 $priceSetID = $priceSet->id;
                             } else {
                                 $priceSetID = $discountPriceSets[$j - 1];
                                 $setParams = array('title' => $params['discount_name'][$j], 'id' => $priceSetID);
                                 if ($this->_defaultValues['financial_type_id'] != $params['financial_type_id']) {
                                     $setParams['financial_type_id'] = $params['financial_type_id'];
                                 }
                                 CRM_Price_BAO_PriceSet::create($setParams);
                                 unset($discountPriceSets[$j - 1]);
                                 $fieldParams['id'] = CRM_Core_DAO::getFieldValue('CRM_Price_BAO_PriceField', $priceSetID, 'id', 'price_set_id');
                             }
                             $fieldParams['name'] = $fieldParams['label'] = $params['fee_label'];
                             $fieldParams['is_required'] = 1;
                             $fieldParams['price_set_id'] = $priceSetID;
                             $fieldParams['html_type'] = 'Radio';
                             $fieldParams['financial_type_id'] = $params['financial_type_id'];
                             foreach ($discountOptions as $value) {
                                 $fieldParams['option_label'][$value['weight']] = $value['label'];
                                 $fieldParams['option_amount'][$value['weight']] = $value['value'];
                                 $fieldParams['option_weight'][$value['weight']] = $value['weight'];
                                 if (!empty($value['is_default'])) {
                                     $fieldParams['default_option'] = $value['weight'];
                                 }
                                 if (!empty($discountFieldIDs[$j]) && !empty($discountFieldIDs[$j][$value['weight']])) {
                                     $fieldParams['option_id'][$value['weight']] = $discountFieldIDs[$j][$value['weight']];
                                     unset($discountFieldIDs[$j][$value['weight']]);
                                 }
                             }
                             //create discount priceset
                             $priceField = CRM_Price_BAO_PriceField::create($fieldParams);
                             if (!empty($discountFieldIDs[$j])) {
                                 foreach ($discountFieldIDs[$j] as $fID) {
                                     CRM_Price_BAO_PriceFieldValue::setIsActive($fID, '0');
                                 }
                             }
                             $discountParams = array('entity_table' => 'civicrm_event', 'entity_id' => $this->_id, 'price_set_id' => $priceSetID, 'start_date' => CRM_Utils_Date::processDate($params['discount_start_date'][$j]), 'end_date' => CRM_Utils_Date::processDate($params['discount_end_date'][$j]));
                             CRM_Core_BAO_Discount::add($discountParams);
                         }
                     }
                 }
             }
             if (!empty($discountPriceSets)) {
                 foreach ($discountPriceSets as $setId) {
                     CRM_Price_BAO_PriceSet::setIsQuickConfig($setId, 0);
                 }
             }
         }
     } else {
         if (!empty($params['price_field_id'])) {
             $priceSetID = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $params['price_field_id'], 'price_set_id');
             CRM_Price_BAO_PriceSet::setIsQuickConfig($priceSetID, 0);
         }
         $params['financial_type_id'] = '';
         $params['is_pay_later'] = 0;
         $params['is_billing_required'] = 0;
     }
     //update 'is_billing_required'
     if (empty($params['is_pay_later'])) {
         $params['is_billing_required'] = FALSE;
     }
     //update events table
     $params['id'] = $this->_id;
     // skip update of financial type in price set
     $params['skipFinancialType'] = TRUE;
     CRM_Event_BAO_Event::add($params);
     // Update tab "disabled" css class
     $this->ajaxResponse['tabValid'] = !empty($params['is_monetary']);
     parent::endPostProcess();
 }
コード例 #21
0
 /**
  * Function to process the form
  *
  * @access public
  *
  * @return void
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         // delete reminder
         CRM_Core_BAO_ActionSchedule::del($this->_id);
         CRM_Core_Session::setStatus(ts('Selected Reminder has been deleted.'), ts('Record Deleted'), 'success');
         return;
     }
     $values = $this->controller->exportValues($this->getName());
     $keys = array('title', 'subject', 'absolute_date', 'group_id', 'record_activity', 'limit_to');
     foreach ($keys as $key) {
         $params[$key] = CRM_Utils_Array::value($key, $values);
     }
     $moreKeys = array('start_action_offset', 'start_action_unit', 'start_action_condition', 'start_action_date', 'repetition_frequency_unit', 'repetition_frequency_interval', 'end_frequency_unit', 'end_frequency_interval', 'end_action', 'end_date');
     if ($absoluteDate = CRM_Utils_Array::value('absolute_date', $params)) {
         $params['absolute_date'] = CRM_Utils_Date::processDate($absoluteDate);
         foreach ($moreKeys as $mkey) {
             $params[$mkey] = 'null';
         }
     } else {
         $params['absolute_date'] = 'null';
         foreach ($moreKeys as $mkey) {
             $params[$mkey] = CRM_Utils_Array::value($mkey, $values);
         }
     }
     $params['body_text'] = CRM_Utils_Array::value('text_message', $values);
     $params['body_html'] = CRM_Utils_Array::value('html_message', $values);
     if (CRM_Utils_Array::value('recipient', $values) == 'manual') {
         $params['recipient_manual'] = CRM_Utils_Array::value('recipient_manual_id', $values);
         $params['group_id'] = $params['recipient'] = $params['recipient_listing'] = 'null';
     } elseif (CRM_Utils_Array::value('recipient', $values) == 'group') {
         $params['group_id'] = $values['group_id'];
         $params['recipient_manual'] = $params['recipient'] = $params['recipient_listing'] = 'null';
     } elseif (!CRM_Utils_System::isNull($values['recipient_listing'])) {
         $params['recipient'] = CRM_Utils_Array::value('recipient', $values);
         $params['recipient_listing'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, CRM_Utils_Array::value('recipient_listing', $values));
         $params['group_id'] = $params['recipient_manual'] = 'null';
     } else {
         $params['recipient'] = CRM_Utils_Array::value('recipient', $values);
         $params['group_id'] = $params['recipient_manual'] = $params['recipient_listing'] = 'null';
     }
     $params['mapping_id'] = $this->_mappingID;
     $params['entity_value'] = $this->_id;
     $params['entity_status'] = implode(CRM_Core_DAO::VALUE_SEPARATOR, $values['entity']);
     $params['is_active'] = CRM_Utils_Array::value('is_active', $values, 0);
     $params['is_repeat'] = CRM_Utils_Array::value('is_repeat', $values, 0);
     if (CRM_Utils_Array::value('is_repeat', $values) == 0) {
         $params['repetition_frequency_unit'] = 'null';
         $params['repetition_frequency_interval'] = 'null';
         $params['end_frequency_unit'] = 'null';
         $params['end_frequency_interval'] = 'null';
         $params['end_action'] = 'null';
         $params['end_date'] = 'null';
     }
     $params['name'] = CRM_Utils_String::munge($params['title'], '_', 64);
     $composeFields = array('template', 'saveTemplate', 'updateTemplate', 'saveTemplateName');
     $msgTemplate = NULL;
     //mail template is composed
     $composeParams = array();
     foreach ($composeFields as $key) {
         if (!empty($values[$key])) {
             $composeParams[$key] = $values[$key];
         }
     }
     if (!empty($composeParams['updateTemplate'])) {
         $templateParams = array('msg_text' => $params['body_text'], 'msg_html' => $params['body_html'], 'msg_subject' => $params['subject'], 'is_active' => TRUE);
         $templateParams['id'] = $values['template'];
         $msgTemplate = CRM_Core_BAO_MessageTemplate::add($templateParams);
     }
     if (!empty($composeParams['saveTemplate'])) {
         $templateParams = array('msg_text' => $params['body_text'], 'msg_html' => $params['body_html'], 'msg_subject' => $params['subject'], 'is_active' => TRUE);
         $templateParams['msg_title'] = $composeParams['saveTemplateName'];
         $msgTemplate = CRM_Core_BAO_MessageTemplate::add($templateParams);
     }
     if (isset($msgTemplate->id)) {
         $params['msg_template_id'] = $msgTemplate->id;
     } else {
         $params['msg_template_id'] = CRM_Utils_Array::value('template', $values);
     }
     CRM_Core_BAO_ActionSchedule::add($params, $ids);
     $status = ts("Your new Reminder titled %1 has been saved.", array(1 => "<strong>{$values['title']}</strong>"));
     CRM_Core_Session::setStatus($status, ts('Saved'), 'success');
     parent::endPostProcess();
 }
コード例 #22
0
ファイル: Case.php プロジェクト: prashantgajare/civicrm-core
 /**
  * Function to get Case Activities
  *
  * @param int $caseID case id
  * @param array $params posted params
  * @param int $contactID contact id
  *
  * @param null $context
  * @param null $userID
  * @param null $type
  *
  * @return returns case activities
  *
  * @static
  */
 static function getCaseActivity($caseID, &$params, $contactID, $context = NULL, $userID = NULL, $type = NULL)
 {
     $values = array();
     $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
     $assigneeID = CRM_Utils_Array::key('Activity Assignees', $activityContacts);
     $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
     $targetID = CRM_Utils_Array::key('Activity Targets', $activityContacts);
     // CRM-5081 - formatting the dates to omit seconds.
     // Note the 00 in the date format string is needed otherwise later on it thinks scheduled ones are overdue.
     $select = "SELECT count(ca.id) as ismultiple, ca.id as id,\n                          ca.activity_type_id as type,\n                          ca.activity_type_id as activity_type_id,\n                          cc.sort_name as reporter,\n                          cc.id as reporter_id,\n                          acc.sort_name AS assignee,\n                          acc.id AS assignee_id,\n                          DATE_FORMAT(IF(ca.activity_date_time < NOW() AND ca.status_id=ov.value,\n                            ca.activity_date_time,\n                            DATE_ADD(NOW(), INTERVAL 1 YEAR)\n                          ), '%Y%m%d%H%i00') as overdue_date,\n                          DATE_FORMAT(ca.activity_date_time, '%Y%m%d%H%i00') as display_date,\n                          ca.status_id as status,\n                          ca.subject as subject,\n                          ca.is_deleted as deleted,\n                          ca.priority_id as priority,\n                          ca.weight as weight,\n                          GROUP_CONCAT(ef.file_id) as attachment_ids ";
     $from = "\n      FROM civicrm_case_activity cca\n                  INNER JOIN civicrm_activity ca ON ca.id = cca.activity_id\n                  INNER JOIN civicrm_activity_contact cac ON cac.activity_id = ca.id AND cac.record_type_id = {$sourceID}\n                  INNER JOIN civicrm_contact cc ON cc.id = cac.contact_id\n                  INNER JOIN civicrm_option_group cog ON cog.name = 'activity_type'\n                  INNER JOIN civicrm_option_value cov ON cov.option_group_id = cog.id\n                         AND cov.value = ca.activity_type_id AND cov.is_active = 1\n                  LEFT JOIN civicrm_entity_file ef on ef.entity_table = 'civicrm_activity'  AND ef.entity_id = ca.id\n                  LEFT OUTER JOIN civicrm_option_group og ON og.name = 'activity_status'\n                  LEFT OUTER JOIN civicrm_option_value ov ON ov.option_group_id=og.id AND ov.name = 'Scheduled'\n                  LEFT JOIN civicrm_activity_contact caa\n                                ON caa.activity_id = ca.id AND caa.record_type_id = {$assigneeID}\n                  LEFT JOIN civicrm_contact acc ON acc.id = caa.contact_id  ";
     $where = 'WHERE cca.case_id= %1
                 AND ca.is_current_revision = 1';
     if (!empty($params['reporter_id'])) {
         $where .= " AND cac.contact_id = " . CRM_Utils_Type::escape($params['reporter_id'], 'Integer');
     }
     if (!empty($params['status_id'])) {
         $where .= " AND ca.status_id = " . CRM_Utils_Type::escape($params['status_id'], 'Integer');
     }
     if (!empty($params['activity_deleted'])) {
         $where .= " AND ca.is_deleted = 1";
     } else {
         $where .= " AND ca.is_deleted = 0";
     }
     if (!empty($params['activity_type_id'])) {
         $where .= " AND ca.activity_type_id = " . CRM_Utils_Type::escape($params['activity_type_id'], 'Integer');
     }
     if (!empty($params['activity_date_low'])) {
         $fromActivityDate = CRM_Utils_Type::escape(CRM_Utils_Date::processDate($params['activity_date_low']), 'Date');
     }
     if (!empty($params['activity_date_high'])) {
         $toActivityDate = CRM_Utils_Type::escape(CRM_Utils_Date::processDate($params['activity_date_high']), 'Date');
         $toActivityDate = $toActivityDate ? $toActivityDate + 235959 : NULL;
     }
     if (!empty($fromActivityDate)) {
         $where .= " AND ca.activity_date_time >= '{$fromActivityDate}'";
     }
     if (!empty($toActivityDate)) {
         $where .= " AND ca.activity_date_time <= '{$toActivityDate}'";
     }
     // hack to handle to allow initial sorting to be done by query
     if (CRM_Utils_Array::value('sortname', $params) == 'undefined') {
         $params['sortname'] = NULL;
     }
     if (CRM_Utils_Array::value('sortorder', $params) == 'undefined') {
         $params['sortorder'] = NULL;
     }
     $sortname = CRM_Utils_Array::value('sortname', $params);
     $sortorder = CRM_Utils_Array::value('sortorder', $params);
     $groupBy = " GROUP BY ca.id ";
     if (!$sortname and !$sortorder) {
         // CRM-5081 - added id to act like creation date
         $orderBy = " ORDER BY overdue_date ASC, display_date DESC, weight DESC";
     } else {
         $sort = "{$sortname} {$sortorder}";
         $sort = CRM_Utils_Type::escape($sort, 'String');
         $orderBy = " ORDER BY {$sort} ";
         if ($sortname != 'display_date') {
             $orderBy .= ', display_date DESC';
         }
     }
     $page = CRM_Utils_Array::value('page', $params);
     $rp = CRM_Utils_Array::value('rp', $params);
     if (!$page) {
         $page = 1;
     }
     if (!$rp) {
         $rp = 10;
     }
     $start = ($page - 1) * $rp;
     $query = $select . $from . $where . $groupBy . $orderBy;
     $params = array(1 => array($caseID, 'Integer'));
     $dao = CRM_Core_DAO::executeQuery($query, $params);
     $params['total'] = $dao->N;
     //FIXME: need to optimize/cache these queries
     $limit = " LIMIT {$start}, {$rp}";
     $query .= $limit;
     //EXIT;
     $dao = CRM_Core_DAO::executeQuery($query, $params);
     $activityTypes = CRM_Case_PseudoConstant::caseActivityType(FALSE, TRUE);
     $activityStatus = CRM_Core_PseudoConstant::activityStatus();
     $activityPriority = CRM_Core_PseudoConstant::get('CRM_Activity_DAO_Activity', 'priority_id');
     $url = CRM_Utils_System::url("civicrm/case/activity", "reset=1&cid={$contactID}&caseid={$caseID}", FALSE, NULL, FALSE);
     $contextUrl = '';
     if ($context == 'fulltext') {
         $contextUrl = "&context={$context}";
     }
     $editUrl = "{$url}&action=update{$contextUrl}";
     $deleteUrl = "{$url}&action=delete{$contextUrl}";
     $restoreUrl = "{$url}&action=renew{$contextUrl}";
     $viewTitle = ts('View this activity.');
     $statusTitle = ts('Edit status');
     $emailActivityTypeIDs = array('Email' => CRM_Core_OptionGroup::getValue('activity_type', 'Email', 'name'), 'Inbound Email' => CRM_Core_OptionGroup::getValue('activity_type', 'Inbound Email', 'name'));
     $emailActivityTypeIDs = array('Email' => CRM_Core_OptionGroup::getValue('activity_type', 'Email', 'name'), 'Inbound Email' => CRM_Core_OptionGroup::getValue('activity_type', 'Inbound Email', 'name'));
     $caseDeleted = CRM_Core_DAO::getFieldValue('CRM_Case_DAO_Case', $caseID, 'is_deleted');
     // define statuses which are handled like Completed status (others are assumed to be handled like Scheduled status)
     $compStatusValues = array();
     $compStatusNames = array('Completed', 'Left Message', 'Cancelled', 'Unreachable', 'Not Required');
     foreach ($compStatusNames as $name) {
         $compStatusValues[] = CRM_Core_OptionGroup::getValue('activity_status', $name, 'name');
     }
     $contactViewUrl = CRM_Utils_System::url("civicrm/contact/view", "reset=1&cid=", FALSE, NULL, FALSE);
     $hasViewContact = CRM_Core_Permission::giveMeAllACLs();
     $clientIds = self::retrieveContactIdsByCaseId($caseID);
     if (!$userID) {
         $session = CRM_Core_Session::singleton();
         $userID = $session->get('userID');
     }
     while ($dao->fetch()) {
         $allowView = self::checkPermission($dao->id, 'view', $dao->activity_type_id, $userID);
         $allowEdit = self::checkPermission($dao->id, 'edit', $dao->activity_type_id, $userID);
         $allowDelete = self::checkPermission($dao->id, 'delete', $dao->activity_type_id, $userID);
         //do not have sufficient permission
         //to access given case activity record.
         if (!$allowView && !$allowEdit && !$allowDelete) {
             continue;
         }
         $values[$dao->id]['id'] = $dao->id;
         $values[$dao->id]['type'] = $activityTypes[$dao->type]['label'];
         $reporterName = $dao->reporter;
         if ($hasViewContact) {
             $reporterName = '<a href="' . $contactViewUrl . $dao->reporter_id . '">' . $dao->reporter . '</a>';
         }
         $values[$dao->id]['reporter'] = $reporterName;
         $targetNames = CRM_Activity_BAO_ActivityContact::getNames($dao->id, $targetID);
         $targetContactUrls = $withContacts = array();
         foreach ($targetNames as $targetId => $targetName) {
             if (!in_array($targetId, $clientIds)) {
                 $withContacts[$targetId] = $targetName;
             }
         }
         foreach ($withContacts as $cid => $name) {
             if ($hasViewContact) {
                 $name = '<a href="' . $contactViewUrl . $cid . '">' . $name . '</a>';
             }
             $targetContactUrls[] = $name;
         }
         $values[$dao->id]['with_contacts'] = implode('; ', $targetContactUrls);
         $values[$dao->id]['display_date'] = CRM_Utils_Date::customFormat($dao->display_date);
         $values[$dao->id]['status'] = $activityStatus[$dao->status];
         //check for view activity.
         $subject = empty($dao->subject) ? '(' . ts('no subject') . ')' : $dao->subject;
         if ($allowView) {
             $url = CRM_Utils_System::url('civicrm/case/activity/view', array('cid' => $contactID, 'aid' => $dao->id));
             $subject = '<a class="crm-popup medium-popup" href="' . $url . '" title="' . $viewTitle . '">' . $subject . '</a>';
         }
         $values[$dao->id]['subject'] = $subject;
         // add activity assignee to activity selector. CRM-4485.
         if (isset($dao->assignee)) {
             if ($dao->ismultiple == 1) {
                 if ($dao->reporter_id != $dao->assignee_id) {
                     $values[$dao->id]['reporter'] .= $hasViewContact ? ' / ' . "<a href='{$contactViewUrl}{$dao->assignee_id}'>{$dao->assignee}</a>" : ' / ' . $dao->assignee;
                 }
                 $values[$dao->id]['assignee'] = $dao->assignee;
             } else {
                 $values[$dao->id]['reporter'] .= ' / ' . ts('(multiple)');
             }
         }
         // FIXME: Why are we not using CRM_Core_Action for these links? This is too much manual work and likely to get out-of-sync with core markup.
         $url = "";
         $css = 'class="action-item crm-hover-button"';
         $additionalUrl = "&id={$dao->id}";
         if (!$dao->deleted) {
             //hide edit link of activity type email.CRM-4530.
             if (!in_array($dao->type, $emailActivityTypeIDs)) {
                 //hide Edit link if activity type is NOT editable (special case activities).CRM-5871
                 if ($allowEdit) {
                     $url = '<a ' . $css . ' href="' . $editUrl . $additionalUrl . '">' . ts('Edit') . '</a> ';
                 }
             }
             if ($allowDelete) {
                 $url .= ' <a ' . str_replace('action-item', 'action-item small-popup', $css) . ' href="' . $deleteUrl . $additionalUrl . '">' . ts('Delete') . '</a>';
             }
         } elseif (!$caseDeleted) {
             $url = ' <a ' . $css . ' href="' . $restoreUrl . $additionalUrl . '">' . ts('Restore') . '</a>';
             $values[$dao->id]['status'] = $values[$dao->id]['status'] . '<br /> (deleted)';
         }
         //check for operations.
         if (self::checkPermission($dao->id, 'Move To Case', $dao->activity_type_id)) {
             $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'move\',' . $dao->id . ', ' . $caseID . ', this ); return false;">' . ts('Move To Case') . '</a> ';
         }
         if (self::checkPermission($dao->id, 'Copy To Case', $dao->activity_type_id)) {
             $url .= ' <a ' . $css . ' href="#" onClick="Javascript:fileOnCase( \'copy\',' . $dao->id . ',' . $caseID . ', this ); return false;">' . ts('Copy To Case') . '</a> ';
         }
         // if there are file attachments we will return how many and, if only one, add a link to it
         if (!empty($dao->attachment_ids)) {
             $attachmentIDs = explode(',', $dao->attachment_ids);
             $values[$dao->id]['no_attachments'] = count($attachmentIDs);
             if ($values[$dao->id]['no_attachments'] == 1) {
                 // if there is only one it's easy to do a link - otherwise just flag it
                 $attachmentViewUrl = CRM_Utils_System::url("civicrm/file", "reset=1&eid=" . $dao->id . "&id=" . $dao->attachment_ids, FALSE, NULL, FALSE);
                 $url .= " <a href='{$attachmentViewUrl}' ><span class='icon paper-icon'></span></a>";
             }
         }
         $values[$dao->id]['links'] = $url;
         $values[$dao->id]['class'] = "";
         if (!empty($dao->priority)) {
             if ($dao->priority == CRM_Core_OptionGroup::getValue('priority', 'Urgent', 'name')) {
                 $values[$dao->id]['class'] = $values[$dao->id]['class'] . "priority-urgent ";
             } elseif ($dao->priority == CRM_Core_OptionGroup::getValue('priority', 'Low', 'name')) {
                 $values[$dao->id]['class'] = $values[$dao->id]['class'] . "priority-low ";
             }
         }
         if (CRM_Utils_Array::crmInArray($dao->status, $compStatusValues)) {
             $values[$dao->id]['class'] = $values[$dao->id]['class'] . " status-completed";
         } else {
             if (CRM_Utils_Date::overdue($dao->display_date)) {
                 $values[$dao->id]['class'] = $values[$dao->id]['class'] . " status-overdue";
             } else {
                 $values[$dao->id]['class'] = $values[$dao->id]['class'] . " status-scheduled";
             }
         }
         if ($allowEdit) {
             $values[$dao->id]['status'] = '<a class="crm-activity-status crm-activity-status-' . $dao->id . ' ' . $values[$dao->id]['class'] . ' crm-activity-change-status crm-editable-enabled" activity_id=' . $dao->id . ' current_status=' . $dao->status . ' case_id=' . $caseID . ' href="#" title=\'' . $statusTitle . '\'>' . $values[$dao->id]['status'] . '</a>';
         }
     }
     $dao->free();
     return $values;
 }
コード例 #23
0
 function from()
 {
     //define table name
     $randomNum = md5(uniqid());
     $this->_tableName = "civicrm_temp_custom_{$randomNum}";
     //grab the contacts added in the date range first
     $sql = "CREATE TEMPORARY TABLE dates_{$this->_tableName} ( id int primary key, date_added date ) ENGINE=HEAP";
     if ($this->_debug > 0) {
         print "-- Date range query: <pre>";
         print "{$sql};";
         print "</pre>";
     }
     CRM_Core_DAO::executeQuery($sql);
     $startDate = CRM_Utils_Date::mysqlToIso(CRM_Utils_Date::processDate($this->_formValues['start_date']));
     $endDateFix = NULL;
     if (!empty($this->_formValues['end_date'])) {
         $endDate = CRM_Utils_Date::mysqlToIso(CRM_Utils_Date::processDate($this->_formValues['end_date']));
         # tack 11:59pm on to make search inclusive of the end date
         $endDateFix = "AND date_added <= '" . substr($endDate, 0, 10) . " 23:59:00'";
     }
     $dateRange = "INSERT INTO dates_{$this->_tableName} ( id, date_added )\n          SELECT\n              civicrm_contact.id,\n              min(civicrm_log.modified_date) AS date_added\n          FROM\n              civicrm_contact LEFT JOIN civicrm_log\n              ON (civicrm_contact.id = civicrm_log.entity_id AND\n                  civicrm_log.entity_table = 'civicrm_contact')\n          GROUP BY\n              civicrm_contact.id\n          HAVING\n              date_added >= '{$startDate}' \n              {$endDateFix}";
     if ($this->_debug > 0) {
         print "-- Date range query: <pre>";
         print "{$dateRange};";
         print "</pre>";
     }
     CRM_Core_DAO::executeQuery($dateRange, CRM_Core_DAO::$_nullArray);
     // Only include groups in the search query of one or more Include OR Exclude groups has been selected.
     // CRM-6356
     if ($this->_groups) {
         //block for Group search
         $smartGroup = array();
         require_once 'CRM/Contact/DAO/Group.php';
         $group = new CRM_Contact_DAO_Group();
         $group->is_active = 1;
         $group->find();
         while ($group->fetch()) {
             $allGroups[] = $group->id;
             if ($group->saved_search_id) {
                 $smartGroup[$group->saved_search_id] = $group->id;
             }
         }
         $includedGroups = implode(',', $allGroups);
         if (!empty($this->_includeGroups)) {
             $iGroups = implode(',', $this->_includeGroups);
         } else {
             //if no group selected search for all groups
             $iGroups = $includedGroups;
         }
         if (is_array($this->_excludeGroups)) {
             $xGroups = implode(',', $this->_excludeGroups);
         } else {
             $xGroups = 0;
         }
         $sql = "DROP TEMPORARY TABLE IF EXISTS Xg_{$this->_tableName}";
         CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
         $sql = "CREATE TEMPORARY TABLE Xg_{$this->_tableName} ( contact_id int primary key) ENGINE=HEAP";
         CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
         //used only when exclude group is selected
         if ($xGroups != 0) {
             $excludeGroup = "INSERT INTO  Xg_{$this->_tableName} ( contact_id )\n                  SELECT  DISTINCT civicrm_group_contact.contact_id\n                  FROM civicrm_group_contact, dates_{$this->_tableName} AS d\n                  WHERE \n                     d.id = civicrm_group_contact.contact_id AND \n                     civicrm_group_contact.status = 'Added' AND\n                     civicrm_group_contact.group_id IN( {$xGroups})";
             CRM_Core_DAO::executeQuery($excludeGroup, CRM_Core_DAO::$_nullArray);
             //search for smart group contacts
             foreach ($this->_excludeGroups as $keys => $values) {
                 if (in_array($values, $smartGroup)) {
                     $ssId = CRM_Utils_Array::key($values, $smartGroup);
                     $smartSql = CRM_Contact_BAO_SavedSearch::contactIDsSQL($ssId);
                     $smartSql = $smartSql . " AND contact_a.id NOT IN ( \n                              SELECT contact_id FROM civicrm_group_contact \n                              WHERE civicrm_group_contact.group_id = {$values} AND civicrm_group_contact.status = 'Removed')";
                     $smartGroupQuery = " INSERT IGNORE INTO Xg_{$this->_tableName}(contact_id) {$smartSql}";
                     CRM_Core_DAO::executeQuery($smartGroupQuery, CRM_Core_DAO::$_nullArray);
                 }
             }
         }
         $sql = "DROP TEMPORARY TABLE IF EXISTS Ig_{$this->_tableName}";
         CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
         $sql = "CREATE TEMPORARY TABLE Ig_{$this->_tableName}\n                ( id int PRIMARY KEY AUTO_INCREMENT,\n                  contact_id int,\n                  group_names varchar(64)) ENGINE=HEAP";
         if ($this->_debug > 0) {
             print "-- Include groups query: <pre>";
             print "{$sql};";
             print "</pre>";
         }
         CRM_Core_DAO::executeQuery($sql, CRM_Core_DAO::$_nullArray);
         $includeGroup = "INSERT INTO Ig_{$this->_tableName} (contact_id, group_names)\n                 SELECT      d.id as contact_id, civicrm_group.name as group_name\n                 FROM        dates_{$this->_tableName} AS d\n                 INNER JOIN  civicrm_group_contact\n                 ON          civicrm_group_contact.contact_id = d.id\n                 LEFT JOIN   civicrm_group\n                 ON          civicrm_group_contact.group_id = civicrm_group.id";
         //used only when exclude group is selected
         if ($xGroups != 0) {
             $includeGroup .= " LEFT JOIN        Xg_{$this->_tableName}\n                                          ON        d.id = Xg_{$this->_tableName}.contact_id";
         }
         $includeGroup .= " WHERE           \n                                     civicrm_group_contact.status = 'Added'  AND\n                                     civicrm_group_contact.group_id IN({$iGroups})";
         //used only when exclude group is selected
         if ($xGroups != 0) {
             $includeGroup .= " AND  Xg_{$this->_tableName}.contact_id IS null";
         }
         if ($this->_debug > 0) {
             print "-- Include groups query: <pre>";
             print "{$includeGroup};";
             print "</pre>";
         }
         CRM_Core_DAO::executeQuery($includeGroup, CRM_Core_DAO::$_nullArray);
         //search for smart group contacts
         foreach ($this->_includeGroups as $keys => $values) {
             if (in_array($values, $smartGroup)) {
                 $ssId = CRM_Utils_Array::key($values, $smartGroup);
                 $smartSql = CRM_Contact_BAO_SavedSearch::contactIDsSQL($ssId);
                 $smartSql .= " AND contact_a.id IN (\n                                   SELECT id AS contact_id\n                                   FROM dates_{$this->_tableName} )";
                 $smartSql .= " AND contact_a.id NOT IN ( \n                                   SELECT contact_id FROM civicrm_group_contact\n                                   WHERE civicrm_group_contact.group_id = {$values} AND civicrm_group_contact.status = 'Removed')";
                 //used only when exclude group is selected
                 if ($xGroups != 0) {
                     $smartSql .= " AND contact_a.id NOT IN (SELECT contact_id FROM  Xg_{$this->_tableName})";
                 }
                 $smartGroupQuery = " INSERT IGNORE INTO\n                        Ig_{$this->_tableName}(contact_id) \n                        {$smartSql}";
                 CRM_Core_DAO::executeQuery($smartGroupQuery, CRM_Core_DAO::$_nullArray);
                 if ($this->_debug > 0) {
                     print "-- Smart group query: <pre>";
                     print "{$smartGroupQuery};";
                     print "</pre>";
                 }
                 $insertGroupNameQuery = "UPDATE IGNORE Ig_{$this->_tableName}\n                        SET group_names = (SELECT title FROM civicrm_group\n                            WHERE civicrm_group.id = {$values})\n                        WHERE Ig_{$this->_tableName}.contact_id IS NOT NULL \n                            AND Ig_{$this->_tableName}.group_names IS NULL";
                 CRM_Core_DAO::executeQuery($insertGroupNameQuery, CRM_Core_DAO::$_nullArray);
                 if ($this->_debug > 0) {
                     print "-- Smart group query: <pre>";
                     print "{$insertGroupNameQuery};";
                     print "</pre>";
                 }
             }
         }
     }
     // end if( $this->_groups ) condition
     $from = "FROM civicrm_contact contact_a";
     /* We need to join to this again to get the date_added value */
     $from .= " INNER JOIN dates_{$this->_tableName} d ON (contact_a.id = d.id)";
     // Only include groups in the search query of one or more Include OR Exclude groups has been selected.
     // CRM-6356
     if ($this->_groups) {
         $from .= " INNER JOIN Ig_{$this->_tableName} temptable1 ON (contact_a.id = temptable1.contact_id)";
     }
     //this makes smart groups using this search compatible w/ CiviMail
     $from .= " LEFT JOIN civicrm_email ON (contact_a.id = civicrm_email.contact_id)";
     return $from;
 }
コード例 #24
0
ファイル: Entry.php プロジェクト: prashantgajare/civicrm-core
 /**
  * process membership records
  *
  * @param array $params associated array of submitted values
  *
  * @access public
  *
  * @return bool
  */
 private function processMembership(&$params)
 {
     $dateTypes = array('join_date' => 'joinDate', 'membership_start_date' => 'startDate', 'membership_end_date' => 'endDate');
     $dates = array('join_date', 'start_date', 'end_date', 'reminder_date');
     // get the price set associated with offline memebership
     $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
     $this->_priceSet = $priceSets = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
     if (isset($params['field'])) {
         $customFields = array();
         foreach ($params['field'] as $key => $value) {
             // if contact is not selected we should skip the row
             if (empty($params['primary_contact_id'][$key])) {
                 continue;
             }
             $value['contact_id'] = CRM_Utils_Array::value($key, $params['primary_contact_id']);
             // update contact information
             $this->updateContactInfo($value);
             $membershipTypeId = $value['membership_type_id'] = $value['membership_type'][1];
             foreach ($dateTypes as $dateField => $dateVariable) {
                 ${$dateVariable} = CRM_Utils_Date::processDate($value[$dateField]);
             }
             $calcDates = array();
             $calcDates[$membershipTypeId] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membershipTypeId, $joinDate, $startDate, $endDate);
             foreach ($calcDates as $memType => $calcDate) {
                 foreach ($dates as $d) {
                     //first give priority to form values then calDates.
                     $date = CRM_Utils_Array::value($d, $value);
                     if (!$date) {
                         $date = CRM_Utils_Array::value($d, $calcDate);
                     }
                     $value[$d] = CRM_Utils_Date::processDate($date);
                 }
             }
             if (!empty($value['send_receipt'])) {
                 $value['receipt_date'] = date('Y-m-d His');
             }
             if (!empty($value['membership_source'])) {
                 $value['source'] = $value['membership_source'];
             }
             unset($value['membership_source']);
             //Get the membership status
             if (!empty($value['membership_status'])) {
                 $value['status_id'] = $value['membership_status'];
                 unset($value['membership_status']);
             }
             if (empty($customFields)) {
                 // membership type custom data
                 $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $membershipTypeId);
                 $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, NULL, NULL, TRUE));
             }
             //check for custom data
             $value['custom'] = CRM_Core_BAO_CustomField::postProcess($params['field'][$key], $customFields, $key, 'Membership', $membershipTypeId);
             if (!empty($value['financial_type'])) {
                 $value['financial_type_id'] = $value['financial_type'];
             }
             if (!empty($value['payment_instrument'])) {
                 $value['payment_instrument_id'] = $value['payment_instrument'];
             }
             // handle soft credit
             if (is_array(CRM_Utils_Array::value('soft_credit_contact_id', $params)) && !empty($params['soft_credit_contact_id'][$key]) && CRM_Utils_Array::value($key, $params['soft_credit_amount'])) {
                 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
                 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
             }
             if (!empty($value['receive_date'])) {
                 $value['receive_date'] = CRM_Utils_Date::processDate($value['receive_date'], $value['receive_date_time'], TRUE);
             }
             $params['actualBatchTotal'] += $value['total_amount'];
             unset($value['financial_type']);
             unset($value['payment_instrument']);
             $value['batch_id'] = $this->_batchId;
             $value['skipRecentView'] = TRUE;
             // make entry in line item for contribution
             $editedFieldParams = array('price_set_id' => $priceSetId, 'name' => $value['membership_type'][0]);
             $editedResults = array();
             CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
             if (!empty($editedResults)) {
                 unset($this->_priceSet['fields']);
                 $this->_priceSet['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
                 unset($this->_priceSet['fields'][$editedResults['id']]['options']);
                 $fid = $editedResults['id'];
                 $editedFieldParams = array('price_field_id' => $editedResults['id'], 'membership_type_id' => $value['membership_type_id']);
                 $editedResults = array();
                 CRM_Price_BAO_PriceFieldValue::retrieve($editedFieldParams, $editedResults);
                 $this->_priceSet['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
                 if (!empty($value['total_amount'])) {
                     $this->_priceSet['fields'][$fid]['options'][$editedResults['id']]['amount'] = $value['total_amount'];
                 }
                 $fieldID = key($this->_priceSet['fields']);
                 $value['price_' . $fieldID] = $editedResults['id'];
                 $lineItem = array();
                 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $value, $lineItem[$priceSetId]);
                 //CRM-11529 for backoffice transactions
                 //when financial_type_id is passed in form, update the
                 //lineitems with the financial type selected in form
                 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
                     foreach ($lineItem[$priceSetId] as &$values) {
                         $values['financial_type_id'] = $value['financial_type_id'];
                     }
                 }
                 $value['lineItems'] = $lineItem;
                 $value['processPriceSet'] = TRUE;
             }
             // end of contribution related section
             unset($value['membership_type']);
             unset($value['membership_start_date']);
             unset($value['membership_end_date']);
             $value['is_renew'] = false;
             if (!empty($params['member_option']) && CRM_Utils_Array::value($key, $params['member_option']) == 2) {
                 $this->_params = $params;
                 $value['is_renew'] = true;
                 $membership = CRM_Member_BAO_Membership::renewMembershipFormWrapper($value['contact_id'], $value['membership_type_id'], FALSE, $this, NULL, NULL, $value['custom']);
                 // make contribution entry
                 CRM_Member_BAO_Membership::recordMembershipContribution(array_merge($value, array('membership_id' => $membership->id)));
             } else {
                 $membership = CRM_Member_BAO_Membership::create($value, CRM_Core_DAO::$_nullArray);
             }
             //process premiums
             if (!empty($value['product_name'])) {
                 if ($value['product_name'][0] > 0) {
                     list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
                     $value['hidden_Premium'] = 1;
                     $value['product_option'] = CRM_Utils_Array::value($value['product_name'][1], $options[$value['product_name'][0]]);
                     $premiumParams = array('product_id' => $value['product_name'][0], 'contribution_id' => $value['contribution_id'], 'product_option' => $value['product_option'], 'quantity' => 1);
                     CRM_Contribute_BAO_Contribution::addPremium($premiumParams);
                 }
             }
             // end of premium
             //send receipt mail.
             if ($membership->id && !empty($value['send_receipt'])) {
                 // add the domain email id
                 $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
                 $domainEmail = "{$domainEmail['0']} <{$domainEmail['1']}>";
                 $value['from_email_address'] = $domainEmail;
                 $value['membership_id'] = $membership->id;
                 CRM_Member_Form_Membership::emailReceipt($this, $value, $membership);
             }
         }
     }
     return TRUE;
 }
コード例 #25
0
 /**
  * process the form after the input has been submitted and validated
  *
  * @access public
  *
  * @return void
  */
 public function postProcess()
 {
     $params = $this->exportValues();
     if (isset($params['field'])) {
         foreach ($params['field'] as $key => $value) {
             $value['custom'] = CRM_Core_BAO_CustomField::postProcess($value, CRM_Core_DAO::$_nullObject, $key, 'Activity');
             $value['id'] = $key;
             if ($value['activity_date_time']) {
                 $value['activity_date_time'] = CRM_Utils_Date::processDate($value['activity_date_time'], $value['activity_date_time_time']);
             }
             if (!empty($value['activity_status_id'])) {
                 $value['status_id'] = $value['activity_status_id'];
             }
             if (!empty($value['activity_details'])) {
                 $value['details'] = $value['activity_details'];
             }
             if (!empty($value['activity_duration'])) {
                 $value['duration'] = $value['activity_duration'];
             }
             if (!empty($value['activity_location'])) {
                 $value['location'] = $value['activity_location'];
             }
             if (!empty($value['activity_subject'])) {
                 $value['subject'] = $value['activity_subject'];
             }
             $query = "\nSELECT a.activity_type_id, ac.contact_id\nFROM   civicrm_activity a\nJOIN   civicrm_activity_contact ac ON ( ac.activity_id = a.id\nAND    ac.record_type_id = %2 )\nWHERE  a.id = %1 ";
             $activityContacts = CRM_Core_OptionGroup::values('activity_contacts', FALSE, FALSE, FALSE, NULL, 'name');
             $sourceID = CRM_Utils_Array::key('Activity Source', $activityContacts);
             $params = array(1 => array($key, 'Integer'), 2 => array($sourceID, 'Integer'));
             $dao = CRM_Core_DAO::executeQuery($query, $params);
             $dao->fetch();
             // Get Activity Type ID
             $value['activity_type_id'] = $dao->activity_type_id;
             // Get Conatct ID
             $value['source_contact_id'] = $dao->contact_id;
             // make call use API 3
             $value['version'] = 3;
             $activityId = civicrm_api('activity', 'update', $value);
             // add custom field values
             if (!empty($value['custom']) && is_array($value['custom'])) {
                 CRM_Core_BAO_CustomValueTable::store($value['custom'], 'civicrm_activity', $activityId['id']);
             }
         }
         CRM_Core_Session::setStatus("", ts("Updates Saved"), "success");
     } else {
         CRM_Core_Session::setStatus("", ts("No Updates Saved"), "info");
     }
 }
コード例 #26
0
ファイル: Membership.php プロジェクト: indydas/civi-demo
 /**
  * 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;
 }
コード例 #27
0
 /**
  * @param bool $includeContactIDs
  *
  * @return string
  */
 function where($includeContactIDs = FALSE)
 {
     $clauses = array();
     // add contact name search; search on primary name, source contact, assignee
     $contactname = $this->_formValues['sort_name'];
     if (!empty($contactname)) {
         $dao = new CRM_Core_DAO();
         $contactname = $dao->escape($contactname);
         $clauses[] = "(contact_a.sort_name LIKE '%{$contactname}%' OR\n                           contact_b.sort_name LIKE '%{$contactname}%' OR\n                           contact_c.display_name LIKE '%{$contactname}%')";
     }
     $subject = $this->_formValues['activity_subject'];
     if (!empty($this->_formValues['contact_type'])) {
         $clauses[] = "contact_a.contact_type LIKE '%{$this->_formValues['contact_type']}%'";
     }
     if (!empty($subject)) {
         $dao = new CRM_Core_DAO();
         $subject = $dao->escape($subject);
         $clauses[] = "activity.subject LIKE '%{$subject}%'";
     }
     if (!empty($this->_formValues['activity_status_id'])) {
         $clauses[] = "activity.status_id = {$this->_formValues['activity_status_id']}";
     }
     if (!empty($this->_formValues['activity_type_id'])) {
         $clauses[] = "activity.activity_type_id = {$this->_formValues['activity_type_id']}";
     }
     $startDate = $this->_formValues['start_date'];
     if (!empty($startDate)) {
         $startDate .= '00:00:00';
         $startDateFormatted = CRM_Utils_Date::processDate($startDate);
         if ($startDateFormatted) {
             $clauses[] = "activity.activity_date_time >= {$startDateFormatted}";
         }
     }
     $endDate = $this->_formValues['end_date'];
     if (!empty($endDate)) {
         $endDate .= '23:59:59';
         $endDateFormatted = CRM_Utils_Date::processDate($endDate);
         if ($endDateFormatted) {
             $clauses[] = "activity.activity_date_time <= {$endDateFormatted}";
         }
     }
     if ($includeContactIDs) {
         $contactIDs = array();
         foreach ($this->_formValues as $id => $value) {
             if ($value && substr($id, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
                 $contactIDs[] = substr($id, CRM_Core_Form::CB_PREFIX_LEN);
             }
         }
         if (!empty($contactIDs)) {
             $contactIDs = implode(', ', $contactIDs);
             $clauses[] = "contact_a.id IN ( {$contactIDs} )";
         }
     }
     return implode(' AND ', $clauses);
 }
コード例 #28
0
ファイル: Batch.php プロジェクト: bhirsch/voipdev
 /**
  * process the form after the input has been submitted and validated
  *
  * @access public
  * @return None
  */
 public function postProcess()
 {
     $params = $this->exportValues();
     $dates = array('receive_date', 'receipt_date', 'thankyou_date', 'cancel_date');
     if (isset($params['field'])) {
         foreach ($params['field'] as $key => $value) {
             $value['custom'] = CRM_Core_BAO_CustomField::postProcess($value, CRM_Core_DAO::$_nullObject, $key, 'Contribution');
             $ids['contribution'] = $key;
             foreach ($dates as $val) {
                 $value[$val] = CRM_Utils_Date::processDate($value[$val]);
             }
             if ($value['contribution_type']) {
                 $value['contribution_type_id'] = $value['contribution_type'];
             }
             if ($value['payment_instrument']) {
                 $value['payment_instrument_id'] = $value['payment_instrument'];
             }
             if ($value['contribution_source']) {
                 $value['source'] = $value['contribution_source'];
             }
             unset($value['contribution_type']);
             unset($value['contribution_source']);
             $contribution = CRM_Contribute_BAO_Contribution::add($value, $ids);
             // add custom field values
             if (CRM_Utils_Array::value('custom', $value) && is_array($value['custom'])) {
                 require_once 'CRM/Core/BAO/CustomValueTable.php';
                 CRM_Core_BAO_CustomValueTable::store($value['custom'], 'civicrm_contribution', $contribution->id);
             }
         }
         CRM_Core_Session::setStatus("Your updates have been saved.");
     } else {
         CRM_Core_Session::setStatus("No updates have been saved.");
     }
 }
コード例 #29
0
 function where($includeContactIDs = FALSE)
 {
     $clauses = array();
     $clauses[] = "contrib.contact_id = contact_a.id";
     $clauses[] = "contrib.is_test = 0";
     $startDate = CRM_Utils_Date::processDate($this->_formValues['start_date']);
     if ($startDate) {
         $clauses[] = "contrib.receive_date >= {$startDate}";
     }
     $endDate = CRM_Utils_Date::processDate($this->_formValues['end_date']);
     if ($endDate) {
         $clauses[] = "contrib.receive_date <= {$endDate}";
     }
     if ($includeContactIDs) {
         $contactIDs = array();
         foreach ($this->_formValues as $id => $value) {
             if ($value && substr($id, 0, CRM_Core_Form::CB_PREFIX_LEN) == CRM_Core_Form::CB_PREFIX) {
                 $contactIDs[] = substr($id, CRM_Core_Form::CB_PREFIX_LEN);
             }
         }
         if (!empty($contactIDs)) {
             $contactIDs = implode(', ', $contactIDs);
             $clauses[] = "contact_a.id IN ( {$contactIDs} )";
         }
     }
     if (!empty($this->_formValues['financial_type_id'])) {
         $financial_type_ids = implode(',', array_keys($this->_formValues['financial_type_id']));
         $clauses[] = "contrib.financial_type_id IN ({$financial_type_ids})";
     }
     return implode(' AND ', $clauses);
 }
コード例 #30
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}"));
     }
 }