Example #1
0
 /**
  * Function to process the form
  *
  * @access public
  * @return None
  */
 function postProcess()
 {
     if ($this->_action & CRM_CORE_ACTION_VIEW) {
         return;
     }
     if ($this->_action & CRM_CORE_ACTION_DELETE) {
         CRM_Core_BAO_Meeting::del($this->_id);
         CRM_Core_Session::setStatus(ts("Selected Meeting is deleted sucessfully."));
         return;
     }
     // store the submitted values in an array
     $params = $this->controller->exportValues($this->_name);
     $ids = array();
     $dateTime = $params['scheduled_date_time'];
     $dateTime = CRM_Utils_Date::format($dateTime);
     // store the date with proper format
     $params['scheduled_date_time'] = $dateTime;
     // store the contact id and current drupal user id
     $params['source_contact_id'] = $this->_userId;
     $params['target_entity_id'] = $this->_contactId;
     $params['target_entity_table'] = 'civicrm_contact';
     //set parent id if exists for follow up activities
     if ($this->_pid) {
         $params['parent_id'] = $this->_pid;
     }
     if ($this->_action & CRM_CORE_ACTION_UPDATE) {
         $ids['meeting'] = $this->_id;
     }
     $meeting = CRM_Core_BAO_Meeting::add($params, $ids);
     CRM_Core_BAO_CustomGroup::postProcess($this->_groupTree, $params);
     // do the updates/inserts
     CRM_Core_BAO_CustomGroup::updateCustomData($this->_groupTree, 'Meeting', $meeting->id);
     if ($meeting->status == 'Completed') {
         // we need to insert an activity history record here
         $params = array('entity_table' => 'civicrm_contact', 'entity_id' => $this->_contactId, 'activity_type' => ts('Meeting'), 'module' => 'CiviCRM', 'callback' => 'CRM_Activity_Form_Meeting::showMeetingDetails', 'activity_id' => $meeting->id, 'activity_summary' => $meeting->subject, 'activity_date' => $meeting->scheduled_date_time);
         if (is_a(crm_create_activity_history($params), 'CRM_Core_Error')) {
             return false;
         }
     }
     if ($meeting->status == 'Completed') {
         CRM_Core_Session::setStatus(ts('Meeting "%1" has been logged to Activity History.', array(1 => $meeting->subject)));
     } else {
         CRM_Core_Session::setStatus(ts('Meeting "%1" has been saved.', array(1 => $meeting->subject)));
     }
 }
 /**
  * send the message to a specific contact
  *
  * @param string $from         the name and email of the sender
  * @param int    $toID         the contact id of the recipient       
  * @param string $subject      the subject of the message
  * @param string $message      the message contents
  * @param string $emailAddress use this 'to' email address instead of the default Primary address 
  * @param int    $activityID   the activity ID that tracks the message
  *
  * @return boolean             true if successfull else false.
  * @access public
  * @static
  */
 function sendMessage($from, $toID, &$subject, &$message, $emailAddress, $activityID)
 {
     list($toDisplayName, $toEmail, $toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($toID);
     if ($emailAddress) {
         $toEmail = trim($emailAddress);
     }
     // make sure both email addresses are valid
     // and that the recipient wants to receive email
     if (empty($toEmail) or $toDoNotEmail) {
         return false;
     }
     if (!trim($toDisplayName)) {
         $toDisplayName = $toEmail;
     }
     if (!CRM_Utils_Mail::send($from, $toDisplayName, $toEmail, $subject, $message)) {
         return false;
     }
     // we need to insert an activity history record here
     $params = array('entity_table' => 'civicrm_contact', 'entity_id' => $toID, 'activity_type' => ts('Email Sent'), 'module' => 'CiviCRM', 'callback' => 'CRM_Core_BAO_EmailHistory::showEmailDetails', 'activity_id' => $activityID, 'activity_summary' => ts('To: %1; Subject: %2', array(1 => "{$toDisplayName} <{$toEmail}>", 2 => $subject)), 'activity_date' => date('YmdHis'));
     if (is_a(crm_create_activity_history($params), CRM_Core_Error)) {
         return false;
     }
     return true;
 }
 function _process_csv($csv_array, $csv_name, $mail_date)
 {
     $this->_addToSummary("Processing {$csv_name}");
     foreach ($csv_array as $row) {
         $this->_addToSummary(null);
         // insert blank line.
         // check if this is a blank line
         if (count($row) <= 1) {
             continue;
         }
         $subscriptionId = $row[0];
         $subscriptionStatus = $row[1];
         $paymentNum = $row[2];
         $totalRecurrences = $row[3];
         $transactionId = $row[4];
         $amount = $row[5];
         $currency = $row[6];
         $custFirstName = $row[8];
         $custLastName = $row[9];
         $contributionStatus = $row[10];
         $recur =& new CRM_Contribute_DAO_ContributionRecur();
         $first_contribution =& new CRM_Contribute_DAO_Contribution();
         // If this is the first payment, load recurring contribution and update
         if ($paymentNum == 1) {
             // Load contribution using SubscriptionID as trxn_id
             $first_contribution->trxn_id = $subscriptionId;
             if (!$first_contribution->find(true)) {
                 $this->_addToSummary("THE RECURRING TRANSACTION FOR SUBSCRIPTION {$subscriptionId} COULD NOT BE FOUND. A TRANSACTION HAS OCCURED THAT WAS NOT EXPECTED.  PLEASE REVIEW {$csv_name}.");
                 continue;
             }
             // Load recurring contribution from contribution
             $recur->id = $first_contribution->contribution_recur_id;
             if (!$recur->find(true)) {
                 $this->_addToSummary("INITIAL RECURRING CONTRIBUTION NOT FOUND FOR {$subscriptionId}. PLEASE REVIEW {$csv_name}");
                 continue;
             }
             $recur->start_date = $mail_date;
             $recur->processor_id = $subscriptionId;
             $recur->trxn_id = $subscriptionId;
             $recur->contribution_status_id = _CRM_PROCESS_AUTHORIZE_REPORT_STATUS_CURRENT;
             // update transaction id for contribution
             $first_contribution->trxn_id = $transactionId;
             $first_contribution->receive_date = $mail_date;
             $first_contribution->contribution_status_id = $this->_get_contribution_status($contributionStatus);
             // load contribution page
             $contribution_page =& new CRM_Contribute_DAO_ContributionPage();
             $contribution_page->id = $first_contribution->contribution_page_id;
             if (!$contribution_page->find(true)) {
                 $this->_addToSummary("COULD NOT FIND CONTRIBUTION PAGE FOR {$subscriptionId}. PLEASE REVIEW {$csv_name}");
                 continue;
             }
             // is there an email receipt
             if ($contribution_page->is_email_receipt) {
                 $first_contribution->receipt_date = date('YmdHis');
             }
         } else {
             $recur->processor_id = $subscriptionId;
             if (!$recur->find(true)) {
                 $this->_addToSummary("THE RECURRING TRANSACTION FOR SUBSCRIPTION {$subscriptionId} COULD NOT BE FOUND. A TRANSACTION HAS OCCURED THAT WAS NOT EXPECTED.  PLEASE REVIEW {$csv_name}.");
                 continue;
             }
             $recur->modified_date = $mail_date;
             // load first contribution
             $first_contribution->contribution_recur_id = $recur->id;
             $first_contribution->orderBy('receive_date');
             $first_contribution->limit(1);
             if (!$first_contribution->find(true)) {
                 $this->_addToSummary("CONTRIBUTION RECORD FOR SUBSCRIPTION {$subscriptonId} COULD NOT BE FOUND.  PLEASE REVIEW {$csv_name}");
                 continue;
             }
             // load contribution page
             $contribution_page =& new CRM_Contribute_DAO_ContributionPage();
             $contribution_page->id = $first_contribution->contribution_page_id;
             if (!$contribution_page->find(true)) {
                 $this->_addToSummary("COULD NOT FIND CONTRIBUTION PAGE FOR {$subscriptionId}. PLEASE REVIEW {$csv_name}");
                 continue;
             }
         }
         // is this valid for failed transactions also?
         if ($amount != $recur->amount) {
             $this->_addToSummary("AN UNEXPECTED AMOUNT WAS RECEIVED FOR SUBSCRIPTION {$subscriptionId}. SKIPPING THIS TRANSACTION. PLEASE REVIEW {$csv_name}");
             continue;
         }
         // Verify contact exists
         if (!$recur->contact_id) {
             // assuming if contact_id is set, contact exists
             $this->_addToSummary("NO USER IS ASSOCIATED WITH THE CONTRIBUTION FOR SUBSCRIPTION {$subscrptionId}, EXPECTED '{$custFirstName} {$custLastName}'. PLEASE REVIEW {$csv_name}");
             continue;
         }
         // Verify number of recurrences
         if ($recur->installments != $totalRecurrences) {
             $this->_addToSummary("SUBSCRIPTION {$subscriptionId} EXPECTS {$recur->installments}, OFFERED {$totalRecurrences}. PLEASE REVIEW {$csv_name}");
             continue;
         }
         // Check if this contribution is complete
         if (!empty($recur->end_date) && $recur->end_date != '0000-00-00 00:00:00') {
             $this->_addToSummary("SUBSCRIPTION {$subscriptionId} IS MARKED AS COMPLETE. PLEASE REVIEW {$csv_name}");
             continue;
         }
         if (!empty($recur->cancel_date) && $recur->cancel_date != '0000-00-00 00:00:00') {
             $this->_addToSummary("SUBSCRIPTION {$subscriptionId} IS MARKED AS CANCELLED. PLEASE REVIEW {$csv_name}");
             continue;
         }
         if ($paymentNum == $totalRecurrences) {
             $recur->end_date = $mail_date;
             $recur->contribution_status_id = _CRM_PROCESS_AUTHORIZE_REPORT_STATUS_COMPLETE;
         }
         if ($contributionStatus != CRM_Core_Payment_AuthorizeNet::AUTH_APPROVED) {
             $recur->failure_count++;
         }
         CRM_Core_DAO::transaction('BEGIN');
         if (!$recur->save()) {
             $this->_addToSummary("THE RECURRING CONTRIBUTION COULD NOT BE UPDATED. PLEASE REVIEW {$csv_name} FOR subscription_id={$subscription_id}");
             CRM_Core_DAO::transaction('ROLLBACK');
             continue;
         }
         $this->_addToSummary("The recurring transaction has been updated.");
         if ($paymentNum == 1) {
             // update first contribution
             if (!$first_contribution->save()) {
                 $this->_addToSummary("THE CONTRIBUTION COULD NOT BE UPDATED. PLEASE REVIEW {$csv_name} FOR subscription_id={$subscription_id}");
                 CRM_Core_DAO::transaction('ROLLBACK');
                 continue;
             }
             // copy $first_contribution to $contribution for use later
             $contribution = $first_contribution;
         } else {
             // create a contribution and then get it processed
             $contribution =& new CRM_Contribute_DAO_Contribution();
             // make sure that the transaction doesn't already exist
             $contribution->trxn_id = $transactionId;
             if ($contribution->find()) {
                 $this->_addToSummary("THE TRANSACTION {$transaction_id} ALREADY EXISTS IN CIVICRM. PLEASE REVIEW {$csv_name} FOR subscription_id={$subscription_id}");
                 CRM_Core_DAO::transaction('ROLLBACK');
                 continue;
             }
             $contribution->contribution_recur_id = $recur->id;
             $contribution->receive_date = $mail_date;
             $contribution->total_amount = $amount;
             $contribution->net_amount = $amount;
             $contribution->trxn_id = $transactionId;
             $contribution->currency = $currency;
             $contribution->contribution_status_id = $this->_get_contribution_status($contributionStatus);
             $contribution->contact_id = $first_contribution->contact_id;
             $contribution->contribution_type_id = $first_contribution->contribution_type_id;
             $contribution->contribution_page_id = $first_contribution->contribution_page_id;
             $contribution->payment_instrument_id = $first_contribution->payment_instrument_id;
             $contribution->is_test = $first_contribution->is_test;
             $contribution->invoice_id = md5(uniqid(rand(), true));
             if ($contribution_page->is_email_receipt) {
                 $contribution->receipt_date = date('YmdHis');
             }
             if (!$contribution->save()) {
                 $this->_addToSummary("THE CONTRIBUTION COULD NOT BE SAVED. PLEASE REVIEW {$csv_name} FOR subscription_id={$subscription_id}");
                 CRM_Core_DAO::transaction('ROLLBACK');
                 continue;
             }
         }
         $this->_addToSummary('Contribution saved');
         // create the transaction record
         $trxnParams = array('entity_table' => 'civicrm_contribution', 'entity_id' => $contribution->id, 'trxn_date' => $mail_date, 'trxn_type' => 'Debit', 'total_amount' => $amount, 'fee_amount' => $contribution->fee_amount, 'net_amount' => $contribution->net_amount, 'currency' => $contribution->currency, 'payment_processor' => 'AuthNet_AIM', 'trxn_id' => $contribution->trxn_id);
         require_once 'CRM/Contribute/BAO/FinancialTrxn.php';
         $trxn =& CRM_Contribute_BAO_FinancialTrxn::create($trxnParams);
         if (is_a($trxn, 'CRM_Core_Error')) {
             $this->_addToSummary("A TRANSACTION RECORD COULD NOT BE CREATED. PLEASE REVIEW {$csv_name} FOR subscription_id={$subscription_id}");
             CRM_Core_DAO::transaction('ROLLBACK');
             continue;
         } else {
             $this->_addToSummary("Transaction record created.");
         }
         // get the title of the contribution page
         $title = $contribution_page->title;
         // format the money
         require_once 'CRM/Utils/Money.php';
         $formattedAmount = CRM_Utils_Money::format($amount, $contribution->currency);
         CRM_Core_DAO::transaction('COMMIT');
         // get the contribution type
         require_once 'CRM/Contribute/BAO/ContributionType.php';
         $contribution_type_name = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionType', $contribution->contribution_type_id, 'name');
         // create an activity history record
         $ahParams = array('entity_table' => 'civicrm_contact', 'entity_id' => $recur->contact_id, 'activity_type' => $contribution_type_name, 'module' => 'CiviContribute', 'callback' => 'CRM_Contribute_Page_Contribution::details', 'activity_id' => $contribution->id, 'activity_summary' => "{$formattedAmount} - {$title} (online)", 'activity_date' => $mail_date);
         require_once 'api/History.php';
         if (is_a(crm_create_activity_history($ahParams), 'CRM_Core_Error')) {
             $this->_addToSummary("AN ACTIVITY HISTORY RECORD COULD NOT BE CREATED.");
         } else {
             $this->_addToSummary("Activity History record created.");
         }
         $this->_addToSummary("Transaction {$transactionId} has been processed.");
         $first_contribution->free();
         $contribution_page->free();
         $contribution->free();
         $recur->free();
         $trxn->free();
     }
     $this->_addToSummary("Done processing {$csv_name}");
     $this->_addToSummary('');
 }
Example #4
0
 /**
  * send the message to a specific contact
  *
  * @param string $from       the name and sms of the sender
  * @param int    $toID       the contact id of the recipient       
  * @param string $message    the message contents
  * @param string $smsNumber  use this 'number' instead of the default primary sms number
  * @param int    $activityID the activity ID that tracks the message
  *
  * @return array             (total, added, notAdded) count of emails sent
  * @access public
  * @static
  */
 function sendMessage($from, $toID, &$message, $smsNumber, $activityID)
 {
     list($toDisplayName, $toSMS) = CRM_Contact_BAO_Contact::getPhoneDetails($toID, 'Mobile');
     if ($toSMS) {
         $to = trim($toSMS);
     }
     // make sure sms number is non-empty
     if (empty($to)) {
         return false;
     }
     $params = array();
     $params['From'] = $from;
     $params['To'] = $to;
     $params['Body'] = $message;
     $params['id'] = substr(md5(uniqid(rand(), true)), 0, 31);
     $params['Type'] = "SMS_TEXT";
     $aggregator =& CRM_SMS_Protocol::singleton();
     if (!$aggregator->sendMessage($params)) {
         return false;
     }
     // we need to insert an activity history record here
     $params = array('entity_table' => 'civicrm_contact', 'entity_id' => $toID, 'activity_type' => ts('SMS Sent'), 'module' => 'CiviCRM', 'callback' => 'CRM_SMS_BAO_History::details', 'activity_id' => $activityID, 'activity_summary' => ts('To: %1; Message: %2', array(1 => "{$toDisplayName} <{$toSMS}>", 2 => $message)), 'activity_date' => date('YmdHis'));
     if (is_a(crm_create_activity_history($params), CRM_Core_Error)) {
         return false;
     }
     return true;
 }
 /**
  * handle the values in import mode
  *
  * @param int $onDuplicate the code for what action to take on duplicates
  * @param array $values the array of values belonging to this line
  *
  * @return boolean      the result of this processing
  * @access public
  */
 function import($onDuplicate, &$values)
 {
     // first make sure this is a valid line
     $response = $this->summary($values);
     if ($response != CRM_HISTORY_IMPORT_PARSER_VALID) {
         return $response;
     }
     $params =& $this->getActiveFieldParams();
     //for date-Formats
     $session =& CRM_Core_Session::singleton();
     $dateType = $session->get("dateTypes");
     foreach ($params as $key => $val) {
         if ($key == 'activity_date') {
             if ($val) {
                 if ($dateType == 1) {
                     $params[$key] = CRM_Utils_Date::customFormat($val, '%Y%m%d');
                 } else {
                     CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key);
                 }
             }
         }
     }
     //date-Format part ends
     $formatted = array();
     if ($GLOBALS['_CRM_HISTORY_IMPORT_PARSER_ACTIVITYHISTORY']['indieFields'] == null) {
         require_once 'CRM/Core/DAO/ActivityHistory.php';
         $tempIndieFields =& CRM_Core_DAO_ActivityHistory::import();
         $GLOBALS['_CRM_HISTORY_IMPORT_PARSER_ACTIVITYHISTORY']['indieFields'] = $tempIndieFields;
     }
     foreach ($params as $key => $field) {
         if ($field == null || $field === '') {
             continue;
         }
         $value = array($key => $field);
         _crm_add_formatted_history_param($value, $formatted);
     }
     if ($this->_contactIdIndex < 0) {
         if ($GLOBALS['_CRM_HISTORY_IMPORT_PARSER_ACTIVITYHISTORY']['cIndieFields'] == null) {
             require_once 'CRM/Contact/BAO/Contact.php';
             $cTempIndieFields = CRM_Contact_BAO_Contact::importableFields('Individual', null);
             $GLOBALS['_CRM_HISTORY_IMPORT_PARSER_ACTIVITYHISTORY']['cIndieFields'] = $cTempIndieFields;
         }
         foreach ($params as $key => $field) {
             if ($field == null || $field === '') {
                 continue;
             }
             if (is_array($field)) {
                 foreach ($field as $value) {
                     $break = false;
                     if (is_array($value)) {
                         foreach ($value as $name => $testForEmpty) {
                             if ($name !== 'phone_type' && ($testForEmpty === '' || $testForEmpty == null)) {
                                 $break = true;
                                 break;
                             }
                         }
                     } else {
                         $break = true;
                     }
                     if (!$break) {
                         _crm_add_formatted_param($value, $contactFormatted);
                     }
                 }
                 continue;
             }
             $value = array($key => $field);
             if (array_key_exists($key, $GLOBALS['_CRM_HISTORY_IMPORT_PARSER_ACTIVITYHISTORY']['cIndieFields'])) {
                 if (substr($key, 0, 6) != 'custom') {
                     $value['contact_type'] = 'Individual';
                 }
             }
             _crm_add_formatted_param($value, $contactFormatted);
         }
         $contactFormatted['contact_type'] = 'Individual';
         $error = _crm_duplicate_formatted_contact($contactFormatted);
         if (CRM_History_Import_Parser_ActivityHistory::isDuplicate($error)) {
             $matchedIDs = explode(',', $error->_errors[0]['params'][0]);
             if (count($matchedIDs) > 1) {
                 array_unshift($values, "Multiple matching contact records detected for this row. The activity history was not imported");
                 return CRM_HISTORY_IMPORT_PARSER_ERROR;
             } else {
                 $cid = $matchedIDs[0];
                 $formatted['entity_id'] = $cid;
                 $formatted['entity_table'] = 'civicrm_contact';
                 $newHistory = crm_create_activity_history($formatted);
                 if (is_a($newHistory, CRM_Core_Error)) {
                     array_unshift($values, $newHistory->_errors[0]['message']);
                     return CRM_HISTORY_IMPORT_PARSER_ERROR;
                 }
                 $this->_newHistory[] = $newHistory->id;
                 return CRM_HISTORY_IMPORT_PARSER_VALID;
             }
         } else {
             require_once 'CRM/Core/DAO/DupeMatch.php';
             $dao =& new CRM_Core_DAO_DupeMatch();
             $dao->find(true);
             $fieldsArray = explode('AND', $dao->rule);
             foreach ($fieldsArray as $value) {
                 if (array_key_exists(trim($value), $params)) {
                     $paramValue = $params[trim($value)];
                     if (is_array($paramValue)) {
                         $disp .= $params[trim($value)][0][trim($value)] . " ";
                     } else {
                         $disp .= $params[trim($value)] . " ";
                     }
                 }
             }
             array_unshift($values, "No matching Contact found for (" . $disp . ")");
             return CRM_HISTORY_IMPORT_PARSER_ERROR;
         }
     } else {
         $formatted['entity_table'] = 'civicrm_contact';
         $newHistory = crm_create_activity_history($formatted);
         if (is_a($newHistory, CRM_Core_Error)) {
             array_unshift($values, $newHistory->_errors[0]['message']);
             return CRM_HISTORY_IMPORT_PARSER_ERROR;
         }
         $this->_newHistory[] = $newHistory->id;
         return CRM_HISTORY_IMPORT_PARSER_VALID;
     }
 }
Example #6
0
 /**
  * Process the form
  *
  * @return void
  * @access public
  */
 function postProcess()
 {
     $contactID = $this->get('contactID');
     if (!$contactID) {
         // make a copy of params so we dont destroy our params
         // (since we pass this by reference)
         $premiumParams = $params = $this->_params;
         // so now we have a confirmed financial transaction
         // lets create or update a contact first
         require_once 'api/crm.php';
         $ids = CRM_Core_BAO_UFGroup::findContact($params);
         $contactsIDs = explode(',', $ids);
         // if we find more than one contact, use the first one
         $contact_id = $contactsIDs[0];
         $contact = null;
         if ($contact_id) {
             $contact =& crm_get_contact(array('contact_id' => $contact_id));
         }
         $ids = array();
         if (!$contact || !is_a($contact, 'CRM_Contact_BAO_Contact')) {
             $contact =& CRM_Contact_BAO_Contact::createFlat($params, $ids);
         } else {
             // need to fix and unify all contact creation
             $idParams = array('id' => $contact_id, 'contact_id' => $contact_id);
             $defaults = array();
             CRM_Contact_BAO_Contact::retrieve($idParams, $defaults, $ids);
             $contact =& CRM_Contact_BAO_Contact::createFlat($params, $ids);
         }
         if (is_a($contact, 'CRM_Core_Error')) {
             CRM_Core_Error::fatal("Failed creating contact for contributor");
         }
         $contactID = $contact->id;
         $this->set('contactID', $contactID);
     }
     $contributionType =& new CRM_Contribute_DAO_ContributionType();
     $contributionType->id = $this->_values['contribution_type_id'];
     if (!$contributionType->find(true)) {
         CRM_Core_Error::fatal("Could not find a system table");
     }
     // add some contribution type details to the params list
     // if folks need to use it
     $this->_params['contributionType_name'] = $contributionType->name;
     $this->_params['contributionType_accounting_code'] = $contributionType->accounting_code;
     $this->_params['contributionForm_id'] = $this->_values['id'];
     require_once 'CRM/Contribute/Payment.php';
     $payment =& CRM_Contribute_Payment::singleton($this->_mode);
     if ($this->_contributeMode == 'express') {
         $result =& $payment->doExpressCheckout($this->_params);
     } else {
         $result =& $payment->doDirectPayment($this->_params);
     }
     if (is_a($result, 'CRM_Core_Error')) {
         CRM_Core_Error::displaySessionError($result);
         CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', '_qf_Main_display=true'));
     }
     $now = date('YmdHis');
     $this->_params = array_merge($this->_params, $result);
     $this->_params['receive_date'] = $now;
     $this->set('params', $this->_params);
     $this->assign('trxn_id', $result['trxn_id']);
     $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($this->_params['receive_date']));
     // result has all the stuff we need
     // lets archive it to a financial transaction
     $config =& CRM_Core_Config::singleton();
     $receiptDate = null;
     if ($this->_values['is_email_receipt']) {
         $receiptDate = $now;
     }
     if ($contributionType->is_deductible) {
         $this->assign('is_deductible', true);
         $this->set('is_deductible', true);
     }
     // assigning Premium information to receipt tpl
     if ($premiumParams['selectProduct'] && $premiumParams['selectProduct'] != 'no_thanks') {
         $startDate = $endDate = "";
         $this->assign('selectPremium', true);
         require_once 'CRM/Contribute/DAO/Product.php';
         $productDAO =& new CRM_Contribute_DAO_Product();
         $productDAO->id = $premiumParams['selectProduct'];
         $productDAO->find(true);
         $this->assign('product_name', $productDAO->name);
         $this->assign('price', $productDAO->price);
         $this->assign('sku', $productDAO->sku);
         $this->assign('option', $premiumParams['options_' . $premiumParams['selectProduct']]);
         $periodType = $productDAO->period_type;
         if ($periodType) {
             $fixed_period_start_day = $productDAO->fixed_period_start_day;
             $duration_unit = $productDAO->duration_unit;
             $duration_interval = $productDAO->duration_interval;
             if ($periodType == 'rolling') {
                 $startDate = date('Y-m-d');
             } else {
                 if ($periodType == 'fixed') {
                     if ($fixed_period_start_day) {
                         $date = explode('-', date('Y-m-d'));
                         $month = substr($fixed_period_start_day, 0, strlen($fixed_period_start_day) - 2);
                         $day = substr($fixed_period_start_day, -2) . "<br>";
                         $year = $date[0];
                         $startDate = $year . '-' . $month . '-' . $day;
                     } else {
                         $startDate = date('Y-m-d');
                     }
                 }
             }
             $date = explode('-', $startDate);
             $year = $date[0];
             $month = $date[1];
             $day = $date[2];
             switch ($duration_unit) {
                 case 'year':
                     $year = $year + $duration_interval;
                     break;
                 case 'month':
                     $month = $month + $duration_interval;
                     break;
                 case 'day':
                     $day = $day + $duration_interval;
                     break;
                 case 'week':
                     $day = $day + $duration_interval * 7;
             }
             $endDate = date('Y-m-d H:i:s', mktime($hour, $minute, $second, $month, $day, $year));
             $this->assign('start_date', $startDate);
             $this->assign('end_date', $endDate);
         }
         require_once 'CRM/Contribute/DAO/Premium.php';
         $dao =& new CRM_Contribute_DAO_Premium();
         $dao->entity_table = 'civicrm_contribution_page';
         $dao->entity_id = $this->_id;
         $dao->find(true);
         $this->assign('contact_phone', $dao->premiums_contact_phone);
         $this->assign('contact_email', $dao->premiums_contact_email);
     }
     CRM_Core_DAO::transaction('BEGIN');
     $nonDeductibleAmount = $result['gross_amount'];
     if ($contributionType->is_deductible) {
         if ($premiumParams['selectProduct'] != 'no_thanks') {
             require_once 'CRM/Contribute/DAO/Product.php';
             $productDAO =& new CRM_Contribute_DAO_Product();
             $productDAO->id = $premiumParams['selectProduct'];
             $productDAO->find(true);
             if ($result['gross_amount'] < $productDAO->price) {
                 $nonDeductibleAmount = $result['gross_amount'];
             } else {
                 $nonDeductibleAmount = $productDAO->price;
             }
         } else {
             $nonDeductibleAmount = '0.00';
         }
     }
     // check contribution Type
     // first create the contribution record
     $params = array('contact_id' => $contactID, 'contribution_type_id' => $contributionType->id, 'payment_instrument_id' => 1, 'receive_date' => $now, 'non_deductible_amount' => $nonDeductibleAmount, 'total_amount' => $result['gross_amount'], 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $result['gross_amount']), 'trxn_id' => $result['trxn_id'], 'invoice_id' => $this->_params['invoiceID'], 'currency' => $this->_params['currencyID'], 'receipt_date' => $receiptDate, 'source' => ts('Online Contribution:') . ' ' . $this->_values['title']);
     $ids = array();
     $contribution =& CRM_Contribute_BAO_Contribution::add($params, $ids);
     //create Premium record
     if ($premiumParams['selectProduct'] && $premiumParams['selectProduct'] != 'no_thanks') {
         require_once 'CRM/Contribute/DAO/Product.php';
         $productDAO =& new CRM_Contribute_DAO_Product();
         $productDAO->id = $premiumParams['selectProduct'];
         $productDAO->find(true);
         $periodType = $productDAO->period_type;
         require_once 'CRM/Utils/Date.php';
         $params = array('product_id' => $premiumParams['selectProduct'], 'contribution_id' => $contribution->id, 'product_option' => $premiumParams['options_' . $premiumParams['selectProduct']], 'quantity' => 1, 'start_date' => CRM_Utils_Date::customFormat($startDate, '%Y%m%d'), 'end_date' => CRM_Utils_Date::customFormat($endDate, '%Y%m%d'));
         CRM_Contribute_BAO_Contribution::addPremium($params);
     }
     // process the custom data that is submitted or that came via the url
     $groupTree = $this->get('groupTree');
     $customValues = $this->get('customGetValues');
     $customValues = array_merge($this->_params, $customValues);
     require_once 'CRM/Core/BAO/CustomGroup.php';
     CRM_Core_BAO_CustomGroup::postProcess($groupTree, $customValues);
     CRM_Core_BAO_CustomGroup::updateCustomData($groupTree, 'Contribution', $contribution->id);
     // next create the transaction record
     $params = array('entity_table' => 'civicrm_contribution', 'entity_id' => $contribution->id, 'trxn_date' => $now, 'trxn_type' => 'Debit', 'total_amount' => $result['gross_amount'], 'fee_amount' => CRM_Utils_Array::value('fee_amount', $result), 'net_amount' => CRM_Utils_Array::value('net_amount', $result, $result['gross_amount']), 'currency' => $this->_params['currencyID'], 'payment_processor' => $config->paymentProcessor, 'trxn_id' => $result['trxn_id']);
     require_once 'CRM/Contribute/BAO/FinancialTrxn.php';
     $trxn =& CRM_Contribute_BAO_FinancialTrxn::create($params);
     // also create an activity history record
     require_once 'CRM/Utils/Money.php';
     $params = array('entity_table' => 'civicrm_contact', 'entity_id' => $contactID, 'activity_type' => $contributionType->name, 'module' => 'CiviContribute', 'callback' => 'CRM_Contribute_Page_Contribution::details', 'activity_id' => $contribution->id, 'activity_summary' => 'Online - ' . CRM_Utils_Money::format($this->_params['amount']), 'activity_date' => $now);
     if (is_a(crm_create_activity_history($params), 'CRM_Core_Error')) {
         CRM_Core_Error::fatal("Could not create a system record");
     }
     CRM_Core_DAO::transaction('COMMIT');
     // finally send an email receipt
     if ($this->_values['is_email_receipt']) {
         list($displayName, $email) = CRM_Contact_BAO_Contact::getEmailDetails($contactID);
         $template =& CRM_Core_Smarty::singleton();
         $subject = trim($template->fetch('CRM/Contribute/Form/Contribution/ReceiptSubject.tpl'));
         $message = $template->fetch('CRM/Contribute/Form/Contribution/ReceiptMessage.tpl');
         $receiptFrom = '"' . $this->_values['receipt_from_name'] . '" <' . $this->_values['receipt_from_email'] . '>';
         require_once 'CRM/Utils/Mail.php';
         CRM_Utils_Mail::send($receiptFrom, $displayName, $email, $subject, $message, $this->_values['cc_receipt'], $this->_values['bcc_receipt']);
     }
 }