/**
  * Test setValues() and GetValues() methods with custom Date field
  */
 public function testSetGetValuesDate()
 {
     $params = array();
     $contactID = $this->individualCreate();
     //create Custom Group
     $customGroup = $this->customGroupCreate(array('is_multiple' => 1));
     //create Custom Field of data type Date
     $fields = array('custom_group_id' => $customGroup['id'], 'data_type' => 'Date', 'html_type' => 'Select Date', 'default_value' => '');
     $customField = $this->customFieldCreate($fields);
     // Retrieve the field ID for sample custom field 'test_Date'
     $params = array('label' => 'test_Date');
     $field = array();
     CRM_Core_BAO_CustomField::retrieve($params, $field);
     $fieldID = $customField['id'];
     // Set test_Date to a valid date value
     $date = '20080608000000';
     $params = array('entityID' => $contactID, 'custom_' . $fieldID => $date);
     $result = CRM_Core_BAO_CustomValueTable::setValues($params);
     $this->assertEquals($result['is_error'], 0, 'Verify that is_error = 0 (success).');
     // Check that the date value is stored
     $values = array();
     $params = array('entityID' => $contactID, 'custom_' . $fieldID => 1);
     $values = CRM_Core_BAO_CustomValueTable::getValues($params);
     $this->assertEquals($values['is_error'], 0, 'Verify that is_error = 0 (success).');
     $this->assertEquals($values['custom_' . $fieldID . '_1'], CRM_Utils_Date::mysqlToIso($date), 'Verify that the date value is stored for contact ' . $contactID);
     // Now set test_Date to an invalid date value and try to reset
     $badDate = '20080631000000';
     $params = array('entityID' => $contactID, 'custom_' . $fieldID => $badDate);
     CRM_Core_TemporaryErrorScope::useException();
     $message = NULL;
     try {
         CRM_Core_BAO_CustomValueTable::setValues($params);
     } catch (Exception $e) {
         $message = $e->getMessage();
     }
     $errorScope = NULL;
     // Check that an exception has been thrown
     $this->assertNotNull($message, 'Verify than an exception is thrown when bad date is passed');
     $params = array('entityID' => $contactID, 'custom_' . $fieldID => 1);
     $values = CRM_Core_BAO_CustomValueTable::getValues($params);
     $this->assertEquals($values['custom_' . $fieldID . '_1'], CRM_Utils_Date::mysqlToIso($date), 'Verify that the date value has NOT been updated for contact ' . $contactID);
     // Test setting test_Date to null
     $params = array('entityID' => $contactID, 'custom_' . $fieldID => NULL);
     $result = CRM_Core_BAO_CustomValueTable::setValues($params);
     // Check that the date value is empty
     $params = array('entityID' => $contactID, 'custom_' . $fieldID => 1);
     $values = CRM_Core_BAO_CustomValueTable::getValues($params);
     $this->assertEquals($values['is_error'], 0, 'Verify that is_error = 0 (success).');
     // Cleanup
     $this->customFieldDelete($customField);
     $this->customGroupDelete($customGroup['id']);
     $this->contactDelete($contactID);
 }
 function testSetGetValuesDate()
 {
     $params = array();
     $contactID = Contact::createIndividual();
     //create Custom Group
     $customGroup = Custom::createGroup($params, 'Individual', true);
     //create Custom Field of data type Date
     $fields = array('groupId' => $customGroup->id, 'dataType' => 'Date', 'htmlType' => 'Select Date');
     $customField = Custom::createField($params, $fields);
     // Retrieve the field ID for sample custom field 'test_Date'
     $params = array('label' => 'test_Date');
     $field = array();
     require_once 'CRM/Core/BAO/CustomField.php';
     CRM_Core_BAO_CustomField::retrieve($params, $field);
     $fieldID = $field['id'];
     // Set test_Date to a valid date value
     $date = '20080608000000';
     $params = array('entityID' => $contactID, 'custom_' . $fieldID => $date);
     require_once 'CRM/Core/BAO/CustomValueTable.php';
     $result = CRM_Core_BAO_CustomValueTable::setValues($params);
     $this->assertEquals($result['is_error'], 0, 'Verify that is_error = 0 (success).');
     // Check that the date value is stored
     $values = array();
     $params = array('entityID' => $contactID, 'custom_' . $fieldID => 1);
     $values = CRM_Core_BAO_CustomValueTable::getValues($params);
     $this->assertEquals($values['is_error'], 0, 'Verify that is_error = 0 (success).');
     require_once 'CRM/Utils/Date.php';
     $this->assertEquals($values['custom_' . $fieldID . '_1'], CRM_Utils_Date::mysqlToIso($date), 'Verify that the date value is stored for contact ' . $contactID);
     // Now set test_Date to an invalid date value and try to reset
     $badDate = '20080631000000';
     $params = array('entityID' => $contactID, 'custom_' . $fieldID => $badDate);
     require_once 'CRM/Core/BAO/CustomValueTable.php';
     $result = CRM_Core_BAO_CustomValueTable::setValues($params);
     // Check that the error flag is set AND that custom date value has not been modified
     $this->assertEquals($result['is_error'], 1, 'Verify that is_error = 1 when bad date is passed.');
     $params = array('entityID' => $contactID, 'custom_' . $fieldID => 1);
     $values = CRM_Core_BAO_CustomValueTable::getValues($params);
     $this->assertEquals($values['custom_' . $fieldID . '_1'], CRM_Utils_Date::mysqlToIso($date), 'Verify that the date value has NOT been updated for contact ' . $contactID);
     // Test setting test_Date to null
     $params = array('entityID' => $contactID, 'custom_' . $fieldID => null);
     require_once 'CRM/Core/BAO/CustomValueTable.php';
     $result = CRM_Core_BAO_CustomValueTable::setValues($params);
     // Check that the date value is empty
     $params = array('entityID' => $contactID, 'custom_' . $fieldID => 1);
     $values = CRM_Core_BAO_CustomValueTable::getValues($params);
     $this->assertEquals($values['is_error'], 0, 'Verify that is_error = 0 (success).');
     // Cleanup
     Custom::deleteField($customField);
     Custom::deleteGroup($customGroup);
     Contact::delete($contactID);
 }
Example #3
0
 /**
  * Function to actually build the form
  *
  * @return void
  * @access public
  */
 function buildQuickForm()
 {
     $this->assignToTemplate();
     $productID = $this->get('productID');
     $option = $this->get('option');
     if ($productID) {
         require_once 'CRM/Contribute/BAO/Premium.php';
         CRM_Contribute_BAO_Premium::buildPremiumBlock($this, $this->_id, false, $productID, $option);
     }
     $this->assign('trxn_id', $this->_params['trxn_id']);
     $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($this->_params['receive_date']));
     // can we blow away the session now to prevent hackery
     $this->controller->reset();
 }
Example #4
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;
 }
Example #5
0
 /**
  * assign the minimal set of variables to the template
  *
  * @return void
  * @access public
  */
 function assignToTemplate()
 {
     $name = CRM_Utils_Array::value('billing_first_name', $this->_params);
     if (CRM_Utils_Array::value('billing_middle_name', $this->_params)) {
         $name .= " {$this->_params['billing_middle_name']}";
     }
     $name .= ' ' . CRM_Utils_Array::value('billing_last_name', $this->_params);
     $name = trim($name);
     $this->assign('billingName', $name);
     $this->set('name', $name);
     $this->assign('paymentProcessor', $this->_paymentProcessor);
     $vars = array('amount', 'currencyID', 'credit_card_type', 'trxn_id', 'amount_level');
     $config = CRM_Core_Config::singleton();
     if (isset($this->_values['is_recur']) && CRM_Utils_Array::value('is_recur', $this->_paymentProcessor)) {
         $this->assign('is_recur_enabled', 1);
         $vars = array_merge($vars, array('is_recur', 'frequency_interval', 'frequency_unit', 'installments'));
     }
     if (in_array('CiviPledge', $config->enableComponents) && CRM_Utils_Array::value('is_pledge', $this->_params) == 1) {
         $this->assign('pledge_enabled', 1);
         $vars = array_merge($vars, array('is_pledge', 'pledge_frequency_interval', 'pledge_frequency_unit', 'pledge_installments'));
     }
     if (isset($this->_params['amount_other']) || isset($this->_params['selectMembership'])) {
         $this->_params['amount_level'] = '';
     }
     foreach ($vars as $v) {
         if (isset($this->_params[$v])) {
             if ($v == 'frequency_unit' || $v == 'pledge_frequency_unit') {
                 $frequencyUnits = CRM_Core_OptionGroup::values('recur_frequency_units');
                 if (array_key_exists($this->_params[$v], $frequencyUnits)) {
                     $this->_params[$v] = $frequencyUnits[$this->_params[$v]];
                 }
             }
             if ($v == "amount" && $this->_params[$v] === 0) {
                 $this->_params[$v] = CRM_Utils_Money::format($this->_params[$v], NULL, NULL, TRUE);
             }
             $this->assign($v, $this->_params[$v]);
         }
     }
     // assign the address formatted up for display
     $addressParts = array("street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "state_province-{$this->_bltID}", "country-{$this->_bltID}");
     $addressFields = array();
     foreach ($addressParts as $part) {
         list($n, $id) = explode('-', $part);
         $addressFields[$n] = CRM_Utils_Array::value('billing_' . $part, $this->_params);
     }
     $this->assign('address', CRM_Utils_Address::format($addressFields));
     if (CRM_Utils_Array::value('hidden_onbehalf_profile', $this->_params)) {
         $this->assign('onBehalfName', $this->_params['organization_name']);
         $locTypeId = array_keys($this->_params['onbehalf_location']['email']);
         $this->assign('onBehalfEmail', $this->_params['onbehalf_location']['email'][$locTypeId[0]]['email']);
     }
     //fix for CRM-3767
     $assignCCInfo = FALSE;
     if ($this->_amount > 0.0) {
         $assignCCInfo = TRUE;
     } elseif (CRM_Utils_array::value('selectMembership', $this->_params)) {
         $memFee = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_params['selectMembership'], 'minimum_fee');
         if ($memFee > 0.0) {
             $assignCCInfo = TRUE;
         }
     }
     if ($this->_contributeMode == 'direct' && $assignCCInfo) {
         if ($this->_paymentProcessor && $this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_DIRECT_DEBIT) {
             $this->assign('payment_type', $this->_paymentProcessor['payment_type']);
             $this->assign('account_holder', $this->_params['account_holder']);
             $this->assign('bank_identification_number', $this->_params['bank_identification_number']);
             $this->assign('bank_name', $this->_params['bank_name']);
             $this->assign('bank_account_number', $this->_params['bank_account_number']);
         } else {
             $date = CRM_Utils_Date::format(CRM_Utils_array::value('credit_card_exp_date', $this->_params));
             $date = CRM_Utils_Date::mysqlToIso($date);
             $this->assign('credit_card_exp_date', $date);
             $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard(CRM_Utils_array::value('credit_card_number', $this->_params)));
         }
     }
     $this->assign('email', $this->controller->exportValue('Main', "email-{$this->_bltID}"));
     // also assign the receipt_text
     if (isset($this->_values['receipt_text'])) {
         $this->assign('receipt_text', $this->_values['receipt_text']);
     }
 }
Example #6
0
 /**
  * Apply variables for message to smarty template - this function is part of analysing what is in the huge
  * function & breaking it down into manageable chunks. Eventually it will be refactored into something else
  * Note we send directly from this function in some cases because it is only partly refactored
  * Don't call this function directly as the signature will change
  *
  * @param $values
  * @param $input
  * @param CRM_Core_SMARTY $template
  * @param bool $recur
  * @param bool $returnMessageText
  *
  * @return mixed
  */
 public function _assignMessageVariablesToTemplate(&$values, $input, &$template, $recur = FALSE, $returnMessageText = TRUE)
 {
     $template->assign('first_name', $this->_relatedObjects['contact']->first_name);
     $template->assign('last_name', $this->_relatedObjects['contact']->last_name);
     $template->assign('displayName', $this->_relatedObjects['contact']->display_name);
     if (!empty($values['lineItem']) && !empty($this->_relatedObjects['membership'])) {
         $template->assign('useForMember', TRUE);
     }
     //assign honor information to receipt message
     $softRecord = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($this->id);
     if (isset($softRecord['soft_credit'])) {
         //if id of contribution page is present
         if (!empty($values['id'])) {
             $values['honor'] = array('honor_profile_values' => array(), 'honor_profile_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'uf_group_id', 'entity_id'), 'honor_id' => $softRecord['soft_credit'][1]['contact_id']);
             $softCreditTypes = CRM_Core_OptionGroup::values('soft_credit_type');
             $template->assign('soft_credit_type', $softRecord['soft_credit'][1]['soft_credit_type_label']);
             $template->assign('honor_block_is_active', CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFJoin', $values['id'], 'is_active', 'entity_id'));
         } else {
             //offline contribution
             $softCreditTypes = $softCredits = array();
             foreach ($softRecord['soft_credit'] as $key => $softCredit) {
                 $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
                 $softCredits[$key] = array('Name' => $softCredit['contact_name'], 'Amount' => CRM_Utils_Money::format($softCredit['amount'], $softCredit['currency']));
             }
             $template->assign('softCreditTypes', $softCreditTypes);
             $template->assign('softCredits', $softCredits);
         }
     }
     $dao = new CRM_Contribute_DAO_ContributionProduct();
     $dao->contribution_id = $this->id;
     if ($dao->find(TRUE)) {
         $premiumId = $dao->product_id;
         $template->assign('option', $dao->product_option);
         $productDAO = new CRM_Contribute_DAO_Product();
         $productDAO->id = $premiumId;
         $productDAO->find(TRUE);
         $template->assign('selectPremium', TRUE);
         $template->assign('product_name', $productDAO->name);
         $template->assign('price', $productDAO->price);
         $template->assign('sku', $productDAO->sku);
     }
     $template->assign('title', CRM_Utils_Array::value('title', $values));
     $amount = CRM_Utils_Array::value('total_amount', $input, CRM_Utils_Array::value('amount', $input), NULL);
     if (empty($amount) && isset($this->total_amount)) {
         $amount = $this->total_amount;
     }
     $template->assign('amount', $amount);
     // add the new contribution values
     if (strtolower($this->_component) == 'contribute') {
         //PCP Info
         $softDAO = new CRM_Contribute_DAO_ContributionSoft();
         $softDAO->contribution_id = $this->id;
         if ($softDAO->find(TRUE)) {
             $template->assign('pcpBlock', TRUE);
             $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll);
             $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname);
             $template->assign('pcp_personal_note', $softDAO->pcp_personal_note);
             //assign the pcp page title for email subject
             $pcpDAO = new CRM_PCP_DAO_PCP();
             $pcpDAO->id = $softDAO->pcp_id;
             if ($pcpDAO->find(TRUE)) {
                 $template->assign('title', $pcpDAO->title);
             }
         }
     }
     if ($this->financial_type_id) {
         $values['financial_type_id'] = $this->financial_type_id;
     }
     $template->assign('trxn_id', $this->trxn_id);
     $template->assign('receive_date', CRM_Utils_Date::mysqlToIso($this->receive_date));
     $template->assign('contributeMode', 'notify');
     $template->assign('action', $this->is_test ? 1024 : 1);
     $template->assign('receipt_text', CRM_Utils_Array::value('receipt_text', $values));
     $template->assign('is_monetary', 1);
     $template->assign('is_recur', (bool) $recur);
     $template->assign('currency', $this->currency);
     $template->assign('address', CRM_Utils_Address::format($input));
     if (!empty($values['customGroup'])) {
         $template->assign('customGroup', $values['customGroup']);
     }
     if ($this->_component == 'event') {
         $template->assign('title', $values['event']['title']);
         $participantRoles = CRM_Event_PseudoConstant::participantRole();
         $viewRoles = array();
         foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_relatedObjects['participant']->role_id) as $k => $v) {
             $viewRoles[] = $participantRoles[$v];
         }
         $values['event']['participant_role'] = implode(', ', $viewRoles);
         $template->assign('event', $values['event']);
         $template->assign('participant', $values['participant']);
         $template->assign('location', $values['location']);
         $template->assign('customPre', $values['custom_pre_id']);
         $template->assign('customPost', $values['custom_post_id']);
         $isTest = FALSE;
         if ($this->_relatedObjects['participant']->is_test) {
             $isTest = TRUE;
         }
         $values['params'] = array();
         //to get email of primary participant.
         $primaryEmail = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $this->_relatedObjects['participant']->contact_id, 'email', 'contact_id');
         $primaryAmount[] = array('label' => $this->_relatedObjects['participant']->fee_level . ' - ' . $primaryEmail, 'amount' => $this->_relatedObjects['participant']->fee_amount);
         //build an array of cId/pId of participants
         $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, NULL, $this->_relatedObjects['contact']->id, $isTest, TRUE);
         unset($additionalIDs[$this->_relatedObjects['participant']->id]);
         //send receipt to additional participant if exists
         if (count($additionalIDs)) {
             $template->assign('isPrimary', 0);
             $template->assign('customProfile', NULL);
             //set additionalParticipant true
             $values['params']['additionalParticipant'] = TRUE;
             foreach ($additionalIDs as $pId => $cId) {
                 $amount = array();
                 //to change the status pending to completed
                 $additional = new CRM_Event_DAO_Participant();
                 $additional->id = $pId;
                 $additional->contact_id = $cId;
                 $additional->find(TRUE);
                 $additional->register_date = $this->_relatedObjects['participant']->register_date;
                 $additional->status_id = 1;
                 $additionalParticipantInfo = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id, 'email', 'contact_id');
                 //if additional participant dont have email
                 //use display name.
                 if (!$additionalParticipantInfo) {
                     $additionalParticipantInfo = CRM_Contact_BAO_Contact::displayName($additional->contact_id);
                 }
                 $amount[0] = array('label' => $additional->fee_level, 'amount' => $additional->fee_amount);
                 $primaryAmount[] = array('label' => $additional->fee_level . ' - ' . $additionalParticipantInfo, 'amount' => $additional->fee_amount);
                 $additional->save();
                 $additional->free();
                 $template->assign('amount', $amount);
                 CRM_Event_BAO_Event::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
             }
         }
         //build an array of custom profile and assigning it to template
         $customProfile = CRM_Event_BAO_Event::buildCustomProfile($this->_relatedObjects['participant']->id, $values, NULL, $isTest);
         if (count($customProfile)) {
             $template->assign('customProfile', $customProfile);
         }
         // for primary contact
         $values['params']['additionalParticipant'] = FALSE;
         $template->assign('isPrimary', 1);
         $template->assign('amount', $primaryAmount);
         $template->assign('register_date', CRM_Utils_Date::isoToMysql($this->_relatedObjects['participant']->register_date));
         if ($this->payment_instrument_id) {
             $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
             $template->assign('paidBy', $paymentInstrument[$this->payment_instrument_id]);
         }
         // carry paylater, since we did not created billing,
         // so need to pull email from primary location, CRM-4395
         $values['params']['is_pay_later'] = $this->_relatedObjects['participant']->is_pay_later;
     }
     return $template;
 }
Example #7
0
 /**
  * Function to process payment after confirmation
  * 
  * @param object  $form   form object  
  * @param array   $paymentParams   array with payment related key
  * value pairs  
  * @param array   $premiumParams   array with premium related key
  * value pairs  
  * @param int     $contactID       contact id  
  * @param int     $contributionTypeId   contribution type id  
  * @param int     $component   component id  
  * 
  * @return array associated array
  *
  * @static
  * @access public
  */
 static function processConfirm(&$form, &$paymentParams, &$premiumParams, $contactID, $contributionTypeId, $component = 'contribution')
 {
     require_once 'CRM/Core/Payment/Form.php';
     CRM_Core_Payment_Form::mapParams($form->_bltID, $form->_params, $paymentParams, true);
     require_once 'CRM/Contribute/DAO/ContributionType.php';
     $contributionType = new CRM_Contribute_DAO_ContributionType();
     if (isset($paymentParams['contribution_type'])) {
         $contributionType->id = $paymentParams['contribution_type'];
     } else {
         if (CRM_Utils_Array::value('pledge_id', $form->_values)) {
             $contributionType->id = CRM_Core_DAO::getFieldValue('CRM_Pledge_DAO_Pledge', $form->_values['pledge_id'], 'contribution_type_id');
         } else {
             $contributionType->id = $contributionTypeId;
         }
     }
     if (!$contributionType->find(true)) {
         CRM_Core_Error::fatal('Could not find a system table');
     }
     // add some contribution type details to the params list
     // if folks need to use it
     $paymentParams['contributionType_name'] = $form->_params['contributionType_name'] = $contributionType->name;
     $paymentParams['contributionType_accounting_code'] = $form->_params['contributionType_accounting_code'] = $contributionType->accounting_code;
     $paymentParams['contributionPageID'] = $form->_params['contributionPageID'] = $form->_values['id'];
     if ($form->_values['is_monetary'] && $form->_amount > 0.0 && is_array($form->_paymentProcessor)) {
         require_once 'CRM/Core/Payment.php';
         $payment =& CRM_Core_Payment::singleton($form->_mode, $form->_paymentProcessor, $form);
     }
     //fix for CRM-2062
     $now = date('YmdHis');
     $result = null;
     if ($form->_contributeMode == 'notify' || $form->_params['is_pay_later']) {
         // this is not going to come back, i.e. we fill in the other details
         // when we get a callback from the payment processor
         // also add the contact ID and contribution ID to the params list
         $paymentParams['contactID'] = $form->_params['contactID'] = $contactID;
         $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($form, $paymentParams, null, $contactID, $contributionType, true, true, true);
         $form->_params['contributionID'] = $contribution->id;
         $form->_params['contributionTypeID'] = $contributionType->id;
         $form->_params['item_name'] = $form->_params['description'];
         $form->_params['receive_date'] = $now;
         if ($form->_values['is_recur'] && $contribution->contribution_recur_id) {
             $form->_params['contributionRecurID'] = $contribution->contribution_recur_id;
         }
         $form->set('params', $form->_params);
         $form->postProcessPremium($premiumParams, $contribution);
         if ($form->_values['is_monetary'] && $form->_amount > 0.0) {
             // add qfKey so we can send to paypal
             $form->_params['qfKey'] = $form->controller->_key;
             if ($component == 'membership') {
                 $membershipResult = array(1 => $contribution);
                 return $membershipResult;
             } else {
                 if (!$form->_params['is_pay_later']) {
                     $result =& $payment->doTransferCheckout($form->_params, 'contribute');
                 } else {
                     // follow similar flow as IPN
                     // send the receipt mail
                     $form->set('params', $form->_params);
                     if ($contributionType->is_deductible) {
                         $form->assign('is_deductible', true);
                         $form->set('is_deductible', true);
                     }
                     if (isset($paymentParams['contribution_source'])) {
                         $form->_params['source'] = $paymentParams['contribution_source'];
                     }
                     // get the price set values for receipt.
                     if ($form->_priceSetId && $form->_lineItem) {
                         $form->_values['lineItem'] = $form->_lineItem;
                         $form->_values['priceSetID'] = $form->_priceSetId;
                     }
                     require_once 'CRM/Contribute/BAO/ContributionPage.php';
                     $form->_values['contribution_id'] = $contribution->id;
                     CRM_Contribute_BAO_ContributionPage::sendMail($contactID, $form->_values, $contribution->is_test);
                     return;
                 }
             }
         }
     } elseif ($form->_contributeMode == 'express') {
         if ($form->_values['is_monetary'] && $form->_amount > 0.0) {
             //LCD determine if express + recurring and direct accordingly
             if ($paymentParams['is_recur'] == 1) {
                 $result =& $payment->createRecurringPayments($paymentParams);
             } else {
                 $result =& $payment->doExpressCheckout($paymentParams);
             }
         }
     } elseif ($form->_values['is_monetary'] && $form->_amount > 0.0) {
         if ($paymentParams['is_recur'] && $form->_contributeMode == 'direct') {
             // For recurring contribution, create Contribution Record first.
             // Contribution ID, Recurring ID and Contact ID needed
             // When we get a callback from the payment processor
             $paymentParams['contactID'] = $contactID;
             $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($form, $paymentParams, null, $contactID, $contributionType, true, true, true);
             $paymentParams['contributionID'] = $contribution->id;
             $paymentParams['contributionTypeID'] = $contribution->contribution_type_id;
             $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
             if ($form->_values['is_recur'] && $contribution->contribution_recur_id) {
                 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
             }
         }
         $result =& $payment->doDirectPayment($paymentParams);
     }
     if ($component == 'membership') {
         $membershipResult = array();
     }
     if (is_a($result, 'CRM_Core_Error')) {
         //make sure to cleanup db for recurring case.
         if (CRM_Utils_Array::value('contributionID', $paymentParams)) {
             CRM_Contribute_BAO_Contribution::deleteContribution($paymentParams['contributionID']);
         }
         if (CRM_Utils_Array::value('contributionRecurID', $paymentParams)) {
             CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
         }
         if ($component !== 'membership') {
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$form->_params['qfKey']}"));
         }
         $membershipResult[1] = $result;
     } else {
         if ($result) {
             $form->_params = array_merge($form->_params, $result);
         }
         $form->_params['receive_date'] = $now;
         $form->set('params', $form->_params);
         $form->assign('trxn_id', $result['trxn_id']);
         $form->assign('receive_date', CRM_Utils_Date::mysqlToIso($form->_params['receive_date']));
         // result has all the stuff we need
         // lets archive it to a financial transaction
         if ($contributionType->is_deductible) {
             $form->assign('is_deductible', true);
             $form->set('is_deductible', true);
         }
         if (isset($paymentParams['contribution_source'])) {
             $form->_params['source'] = $paymentParams['contribution_source'];
         }
         // check if pending was set to true by payment processor
         $pending = false;
         if (CRM_Utils_Array::value('contribution_status_pending', $form->_params)) {
             $pending = true;
         }
         if (!($paymentParams['is_recur'] && $form->_contributeMode == 'direct')) {
             $contribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($form, $form->_params, $result, $contactID, $contributionType, true, $pending, true);
         }
         $form->postProcessPremium($premiumParams, $contribution);
         $membershipResult[1] = $contribution;
     }
     if ($component == 'membership') {
         return $membershipResult;
     }
     //Do not send an email if Recurring contribution is done via Direct Mode
     //Email will we send once the IPN will receive.
     if ($paymentParams['is_recur'] && $form->_contributeMode == 'direct') {
         return true;
     }
     // get the price set values for receipt.
     if ($form->_priceSetId && $form->_lineItem) {
         $form->_values['lineItem'] = $form->_lineItem;
         $form->_values['priceSetID'] = $form->_priceSetId;
     }
     // finally send an email receipt
     require_once 'CRM/Contribute/BAO/ContributionPage.php';
     $form->_values['contribution_id'] = $contribution->id;
     CRM_Contribute_BAO_ContributionPage::sendMail($contactID, $form->_values, $contribution->is_test);
 }
 /**
  * Function to actually build the form
  *
  * @return void
  * @access public
  */
 public function buildQuickForm()
 {
     $this->assignToTemplate();
     $productID = $this->get('productID');
     $option = $this->get('option');
     $membershipTypeID = $this->get('membershipTypeID');
     $this->assign('receiptFromEmail', CRM_Utils_Array::value('receipt_from_email', $this->_values));
     if ($productID) {
         CRM_Contribute_BAO_Premium::buildPremiumBlock($this, $this->_id, FALSE, $productID, $option);
     }
     if ($this->_priceSetId && !CRM_Core_DAO::getFieldValue('CRM_Price_DAO_Set', $this->_priceSetId, 'is_quick_config')) {
         $this->assign('lineItem', $this->_lineItem);
     } else {
         if (is_array($membershipTypeID)) {
             $membershipTypeID = current($membershipTypeID);
         }
         $this->assign('is_quick_config', 1);
         $this->_params['is_quick_config'] = 1;
     }
     $this->assign('priceSetID', $this->_priceSetId);
     $this->assign('useForMember', $this->get('useForMember'));
     $params = $this->_params;
     $honor_block_is_active = $this->get('honor_block_is_active');
     if ($honor_block_is_active && (!empty($params["honor_first_name"]) && !empty($params["honor_last_name"]) || !empty($params["honor_email"]))) {
         $this->assign('honor_block_is_active', $honor_block_is_active);
         $this->assign('honor_block_title', CRM_Utils_Array::value('honor_block_title', $this->_values));
         $prefix = CRM_Core_PseudoConstant::individualPrefix();
         $honor = CRM_Core_PseudoConstant::honor();
         $this->assign('honor_type', $honor[$params["honor_type_id"]]);
         $this->assign('honor_prefix', $params["honor_prefix_id"] ? $prefix[$params["honor_prefix_id"]] : ' ');
         $this->assign('honor_first_name', $params["honor_first_name"]);
         $this->assign('honor_last_name', $params["honor_last_name"]);
         $this->assign('honor_email', $params["honor_email"]);
     }
     $qParams = "reset=1&amp;id={$this->_id}";
     //pcp elements
     if ($this->_pcpId) {
         $qParams .= "&amp;pcpId={$this->_pcpId}";
         $this->assign('pcpBlock', TRUE);
         foreach (array('pcp_display_in_roll', 'pcp_is_anonymous', 'pcp_roll_nickname', 'pcp_personal_note') as $val) {
             if (CRM_Utils_Array::value($val, $this->_params)) {
                 $this->assign($val, $this->_params[$val]);
             }
         }
     }
     $this->assign('qParams', $qParams);
     if ($membershipTypeID) {
         $transactionID = $this->get('membership_trx_id');
         $membershipAmount = $this->get('membership_amount');
         $renewalMode = $this->get('renewal_mode');
         $this->assign('membership_trx_id', $transactionID);
         $this->assign('membership_amount', $membershipAmount);
         $this->assign('renewal_mode', $renewalMode);
         CRM_Member_BAO_Membership::buildMembershipBlock($this, $this->_id, FALSE, $membershipTypeID, TRUE, NULL, $this->_membershipContactID);
     }
     $this->_separateMembershipPayment = $this->get('separateMembershipPayment');
     $this->assign("is_separate_payment", $this->_separateMembershipPayment);
     $this->buildCustom($this->_values['custom_pre_id'], 'customPre', TRUE);
     $this->buildCustom($this->_values['custom_post_id'], 'customPost', TRUE);
     if (CRM_Utils_Array::value('hidden_onbehalf_profile', $params)) {
         $ufJoinParams = array('module' => 'onBehalf', 'entity_table' => 'civicrm_contribution_page', 'entity_id' => $this->_id);
         $OnBehalfProfile = CRM_Core_BAO_UFJoin::getUFGroupIds($ufJoinParams);
         $profileId = $OnBehalfProfile[0];
         $fieldTypes = array('Contact', 'Organization');
         $contactSubType = CRM_Contact_BAO_ContactType::subTypes('Organization');
         $fieldTypes = array_merge($fieldTypes, $contactSubType);
         if (is_array($this->_membershipBlock) && !empty($this->_membershipBlock)) {
             $fieldTypes = array_merge($fieldTypes, array('Membership'));
         } else {
             $fieldTypes = array_merge($fieldTypes, array('Contribution'));
         }
         $this->buildCustom($profileId, 'onbehalfProfile', TRUE, TRUE, $fieldTypes);
     }
     $this->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $this->_params));
     $this->assign('receive_date', CRM_Utils_Date::mysqlToIso(CRM_Utils_Array::value('receive_date', $this->_params)));
     $defaults = array();
     $options = array();
     $fields = array();
     $removeCustomFieldTypes = array('Contribution');
     foreach ($this->_fields as $name => $dontCare) {
         if ($name == 'onbehalf') {
             foreach ($dontCare as $key => $value) {
                 $fields['onbehalf'][$key] = 1;
             }
         } else {
             $fields[$name] = 1;
         }
     }
     $fields['state_province'] = $fields['country'] = $fields['email'] = 1;
     $contact = $this->_params = $this->controller->exportValues('Main');
     foreach ($fields as $name => $dontCare) {
         if ($name == 'onbehalf') {
             foreach ($dontCare as $key => $value) {
                 //$defaults[$key] = $contact['onbehalf'][$key];
                 if (isset($contact['onbehalf'][$key])) {
                     $defaults[$key] = $contact['onbehalf'][$key];
                 }
                 if (isset($contact['onbehalf']["{$key}_id"])) {
                     $defaults["{$key}_id"] = $contact['onbehalf']["{$key}_id"];
                 }
             }
         } elseif (isset($contact[$name])) {
             $defaults[$name] = $contact[$name];
             if (substr($name, 0, 7) == 'custom_') {
                 $timeField = "{$name}_time";
                 if (isset($contact[$timeField])) {
                     $defaults[$timeField] = $contact[$timeField];
                 }
             } elseif (in_array($name, array('addressee', 'email_greeting', 'postal_greeting')) && CRM_Utils_Array::value($name . '_custom', $contact)) {
                 $defaults[$name . '_custom'] = $contact[$name . '_custom'];
             }
         }
     }
     // now fix all state country selectors
     CRM_Core_BAO_Address::fixAllStateSelects($this, $defaults);
     $this->_submitValues = array_merge($this->_submitValues, $defaults);
     $this->setDefaults($defaults);
     $values['entity_id'] = $this->_id;
     $values['entity_table'] = 'civicrm_contribution_page';
     CRM_Friend_BAO_Friend::retrieve($values, $data);
     $tellAFriend = FALSE;
     if ($this->_pcpId) {
         if ($this->_pcpBlock['is_tellfriend_enabled']) {
             $this->assign('friendText', ts('Tell a Friend'));
             $subUrl = "eid={$this->_pcpId}&blockId={$this->_pcpBlock['id']}&pcomponent=pcp";
             $tellAFriend = TRUE;
         }
     } elseif (CRM_Utils_Array::value('is_active', $data)) {
         $friendText = $data['title'];
         $this->assign('friendText', $friendText);
         $subUrl = "eid={$this->_id}&pcomponent=contribute";
         $tellAFriend = TRUE;
     }
     if ($tellAFriend) {
         if ($this->_action & CRM_Core_Action::PREVIEW) {
             $url = CRM_Utils_System::url("civicrm/friend", "reset=1&action=preview&{$subUrl}");
         } else {
             $url = CRM_Utils_System::url("civicrm/friend", "reset=1&{$subUrl}");
         }
         $this->assign('friendURL', $url);
     }
     $this->freeze();
     // can we blow away the session now to prevent hackery
     // CRM-9491
     $this->controller->reset();
 }
 /**
  * Submit function.
  *
  * This is also accessed by unit tests.
  *
  * @param array $formValues
  *
  * @return array
  */
 public function submit($formValues)
 {
     $isTest = $this->_mode == 'test' ? 1 : 0;
     $joinDate = $startDate = $endDate = NULL;
     $membershipTypes = $membership = $calcDate = array();
     $membershipType = NULL;
     $mailSend = FALSE;
     $formValues = $this->setPriceSetParameters($formValues);
     $params = $softParams = $ids = array();
     $allMemberStatus = CRM_Member_PseudoConstant::membershipStatus();
     $allContributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
     if ($this->_id) {
         $ids['membership'] = $params['id'] = $this->_id;
     }
     $ids['userId'] = CRM_Core_Session::singleton()->get('userID');
     // Set variables that we normally get from context.
     // In form mode these are set in preProcess.
     //TODO: set memberships, fixme
     $this->setContextVariables($formValues);
     $this->_memTypeSelected = self::getSelectedMemberships($this->_priceSet, $formValues);
     if (empty($formValues['financial_type_id'])) {
         $formValues['financial_type_id'] = $this->_priceSet['financial_type_id'];
     }
     $config = CRM_Core_Config::singleton();
     $this->convertDateFieldsToMySQL($formValues);
     $membershipTypeValues = array();
     foreach ($this->_memTypeSelected as $memType) {
         $membershipTypeValues[$memType]['membership_type_id'] = $memType;
     }
     //take the required membership recur values.
     if ($this->_mode && !empty($formValues['auto_renew'])) {
         $params['is_recur'] = $formValues['is_recur'] = TRUE;
         $mapping = array('frequency_interval' => 'duration_interval', 'frequency_unit' => 'duration_unit');
         $count = 0;
         foreach ($this->_memTypeSelected as $memType) {
             $recurMembershipTypeValues = CRM_Utils_Array::value($memType, $this->_recurMembershipTypes, array());
             foreach ($mapping as $mapVal => $mapParam) {
                 $membershipTypeValues[$memType][$mapVal] = CRM_Utils_Array::value($mapParam, $recurMembershipTypeValues);
                 if (!$count) {
                     $formValues[$mapVal] = CRM_Utils_Array::value($mapParam, $recurMembershipTypeValues);
                 }
             }
             $count++;
         }
     }
     $isQuickConfig = $this->_priceSet['is_quick_config'];
     $termsByType = array();
     $lineItem = array($this->_priceSetId => array());
     CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $formValues, $lineItem[$this->_priceSetId]);
     if (CRM_Utils_Array::value('tax_amount', $formValues)) {
         $params['tax_amount'] = $formValues['tax_amount'];
     }
     $params['total_amount'] = CRM_Utils_Array::value('amount', $formValues);
     $submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $formValues);
     if (!empty($lineItem[$this->_priceSetId])) {
         foreach ($lineItem[$this->_priceSetId] as &$li) {
             if (!empty($li['membership_type_id'])) {
                 if (!empty($li['membership_num_terms'])) {
                     $termsByType[$li['membership_type_id']] = $li['membership_num_terms'];
                 }
             }
             ///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
             if ($isQuickConfig && $submittedFinancialType) {
                 $li['financial_type_id'] = $submittedFinancialType;
             }
         }
     }
     $this->storeContactFields($formValues);
     $params['contact_id'] = $this->_contactID;
     $fields = array('status_id', 'source', 'is_override', 'campaign_id');
     foreach ($fields as $f) {
         $params[$f] = CRM_Utils_Array::value($f, $formValues);
     }
     // fix for CRM-3724
     // when is_override false ignore is_admin statuses during membership
     // status calculation. similarly we did fix for import in CRM-3570.
     if (empty($params['is_override'])) {
         $params['exclude_is_admin'] = TRUE;
     }
     // process date params to mysql date format.
     $dateTypes = array('join_date' => 'joinDate', 'start_date' => 'startDate', 'end_date' => 'endDate');
     foreach ($dateTypes as $dateField => $dateVariable) {
         ${$dateVariable} = CRM_Utils_Date::processDate($formValues[$dateField]);
     }
     $memTypeNumTerms = empty($termsByType) ? CRM_Utils_Array::value('num_terms', $formValues) : NULL;
     $calcDates = array();
     foreach ($this->_memTypeSelected as $memType) {
         if (empty($memTypeNumTerms)) {
             $memTypeNumTerms = CRM_Utils_Array::value($memType, $termsByType, 1);
         }
         $calcDates[$memType] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($memType, $joinDate, $startDate, $endDate, $memTypeNumTerms);
     }
     foreach ($calcDates as $memType => $calcDate) {
         foreach (array_keys($dateTypes) as $d) {
             //first give priority to form values then calDates.
             $date = CRM_Utils_Array::value($d, $formValues);
             if (!$date) {
                 $date = CRM_Utils_Array::value($d, $calcDate);
             }
             $membershipTypeValues[$memType][$d] = CRM_Utils_Date::processDate($date);
         }
     }
     // max related memberships - take from form or inherit from membership type
     foreach ($this->_memTypeSelected as $memType) {
         if (array_key_exists('max_related', $formValues)) {
             $membershipTypeValues[$memType]['max_related'] = CRM_Utils_Array::value('max_related', $formValues);
         }
         $membershipTypeValues[$memType]['custom'] = CRM_Core_BAO_CustomField::postProcess($formValues, $this->_id, 'Membership');
         $membershipTypes[$memType] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $memType);
     }
     $membershipType = implode(', ', $membershipTypes);
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     list($userName) = CRM_Contact_BAO_Contact_Location::getEmailDetails($ids['userId']);
     //CRM-13981, allow different person as a soft-contributor of chosen type
     if ($this->_contributorContactID != $this->_contactID) {
         $params['contribution_contact_id'] = $this->_contributorContactID;
         if (!empty($formValues['soft_credit_type_id'])) {
             $softParams['soft_credit_type_id'] = $formValues['soft_credit_type_id'];
             $softParams['contact_id'] = $this->_contactID;
         }
     }
     if (!empty($formValues['record_contribution'])) {
         $recordContribution = array('total_amount', 'financial_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'check_number', 'campaign_id', 'receive_date');
         foreach ($recordContribution as $f) {
             $params[$f] = CRM_Utils_Array::value($f, $formValues);
         }
         if (!$this->_onlinePendingContributionId) {
             if (empty($formValues['source'])) {
                 $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)', array(1 => $membershipType, 2 => $userName));
             } else {
                 $params['contribution_source'] = $formValues['source'];
             }
         }
         if (empty($params['is_override']) && CRM_Utils_Array::value('contribution_status_id', $params) == array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'))) {
             $params['status_id'] = array_search('Pending', $allMemberStatus);
             $params['skipStatusCal'] = TRUE;
             $params['is_pay_later'] = 1;
             $this->assign('is_pay_later', 1);
         }
         if (!empty($formValues['send_receipt'])) {
             $params['receipt_date'] = CRM_Utils_Array::value('receive_date', $formValues);
         }
         //insert financial type name in receipt.
         $formValues['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $formValues['financial_type_id']);
     }
     // process line items, until no previous line items.
     if (!empty($lineItem)) {
         $params['lineItems'] = $lineItem;
         $params['processPriceSet'] = TRUE;
     }
     $createdMemberships = array();
     if ($this->_mode) {
         $params['total_amount'] = CRM_Utils_Array::value('total_amount', $formValues, 0);
         if (!$isQuickConfig) {
             $params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId, 'financial_type_id');
         } else {
             $params['financial_type_id'] = CRM_Utils_Array::value('financial_type_id', $formValues);
         }
         $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($formValues['payment_processor_id'], $this->_mode);
         //get the payment processor id as per mode.
         $params['payment_processor_id'] = $formValues['payment_processor_id'] = $this->_paymentProcessor['id'];
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields['email-Primary'] = 1;
         $formValues['email-5'] = $formValues['email-Primary'] = $this->_memberEmail;
         $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
         $formValues["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_middle_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_last_name', $formValues);
         $formValues["address_name-{$this->_bltID}"] = trim($formValues["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         //ensure we don't over-write the payer's email with the member's email
         if ($this->_contributorContactID == $this->_contactID) {
             $fields["email-{$this->_bltID}"] = 1;
         }
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $formValues)) {
                 $formValues[$name] = $formValues["billing_{$name}"];
                 $formValues['preserveDBName'] = TRUE;
             }
         }
         if ($this->_contributorContactID == $this->_contactID) {
             //see CRM-12869 for discussion of why we don't do this for separate payee payments
             CRM_Contact_BAO_Contact::createProfileContact($formValues, $fields, $this->_contributorContactID, NULL, NULL, CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type'));
         }
         // add all the additional payment params we need
         $formValues["state_province-{$this->_bltID}"] = $formValues["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($formValues["billing_state_province_id-{$this->_bltID}"]);
         $formValues["country-{$this->_bltID}"] = $formValues["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($formValues["billing_country_id-{$this->_bltID}"]);
         $formValues['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($formValues);
         $formValues['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($formValues);
         $formValues['ip_address'] = CRM_Utils_System::ipAddress();
         $formValues['amount'] = $params['total_amount'];
         $formValues['currencyID'] = $config->defaultCurrency;
         $formValues['description'] = ts("Contribution submitted by a staff person using member's credit card for signup");
         $formValues['invoiceID'] = md5(uniqid(rand(), TRUE));
         $formValues['financial_type_id'] = $params['financial_type_id'];
         // at this point we've created a contact and stored its address etc
         // all the payment processors expect the name and address to be in the
         // so we copy stuff over to first_name etc.
         $paymentParams = $formValues;
         $paymentParams['contactID'] = $this->_contributorContactID;
         //CRM-10377 if payment is by an alternate contact then we need to set that person
         // as the contact in the payment params
         if ($this->_contributorContactID != $this->_contactID) {
             if (!empty($formValues['soft_credit_type_id'])) {
                 $softParams['contact_id'] = $params['contact_id'];
                 $softParams['soft_credit_type_id'] = $formValues['soft_credit_type_id'];
             }
         }
         if (!empty($formValues['send_receipt'])) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         CRM_Core_Payment_Form::mapParams($this->_bltID, $formValues, $paymentParams, TRUE);
         // CRM-7137 -for recurring membership,
         // we do need contribution and recurring records.
         $result = NULL;
         if (!empty($paymentParams['is_recur'])) {
             $financialType = new CRM_Financial_DAO_FinancialType();
             $financialType->id = $params['financial_type_id'];
             $financialType->find(TRUE);
             $this->_params = $formValues;
             $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($this, $paymentParams, NULL, array('contact_id' => $this->_contributorContactID, 'line_item' => $lineItem, 'is_test' => $isTest, 'campaign_id' => CRM_Utils_Array::value('campaign_id', $paymentParams), 'contribution_page_id' => CRM_Utils_Array::value('contribution_page_id', $formValues), 'source' => CRM_Utils_Array::value('source', $paymentParams, CRM_Utils_Array::value('description', $paymentParams)), 'thankyou_date' => CRM_Utils_Array::value('thankyou_date', $paymentParams), 'payment_instrument_id' => $this->_paymentProcessor['payment_instrument_id']), $financialType, TRUE, FALSE, $this->_bltID);
             //create new soft-credit record, CRM-13981
             if ($softParams) {
                 $softParams['contribution_id'] = $contribution->id;
                 $softParams['currency'] = $contribution->currency;
                 $softParams['amount'] = $contribution->total_amount;
                 CRM_Contribute_BAO_ContributionSoft::add($softParams);
             }
             $paymentParams['contactID'] = $this->_contactID;
             $paymentParams['contributionID'] = $contribution->id;
             $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
             $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
             $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
             $ids['contribution'] = $contribution->id;
             $params['contribution_recur_id'] = $paymentParams['contributionRecurID'];
         }
         if ($params['total_amount'] > 0.0) {
             $payment = $this->_paymentProcessor['object'];
             try {
                 $result = $payment->doPayment($paymentParams);
                 $formValues = array_merge($formValues, $result);
                 // Assign amount to template if payment was successful.
                 $this->assign('amount', $params['total_amount']);
             } catch (PaymentProcessorException $e) {
                 if (!empty($paymentParams['contributionID'])) {
                     CRM_Contribute_BAO_Contribution::failPayment($paymentParams['contributionID'], $this->_contactID, $e->getMessage());
                 }
                 if (!empty($paymentParams['contributionRecurID'])) {
                     CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
                 }
                 CRM_Core_Error::displaySessionError($result);
                 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=add&cid={$this->_contactID}&context=&mode={$this->_mode}"));
             }
         }
         if ($formValues['payment_status_id'] != array_search('Completed', $allContributionStatus)) {
             $params['status_id'] = array_search('Pending', $allMemberStatus);
             $params['skipStatusCal'] = TRUE;
             // unset send-receipt option, since receipt will be sent when ipn is received.
             unset($formValues['send_receipt'], $formValues['send_receipt']);
             //as membership is pending set dates to null.
             $memberDates = array('join_date' => 'joinDate', 'start_date' => 'startDate', 'end_date' => 'endDate');
             foreach ($memberDates as $dv) {
                 ${$dv} = NULL;
                 foreach ($this->_memTypeSelected as $memType) {
                     $membershipTypeValues[$memType][$dv] = NULL;
                 }
             }
         }
         $params['receive_date'] = $now;
         $params['invoice_id'] = $formValues['invoiceID'];
         $params['contribution_source'] = ts('%1 Membership Signup: Credit card or direct debit (by %2)', array(1 => $membershipType, 2 => $userName));
         $params['source'] = $formValues['source'] ? $formValues['source'] : $params['contribution_source'];
         $params['trxn_id'] = CRM_Utils_Array::value('trxn_id', $result);
         $params['payment_instrument_id'] = 1;
         $params['is_test'] = $this->_mode == 'live' ? 0 : 1;
         if (!empty($formValues['send_receipt'])) {
             $params['receipt_date'] = $now;
         } else {
             $params['receipt_date'] = NULL;
         }
         $this->set('params', $formValues);
         $this->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $result));
         $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($params['receive_date']));
         // required for creating membership for related contacts
         $params['action'] = $this->_action;
         //create membership record.
         $count = 0;
         foreach ($this->_memTypeSelected as $memType) {
             if ($count && ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))) {
                 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
             }
             $membershipParams = array_merge($membershipTypeValues[$memType], $params);
             //CRM-15366
             if (!empty($softParams) && empty($paymentParams['is_recur'])) {
                 $membershipParams['soft_credit'] = $softParams;
             }
             // This is required to trigger the recording of the membership contribution in the
             // CRM_Member_BAO_Membership::Create function.
             // @todo stop setting this & 'teach' the create function to respond to something
             // appropriate as part of our 2-step always create the pending contribution & then finally add the payment
             // process -
             // @see http://wiki.civicrm.org/confluence/pages/viewpage.action?pageId=261062657#Payments&AccountsRoadmap-Movetowardsalwaysusinga2-steppaymentprocess
             $membershipParams['contribution_status_id'] = CRM_Utils_Array::value('payment_status_id', $result);
             if (!empty($paymentParams['is_recur'])) {
                 // The earlier process created the line items (although we want to get rid of the earlier one in favour
                 // of a single path!
                 unset($membershipParams['lineItems']);
             }
             $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
             $params['contribution'] = CRM_Utils_Array::value('contribution', $membershipParams);
             unset($params['lineItems']);
             $this->_membershipIDs[] = $membership->id;
             $createdMemberships[$memType] = $membership;
             $count++;
         }
     } else {
         $params['action'] = $this->_action;
         if ($this->_onlinePendingContributionId && !empty($formValues['record_contribution'])) {
             // update membership as well as contribution object, CRM-4395
             $params['contribution_id'] = $this->_onlinePendingContributionId;
             $params['componentId'] = $params['id'];
             $params['componentName'] = 'contribute';
             $result = CRM_Contribute_BAO_Contribution::transitionComponents($params, TRUE);
             if (!empty($result) && !empty($params['contribution_id'])) {
                 $lineItem = array();
                 $lineItems = CRM_Price_BAO_LineItem::getLineItems($params['contribution_id'], 'contribution', NULL, TRUE, TRUE);
                 $itemId = key($lineItems);
                 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
                 $lineItems[$itemId]['unit_price'] = $params['total_amount'];
                 $lineItems[$itemId]['line_total'] = $params['total_amount'];
                 $lineItems[$itemId]['id'] = $itemId;
                 $lineItem[$priceSetId] = $lineItems;
                 $contributionBAO = new CRM_Contribute_BAO_Contribution();
                 $contributionBAO->id = $params['contribution_id'];
                 $contributionBAO->contact_id = $params['contact_id'];
                 $contributionBAO->find();
                 CRM_Price_BAO_LineItem::processPriceSet($params['contribution_id'], $lineItem, $contributionBAO, 'civicrm_membership');
                 //create new soft-credit record, CRM-13981
                 if ($softParams) {
                     $softParams['contribution_id'] = $params['contribution_id'];
                     while ($contributionBAO->fetch()) {
                         $softParams['currency'] = $contributionBAO->currency;
                         $softParams['amount'] = $contributionBAO->total_amount;
                     }
                     CRM_Contribute_BAO_ContributionSoft::add($softParams);
                 }
             }
             //carry updated membership object.
             $membership = new CRM_Member_DAO_Membership();
             $membership->id = $this->_id;
             $membership->find(TRUE);
             $cancelled = TRUE;
             if ($membership->end_date) {
                 //display end date w/ status message.
                 $endDate = $membership->end_date;
                 if (!in_array($membership->status_id, array(array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)), array_search('Expired', CRM_Member_PseudoConstant::membershipStatus())))) {
                     $cancelled = FALSE;
                 }
             }
             // suppress form values in template.
             $this->assign('cancelled', $cancelled);
             $createdMemberships[] = $membership;
         } else {
             $count = 0;
             foreach ($this->_memTypeSelected as $memType) {
                 if ($count && !empty($formValues['record_contribution']) && ($relateContribution = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id))) {
                     $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
                 }
                 $membershipParams = array_merge($params, $membershipTypeValues[$memType]);
                 if (!empty($formValues['int_amount'])) {
                     $init_amount = array();
                     foreach ($formValues as $key => $value) {
                         if (strstr($key, 'txt-price')) {
                             $init_amount[$key] = $value;
                         }
                     }
                     $membershipParams['init_amount'] = $init_amount;
                 }
                 if (!empty($softParams)) {
                     $membershipParams['soft_credit'] = $softParams;
                 }
                 $membership = CRM_Member_BAO_Membership::create($membershipParams, $ids);
                 $params['contribution'] = CRM_Utils_Array::value('contribution', $membershipParams);
                 unset($params['lineItems']);
                 $this->_membershipIDs[] = $membership->id;
                 $createdMemberships[$memType] = $membership;
                 $count++;
             }
         }
     }
     if (!empty($lineItem[$this->_priceSetId])) {
         $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
         $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
         $taxAmount = FALSE;
         $totalTaxAmount = 0;
         foreach ($lineItem[$this->_priceSetId] as &$priceFieldOp) {
             if (!empty($priceFieldOp['membership_type_id'])) {
                 $priceFieldOp['start_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'], '%B %E%f, %Y') : '-';
                 $priceFieldOp['end_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'] ? CRM_Utils_Date::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'], '%B %E%f, %Y') : '-';
             } else {
                 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
             }
             if ($invoicing && isset($priceFieldOp['tax_amount'])) {
                 $taxAmount = TRUE;
                 $totalTaxAmount += $priceFieldOp['tax_amount'];
             }
         }
         if ($invoicing) {
             $dataArray = array();
             foreach ($lineItem[$this->_priceSetId] as $key => $value) {
                 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
                     if (isset($dataArray[$value['tax_rate']])) {
                         $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array::value('tax_amount', $value);
                     } else {
                         $dataArray[$value['tax_rate']] = CRM_Utils_Array::value('tax_amount', $value);
                     }
                 }
             }
             if ($taxAmount) {
                 $this->assign('totalTaxAmount', $totalTaxAmount);
                 $this->assign('taxTerm', CRM_Utils_Array::value('tax_term', $invoiceSettings));
             }
             $this->assign('dataArray', $dataArray);
         }
     }
     $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ? $lineItem : FALSE);
     $receiptSend = FALSE;
     $contributionId = CRM_Member_BAO_Membership::getMembershipContributionId($membership->id);
     $membershipIds = $this->_membershipIDs;
     if ($contributionId && !empty($membershipIds)) {
         $contributionDetails = CRM_Contribute_BAO_Contribution::getContributionDetails(CRM_Export_Form_Select::MEMBER_EXPORT, $this->_membershipIDs);
         if ($contributionDetails[$membership->id]['contribution_status'] == 'Completed') {
             $receiptSend = TRUE;
         }
     }
     if (!empty($formValues['send_receipt']) && $receiptSend) {
         $formValues['contact_id'] = $this->_contactID;
         $formValues['contribution_id'] = $contributionId;
         // We really don't need a distinct receipt_text_signup vs receipt_text_renewal as they are
         // handled in the receipt. But by setting one we avoid breaking templates for now
         // although at some point we should switch in the templates.
         $formValues['receipt_text_signup'] = $formValues['receipt_text'];
         // send email receipt
         $mailSend = self::emailReceipt($this, $formValues, $membership);
     }
     // finally set membership id if already not set
     if (!$this->_id) {
         $this->_id = $membership->id;
     }
     $isRecur = CRM_Utils_Array::value('is_recur', $params);
     $this->setStatusMessage($membership, $endDate, $receiptSend, $membershipTypes, $createdMemberships, $isRecur, $calcDates, $mailSend);
     return $createdMemberships;
 }
Example #10
0
 /**
  * Process the form submission.
  */
 public function postProcess()
 {
     $now = date('YmdHis');
     $this->_params = $this->get('params');
     if (!empty($this->_params[0]['contact_id'])) {
         // unclear when this would be set & whether it could be checked in getContactID.
         // perhaps it relates to when cid is in the url
         //@todo someone who knows add comments on the various contactIDs in this form
         $contactID = $this->_params[0]['contact_id'];
     } else {
         $contactID = $this->getContactID();
     }
     // if a discount has been applied, lets now deduct it from the amount
     // and fix the fee level
     if (!empty($this->_params[0]['discount']) && !empty($this->_params[0]['discount']['applied'])) {
         foreach ($this->_params as $k => $v) {
             if (CRM_Utils_Array::value('amount', $this->_params[$k]) > 0 && !empty($this->_params[$k]['discountAmount'])) {
                 $this->_params[$k]['amount'] -= $this->_params[$k]['discountAmount'];
                 $this->_params[$k]['amount_level'] .= CRM_Utils_Array::value('discountMessage', $this->_params[$k]);
             }
         }
         $this->set('params', $this->_params);
     }
     // CRM-4320, lets build array of cancelled additional participant ids
     // those are drop or skip by primary at the time of confirmation.
     // get all in and then unset those we want to process.
     $cancelledIds = $this->_additionalParticipantIds;
     $params = $this->_params;
     if ($this->_values['event']['is_monetary']) {
         $this->set('finalAmount', $this->_amount);
     }
     $participantCount = array();
     //unset the skip participant from params.
     //build the $participantCount array.
     //maintain record for all participants.
     foreach ($params as $participantNum => $record) {
         if ($record == 'skip') {
             unset($params[$participantNum]);
             $participantCount[$participantNum] = 'skip';
         } elseif ($participantNum) {
             $participantCount[$participantNum] = 'participant';
         }
         //lets get additional participant id to cancel.
         if ($this->_allowConfirmation && is_array($cancelledIds)) {
             $additonalId = CRM_Utils_Array::value('participant_id', $record);
             if ($additonalId && ($key = array_search($additonalId, $cancelledIds))) {
                 unset($cancelledIds[$key]);
             }
         }
     }
     $payment = $registerByID = $primaryCurrencyID = $contribution = NULL;
     $paymentObjError = ts('The system did not record payment details for this payment and so could not process the transaction. Please report this error to the site administrator.');
     $this->participantIDS = array();
     $fields = array();
     foreach ($params as $key => $value) {
         CRM_Event_Form_Registration_Confirm::fixLocationFields($value, $fields, $this);
         //unset the billing parameters if it is pay later mode
         //to avoid creation of billing location
         // @todo - the reasoning for this is unclear - elsewhere we check what fields are provided by
         // the form & if billing fields exist we create the address, relying on the form to collect
         // only information we intend to store.
         if ($this->_allowWaitlist || $this->_requireApproval || !empty($value['is_pay_later']) && !$this->_isBillingAddressRequiredForPayLater || empty($value['is_primary'])) {
             $billingFields = array("email-{$this->_bltID}", 'billing_first_name', 'billing_middle_name', 'billing_last_name', "billing_street_address-{$this->_bltID}", "billing_city-{$this->_bltID}", "billing_state_province-{$this->_bltID}", "billing_state_province_id-{$this->_bltID}", "billing_postal_code-{$this->_bltID}", "billing_country-{$this->_bltID}", "billing_country_id-{$this->_bltID}", "address_name-{$this->_bltID}");
             foreach ($billingFields as $field) {
                 unset($value[$field]);
             }
             if (!empty($value['is_pay_later'])) {
                 $this->_values['params']['is_pay_later'] = TRUE;
             }
         }
         //Unset ContactID for additional participants and set RegisterBy Id.
         if (empty($value['is_primary'])) {
             $contactID = CRM_Utils_Array::value('contact_id', $value);
             $registerByID = $this->get('registerByID');
             if ($registerByID) {
                 $value['registered_by_id'] = $registerByID;
             }
         } else {
             $value['amount'] = $this->_totalAmount;
         }
         $contactID = CRM_Event_Form_Registration_Confirm::updateContactFields($contactID, $value, $fields, $this);
         // lets store the contactID in the session
         // we dont store in userID in case the user is doing multiple
         // transactions etc
         // for things like tell a friend
         if (!$this->getContactID() && !empty($value['is_primary'])) {
             $session = CRM_Core_Session::singleton();
             $session->set('transaction.userID', $contactID);
         }
         $value['description'] = ts('Online Event Registration') . ': ' . $this->_values['event']['title'];
         $value['accountingCode'] = CRM_Utils_Array::value('accountingCode', $this->_values['event']);
         $pending = FALSE;
         if ($this->_allowWaitlist || $this->_requireApproval) {
             //get the participant statuses.
             $waitingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Waiting'");
             if ($this->_allowWaitlist) {
                 $value['participant_status_id'] = $value['participant_status'] = array_search('On waitlist', $waitingStatuses);
             } else {
                 $value['participant_status_id'] = $value['participant_status'] = array_search('Awaiting approval', $waitingStatuses);
             }
             //there might be case user seleted pay later and
             //now becomes part of run time waiting list.
             $value['is_pay_later'] = FALSE;
         }
         // required only if paid event
         if ($this->_values['event']['is_monetary'] && !($this->_allowWaitlist || $this->_requireApproval)) {
             if (is_array($this->_paymentProcessor)) {
                 $payment = $this->_paymentProcessor['object'];
             }
             if (!empty($this->_paymentProcessor) && $this->_paymentProcessor['object']->supports('preApproval')) {
                 $preApprovalParams = $this->_paymentProcessor['object']->getPreApprovalDetails($this->get('pre_approval_parameters'));
                 $value = array_merge($value, $preApprovalParams);
             }
             $result = NULL;
             if (!empty($value['is_pay_later']) || $value['amount'] == 0 || $this->_contributeMode == 'checkout' || $this->_contributeMode == 'notify') {
                 if ($value['amount'] != 0) {
                     $pending = TRUE;
                     //get the participant statuses.
                     $pendingStatuses = CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Pending'");
                     $status = !empty($value['is_pay_later']) ? 'Pending from pay later' : 'Pending from incomplete transaction';
                     $value['participant_status_id'] = $value['participant_status'] = array_search($status, $pendingStatuses);
                 }
             } elseif (!empty($value['is_primary'])) {
                 CRM_Core_Payment_Form::mapParams($this->_bltID, $value, $value, TRUE);
                 // payment email param can be empty for _bltID mapping
                 // thus provide mapping for it with a different email value
                 if (empty($value['email'])) {
                     $value['email'] = CRM_Utils_Array::valueByRegexKey('/^email-/', $value);
                 }
                 if (is_object($payment)) {
                     try {
                         $result = $payment->doPayment($value);
                         $value = array_merge($value, $result);
                     } catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
                         CRM_Core_Session::singleton()->setStatus($e->getMessage());
                         CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/event/register', "id={$this->_eventId}"));
                     }
                 } else {
                     CRM_Core_Error::fatal($paymentObjError);
                 }
             }
             $value['receive_date'] = $now;
             if ($this->_allowConfirmation) {
                 $value['participant_register_date'] = $this->_values['participant']['register_date'];
             }
             $createContrib = $value['amount'] != 0 ? TRUE : FALSE;
             // force to create zero amount contribution, CRM-5095
             if (!$createContrib && $value['amount'] == 0 && $this->_priceSetId && $this->_lineItem) {
                 $createContrib = TRUE;
             }
             if ($createContrib && !empty($value['is_primary']) && !$this->_allowWaitlist && !$this->_requireApproval) {
                 // if paid event add a contribution record
                 //if primary participant contributing additional amount
                 //append (multiple participants) to its fee level. CRM-4196.
                 $isAdditionalAmount = FALSE;
                 if (count($params) > 1) {
                     $isAdditionalAmount = TRUE;
                 }
                 //passing contribution id is already registered.
                 $contribution = self::processContribution($this, $value, $result, $contactID, $pending, $isAdditionalAmount);
                 $value['contributionID'] = $contribution->id;
                 $value['contributionTypeID'] = $contribution->financial_type_id;
                 $value['receive_date'] = $contribution->receive_date;
                 $value['trxn_id'] = $contribution->trxn_id;
                 $value['contributionID'] = $contribution->id;
                 $value['contributionTypeID'] = $contribution->financial_type_id;
             }
             $value['contactID'] = $contactID;
             $value['eventID'] = $this->_eventId;
             $value['item_name'] = $value['description'];
         }
         if (!empty($value['contributionID'])) {
             $this->_values['contributionId'] = $value['contributionID'];
         }
         //CRM-4453.
         if (!empty($value['is_primary'])) {
             $primaryCurrencyID = CRM_Utils_Array::value('currencyID', $value);
         }
         if (empty($value['currencyID'])) {
             $value['currencyID'] = $primaryCurrencyID;
         }
         // CRM-11182 - Confirmation page might not be monetary
         if ($this->_values['event']['is_monetary']) {
             if (!$pending && !empty($value['is_primary']) && !$this->_allowWaitlist && !$this->_requireApproval) {
                 // transactionID & receive date required while building email template
                 $this->assign('trxn_id', $value['trxn_id']);
                 $this->assign('receive_date', CRM_Utils_Date::mysqlToIso($value['receive_date']));
                 $this->set('receiveDate', CRM_Utils_Date::mysqlToIso($value['receive_date']));
                 $this->set('trxnId', CRM_Utils_Array::value('trxn_id', $value));
             }
         }
         $value['fee_amount'] = CRM_Utils_Array::value('amount', $value);
         $this->set('value', $value);
         // handle register date CRM-4320
         if ($this->_allowConfirmation) {
             $registerDate = CRM_Utils_Array::value('participant_register_date', $params);
         } elseif (!empty($params['participant_register_date']) && is_array($params['participant_register_date']) && !empty($params['participant_register_date'])) {
             $registerDate = CRM_Utils_Date::format($params['participant_register_date']);
         } else {
             $registerDate = date('YmdHis');
         }
         $this->assign('register_date', $registerDate);
         $this->confirmPostProcess($contactID, $contribution, $payment);
     }
     //handle if no additional participant.
     if (!$registerByID) {
         $registerByID = $this->get('registerByID');
     }
     $this->set('participantIDs', $this->_participantIDS);
     // create line items, CRM-5313
     if ($this->_priceSetId && !empty($this->_lineItem)) {
         // take all processed participant ids.
         $allParticipantIds = $this->_participantIDS;
         // when participant re-walk wizard.
         if ($this->_allowConfirmation && !empty($this->_additionalParticipantIds)) {
             $allParticipantIds = array_merge(array($registerByID), $this->_additionalParticipantIds);
         }
         $entityTable = 'civicrm_participant';
         $invoiceSettings = Civi::settings()->get('contribution_invoice_settings');
         $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
         $totalTaxAmount = 0;
         $dataArray = array();
         foreach ($this->_lineItem as $key => $value) {
             if ($value == 'skip') {
                 continue;
             }
             if ($entityId = CRM_Utils_Array::value($key, $allParticipantIds)) {
                 // do cleanup line  items if participant re-walking wizard.
                 if ($this->_allowConfirmation) {
                     CRM_Price_BAO_LineItem::deleteLineItems($entityId, $entityTable);
                 }
                 $lineItem[$this->_priceSetId] = $value;
                 CRM_Price_BAO_LineItem::processPriceSet($entityId, $lineItem, $contribution, $entityTable);
             }
             if ($invoicing) {
                 foreach ($value as $line) {
                     if (isset($line['tax_amount']) && isset($line['tax_rate'])) {
                         $totalTaxAmount = $line['tax_amount'] + $totalTaxAmount;
                         if (isset($dataArray[$line['tax_rate']])) {
                             $dataArray[$line['tax_rate']] = $dataArray[$line['tax_rate']] + CRM_Utils_Array::value('tax_amount', $line);
                         } else {
                             $dataArray[$line['tax_rate']] = CRM_Utils_Array::value('tax_amount', $line);
                         }
                     }
                 }
             }
         }
         if ($invoicing) {
             $this->assign('dataArray', $dataArray);
             $this->assign('totalTaxAmount', $totalTaxAmount);
         }
     }
     //update status and send mail to cancelled additional participants, CRM-4320
     if ($this->_allowConfirmation && is_array($cancelledIds) && !empty($cancelledIds)) {
         $cancelledId = array_search('Cancelled', CRM_Event_PseudoConstant::participantStatus(NULL, "class = 'Negative'"));
         CRM_Event_BAO_Participant::transitionParticipants($cancelledIds, $cancelledId);
     }
     $isTest = FALSE;
     if ($this->_action & CRM_Core_Action::PREVIEW) {
         $isTest = TRUE;
     }
     // for Transfer checkout.
     // The concept of contributeMode is deprecated.
     if (($this->_contributeMode == 'checkout' || $this->_contributeMode == 'notify') && empty($params[0]['is_pay_later']) && !$this->_allowWaitlist && !$this->_requireApproval && $this->_totalAmount > 0) {
         $primaryParticipant = $this->get('primaryParticipant');
         if (empty($primaryParticipant['participantID'])) {
             $primaryParticipant['participantID'] = $registerByID;
         }
         //build an array of custom profile and assigning it to template
         $customProfile = CRM_Event_BAO_Event::buildCustomProfile($registerByID, $this->_values, NULL, $isTest);
         if (count($customProfile)) {
             $this->assign('customProfile', $customProfile);
             $this->set('customProfile', $customProfile);
         }
         // do a transfer only if a monetary payment greater than 0
         if ($this->_values['event']['is_monetary'] && $primaryParticipant) {
             if ($payment && is_object($payment)) {
                 //CRM 14512 provide line items of all participants to payment gateway
                 $primaryContactId = $this->get('primaryContactId');
                 //build an array of cId/pId of participants
                 $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($registerByID, NULL, $primaryContactId, $isTest, TRUE);
                 //need to copy, since we are unsetting on the way.
                 $copyParticipantCountLines = $participantCount;
                 //lets carry all participant params w/ values.
                 foreach ($additionalIDs as $participantID => $contactId) {
                     $participantNum = NULL;
                     $participantNum = $participantID;
                     if ($participantID == $registerByID) {
                         // This is the is primary participant.
                         $participantNum = 0;
                     } else {
                         if ($participantNum = array_search('participant', $copyParticipantCountLines)) {
                             //if no participant found break.
                             if ($participantNum === NULL) {
                                 break;
                             }
                             //unset current particpant so we don't check them again
                             unset($copyParticipantCountLines[$participantNum]);
                         }
                     }
                     // get values of line items
                     if ($this->_amount) {
                         $amount = array();
                         $amount[$participantNum]['label'] = preg_replace('//', '', $params[$participantNum]['amount_level']);
                         $amount[$participantNum]['amount'] = $params[$participantNum]['amount'];
                         $params[$participantNum]['amounts'] = $amount;
                     }
                     if (!empty($this->_lineItem)) {
                         $lineItems = $this->_lineItem;
                         $lineItem = array();
                         if ($lineItemValue = CRM_Utils_Array::value($participantNum, $lineItems)) {
                             $lineItem[] = $lineItemValue;
                         }
                         $params[$participantNum]['lineItem'] = $lineItem;
                     }
                     //only add additional particpants and not the primary particpant as we already have that
                     //added to $primaryParticipant so that this change doesn't break or require changes to
                     //existing gateway implementations
                     $primaryParticipant['participants_info'][$participantID] = $params[$participantNum];
                 }
                 //get event custom field information
                 $groupTree = CRM_Core_BAO_CustomGroup::getTree('Event', $this, $this->_eventId, 0, $this->_values['event']['event_type_id']);
                 $primaryParticipant['eventCustomFields'] = $groupTree;
                 // call postprocess hook before leaving
                 $this->postProcessHook();
                 // this does not return
                 $payment->doPayment($primaryParticipant, 'event');
             } else {
                 CRM_Core_Error::fatal($paymentObjError);
             }
         }
     } else {
         //otherwise send mail Confirmation/Receipt
         $primaryContactId = $this->get('primaryContactId');
         //build an array of cId/pId of participants
         $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($registerByID, NULL, $primaryContactId, $isTest, TRUE);
         //lets send  mails to all with meaningful text, CRM-4320.
         $this->assign('isOnWaitlist', $this->_allowWaitlist);
         $this->assign('isRequireApproval', $this->_requireApproval);
         //need to copy, since we are unsetting on the way.
         $copyParticipantCount = $participantCount;
         //lets carry all paticipant params w/ values.
         foreach ($additionalIDs as $participantID => $contactId) {
             $participantNum = NULL;
             if ($participantID == $registerByID) {
                 $participantNum = 0;
             } else {
                 if ($participantNum = array_search('participant', $copyParticipantCount)) {
                     unset($copyParticipantCount[$participantNum]);
                 }
             }
             if ($participantNum === NULL) {
                 break;
             }
             //carry the participant submitted values.
             $this->_values['params'][$participantID] = $params[$participantNum];
         }
         foreach ($additionalIDs as $participantID => $contactId) {
             $participantNum = 0;
             if ($participantID == $registerByID) {
                 //set as Primary Participant
                 $this->assign('isPrimary', 1);
                 //build an array of custom profile and assigning it to template.
                 $customProfile = CRM_Event_BAO_Event::buildCustomProfile($participantID, $this->_values, NULL, $isTest);
                 if (count($customProfile)) {
                     $this->assign('customProfile', $customProfile);
                     $this->set('customProfile', $customProfile);
                 }
                 $this->_values['params']['additionalParticipant'] = FALSE;
             } else {
                 //take the Additional participant number.
                 if ($participantNum = array_search('participant', $participantCount)) {
                     unset($participantCount[$participantNum]);
                 }
                 // Change $this->_values['participant'] to include additional participant values
                 $ids = $participantValues = array();
                 $participantParams = array('id' => $participantID);
                 CRM_Event_BAO_Participant::getValues($participantParams, $participantValues, $ids);
                 $this->_values['participant'] = $participantValues[$participantID];
                 $this->assign('isPrimary', 0);
                 $this->assign('customProfile', NULL);
                 //Additional Participant should get only it's payment information
                 if (!empty($this->_amount)) {
                     $amount = array();
                     $params = $this->get('params');
                     $amount[$participantNum]['label'] = preg_replace('//', '', $params[$participantNum]['amount_level']);
                     $amount[$participantNum]['amount'] = $params[$participantNum]['amount'];
                     $this->assign('amounts', $amount);
                 }
                 if ($this->_lineItem) {
                     $lineItems = $this->_lineItem;
                     $lineItem = array();
                     if ($lineItemValue = CRM_Utils_Array::value($participantNum, $lineItems)) {
                         $lineItem[] = $lineItemValue;
                     }
                     if ($invoicing) {
                         $individual = $this->get('individual');
                         $dataArray[key($dataArray)] = $individual[$participantNum]['totalTaxAmt'];
                         $this->assign('dataArray', $dataArray);
                         $this->assign('totalAmount', $individual[$participantNum]['totalAmtWithTax']);
                         $this->assign('totalTaxAmount', $individual[$participantNum]['totalTaxAmt']);
                         $this->assign('individual', array($individual[$participantNum]));
                     }
                     $this->assign('lineItem', $lineItem);
                 }
                 $this->_values['params']['additionalParticipant'] = TRUE;
                 $this->assign('isAdditionalParticipant', $this->_values['params']['additionalParticipant']);
             }
             //pass these variables since these are run time calculated.
             $this->_values['params']['isOnWaitlist'] = $this->_allowWaitlist;
             $this->_values['params']['isRequireApproval'] = $this->_requireApproval;
             //send mail to primary as well as additional participants.
             $this->assign('contactID', $contactId);
             $this->assign('participantID', $participantID);
             CRM_Event_BAO_Event::sendMail($contactId, $this->_values, $participantID, $isTest);
         }
     }
 }
Example #11
0
 public function buildQuickForm()
 {
     parent::buildQuickForm();
     $params = array(1 => array($this->log_conn_id, 'Integer'), 2 => array($this->log_date, 'String'));
     $this->assign('whom_url', CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->cid}"));
     $this->assign('who_url', CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->altered_by_id}"));
     $this->assign('whom_name', $this->altered_name);
     $this->assign('who_name', $this->altered_by);
     $this->assign('log_date', CRM_Utils_Date::mysqlToIso($this->log_date));
     $q = "reset=1&log_conn_id={$this->log_conn_id}&log_date={$this->log_date}";
     $this->assign('revertURL', CRM_Report_Utils_Report::getNextUrl($this->detail, "{$q}&revert=1", FALSE, TRUE));
     $this->assign('revertConfirm', ts('Are you sure you want to revert all changes?'));
 }
Example #12
0
 function sendMail(&$input, &$ids, &$objects, &$values, $recur = false, $returnMessageText = false)
 {
     $contribution =& $objects['contribution'];
     $membership =& $objects['membership'];
     $participant =& $objects['participant'];
     $event =& $objects['event'];
     if (empty($values)) {
         $values = array();
         if ($input['component'] == 'contribute') {
             require_once 'CRM/Contribute/BAO/ContributionPage.php';
             if (isset($contribution->contribution_page_id)) {
                 CRM_Contribute_BAO_ContributionPage::setValues($contribution->contribution_page_id, $values);
             } else {
                 // Handle re-print receipt for offline contributions (call from PDF.php - no contribution_page_id)
                 $values['is_email_receipt'] = 1;
                 $values['title'] = 'Contribution';
             }
         } else {
             // event
             $eventParams = array('id' => $objects['event']->id);
             $values['event'] = array();
             require_once 'CRM/Event/BAO/Event.php';
             CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
             $eventParams = array('id' => $objects['event']->id);
             $values['event'] = array();
             require_once 'CRM/Event/BAO/Event.php';
             CRM_Event_BAO_Event::retrieve($eventParams, $values['event']);
             //get location details
             $locationParams = array('entity_id' => $objects['event']->id, 'entity_table' => 'civicrm_event');
             require_once 'CRM/Core/BAO/Location.php';
             require_once 'CRM/Event/Form/ManageEvent/Location.php';
             $values['location'] = CRM_Core_BAO_Location::getValues($locationParams);
             require_once 'CRM/Core/BAO/UFJoin.php';
             $ufJoinParams = array('entity_table' => 'civicrm_event', 'entity_id' => $ids['event'], 'weight' => 1);
             $values['custom_pre_id'] = CRM_Core_BAO_UFJoin::findUFGroupId($ufJoinParams);
             $ufJoinParams['weight'] = 2;
             $values['custom_post_id'] = CRM_Core_BAO_UFJoin::findUFGroupId($ufJoinParams);
         }
     }
     $template =& CRM_Core_Smarty::singleton();
     // CRM_Core_Error::debug('tpl',$template);
     //assign honor infomation to receiptmessage
     if ($honarID = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'honor_contact_id')) {
         $honorDefault = array();
         $honorIds = array();
         $honorIds['contribution'] = $contribution->id;
         $idParams = array('id' => $honarID, 'contact_id' => $honarID);
         require_once "CRM/Contact/BAO/Contact.php";
         CRM_Contact_BAO_Contact::retrieve($idParams, $honorDefault, $honorIds);
         require_once "CRM/Core/PseudoConstant.php";
         $honorType = CRM_Core_PseudoConstant::honor();
         $prefix = CRM_Core_PseudoConstant::individualPrefix();
         $template->assign('honor_block_is_active', 1);
         $template->assign('honor_prefix', $prefix[$honorDefault["prefix_id"]]);
         $template->assign('honor_first_name', CRM_Utils_Array::value("first_name", $honorDefault));
         $template->assign('honor_last_name', CRM_Utils_Array::value("last_name", $honorDefault));
         $template->assign('honor_email', CRM_Utils_Array::value("email", $honorDefault["email"][1]));
         $template->assign('honor_type', $honorType[$contribution->honor_type_id]);
     }
     require_once 'CRM/Contribute/DAO/ContributionProduct.php';
     $dao =& new CRM_Contribute_DAO_ContributionProduct();
     $dao->contribution_id = $contribution->id;
     if ($dao->find(true)) {
         $premiumId = $dao->product_id;
         $template->assign('option', $dao->product_option);
         require_once 'CRM/Contribute/DAO/Product.php';
         $productDAO =& new CRM_Contribute_DAO_Product();
         $productDAO->id = $premiumId;
         $productDAO->find(true);
         $template->assign('selectPremium', true);
         $template->assign('product_name', $productDAO->name);
         $template->assign('price', $productDAO->price);
         $template->assign('sku', $productDAO->sku);
     }
     // add the new contribution values
     if ($input['component'] == 'contribute') {
         $template->assign('title', $values['title']);
         $template->assign('amount', $input['amount']);
         //PCP Info
         require_once 'CRM/Contribute/DAO/ContributionSoft.php';
         $softDAO =& new CRM_Contribute_DAO_ContributionSoft();
         $softDAO->contribution_id = $contribution->id;
         if ($softDAO->find(true)) {
             $template->assign('pcpBlock', true);
             $template->assign('pcp_display_in_roll', $softDAO->pcp_display_in_roll);
             $template->assign('pcp_roll_nickname', $softDAO->pcp_roll_nickname);
             $template->assign('pcp_personal_note', $softDAO->pcp_personal_note);
             //assign the pcp page title for email subject
             require_once 'CRM/Contribute/DAO/PCP.php';
             $pcpDAO =& new CRM_Contribute_DAO_PCP();
             $pcpDAO->id = $softDAO->pcp_id;
             if ($pcpDAO->find(true)) {
                 $template->assign('title', $pcpDAO->title);
             }
         }
     } else {
         $template->assign('title', $values['event']['title']);
         $template->assign('totalAmount', $input['amount']);
     }
     $template->assign('trxn_id', $contribution->trxn_id);
     $template->assign('receive_date', CRM_Utils_Date::mysqlToIso($contribution->receive_date));
     $template->assign('contributeMode', 'notify');
     $template->assign('action', $contribution->is_test ? 1024 : 1);
     $template->assign('receipt_text', CRM_Utils_Array::value('receipt_text', $values));
     $template->assign('is_monetary', 1);
     $template->assign('is_recur', $recur);
     if ($recur) {
         require_once 'CRM/Core/Payment.php';
         $paymentObject =& CRM_Core_Payment::singleton($contribution->is_test ? 'test' : 'live', 'Contribute', $objects['paymentProcessor']);
         $url = $paymentObject->cancelSubscriptionURL();
         $template->assign('cancelSubscriptionUrl', $url);
         if ($objects['paymentProcessor']['billing_mode'] & CRM_Core_Payment::BILLING_MODE_FORM) {
             //direct mode showing billing block, so use directIPN for temporary
             $template->assign('contributeMode', 'directIPN');
         }
     }
     require_once 'CRM/Utils/Address.php';
     $template->assign('address', CRM_Utils_Address::format($input));
     if ($input['component'] == 'event') {
         require_once 'CRM/Core/OptionGroup.php';
         $participant_role = CRM_Core_OptionGroup::values('participant_role');
         $values['event']['participant_role'] = $participant_role[$participant->role_id];
         $template->assign('event', $values['event']);
         $template->assign('location', $values['location']);
         $template->assign('customPre', $values['custom_pre_id']);
         $template->assign('customPost', $values['custom_post_id']);
         $isTest = false;
         if ($participant->is_test) {
             $isTest = true;
         }
         $values['params'] = array();
         require_once "CRM/Event/BAO/Event.php";
         //to get email of primary participant.
         $primaryEmail = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $participant->contact_id, 'email', 'contact_id');
         $primaryAmount[] = array('label' => $participant->fee_level . ' - ' . $primaryEmail, 'amount' => $participant->fee_amount);
         //build an array of cId/pId of participants
         $additionalIDs = CRM_Event_BAO_Event::buildCustomProfile($participant->id, null, $ids['contact'], $isTest, true);
         unset($additionalIDs[$participant->id]);
         //send receipt to additional participant if exists
         if (count($additionalIDs)) {
             $template->assign('isPrimary', 0);
             $template->assign('customProfile', null);
             //set additionalParticipant true
             $values['params']['additionalParticipant'] = true;
             foreach ($additionalIDs as $pId => $cId) {
                 $amount = array();
                 //to change the status pending to completed
                 $additional =& new CRM_Event_DAO_Participant();
                 $additional->id = $pId;
                 $additional->contact_id = $cId;
                 $additional->find(true);
                 $additional->register_date = $participant->register_date;
                 $additional->status_id = 1;
                 $additionalParticipantInfo = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Email', $additional->contact_id, 'email', 'contact_id');
                 //if additional participant dont have email
                 //use display name.
                 if (!$additionalParticipantInfo) {
                     require_once "CRM/Contact/BAO/Contact.php";
                     $additionalParticipantInfo = CRM_Contact_BAO_Contact::displayName($additional->contact_id);
                 }
                 $amount[0] = array('label' => $additional->fee_level, 'amount' => $additional->fee_amount);
                 $primaryAmount[] = array('label' => $additional->fee_level . ' - ' . $additionalParticipantInfo, 'amount' => $additional->fee_amount);
                 $additional->save();
                 $additional->free();
                 $template->assign('amount', $amount);
                 CRM_Event_BAO_Event::sendMail($cId, $values, $pId, $isTest, $returnMessageText);
             }
         }
         //build an array of custom profile and assigning it to template
         $customProfile = CRM_Event_BAO_Event::buildCustomProfile($participant->id, $values, null, $isTest);
         if (count($customProfile)) {
             $template->assign('customProfile', $customProfile);
         }
         // for primary contact
         $values['params']['additionalParticipant'] = false;
         $template->assign('isPrimary', 1);
         $template->assign('amount', $primaryAmount);
         // carry paylater, since we did not created billing,
         // so need to pull email from primary location, CRM-4395
         $values['params']['is_pay_later'] = $participant->is_pay_later;
         return CRM_Event_BAO_Event::sendMail($ids['contact'], $values, $participant->id, $isTest, $returnMessageText);
     } else {
         if ($membership) {
             $values['membership_id'] = $membership->id;
             // need to set the membership values here
             $template->assign('membership_assign', 1);
             require_once 'CRM/Member/PseudoConstant.php';
             $template->assign('membership_name', CRM_Member_PseudoConstant::membershipType($membership->membership_type_id));
             $template->assign('mem_start_date', $membership->start_date);
             $template->assign('mem_end_date', $membership->end_date);
             // if separate payment there are two contributions recorded and the
             // admin will need to send a receipt for each of them separately.
             // we dont link the two in the db (but can potentially infer it if needed)
             $template->assign('is_separate_payment', 0);
         }
         $values['contribution_id'] = $contribution->id;
         if (CRM_Utils_Array::value('related_contact', $ids)) {
             $values['related_contact'] = $ids['related_contact'];
             if (isset($ids['onbehalf_dupe_alert'])) {
                 $values['onbehalf_dupe_alert'] = $ids['onbehalf_dupe_alert'];
             }
             require_once 'CRM/Core/BAO/Address.php';
             $entityBlock = array('contact_id' => $ids['contact'], 'location_type_id' => CRM_Core_DAO::getFieldValue('CRM_Core_DAO_LocationType', 'Main', 'id', 'name'));
             $address = CRM_Core_BAO_Address::getValues($entityBlock);
             $template->assign('onBehalfAddress', $address[$entityBlock['location_type_id']]['display']);
         }
         $isTest = false;
         if ($contribution->is_test) {
             $isTest = true;
         }
         // CRM_Core_Error::debug('val',$values);
         return CRM_Contribute_BAO_ContributionPage::sendMail($ids['contact'], $values, $isTest, $returnMessageText);
     }
 }
 /**
  * Process the renewal form.
  *
  *
  * @return void
  */
 public function postProcess()
 {
     $ids = array();
     $config = CRM_Core_Config::singleton();
     // get the submitted form values.
     $this->_params = $formValues = $this->controller->exportValues($this->_name);
     $this->storeContactFields($formValues);
     // use values from screen
     if ($formValues['membership_type_id'][1] != 0) {
         $defaults['receipt_text_renewal'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $formValues['membership_type_id'][1], 'receipt_text_renewal');
     }
     $now = CRM_Utils_Date::getToday(NULL, 'YmdHis');
     $this->convertDateFieldsToMySQL($formValues);
     $this->assign('receive_date', $formValues['receive_date']);
     if (!empty($this->_params['send_receipt'])) {
         $formValues['receipt_date'] = $now;
         $this->assign('receipt_date', CRM_Utils_Date::mysqlToIso($formValues['receipt_date']));
     } else {
         $formValues['receipt_date'] = NULL;
     }
     if ($this->_mode) {
         $formValues['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_params, CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'minimum_fee'));
         if (empty($formValues['financial_type_id'])) {
             $formValues['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'financial_type_id');
         }
         $this->_paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($formValues['payment_processor_id'], $this->_mode);
         $fields = array();
         // set email for primary location.
         $fields['email-Primary'] = 1;
         $formValues['email-5'] = $formValues['email-Primary'] = $this->_contributorEmail;
         $formValues['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
         $formValues["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_middle_name', $formValues) . ' ' . CRM_Utils_Array::value('billing_last_name', $formValues);
         $formValues["address_name-{$this->_bltID}"] = trim($formValues["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}", $formValues)) {
                 $formValues[$name] = $formValues["billing_{$name}"];
                 $formValues['preserveDBName'] = TRUE;
             }
         }
         //here we are setting up the billing contact - if different from the member they are already created
         // but they will get billing details assigned
         CRM_Contact_BAO_Contact::createProfileContact($formValues, $fields, $this->_contributorContactID, NULL, NULL, $ctype);
         // 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['description'] = ts('Office Credit Card Membership Renewal Contribution');
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $formValues['total_amount'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['payment_action'] = 'Sale';
         $paymentParams['invoiceID'] = $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 passed params
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         if (!empty($this->_params['send_receipt'])) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         $paymentParams['contactID'] = $this->_contributorContactID;
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
         $payment = CRM_Core_Payment::singleton($this->_mode, $this->_paymentProcessor, $this);
         if (!empty($paymentParams['auto_renew'])) {
             $contributionRecurParams = $this->processRecurringContribution($paymentParams);
             $this->_params['contributionRecurID'] = $contributionRecurParams['contributionRecurID'];
             $paymentParams = array_merge($paymentParams, $contributionRecurParams);
         }
         $result = $payment->doDirectPayment($paymentParams);
         if (is_a($result, 'CRM_Core_Error')) {
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/membership', "reset=1&action=renew&cid={$this->_contactID}&id={$this->_id}&context=membership&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $formValues['contribution_status_id'] = 1;
         $formValues['invoice_id'] = $this->_params['invoiceID'];
         $formValues['trxn_id'] = $result['trxn_id'];
         $formValues['payment_instrument_id'] = 1;
         $formValues['is_test'] = $this->_mode == 'live' ? 0 : 1;
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
     }
     $renewalDate = NULL;
     if ($formValues['renewal_date']) {
         $this->set('renewalDate', CRM_Utils_Date::processDate($formValues['renewal_date']));
     }
     $this->_membershipId = $this->_id;
     // membership type custom data
     $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $formValues['membership_type_id'][1]);
     $customFields = CRM_Utils_Array::crmArrayMerge($customFields, CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, NULL, NULL, TRUE));
     $customFieldsFormatted = CRM_Core_BAO_CustomField::postProcess($formValues, $customFields, $this->_id, 'Membership');
     // check for test membership.
     $isTestMembership = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_membershipId, 'is_test');
     // chk for renewal for multiple terms CRM-8750
     $numRenewTerms = 1;
     if (is_numeric(CRM_Utils_Array::value('num_terms', $formValues))) {
         $numRenewTerms = $formValues['num_terms'];
     }
     //if contribution status is pending then set pay later
     if ($formValues['contribution_status_id'] == array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus())) {
         $this->_params['is_pay_later'] = 1;
     }
     $renewMembership = CRM_Member_BAO_Membership::renewMembershipFormWrapper($this->_contactID, $formValues['membership_type_id'][1], $isTestMembership, $this, NULL, NULL, $customFieldsFormatted, $numRenewTerms, $this->_membershipId);
     $endDate = CRM_Utils_Date::processDate($renewMembership->end_date);
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     $session = CRM_Core_Session::singleton();
     $userID = $session->get('userID');
     list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
     $memType = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $renewMembership->membership_type_id, 'name');
     if (!empty($formValues['record_contribution']) || $this->_mode) {
         // set the source
         $formValues['contribution_source'] = "{$memType} Membership: Offline membership renewal (by {$userName})";
         //create line items
         $lineItem = array();
         $priceSetId = NULL;
         CRM_Member_BAO_Membership::createLineItems($this, $formValues['membership_type_id'], $priceSetId);
         CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $this->_params, $lineItem[$priceSetId]);
         //CRM-11529 for quick config backoffice transactions
         //when financial_type_id is passed in form, update the
         //line items with the financial type selected in form
         if ($submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $formValues)) {
             foreach ($lineItem[$priceSetId] as &$li) {
                 $li['financial_type_id'] = $submittedFinancialType;
             }
         }
         $formValues['total_amount'] = CRM_Utils_Array::value('amount', $this->_params);
         if (!empty($lineItem)) {
             $formValues['lineItems'] = $lineItem;
             $formValues['processPriceSet'] = TRUE;
         }
         //assign contribution contact id to the field expected by recordMembershipContribution
         if ($this->_contributorContactID != $this->_contactID) {
             $formValues['contribution_contact_id'] = $this->_contributorContactID;
             if (!empty($this->_params['soft_credit_type_id'])) {
                 $formValues['soft_credit'] = array('soft_credit_type_id' => $this->_params['soft_credit_type_id'], 'contact_id' => $this->_contactID);
             }
         }
         $formValues['contact_id'] = $this->_contactID;
         //recordMembershipContribution receives params as a reference & adds one variable. This is
         // not a great pattern & ideally it would not receive as a reference. We assign our params as a
         // temporary variable to avoid e-notice & to make it clear to future refactorer that
         // this function is NOT reliant on that var being set
         $temporaryParams = array_merge($formValues, array('membership_id' => $renewMembership->id));
         CRM_Member_BAO_Membership::recordMembershipContribution($temporaryParams);
     }
     $receiptSend = FALSE;
     if (!empty($formValues['send_receipt'])) {
         $receiptSend = TRUE;
         $receiptFrom = $formValues['from_email_address'];
         if (!empty($formValues['payment_instrument_id'])) {
             $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
             $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
         }
         //get the group Tree
         $this->_groupTree = CRM_Core_BAO_CustomGroup::getTree('Membership', $this, $this->_id, FALSE, $this->_memType);
         // retrieve custom data
         $customFields = $customValues = $fo = array();
         foreach ($this->_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', '=', $this->_membershipId, 0, 0));
         // check whether its a test drive
         if ($this->_mode == 'test') {
             $members[] = array('member_test', '=', 1, 0, 0);
         }
         CRM_Core_BAO_UFGroup::getValues($this->_contactID, $customFields, $customValues, FALSE, $members);
         $this->assign_by_ref('formValues', $formValues);
         if (!empty($formValues['contribution_id'])) {
             $this->assign('contributionID', $formValues['contribution_id']);
         }
         $this->assign('membershipID', $this->_id);
         $this->assign('contactID', $this->_contactID);
         $this->assign('module', 'Membership');
         $this->assign('receiptType', 'membership renewal');
         $this->assign('mem_start_date', CRM_Utils_Date::customFormat($renewMembership->start_date));
         $this->assign('mem_end_date', CRM_Utils_Date::customFormat($renewMembership->end_date));
         $this->assign('membership_name', CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $renewMembership->membership_type_id));
         $this->assign('customValues', $customValues);
         if ($this->_mode) {
             if (!empty($this->_params['billing_first_name'])) {
                 $name = $this->_params['billing_first_name'];
             }
             if (!empty($this->_params['billing_middle_name'])) {
                 $name .= " {$this->_params['billing_middle_name']}";
             }
             if (!empty($this->_params['billing_last_name'])) {
                 $name .= " {$this->_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($this->_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($this->_params['credit_card_number']));
             $this->assign('credit_card_type', $this->_params['credit_card_type']);
             $this->assign('contributeMode', 'direct');
             $this->assign('isAmountzero', 0);
             $this->assign('is_pay_later', 0);
             $this->assign('isPrimary', 1);
             if ($this->_mode == 'test') {
                 $this->assign('action', '1024');
             }
         }
         list($mailSend, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_membership', 'valueName' => 'membership_offline_receipt', 'contactId' => $this->_receiptContactId, 'from' => $receiptFrom, 'toName' => $this->_contributorDisplayName, 'toEmail' => $this->_contributorEmail, 'isTest' => $this->_mode == 'test'));
     }
     $statusMsg = ts('%1 membership for %2 has been renewed.', array(1 => $memType, 2 => $this->_memberDisplayName));
     if ($endDate) {
         $statusMsg .= ' ' . ts('The new membership End Date is %1.', array(1 => CRM_Utils_Date::customFormat(substr($endDate, 0, 8))));
     }
     if ($receiptSend && $mailSend) {
         $statusMsg .= ' ' . ts('A renewal confirmation and receipt has been sent to %1.', array(1 => $this->_contributorEmail));
     }
     CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
 }
 /**
  * Process the Memberships
  *
  * @param array  $membershipParams array of membership fields
  * @param int    $contactID        contact id
  * @param object $form             form object
  *
  * @return void
  * @access public
  */
 public static function postProcessMembership($membershipParams, $contactID, &$form, &$premiumParams, $customFieldsFormatted = NULL, $includeFieldTypes = NULL)
 {
     $tempParams = $membershipParams;
     $paymentDone = FALSE;
     $result = NULL;
     $isTest = CRM_Utils_Array::value('is_test', $membershipParams, FALSE);
     $form->assign('membership_assign', TRUE);
     $form->set('membershipTypeID', $membershipParams['selectMembership']);
     $singleMembershipTypeID = $membershipTypeID = $membershipParams['selectMembership'];
     if (is_array($membershipTypeID) && count($membershipTypeID) == 1) {
         $singleMembershipTypeID = $membershipTypeID[0];
     }
     $membershipDetails = self::buildMembershipTypeValues($form, $singleMembershipTypeID);
     $form->assign('membership_name', CRM_Utils_Array::value('name', $membershipDetails));
     $minimumFee = CRM_Utils_Array::value('minimum_fee', $membershipDetails);
     $contributionTypeId = NULL;
     if ($form->_values['amount_block_is_active']) {
         $contributionTypeId = $form->_values['financial_type_id'];
     } else {
         $paymentDone = TRUE;
         $params['amount'] = $minimumFee;
         $contributionTypeId = CRM_Utils_Array::value('financial_type_id', $membershipDetails);
         if (!$contributionTypeId) {
             $contributionTypeId = CRM_Utils_Array::value('financial_type_id', $membershipParams);
         }
     }
     //amount must be greater than zero for
     //adding contribution record  to contribution table.
     //this condition arises when separate membership payment is
     //enabled and contribution amount is not selected. fix for CRM-3010
     if ($form->_amount > 0.0 && $membershipParams['amount']) {
         $result = CRM_Contribute_BAO_Contribution_Utils::processConfirm($form, $membershipParams, $premiumParams, $contactID, $contributionTypeId, 'membership');
     } else {
         // we need to explicitly create a CMS user in case of free memberships
         // since the below has already been done under processConfirm for paid memberships
         CRM_Contribute_BAO_Contribution_Utils::createCMSUser($membershipParams, $membershipParams['cms_contactID'], 'email-' . $form->_bltID);
     }
     $errors = array();
     if (is_a($result[1], 'CRM_Core_Error')) {
         $errors[1] = CRM_Core_Error::getMessages($result[1]);
     } elseif (CRM_Utils_Array::value(1, $result)) {
         // Save the contribution ID so that I can be used in email receipts
         // For example, if you need to generate a tax receipt for the donation only.
         $form->_values['contribution_other_id'] = $result[1]->id;
         $contribution[1] = $result[1];
     }
     $memBlockDetails = CRM_Member_BAO_Membership::getMembershipBlock($form->_id);
     if (CRM_Utils_Array::value('is_separate_payment', $memBlockDetails) && !$paymentDone) {
         $form->_lineItem = $form->_memLineItem;
         $contributionType = new CRM_Financial_DAO_FinancialType();
         $contributionType->id = CRM_Utils_Array::value('financial_type_id', $membershipDetails);
         if (!$contributionType->find(TRUE)) {
             CRM_Core_Error::fatal(ts("Could not find a system table"));
         }
         $tempParams['amount'] = $minimumFee;
         $invoiceID = md5(uniqid(rand(), TRUE));
         $tempParams['invoiceID'] = $invoiceID;
         //we don't allow recurring membership.CRM-3781.
         if (CRM_Utils_Array::value('is_recur', $tempParams)) {
             $tempParams['is_recur'] = 0;
         }
         $result = NULL;
         if ($form->_values['is_monetary'] && !$form->_params['is_pay_later'] && $minimumFee > 0.0) {
             $payment = CRM_Core_Payment::singleton($form->_mode, $form->_paymentProcessor, $form);
             if ($form->_contributeMode == 'express') {
                 $result =& $payment->doExpressCheckout($tempParams);
             } else {
                 $result =& $payment->doDirectPayment($tempParams);
             }
         }
         if (is_a($result, 'CRM_Core_Error')) {
             $errors[2] = CRM_Core_Error::getMessages($result);
         } else {
             //assign receive date when separate membership payment
             //and contribution amount not selected.
             if ($form->_amount == 0) {
                 $now = date('YmdHis');
                 $form->_params['receive_date'] = $now;
                 $receiveDate = CRM_Utils_Date::mysqlToIso($now);
                 $form->set('params', $form->_params);
                 $form->assign('receive_date', $receiveDate);
             }
             $form->set('membership_trx_id', $result['trxn_id']);
             $form->set('membership_amount', $minimumFee);
             $form->assign('membership_trx_id', $result['trxn_id']);
             $form->assign('membership_amount', $minimumFee);
             // we dont need to create the user twice, so lets disable cms_create_account
             // irrespective of the value, CRM-2888
             $tempParams['cms_create_account'] = 0;
             $pending = $form->_params['is_pay_later'] ? CRM_Utils_Array::value('minimum_fee', $membershipDetails, 0) > 0.0 ? TRUE : FALSE : FALSE;
             //set this variable as we are not creating pledge for
             //separate membership payment contribution.
             //so for differentiating membership contributon from
             //main contribution.
             $form->_params['separate_membership_payment'] = 1;
             $contribution[2] = CRM_Contribute_Form_Contribution_Confirm::processContribution($form, $tempParams, $result, $contactID, $contributionType, TRUE, $pending);
         }
     }
     $index = CRM_Utils_Array::value('is_separate_payment', $memBlockDetails) ? 2 : 1;
     if (!CRM_Utils_Array::value($index, $errors)) {
         if (isset($membershipParams['onbehalf']) && CRM_Utils_Array::value('member_campaign_id', $membershipParams['onbehalf'])) {
             $form->_params['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
         }
         if (is_array($membershipTypeID)) {
             $typesTerms = CRM_Utils_Array::value('types_terms', $membershipParams, array());
             $createdMemberships = array();
             foreach ($membershipTypeID as $memType) {
                 $numTerms = CRM_Utils_Array::value($memType, $typesTerms, 1);
                 $membership = self::renewMembership($contactID, $memType, $isTest, $form, NULL, CRM_Utils_Array::value('cms_contactID', $membershipParams), $customFieldsFormatted, CRM_Utils_Array::value($memType, $typesTerms, 1));
                 $createdMemberships[$memType] = $membership;
                 if (isset($contribution[$index])) {
                     //insert payment record
                     $dao = new CRM_Member_DAO_MembershipPayment();
                     $dao->membership_id = $membership->id;
                     $dao->contribution_id = $contribution[$index]->id;
                     //Fixed for avoiding duplicate entry error when user goes
                     //back and forward during payment mode is notify
                     if (!$dao->find(TRUE)) {
                         CRM_Utils_Hook::pre('create', 'MembershipPayment', NULL, $dao);
                         $dao->save();
                         CRM_Utils_Hook::post('create', 'MembershipPayment', $dao->id, $dao);
                     }
                 }
             }
             if ($form->_priceSetId && !empty($form->_useForMember) && !empty($form->_lineItem)) {
                 foreach ($form->_lineItem[$form->_priceSetId] as &$priceFieldOp) {
                     if (CRM_Utils_Array::value('membership_type_id', $priceFieldOp) && isset($createdMemberships[$priceFieldOp['membership_type_id']])) {
                         $membershipOb = $createdMemberships[$priceFieldOp['membership_type_id']];
                         $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date::customFormat($membershipOb->start_date, '%d%f %b, %Y') : '-';
                         $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date::customFormat($membershipOb->end_date, '%d%f %b, %Y') : '-';
                     } else {
                         $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
                     }
                 }
                 $form->_values['lineItem'] = $form->_lineItem;
                 $form->assign('lineItem', $form->_lineItem);
             }
         } else {
             $membership = self::renewMembership($contactID, $membershipTypeID, $isTest, $form, NULL, CRM_Utils_Array::value('cms_contactID', $membershipParams), $customFieldsFormatted, CRM_Utils_Array::value('types_terms', $membershipParams, 1), CRM_Utils_Array::value('contribution_status_id', $result) == 2 ? TRUE : FALSE);
             if (isset($contribution[$index])) {
                 //insert payment record
                 $dao = new CRM_Member_DAO_MembershipPayment();
                 $dao->membership_id = $membership->id;
                 $dao->contribution_id = $contribution[$index]->id;
                 //Fixed for avoiding duplicate entry error when user goes
                 //back and forward during payment mode is notify
                 if (!$dao->find(TRUE)) {
                     CRM_Utils_Hook::pre('create', 'MembershipPayment', NULL, $dao);
                     $dao->save();
                     CRM_Utils_Hook::post('create', 'MembershipPayment', $dao->id, $dao);
                 }
             }
         }
     }
     if (!empty($errors)) {
         foreach ($errors as $error) {
             if (is_string($error)) {
                 $message[] = $error;
             }
         }
         $message = ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
         throw new CRM_Core_Exception($message);
     }
     // CRM-7851
     CRM_Core_BAO_CustomValueTable::postProcess($form->_params, CRM_Core_DAO::$_nullArray, 'civicrm_membership', $membership->id, 'Membership');
     $form->_params['membershipID'] = $membership->id;
     if ($form->_contributeMode == 'notify') {
         if ($form->_values['is_monetary'] && $form->_amount > 0.0 && !$form->_params['is_pay_later']) {
             // call postprocess hook before leaving
             $form->postProcessHook();
             // this does not return
             $payment = CRM_Core_Payment::singleton($form->_mode, $form->_paymentProcessor, $form);
             $payment->doTransferCheckout($form->_params, 'contribute');
         }
     }
     $form->_values['membership_id'] = $membership->id;
     if (isset($contribution[$index]->id)) {
         $form->_values['contribution_id'] = $contribution[$index]->id;
     }
     // Do not send an email if Recurring transaction is done via Direct Mode
     // Email will we sent when the IPN is received.
     if (CRM_Utils_Array::value('is_recur', $form->_params) && $form->_contributeMode == 'direct') {
         return TRUE;
     }
     //finally send an email receipt
     CRM_Contribute_BAO_ContributionPage::sendMail($contactID, $form->_values, $isTest, FALSE, $includeFieldTypes);
 }
 /**
  * Send email receipt.
  *
  * @param CRM_Core_Form $form
  *   instance of Contribution form.
  * @param array $params
  *   (reference ) an assoc array of name/value pairs.
  * @param bool $ccContribution
  *   is it credit card contribution.
  *
  * @return array
  */
 public static function emailReceipt(&$form, &$params, $ccContribution = FALSE)
 {
     $form->assign('receiptType', 'contribution');
     // Retrieve Financial Type Name from financial_type_id
     $params['contributionType_name'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_FinancialType', $params['financial_type_id']);
     if (!empty($params['payment_instrument_id'])) {
         $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
         $params['paidBy'] = $paymentInstrument[$params['payment_instrument_id']];
         if ($params['paidBy'] != 'Check' && isset($params['check_number'])) {
             unset($params['check_number']);
         }
     }
     // retrieve individual prefix value for honoree
     if (isset($params['soft_credit'])) {
         $softCreditTypes = $softCredits = array();
         foreach ($params['soft_credit'] as $key => $softCredit) {
             $softCredits[$key] = array('Name' => $softCredit['contact_name'], 'Amount' => CRM_Utils_Money::format($softCredit['amount'], $softCredit['currency']));
             $softCreditTypes[$key] = $softCredit['soft_credit_type_label'];
         }
         $form->assign('softCreditTypes', $softCreditTypes);
         $form->assign('softCredits', $softCredits);
     }
     // retrieve premium product name and assigned fulfilled
     // date to template
     if (!empty($params['hidden_Premium'])) {
         if (isset($params['product_name']) && is_array($params['product_name']) && !empty($params['product_name'])) {
             $productDAO = new CRM_Contribute_DAO_Product();
             $productDAO->id = $params['product_name'][0];
             $productOptionID = $params['product_name'][1];
             $productDAO->find(TRUE);
             $params['product_name'] = $productDAO->name;
             $params['product_sku'] = $productDAO->sku;
             if (empty($params['product_option']) && !empty($form->_options[$productDAO->id])) {
                 $params['product_option'] = $form->_options[$productDAO->id][$productOptionID];
             }
         }
         if (!empty($params['fulfilled_date'])) {
             $form->assign('fulfilled_date', CRM_Utils_Date::processDate($params['fulfilled_date']));
         }
     }
     $form->assign('ccContribution', $ccContribution);
     if ($ccContribution) {
         //build the name.
         $name = CRM_Utils_Array::value('billing_first_name', $params);
         if (!empty($params['billing_middle_name'])) {
             $name .= " {$params['billing_middle_name']}";
         }
         $name .= ' ' . CRM_Utils_Array::value('billing_last_name', $params);
         $name = trim($name);
         $form->assign('billingName', $name);
         //assign the address formatted up for display
         $addressParts = array("street_address" => "billing_street_address-{$form->_bltID}", "city" => "billing_city-{$form->_bltID}", "postal_code" => "billing_postal_code-{$form->_bltID}", "state_province" => "state_province-{$form->_bltID}", "country" => "country-{$form->_bltID}");
         $addressFields = array();
         foreach ($addressParts as $name => $field) {
             $addressFields[$name] = CRM_Utils_Array::value($field, $params);
         }
         $form->assign('address', CRM_Utils_Address::format($addressFields));
         $date = CRM_Utils_Date::format($params['credit_card_exp_date']);
         $date = CRM_Utils_Date::mysqlToIso($date);
         $form->assign('credit_card_type', CRM_Utils_Array::value('credit_card_type', $params));
         $form->assign('credit_card_exp_date', $date);
         $form->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($params['credit_card_number']));
     } else {
         //offline contribution
         // assigned various dates to the templates
         $form->assign('receipt_date', CRM_Utils_Date::processDate($params['receipt_date']));
         if (!empty($params['cancel_date'])) {
             $form->assign('cancel_date', CRM_Utils_Date::processDate($params['cancel_date']));
         }
         if (!empty($params['thankyou_date'])) {
             $form->assign('thankyou_date', CRM_Utils_Date::processDate($params['thankyou_date']));
         }
         if ($form->_action & CRM_Core_Action::UPDATE) {
             $form->assign('lineItem', empty($form->_lineItems) ? FALSE : $form->_lineItems);
         }
     }
     //handle custom data
     if (!empty($params['hidden_custom'])) {
         $contribParams = array(array('contribution_id', '=', $params['contribution_id'], 0, 0));
         if ($form->_mode == 'test') {
             $contribParams[] = array('contribution_test', '=', 1, 0, 0);
         }
         //retrieve custom data
         $customGroup = array();
         foreach ($form->_groupTree as $groupID => $group) {
             $customFields = $customValues = array();
             if ($groupID == 'info') {
                 continue;
             }
             foreach ($group['fields'] as $k => $field) {
                 $field['title'] = $field['label'];
                 $customFields["custom_{$k}"] = $field;
             }
             //build the array of customgroup contain customfields.
             CRM_Core_BAO_UFGroup::getValues($params['contact_id'], $customFields, $customValues, FALSE, $contribParams);
             $customGroup[$group['title']] = $customValues;
         }
         //assign all custom group and corresponding fields to template.
         $form->assign('customGroup', $customGroup);
     }
     $form->assign_by_ref('formValues', $params);
     list($contributorDisplayName, $contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($params['contact_id']);
     $form->assign('contactID', $params['contact_id']);
     $form->assign('contributionID', $params['contribution_id']);
     if (!empty($params['currency'])) {
         $form->assign('currency', $params['currency']);
     }
     if (!empty($params['receive_date'])) {
         $form->assign('receive_date', CRM_Utils_Date::processDate($params['receive_date']));
     }
     $template = CRM_Core_Smarty::singleton();
     $taxAmt = $template->get_template_vars('dataArray');
     $eventTaxAmt = $template->get_template_vars('totalTaxAmount');
     $prefixValue = Civi::settings()->get('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($sendReceipt, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'contribution_offline_receipt', 'contactId' => $params['contact_id'], 'contributionId' => $params['contribution_id'], 'from' => $params['from_email_address'], 'toName' => $contributorDisplayName, 'toEmail' => $contributorEmail, 'isTest' => $form->_mode == 'test', 'PDFFilename' => ts('receipt') . '.pdf', 'isEmailPdf' => $isEmailPdf));
     return $sendReceipt;
 }
Example #16
0
 /** 
  * Function to process the form 
  * 
  * @access public 
  */
 public function postProcess()
 {
     if ($this->_action & CRM_Core_Action::DELETE) {
         require_once "CRM/Event/BAO/Participant.php";
         CRM_Event_BAO_Participant::deleteParticipant($this->_participantId);
         return;
     }
     // get the submitted form values.
     $params = $this->controller->exportValues($this->_name);
     // set the contact, when contact is selected
     if (CRM_Utils_Array::value('contact_select_id', $params)) {
         $this->_contactID = CRM_Utils_Array::value('contact_select_id', $params);
     }
     $config =& CRM_Core_Config::singleton();
     //check if discount is selected
     if (CRM_Utils_Array::value('discount_id', $params)) {
         $discountId = $params['discount_id'];
     } else {
         $params['discount_id'] = 'null';
         $discountId = null;
     }
     if ($this->_isPaidEvent) {
         //lets carry currency, CRM-4453
         $params['fee_currency'] = $config->defaultCurrency;
         // fix for CRM-3088
         if ($discountId && !empty($this->_values['discount'][$discountId])) {
             $params['amount_level'] = $this->_values['discount'][$discountId][$params['amount']]['label'];
             $params['amount'] = $this->_values['discount'][$discountId][$params['amount']]['value'];
             $this->assign('amount_level', $params['amount_level']);
         } else {
             if (!isset($params['priceSetId'])) {
                 $params['amount_level'] = $this->_values['fee'][$params['amount']]['label'];
                 $params['amount'] = $this->_values['fee'][$params['amount']]['value'];
                 $this->assign('amount_level', $params['amount_level']);
             } else {
                 if (!$this->_online) {
                     $lineItem = array();
                     CRM_Price_BAO_Set::processAmount($this->_values['fee']['fields'], $params, $lineItem[0]);
                     $this->set('lineItem', $lineItem);
                     $this->assign('lineItem', $lineItem);
                     $this->_lineItem = $lineItem;
                 }
             }
         }
         $params['fee_level'] = $params['amount_level'];
         $contributionParams = array();
         $contributionParams['total_amount'] = $params['amount'];
     }
     //fix for CRM-3086
     $params['fee_amount'] = $params['amount'];
     $this->_params = $params;
     unset($params['amount']);
     $params['register_date'] = CRM_Utils_Date::processDate($params['register_date'], $params['register_date_time']);
     $params['receive_date'] = CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $params));
     $params['contact_id'] = $this->_contactID;
     if ($this->_participantId) {
         $params['id'] = $this->_participantId;
     }
     $status = null;
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $participantBAO =& new CRM_Event_BAO_Participant();
         $participantBAO->id = $this->_participantId;
         $participantBAO->find();
         while ($participantBAO->fetch()) {
             $status = $participantBAO->status_id;
             $contributionParams['total_amount'] = $participantBAO->fee_amount;
         }
         $params['discount_id'] = null;
         //re-enter the values for UPDATE mode
         $params['fee_level'] = $params['amount_level'] = $participantBAO->fee_level;
         $params['fee_amount'] = $participantBAO->fee_amount;
     }
     require_once 'CRM/Contact/BAO/Contact.php';
     // Retrieve the name and email of the current user - this will be the FROM for the receipt email
     $session =& CRM_Core_Session::singleton();
     $userID = $session->get('userID');
     list($userName, $userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($userID);
     require_once "CRM/Event/BAO/Participant.php";
     if ($this->_mode) {
         if (!$this->_isPaidEvent) {
             CRM_Core_Error::fatal(ts('Selected Event is not Paid Event '));
         }
         //modify params according to parameter used in create
         //participant method (addParticipant)
         $params['participant_status_id'] = $params['status_id'];
         $params['participant_role_id'] = $params['role_id'];
         $params['participant_register_date'] = $params['register_date'];
         $params['participant_source'] = $params['source'];
         require_once 'CRM/Core/BAO/PaymentProcessor.php';
         $this->_paymentProcessor = CRM_Core_BAO_PaymentProcessor::getPayment($this->_params['payment_processor_id'], $this->_mode);
         require_once "CRM/Contact/BAO/Contact.php";
         $now = date('YmdHis');
         $fields = array();
         // set email for primary location.
         $fields["email-Primary"] = 1;
         $params["email-Primary"] = $params["email-{$this->_bltID}"] = $this->_contributorEmail;
         $params['register_date'] = $now;
         // now set the values for the billing location.
         foreach ($this->_fields as $name => $dontCare) {
             $fields[$name] = 1;
         }
         // also add location name to the array
         $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
         $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
         $fields["address_name-{$this->_bltID}"] = 1;
         $fields["email-{$this->_bltID}"] = 1;
         $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactID, 'contact_type');
         $nameFields = array('first_name', 'middle_name', 'last_name');
         foreach ($nameFields as $name) {
             $fields[$name] = 1;
             if (array_key_exists("billing_{$name}", $params)) {
                 $params[$name] = $params["billing_{$name}"];
                 $params['preserveDBName'] = true;
             }
         }
         $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactID, null, null, $ctype);
     }
     // build custom data getFields array
     $customFieldsRole = CRM_Core_BAO_CustomField::getFields('Participant', false, false, CRM_Utils_Array::value('role_id', $params), $this->_roleCustomDataTypeID);
     $customFieldsEvent = CRM_Core_BAO_CustomField::getFields('Participant', false, false, CRM_Utils_Array::value('event_id', $params), $this->_eventNameCustomDataTypeID);
     $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsRole, CRM_Core_BAO_CustomField::getFields('Participant', false, false, null, null, true));
     $customFields = CRM_Utils_Array::crmArrayMerge($customFieldsEvent, $customFields);
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_participantId, 'Participant');
     if ($this->_mode) {
         // add all the additioanl payment params we need
         $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
         $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
         $this->_params['year'] = $this->_params['credit_card_exp_date']['Y'];
         $this->_params['month'] = $this->_params['credit_card_exp_date']['M'];
         $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
         $this->_params['amount'] = $params['fee_amount'];
         $this->_params['amount_level'] = $params['amount_level'];
         $this->_params['currencyID'] = $config->defaultCurrency;
         $this->_params['payment_action'] = 'Sale';
         $this->_params['invoiceID'] = md5(uniqid(rand(), true));
         // at this point we've created a contact and stored its address etc
         // all the payment processors expect the name and address to be in the
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         require_once 'CRM/Core/Payment/Form.php';
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, true);
         $payment =& CRM_Core_Payment::singleton($this->_mode, 'Event', $this->_paymentProcessor, $this);
         $result =& $payment->doDirectPayment($paymentParams);
         if (is_a($result, 'CRM_Core_Error')) {
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&cid={$this->_contactID}&context=participant&mode={$this->_mode}"));
         }
         if ($result) {
             $this->_params = array_merge($this->_params, $result);
         }
         $this->_params['receive_date'] = $now;
         if (CRM_Utils_Array::value('send_receipt', $this->_params)) {
             $this->_params['receipt_date'] = $now;
         } else {
             $this->_params['receipt_date'] = null;
         }
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
         $this->assign('receive_date', CRM_Utils_Date::processDate($this->_params['receive_date']));
         // set source if not set
         $this->_params['description'] = ts('Submit Credit Card for Event Registration by: %1', array(1 => $userName));
         require_once 'CRM/Event/Form/Registration/Confirm.php';
         require_once 'CRM/Event/Form/Registration.php';
         //add contribution record
         $this->_params['contribution_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'contribution_type_id');
         $this->_params['mode'] = $this->_mode;
         //add contribution reocord
         $contribution = CRM_Event_Form_Registration_Confirm::processContribution($this, $this->_params, $result, $contactID, false);
         // add participant record
         $participants = array();
         $participants[] = CRM_Event_Form_Registration::addParticipant($this->_params, $contactID);
         //add custom data for participant
         require_once 'CRM/Core/BAO/CustomValueTable.php';
         CRM_Core_BAO_CustomValueTable::postProcess($this->_params, CRM_Core_DAO::$_nullArray, 'civicrm_participant', $participants[0]->id, 'Participant');
         //add participant payment
         require_once 'CRM/Event/BAO/ParticipantPayment.php';
         $paymentParticipant = array('participant_id' => $participants[0]->id, 'contribution_id' => $contribution->id);
         $ids = array();
         CRM_Event_BAO_ParticipantPayment::create($paymentParticipant, $ids);
         $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         $this->_contactIds[] = $this->_contactID;
     } else {
         $participants = array();
         // fix note if deleted
         if (!$params['note']) {
             $params['note'] = 'null';
         }
         if ($this->_single) {
             $participants[] = CRM_Event_BAO_Participant::create($params);
         } else {
             foreach ($this->_contactIds as $contactID) {
                 $commonParams = $params;
                 $commonParams['contact_id'] = $contactID;
                 $participants[] = CRM_Event_BAO_Participant::create($commonParams);
             }
         }
         if (isset($params['event_id'])) {
             $eventTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $params['event_id'], 'title');
         }
         if ($this->_single) {
             $this->_contactIds[] = $this->_contactID;
         }
         if (CRM_Utils_Array::value('record_contribution', $params)) {
             if (CRM_Utils_Array::value('id', $params)) {
                 if ($this->_onlinePendingContributionId) {
                     $ids['contribution'] = $this->_onlinePendingContributionId;
                 } else {
                     $ids['contribution'] = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_ParticipantPayment', $params['id'], 'contribution_id', 'participant_id');
                 }
             }
             unset($params['note']);
             //build contribution params
             if (!$this->_onlinePendingContributionId) {
                 $contributionParams['source'] = "{$eventTitle}: Offline registration (by {$userName})";
             }
             $contributionParams['currency'] = $config->defaultCurrency;
             $contributionParams['non_deductible_amount'] = 'null';
             $contributionParams['receipt_date'] = CRM_Utils_Array::value('send_receipt', $params) ? CRM_Utils_Array::value('receive_date', $params) : 'null';
             $recordContribution = array('contact_id', 'contribution_type_id', 'payment_instrument_id', 'trxn_id', 'contribution_status_id', 'receive_date', 'check_number');
             foreach ($recordContribution as $f) {
                 $contributionParams[$f] = CRM_Utils_Array::value($f, $params);
                 if ($f == 'trxn_id') {
                     $this->assign('trxn_id', $contributionParams[$f]);
                 }
             }
             //insert contribution type name in receipt.
             $this->assign('contributionTypeName', CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionType', $contributionParams['contribution_type_id']));
             require_once 'CRM/Contribute/BAO/Contribution.php';
             $contributions = array();
             if ($this->_single) {
                 $contributions[] =& CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
             } else {
                 $ids = array();
                 foreach ($this->_contactIds as $contactID) {
                     $contributionParams['contact_id'] = $contactID;
                     $contributions[] =& CRM_Contribute_BAO_Contribution::create($contributionParams, $ids);
                 }
             }
             //insert payment record for this participation
             if (!$ids['contribution']) {
                 require_once 'CRM/Event/DAO/ParticipantPayment.php';
                 foreach ($this->_contactIds as $num => $contactID) {
                     $ppDAO =& new CRM_Event_DAO_ParticipantPayment();
                     $ppDAO->participant_id = $participants[$num]->id;
                     $ppDAO->contribution_id = $contributions[$num]->id;
                     $ppDAO->save();
                 }
             }
         }
     }
     // also store lineitem stuff here
     if ($this->_lineItem) {
         require_once 'CRM/Price/BAO/LineItem.php';
         foreach ($this->_contactIds as $num => $contactID) {
             foreach ($this->_lineItem as $key => $value) {
                 if (is_array($value) && $value != 'skip') {
                     foreach ($value as $line) {
                         $line['entity_table'] = 'civicrm_participant';
                         $line['entity_id'] = $participants[$num]->id;
                         CRM_Price_BAO_LineItem::create($line);
                     }
                 }
             }
         }
     }
     $updateStatusMsg = null;
     //send mail when participant status changed, CRM-4326
     if ($this->_participantId && $this->_statusId && $this->_statusId != CRM_Utils_Array::value('status_id', $params) && CRM_Utils_Array::value('is_notify', $params)) {
         require_once "CRM/Event/BAO/Participant.php";
         $updateStatusMsg = CRM_Event_BAO_Participant::updateStatusMessage($this->_participantId, $params['status_id'], $this->_statusId);
     }
     if (CRM_Utils_Array::value('send_receipt', $params)) {
         $receiptFrom = "{$userName} <{$userEmail}>";
         $this->assign('module', 'Event Registration');
         //use of the message template below requires variables in different format
         $event = $events = array();
         $returnProperties = array('fee_label', 'start_date', 'end_date', 'is_show_location', 'title');
         //get all event details.
         CRM_Core_DAO::commonRetrieveAll('CRM_Event_DAO_Event', 'id', $params['event_id'], $events, $returnProperties);
         $event = $events[$params['event_id']];
         unset($event['start_date']);
         unset($event['end_date']);
         $role = CRM_Event_PseudoConstant::participantRole();
         $event['participant_role'] = $role[$params['role_id']];
         $event['is_monetary'] = $this->_isPaidEvent;
         if ($params['receipt_text']) {
             $event['confirm_email_text'] = $params['receipt_text'];
         }
         $this->assign('isAmountzero', 1);
         $this->assign('event', $event);
         $this->assign('isShowLocation', $event['is_show_location']);
         if (CRM_Utils_Array::value('is_show_location', $event) == 1) {
             $locationParams = array('entity_id' => $params['event_id'], 'entity_table' => 'civicrm_event');
             require_once 'CRM/Core/BAO/Location.php';
             $location = CRM_Core_BAO_Location::getValues($locationParams, true);
             $this->assign('location', $location);
         }
         $status = CRM_Event_PseudoConstant::participantStatus();
         if ($this->_isPaidEvent) {
             $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
             if (!$this->_mode) {
                 $this->assign('paidBy', CRM_Utils_Array::value($params['payment_instrument_id'], $paymentInstrument));
             }
             $this->assign('totalAmount', $contributionParams['total_amount']);
             $this->assign('isPrimary', 1);
             $this->assign('checkNumber', CRM_Utils_Array::value('check_number', $params));
         }
         if ($this->_mode) {
             if (CRM_Utils_Array::value('billing_first_name', $params)) {
                 $name = $params['billing_first_name'];
             }
             if (CRM_Utils_Array::value('billing_middle_name', $params)) {
                 $name .= " {$params['billing_middle_name']}";
             }
             if (CRM_Utils_Array::value('billing_last_name', $params)) {
                 $name .= " {$params['billing_last_name']}";
             }
             $this->assign('billingName', $name);
             // assign the address formatted up for display
             $addressParts = array("street_address-{$this->_bltID}", "city-{$this->_bltID}", "postal_code-{$this->_bltID}", "state_province-{$this->_bltID}", "country-{$this->_bltID}");
             $addressFields = array();
             foreach ($addressParts as $part) {
                 list($n, $id) = explode('-', $part);
                 if (isset($this->_params['billing_' . $part])) {
                     $addressFields[$n] = $this->_params['billing_' . $part];
                 }
             }
             require_once 'CRM/Utils/Address.php';
             $this->assign('address', CRM_Utils_Address::format($addressFields));
             $date = CRM_Utils_Date::format($params['credit_card_exp_date']);
             $date = CRM_Utils_Date::mysqlToIso($date);
             $this->assign('credit_card_exp_date', $date);
             $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($params['credit_card_number']));
             $this->assign('credit_card_type', $params['credit_card_type']);
             $this->assign('contributeMode', 'direct');
             $this->assign('isAmountzero', 0);
             $this->assign('is_pay_later', 0);
             $this->assign('isPrimary', 1);
         }
         $this->assign('register_date', $params['register_date']);
         if ($params['receive_date']) {
             $this->assign('receive_date', $params['receive_date']);
         }
         $participant = array(array('participant_id', '=', $participants[0]->id, 0, 0));
         // check whether its a test drive ref CRM-3075
         if (CRM_Utils_Array::value('is_test', $this->_defaultValues)) {
             $participant[] = array('participant_test', '=', 1, 0, 0);
         }
         $template =& CRM_Core_Smarty::singleton();
         $customGroup = array();
         //format submitted data
         foreach ($params['custom'] as $fieldID => $values) {
             foreach ($values as $fieldValue) {
                 $customValue = array('data' => $fieldValue['value']);
                 $customFields[$fieldID]['id'] = $fieldID;
                 $formattedValue = CRM_Core_BAO_CustomGroup::formatCustomValues($customValue, $customFields[$fieldID]);
                 $customGroup[$customFields[$fieldID]['groupTitle']][$customFields[$fieldID]['label']] = str_replace('&nbsp;', '', $formattedValue);
             }
         }
         foreach ($this->_contactIds as $num => $contactID) {
             // Retrieve the name and email of the contact - this will be the TO for receipt email
             list($this->_contributorDisplayName, $this->_contributorEmail, $this->_toDoNotEmail) = CRM_Contact_BAO_Contact::getContactDetails($contactID);
             $this->_contributorDisplayName = $this->_contributorDisplayName == ' ' ? $this->_contributorEmail : $this->_contributorDisplayName;
             $this->assign('customGroup', $customGroup);
             $this->assign('contactID', $contactID);
             $this->assign('participantID', $participants[$num]->id);
             if ($this->_isPaidEvent) {
                 // fix amount for each of participants ( for bulk mode )
                 $eventAmount = array();
                 $eventAmount[$num] = array('label' => $params['amount_level'], 'amount' => $params['fee_amount']);
                 //as we are using same template for online & offline registration.
                 //So we have to build amount as array.
                 $this->assign('amount', $eventAmount);
             }
             $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'event_offline_receipt', 'contactId' => $contactID, 'isTest' => (bool) CRM_Utils_Array::value('is_test', $this->_defaultValues));
             // try to send emails only if email id is present
             // and the do-not-email option is not checked for that contact
             if ($this->_contributorEmail and !$this->_toDoNotEmail) {
                 $sendTemplateParams['from'] = $receiptFrom;
                 $sendTemplateParams['toName'] = $this->_contributorDisplayName;
                 $sendTemplateParams['toEmail'] = $this->_contributorEmail;
             }
             require_once 'CRM/Core/BAO/MessageTemplates.php';
             list($mailSent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplates::sendTemplate($sendTemplateParams);
             if ($mailSent) {
                 $sent[] = $contactID;
             } else {
                 $notSent[] = $contactID;
             }
         }
     }
     if ($this->_action & CRM_Core_Action::UPDATE) {
         $statusMsg = ts('Event registration information for %1 has been updated.', array(1 => $this->_contributorDisplayName));
         if ($params['send_receipt'] && count($sent)) {
             $statusMsg .= ' ' . ts('A confirmation email has been sent to %1', array(1 => $this->_contributorEmail));
         }
         if ($updateStatusMsg) {
             $statusMsg = "{$statusMsg} {$updateStatusMsg}";
         }
     } elseif ($this->_action & CRM_Core_Action::ADD) {
         if ($this->_single) {
             $statusMsg = ts('Event registration for %1 has been added.', array(1 => $this->_contributorDisplayName));
             if (CRM_Utils_Array::value('send_receipt', $params) && count($sent)) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to %1.', array(1 => $this->_contributorEmail));
             }
         } else {
             $statusMsg = ts('Total Participant(s) added to event: %1.', array(1 => count($this->_contactIds)));
             if (count($notSent) > 0) {
                 $statusMsg .= ' ' . ts('Email has NOT been sent to %1 contact - communication preferences specify DO NOT EMAIL OR valid Email is NOT present. ', array(1 => count($notSent)));
             } elseif (isset($params['send_receipt'])) {
                 $statusMsg .= ' ' . ts('A confirmation email has been sent to ALL participants');
             }
         }
     }
     require_once "CRM/Core/Session.php";
     CRM_Core_Session::setStatus("{$statusMsg}");
     $buttonName = $this->controller->getButtonName();
     if ($this->_context == 'standalone') {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/participant/add', 'reset=1&action=add&context=standalone'));
         } else {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactID}&selectedChild=participant"));
         }
     } else {
         if ($buttonName == $this->getButtonName('upload', 'new')) {
             $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view/participant', "reset=1&action=add&context=participant&cid={$this->_contactID}"));
         }
     }
 }
Example #17
0
 /**
  * Process the Memberships
  *
  * @param array  $membershipParams array of membership fields
  * @param int    $contactID        contact id 
  * @param object $form             form object  
  *
  * @return void
  * @access public
  */
 public function postProcessMembership($membershipParams, $contactID, &$form, &$premiumParams)
 {
     $tempParams = $membershipParams;
     $paymentDone = false;
     $result = null;
     $isTest = CRM_Utils_Array::value('is_test', $membershipParams, false);
     $form->assign('membership_assign', true);
     $form->set('membershipTypeID', $membershipParams['selectMembership']);
     require_once 'CRM/Member/BAO/MembershipType.php';
     require_once 'CRM/Member/BAO/Membership.php';
     $membershipTypeID = $membershipParams['selectMembership'];
     $membershipDetails = self::buildMembershipTypeValues($form, $membershipTypeID);
     $form->assign('membership_name', $membershipDetails['name']);
     $minimumFee = CRM_Utils_Array::value('minimum_fee', $membershipDetails);
     $contributionTypeId = null;
     if ($form->_values['amount_block_is_active']) {
         $contributionTypeId = $form->_values['contribution_type_id'];
     } else {
         $paymentDone = true;
         $params['amount'] = $minimumFee;
         $contributionTypeId = $membershipDetails['contribution_type_id'];
     }
     //amount must be greater than zero for
     //adding contribution record  to contribution table.
     //this condition is arises when separate membership payment is
     //enable and contribution amount is not selected. fix for CRM-3010
     require_once 'CRM/Contribute/BAO/Contribution/Utils.php';
     if ($form->_amount > 0.0) {
         $result = CRM_Contribute_BAO_Contribution_Utils::processConfirm($form, $membershipParams, $premiumParams, $contactID, $contributionTypeId, 'membership');
     } else {
         // create the CMS contact here since we normally do this under processConfirm
         CRM_Contribute_BAO_Contribution_Utils::createCMSUser($membershipParams, $membershipParams['cms_contactID'], 'email-' . $form->_bltID);
     }
     $errors = array();
     if (is_a($result[1], 'CRM_Core_Error')) {
         $errors[1] = CRM_Core_Error::getMessages($result[1]);
     } else {
         $contribution[1] = $result[1];
     }
     $memBlockDetails = CRM_Member_BAO_Membership::getMembershipBlock($form->_id);
     if ($memBlockDetails['is_separate_payment'] && !$paymentDone) {
         require_once 'CRM/Contribute/DAO/ContributionType.php';
         $contributionType = new CRM_Contribute_DAO_ContributionType();
         $contributionType->id = $membershipDetails['contribution_type_id'];
         if (!$contributionType->find(true)) {
             CRM_Core_Error::fatal("Could not find a system table");
         }
         $tempParams['amount'] = $minimumFee;
         $invoiceID = md5(uniqid(rand(), true));
         $tempParams['invoiceID'] = $invoiceID;
         //we don't allow recurring membership.CRM-3781.
         if (CRM_Utils_Array::value('is_recur', $tempParams)) {
             $tempParams['is_recur'] = 0;
         }
         $result = null;
         if ($form->_values['is_monetary'] && !$form->_params['is_pay_later']) {
             require_once 'CRM/Core/Payment.php';
             $payment =& CRM_Core_Payment::singleton($form->_mode, $form->_paymentProcessor, $form);
             if ($form->_contributeMode == 'express') {
                 $result =& $payment->doExpressCheckout($tempParams);
             } else {
                 $result =& $payment->doDirectPayment($tempParams);
             }
         }
         if (is_a($result, 'CRM_Core_Error')) {
             $errors[2] = CRM_Core_Error::getMessages($result);
         } else {
             //assign receive date when separate membership payment
             //and contribution amount not selected.
             if ($form->_amount == 0) {
                 $now = date('YmdHis');
                 $form->_params['receive_date'] = $now;
                 $receiveDate = CRM_Utils_Date::mysqlToIso($now);
                 $form->set('params', $form->_params);
                 $form->assign('receive_date', $receiveDate);
             }
             $form->set('membership_trx_id', $result['trxn_id']);
             $form->set('membership_amount', $minimumFee);
             $form->assign('membership_trx_id', $result['trxn_id']);
             $form->assign('membership_amount', $minimumFee);
             // we dont need to create the user twice, so lets disable cms_create_account
             // irrespective of the value, CRM-2888
             $tempParams['cms_create_account'] = 0;
             $pending = $form->_params['is_pay_later'] ? true : false;
             //set this variable as we are not creating pledge for
             //separate membership payment contribution.
             //so for differentiating membership contributon from
             //main contribution.
             $form->_params['separate_membership_payment'] = 1;
             $contribution[2] = CRM_Contribute_Form_Contribution_Confirm::processContribution($form, $tempParams, $result, $contactID, $contributionType, false, $pending);
         }
     }
     $index = $memBlockDetails['is_separate_payment'] ? 2 : 1;
     if (!CRM_Utils_Array::value($index, $errors)) {
         $membership = self::renewMembership($contactID, $membershipTypeID, $isTest, $form, null, CRM_Utils_Array::value('cms_contactID', $membershipParams));
         if (isset($contribution[$index])) {
             //insert payment record
             require_once 'CRM/Member/DAO/MembershipPayment.php';
             $dao = new CRM_Member_DAO_MembershipPayment();
             $dao->membership_id = $membership->id;
             $dao->contribution_id = $contribution[$index]->id;
             //Fixed for avoiding duplicate entry error when user goes
             //back and forward during payment mode is notify
             if (!$dao->find(true)) {
                 CRM_Utils_Hook::pre('create', 'MembershipPayment', null, $dao);
                 $dao->save();
                 CRM_Utils_Hook::post('create', 'MembershipPayment', $dao->id, $dao);
             }
         }
     }
     require_once 'CRM/Core/BAO/CustomValueTable.php';
     CRM_Core_BAO_CustomValueTable::postProcess($form->_params, CRM_Core_DAO::$_nullArray, 'civicrm_membership', $membership->id, 'Membership');
     if (!empty($errors)) {
         foreach ($errors as $error) {
             if (is_string($error)) {
                 $message[] = $error;
             }
         }
         $message = ts("Payment Processor Error message") . ": " . implode('<br/>', $message);
         $session = CRM_Core_Session::singleton();
         $session->setStatus($message);
         CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$form->_params['qfKey']}"));
     }
     $form->_params['membershipID'] = $membership->id;
     if ($form->_contributeMode == 'notify') {
         if ($form->_values['is_monetary'] && $form->_amount > 0.0 && !$form->_params['is_pay_later']) {
             // this does not return
             require_once 'CRM/Core/Payment.php';
             $payment =& CRM_Core_Payment::singleton($form->_mode, $form->_paymentProcessor, $form);
             $payment->doTransferCheckout($form->_params, 'contribute');
         }
     }
     $form->_values['membership_id'] = $membership->id;
     if (isset($contribution[$index]->id)) {
         $form->_values['contribution_id'] = $contribution[$index]->id;
     }
     // Do not send an email if Recurring transaction is done via Direct Mode
     // Email will we sent when the IPN is received.
     if ($form->_params['is_recur'] && $form->_contributeMode == 'direct') {
         return true;
     }
     //finally send an email receipt
     require_once "CRM/Contribute/BAO/ContributionPage.php";
     CRM_Contribute_BAO_ContributionPage::sendMail($contactID, $form->_values, $isTest);
 }
Example #18
0
 /**
  * convert any given date string to default date array.
  *
  * @param array  $params     has given date-format
  * @param array  $formatted  store formatted date in this array
  * @param int    $dateType   type of date  
  * @param string $dateParam  index of params
  * @static
  */
 function formatCustomDate(&$params, &$formatted, $dateType, $dateParam)
 {
     //fix for CRM-2687
     CRM_Utils_Date::convertToDefaultDate($params, $dateType, $dateParam);
     if ($dateType == 1) {
         if (strstr($params[$dateParam], '-')) {
             $formatted[$dateParam] = CRM_Utils_Date::unformat($params[$dateParam]);
         } else {
             $formatted[$dateParam] = CRM_Utils_Date::unformat(CRM_Utils_Date::mysqlToIso($params[$dateParam]));
         }
     } else {
         $formatted[$dateParam] = CRM_Utils_Date::unformat(CRM_Utils_Date::mysqlToIso($params[$dateParam]));
     }
 }
Example #19
0
 /**
  * Function to process the form
  *
  * @access public
  * @return None
  */
 public function endPostProcess(&$form, &$params, $activity)
 {
     if (CRM_Utils_Array::value('start_date', $params)) {
         $params['start_date'] = CRM_Utils_Date::processDate($params['start_date']);
     }
     $caseType = $form->_caseType;
     if (!$caseType && $form->_caseId) {
         $query = "\nSELECT  cov_type.label as case_type FROM civicrm_case \nLEFT JOIN  civicrm_option_group cog_type ON cog_type.name = 'case_type'\nLEFT JOIN civicrm_option_value cov_type ON \n( civicrm_case.case_type_id = cov_type.value AND cog_type.id = cov_type.option_group_id ) \nWHERE civicrm_case.id=  %1";
         $queryParams = array(1 => array($form->_caseId, 'Integer'));
         $caseType = CRM_Core_DAO::singleValueQuery($query, $queryParams);
     }
     if (!$form->_currentlyViewedContactId || !$form->_currentUserId || !$form->_caseId || !$caseType) {
         CRM_Core_Error::fatal('Required parameter missing for ChangeCaseType - end post processing');
     }
     // 1. save activity subject with new start date
     $currentStartDate = CRM_Utils_Date::customFormat(CRM_Core_DAO::getFieldValue('CRM_Case_DAO_Case', $form->_caseId, 'start_date'));
     $newStartDate = CRM_Utils_Date::customFormat(CRM_Utils_Date::mysqlToIso($params['start_date']));
     $subject = 'Change Case Start Date from ' . $currentStartDate . ' to ' . $newStartDate;
     $activity->subject = $subject;
     $activity->save();
     // 2. initiate xml processor
     $xmlProcessor = new CRM_Case_XMLProcessor_Process();
     $xmlProcessorParams = array('clientID' => $form->_currentlyViewedContactId, 'creatorID' => $form->_currentUserId, 'standardTimeline' => 0, 'activity_date_time' => $params['start_date'], 'caseID' => $form->_caseId, 'caseType' => $caseType, 'activityTypeName' => 'Change Case Start Date', 'activitySetName' => 'standard_timeline', 'resetTimeline' => 1);
     $xmlProcessor->run($caseType, $xmlProcessorParams);
     // 3.status msg
     $params['statusMsg'] = ts('Case Start Date changed successfully.');
 }
Example #20
0
 /**
  * Where a second separate financial transaction is supported we will process it here.
  *
  * @param int $contactID
  * @param CRM_Contribute_Form_Contribution_Confirm $form
  * @param array $tempParams
  * @param $isTest
  * @param array $lineItems
  * @param $minimumFee
  * @param int $financialTypeID
  *
  * @throws CRM_Core_Exception
  * @throws Exception
  * @return CRM_Contribute_BAO_Contribution
  */
 public static function processSecondaryFinancialTransaction($contactID, &$form, $tempParams, $isTest, $lineItems, $minimumFee, $financialTypeID)
 {
     $financialType = new CRM_Financial_DAO_FinancialType();
     $financialType->id = $financialTypeID;
     if (!$financialType->find(TRUE)) {
         CRM_Core_Error::fatal(ts("Could not find a system table"));
     }
     $tempParams['amount'] = $minimumFee;
     $tempParams['invoiceID'] = md5(uniqid(rand(), TRUE));
     $result = NULL;
     if ($form->_values['is_monetary'] && !$form->_params['is_pay_later'] && $minimumFee > 0.0) {
         $payment = CRM_Core_Payment::singleton($form->_mode, $form->_paymentProcessor, $form);
         if ($form->_contributeMode == 'express') {
             $result = $payment->doExpressCheckout($tempParams);
             if (is_a($result, 'CRM_Core_Error')) {
                 throw new CRM_Core_Exception(CRM_Core_Error::getMessages($result));
             }
         } else {
             $result = $payment->doPayment($tempParams, 'contribute');
         }
     }
     //assign receive date when separate membership payment
     //and contribution amount not selected.
     if ($form->_amount == 0) {
         $now = date('YmdHis');
         $form->_params['receive_date'] = $now;
         $receiveDate = CRM_Utils_Date::mysqlToIso($now);
         $form->set('params', $form->_params);
         $form->assign('receive_date', $receiveDate);
     }
     $form->set('membership_trx_id', $result['trxn_id']);
     $form->set('membership_amount', $minimumFee);
     $form->assign('membership_trx_id', $result['trxn_id']);
     $form->assign('membership_amount', $minimumFee);
     // we don't need to create the user twice, so lets disable cms_create_account
     // irrespective of the value, CRM-2888
     $tempParams['cms_create_account'] = 0;
     //CRM-16165, scenarios are
     // 1) If contribution is_pay_later and if contribution amount is > 0.0 we set pending = TRUE, vice-versa FALSE
     // 2) If not pay later but auto-renewal membership is chosen then pending = TRUE as it later triggers
     //   pending recurring contribution, vice-versa FALSE
     $pending = $form->_params['is_pay_later'] ? $minimumFee > 0.0 ? TRUE : FALSE : (!empty($form->_params['auto_renew']) ? TRUE : FALSE);
     //set this variable as we are not creating pledge for
     //separate membership payment contribution.
     //so for differentiating membership contribution from
     //main contribution.
     $form->_params['separate_membership_payment'] = 1;
     $membershipContribution = CRM_Contribute_Form_Contribution_Confirm::processContribution($form, $tempParams, $result, $contactID, $financialType, $pending, TRUE, $isTest, $lineItems);
     return $membershipContribution;
 }
Example #21
0
 /**
  * Process that send e-mails
  *
  * @param $contactID
  * @param $values
  * @param $participantId
  * @param bool $isTest
  * @param bool $returnMessageText
  *
  * @return void
  * @access public
  */
 static function sendMail($contactID, &$values, $participantId, $isTest = FALSE, $returnMessageText = FALSE)
 {
     $template = CRM_Core_Smarty::singleton();
     $gIds = array('custom_pre_id' => $values['custom_pre_id'], 'custom_post_id' => $values['custom_post_id']);
     //get the params submitted by participant.
     $participantParams = CRM_Utils_Array::value($participantId, $values['params'], array());
     if (!$returnMessageText) {
         //send notification email if field values are set (CRM-1941)
         foreach ($gIds as $key => $gIdValues) {
             if ($gIdValues) {
                 if (!is_array($gIdValues)) {
                     $gIdValues = array($gIdValues);
                 }
                 foreach ($gIdValues as $gId) {
                     $email = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $gId, 'notify');
                     if ($email) {
                         //get values of corresponding profile fields for notification
                         list($profileValues) = self::buildCustomDisplay($gId, NULL, $contactID, $template, $participantId, $isTest, TRUE, $participantParams);
                         list($profileValues) = $profileValues;
                         $val = array('id' => $gId, 'values' => $profileValues, 'email' => $email);
                         CRM_Core_BAO_UFGroup::commonSendMail($contactID, $val);
                     }
                 }
             }
         }
     }
     if ($values['event']['is_email_confirm'] || $returnMessageText) {
         list($displayName, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($contactID);
         //send email only when email is present
         if (isset($email) || $returnMessageText) {
             $preProfileID = CRM_Utils_Array::value('custom_pre_id', $values);
             $postProfileID = CRM_Utils_Array::value('custom_post_id', $values);
             if (!empty($values['params']['additionalParticipant'])) {
                 $preProfileID = CRM_Utils_Array::value('additional_custom_pre_id', $values, $preProfileID);
                 $postProfileID = CRM_Utils_Array::value('additional_custom_post_id', $values, $postProfileID);
             }
             self::buildCustomDisplay($preProfileID, 'customPre', $contactID, $template, $participantId, $isTest, NULL, $participantParams);
             self::buildCustomDisplay($postProfileID, 'customPost', $contactID, $template, $participantId, $isTest, NULL, $participantParams);
             $sessions = CRM_Event_Cart_BAO_Conference::get_participant_sessions($participantId);
             $tplParams = array_merge($values, $participantParams, array('email' => $email, 'confirm_email_text' => CRM_Utils_Array::value('confirm_email_text', $values['event']), 'isShowLocation' => CRM_Utils_Array::value('is_show_location', $values['event']), 'contributeMode' => CRM_Utils_Array::value('contributeMode', $template->_tpl_vars), 'participantID' => $participantId, 'conference_sessions' => $sessions, 'credit_card_number' => CRM_Utils_System::mungeCreditCard(CRM_Utils_Array::value('credit_card_number', $participantParams)), 'credit_card_exp_date' => CRM_Utils_Date::mysqlToIso(CRM_Utils_Date::format(CRM_Utils_Array::value('credit_card_exp_date', $participantParams)))));
             // CRM-13890 : NOTE wait list condition need to be given so that
             // wait list message is shown properly in email i.e. WRT online event registration template
             if (empty($tplParams['participant_status']) && empty($values['params']['isOnWaitlist'])) {
                 $statusId = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Participant', $participantId, 'status_id', 'id');
                 $tplParams['participant_status'] = CRM_Event_PseudoConstant::participantStatus($statusId, NULL, 'label');
             }
             $sendTemplateParams = array('groupName' => 'msg_tpl_workflow_event', 'valueName' => 'event_online_receipt', 'contactId' => $contactID, 'isTest' => $isTest, 'tplParams' => $tplParams, 'PDFFilename' => ts('confirmation') . '.pdf');
             // address required during receipt processing (pdf and email receipt)
             if ($displayAddress = CRM_Utils_Array::value('address', $values)) {
                 $sendTemplateParams['tplParams']['address'] = $displayAddress;
                 $sendTemplateParams['tplParams']['contributeMode'] = NULL;
             }
             // set lineItem details
             if ($lineItem = CRM_Utils_Array::value('lineItem', $values)) {
                 // check if additional prticipant, if so filter only to relevant ones
                 // CRM-9902
                 if (!empty($values['params']['additionalParticipant'])) {
                     $ownLineItems = array();
                     foreach ($lineItem as $liKey => $liValue) {
                         $firstElement = array_pop($liValue);
                         if ($firstElement['entity_id'] == $participantId) {
                             $ownLineItems[0] = $lineItem[$liKey];
                             break;
                         }
                     }
                     if (!empty($ownLineItems)) {
                         $sendTemplateParams['tplParams']['lineItem'] = $ownLineItems;
                     }
                 } else {
                     $sendTemplateParams['tplParams']['lineItem'] = $lineItem;
                 }
             }
             if ($returnMessageText) {
                 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
                 return array('subject' => $subject, 'body' => $message, 'to' => $displayName, 'html' => $html);
             } else {
                 $sendTemplateParams['from'] = CRM_Utils_Array::value('confirm_from_name', $values['event']) . " <" . CRM_Utils_Array::value('confirm_from_email', $values['event']) . ">";
                 $sendTemplateParams['toName'] = $displayName;
                 $sendTemplateParams['toEmail'] = $email;
                 $sendTemplateParams['autoSubmitted'] = TRUE;
                 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_confirm', $values['event']);
                 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_confirm', $values['event']);
                 CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
             }
         }
     }
 }
 /**
  * @param $submittedValues
  */
 public function processCreditCard($submittedValues)
 {
     $config = CRM_Core_Config::singleton();
     $session = CRM_Core_Session::singleton();
     $unsetParams = array('trxn_id', 'payment_instrument_id', 'contribution_status_id');
     foreach ($unsetParams as $key) {
         if (isset($submittedValues[$key])) {
             unset($submittedValues[$key]);
         }
     }
     // Get the required fields value only.
     $params = $this->_params = $submittedValues;
     //get the payment processor id as per mode.
     //@todo unclear relevance of mode - seems like a lot of duplicated params here!
     $this->_params['payment_processor'] = $params['payment_processor_id'] = $this->_params['payment_processor_id'] = $submittedValues['payment_processor_id'] = $this->_paymentProcessor['id'];
     $now = date('YmdHis');
     $fields = array();
     // we need to retrieve email address
     if ($this->_context == 'standalone' && !empty($submittedValues['is_email_receipt'])) {
         list($this->userDisplayName, $this->userEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($this->_contactId);
         $this->assign('displayName', $this->userDisplayName);
     }
     //set email for primary location.
     $fields['email-Primary'] = 1;
     $params['email-Primary'] = $this->_contributorEmail;
     // now set the values for the billing location.
     foreach ($this->_fields as $name => $dontCare) {
         $fields[$name] = 1;
     }
     // also add location name to the array
     $params["address_name-{$this->_bltID}"] = CRM_Utils_Array::value('billing_first_name', $params) . ' ' . CRM_Utils_Array::value('billing_middle_name', $params) . ' ' . CRM_Utils_Array::value('billing_last_name', $params);
     $params["address_name-{$this->_bltID}"] = trim($params["address_name-{$this->_bltID}"]);
     $fields["address_name-{$this->_bltID}"] = 1;
     $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_contactId, 'contact_type');
     $nameFields = array('first_name', 'middle_name', 'last_name');
     foreach ($nameFields as $name) {
         $fields[$name] = 1;
         if (array_key_exists("billing_{$name}", $params)) {
             $params[$name] = $params["billing_{$name}"];
             $params['preserveDBName'] = TRUE;
         }
     }
     if (!empty($params['source'])) {
         unset($params['source']);
     }
     $contactID = CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_contactId, NULL, NULL, $ctype);
     // Add all the additional payment params we need.
     $this->_params["state_province-{$this->_bltID}"] = $this->_params["billing_state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvinceAbbreviation($this->_params["billing_state_province_id-{$this->_bltID}"]);
     $this->_params["country-{$this->_bltID}"] = $this->_params["billing_country-{$this->_bltID}"] = CRM_Core_PseudoConstant::countryIsoCode($this->_params["billing_country_id-{$this->_bltID}"]);
     if ($this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_CREDIT_CARD) {
         $this->_params['year'] = CRM_Core_Payment_Form::getCreditCardExpirationYear($this->_params);
         $this->_params['month'] = CRM_Core_Payment_Form::getCreditCardExpirationMonth($this->_params);
     }
     $this->_params['ip_address'] = CRM_Utils_System::ipAddress();
     $this->_params['amount'] = $this->_params['total_amount'];
     // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
     // function to get correct amount level consistently. Remove setting of the amount level in
     // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
     // to cover all variants.
     $this->_params['amount_level'] = 0;
     $this->_params['currencyID'] = CRM_Utils_Array::value('currency', $this->_params, $config->defaultCurrency);
     if (!empty($this->_params['trxn_date'])) {
         $this->_params['receive_date'] = CRM_Utils_Date::processDate($this->_params['trxn_date'], $this->_params['trxn_date_time']);
     }
     if (empty($this->_params['invoice_id'])) {
         $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
     } else {
         $this->_params['invoiceID'] = $this->_params['invoice_id'];
     }
     $this->assignBillingName($params);
     $this->assign('address', CRM_Utils_Address::getFormattedBillingAddressFieldsFromParameters($params, $this->_bltID));
     $date = CRM_Utils_Date::format($params['credit_card_exp_date']);
     $date = CRM_Utils_Date::mysqlToIso($date);
     $this->assign('credit_card_type', CRM_Utils_Array::value('credit_card_type', $params));
     $this->assign('credit_card_exp_date', $date);
     $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($params['credit_card_number']));
     //Add common data to formatted params
     CRM_Contribute_Form_AdditionalInfo::postProcessCommon($params, $this->_params, $this);
     // at this point we've created a contact and stored its address etc
     // all the payment processors expect the name and address to be in the
     // so we copy stuff over to first_name etc.
     $paymentParams = $this->_params;
     $paymentParams['contactID'] = $this->_contactId;
     CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
     // add some financial type details to the params list
     // if folks need to use it
     $paymentParams['contributionType_name'] = $this->_params['contributionType_name'] = $contributionType->name;
     $paymentParams['contributionPageID'] = NULL;
     if (!empty($this->_params['is_email_receipt'])) {
         $paymentParams['email'] = $this->_contributorEmail;
         $paymentParams['is_email_receipt'] = 1;
     } else {
         $paymentParams['is_email_receipt'] = 0;
         $this->_params['is_email_receipt'] = 0;
     }
     if (!empty($this->_params['receive_date'])) {
         $paymentParams['receive_date'] = $this->_params['receive_date'];
     }
     if (!empty($this->_params['receive_date'])) {
         $paymentParams['receive_date'] = $this->_params['receive_date'];
     }
     $result = NULL;
     if ($paymentParams['amount'] > 0.0) {
         try {
             // force a reget of the payment processor in case the form changed it, CRM-7179
             $payment = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
             $result = $payment->doPayment($paymentParams);
         } catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
             //set the contribution mode.
             $urlParams = "action=add&cid={$this->_contactId}&id={$this->_id}&component={$this->_component}";
             if ($this->_mode) {
                 $urlParams .= "&mode={$this->_mode}";
             }
             CRM_Core_Error::displaySessionError($result);
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/payment/add', $urlParams));
         }
     }
     if ($result) {
         $this->_params = array_merge($this->_params, $result);
     }
     if (empty($this->_params['receive_date'])) {
         $this->_params['receive_date'] = $now;
     }
     $this->set('params', $this->_params);
     // set source if not set
     if (empty($this->_params['source'])) {
         $userID = $session->get('userID');
         $userSortName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $userID, 'sort_name');
         $this->_params['source'] = ts('Submit Credit Card Payment by: %1', array(1 => $userSortName));
     }
     // process the additional payment
     $participantId = NULL;
     if ($this->_component == 'event') {
         $participantId = $this->_id;
     }
     $trxnRecord = CRM_Contribute_BAO_Contribution::recordAdditionalPayment($this->_contributionId, $submittedValues, $this->_paymentType, $participantId);
     if ($trxnRecord->id && !empty($this->_params['is_email_receipt'])) {
         $sendReceipt = $this->emailReceipt($this->_params);
     }
     if ($trxnRecord->id) {
         $statusMsg = ts('The payment record has been processed.');
         if (!empty($this->_params['is_email_receipt']) && $sendReceipt) {
             $statusMsg .= ' ' . ts('A receipt has been emailed to the contributor.');
         }
         CRM_Core_Session::setStatus($statusMsg, ts('Complete'), 'success');
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->_contactId}&selectedChild=participant"));
     }
 }
Example #23
0
 /**
  * Where a second separate financial transaction is supported we will process it here.
  *
  * @param int $contactID
  * @param CRM_Contribute_Form_Contribution_Confirm $form
  * @param array $tempParams
  * @param bool $isTest
  * @param array $lineItems
  * @param $minimumFee
  * @param int $financialTypeID
  *
  * @throws CRM_Core_Exception
  * @throws Exception
  * @return CRM_Contribute_BAO_Contribution
  */
 protected function processSecondaryFinancialTransaction($contactID, &$form, $tempParams, $isTest, $lineItems, $minimumFee, $financialTypeID)
 {
     $financialType = new CRM_Financial_DAO_FinancialType();
     $financialType->id = $financialTypeID;
     $financialType->find(TRUE);
     $tempParams['amount'] = $minimumFee;
     $tempParams['invoiceID'] = md5(uniqid(rand(), TRUE));
     $isRecur = CRM_Utils_Array::value('is_recur', $tempParams);
     //assign receive date when separate membership payment
     //and contribution amount not selected.
     if ($form->_amount == 0) {
         $now = date('YmdHis');
         $form->_params['receive_date'] = $now;
         $receiveDate = CRM_Utils_Date::mysqlToIso($now);
         $form->set('params', $form->_params);
         $form->assign('receive_date', $receiveDate);
     }
     $form->set('membership_amount', $minimumFee);
     $form->assign('membership_amount', $minimumFee);
     // we don't need to create the user twice, so lets disable cms_create_account
     // irrespective of the value, CRM-2888
     $tempParams['cms_create_account'] = 0;
     //set this variable as we are not creating pledge for
     //separate membership payment contribution.
     //so for differentiating membership contribution from
     //main contribution.
     $form->_params['separate_membership_payment'] = 1;
     $contributionParams = array('contact_id' => $contactID, 'line_item' => $lineItems, 'is_test' => $isTest, 'campaign_id' => CRM_Utils_Array::value('campaign_id', $tempParams, CRM_Utils_Array::value('campaign_id', $form->_values)), 'contribution_page_id' => $form->_id, 'source' => CRM_Utils_Array::value('source', $tempParams, CRM_Utils_Array::value('description', $tempParams)));
     $isMonetary = !empty($form->_values['is_monetary']);
     if ($isMonetary) {
         if (empty($paymentParams['is_pay_later'])) {
             $contributionParams['payment_instrument_id'] = $form->_paymentProcessor['payment_instrument_id'];
         }
     }
     $membershipContribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($form, $tempParams, $tempParams, $contributionParams, $financialType, TRUE, $form->_bltID, $isRecur);
     $result = array();
     if ($form->_values['is_monetary'] && !$form->_params['is_pay_later'] && $minimumFee > 0.0) {
         // At the moment our tests are calling this form in a way that leaves 'object' empty. For
         // now we compensate here.
         if (empty($form->_paymentProcessor['object'])) {
             $payment = Civi\Payment\System::singleton()->getByProcessor($this->_paymentProcessor);
         } else {
             $payment = $form->_paymentProcessor['object'];
         }
         $result = $payment->doPayment($tempParams, 'contribute');
         $form->set('membership_trx_id', $result['trxn_id']);
         $form->assign('membership_trx_id', $result['trxn_id']);
     }
     return array($membershipContribution, $result);
 }
 /**
  * @param $entityTable
  */
 public static function preProcess($entityTable)
 {
     self::$_entityId = (int) CRM_Utils_Request::retrieve('id', 'Positive');
     self::$_entityTable = $entityTable;
     if (self::$_entityId && $entityTable) {
         $checkParentExistsForThisId = CRM_Core_BAO_RecurringEntity::getParentFor(self::$_entityId, $entityTable);
         if ($checkParentExistsForThisId) {
             self::$_hasParent = TRUE;
             self::$_parentEntityId = $checkParentExistsForThisId;
             self::$_scheduleReminderDetails = CRM_Core_BAO_RecurringEntity::getReminderDetailsByEntityId($checkParentExistsForThisId, $entityTable);
         } else {
             self::$_parentEntityId = self::$_entityId;
             self::$_scheduleReminderDetails = CRM_Core_BAO_RecurringEntity::getReminderDetailsByEntityId(self::$_entityId, $entityTable);
         }
         if (property_exists(self::$_scheduleReminderDetails, 'id')) {
             self::$_scheduleReminderID = self::$_scheduleReminderDetails->id;
         }
     }
     CRM_Core_OptionValue::getValues(array('name' => $entityTable . '_repeat_exclude_dates_' . self::$_parentEntityId), $optionValue);
     $excludeOptionValues = array();
     if (!empty($optionValue)) {
         foreach ($optionValue as $key => $val) {
             $excludeOptionValues[$val['value']] = substr(CRM_Utils_Date::mysqlToIso($val['value']), 0, 10);
         }
         self::$_excludeDateInfo = $excludeOptionValues;
     }
     // Assign variables
     $entityType = CRM_Core_DAO_AllCoreTables::getBriefName(CRM_Core_DAO_AllCoreTables::getClassForTable($entityTable));
     $tpl = CRM_Core_Smarty::singleton();
     $tpl->assign('recurringEntityType', ts($entityType));
     $tpl->assign('currentEntityId', self::$_entityId);
     $tpl->assign('entityTable', self::$_entityTable);
     $tpl->assign('scheduleReminderId', self::$_scheduleReminderID);
     $tpl->assign('hasParent', self::$_hasParent);
 }
Example #25
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}"));
     }
 }
 /**
  * Process the form submission.
  *
  *
  * @param CRM_Core_Form $form
  * @param array $params
  * @param $activity
  */
 public static function endPostProcess(&$form, &$params, $activity)
 {
     if (!empty($params['start_date'])) {
         $params['start_date'] = CRM_Utils_Date::processDate($params['start_date'], $params['start_date_time']);
     }
     $caseType = CRM_Utils_Array::first($form->_caseType);
     $caseId = CRM_Utils_Array::first($form->_caseId);
     if (!$caseType && $caseId) {
         $caseType = CRM_Case_BAO_Case::getCaseType($caseId, 'title');
     }
     if (!$form->_currentlyViewedContactId || !$form->_currentUserId || !$caseId || !$caseType) {
         CRM_Core_Error::fatal('Required parameter missing for ChangeCaseType - end post processing');
     }
     $config = CRM_Core_Config::singleton();
     $params['status_id'] = CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name');
     $activity->status_id = $params['status_id'];
     $params['priority_id'] = CRM_Core_OptionGroup::getValue('priority', 'Normal', 'name');
     $activity->priority_id = $params['priority_id'];
     // 1. save activity subject with new start date
     $currentStartDate = CRM_Utils_Date::customFormat(CRM_Core_DAO::getFieldValue('CRM_Case_DAO_Case', $caseId, 'start_date'), $config->dateformatFull);
     $newStartDate = CRM_Utils_Date::customFormat(CRM_Utils_Date::mysqlToIso($params['start_date']), $config->dateformatFull);
     $subject = 'Change Case Start Date from ' . $currentStartDate . ' to ' . $newStartDate;
     $activity->subject = $subject;
     $activity->save();
     // 2. initiate xml processor
     $xmlProcessor = new CRM_Case_XMLProcessor_Process();
     $xmlProcessorParams = array('clientID' => $form->_currentlyViewedContactId, 'creatorID' => $form->_currentUserId, 'standardTimeline' => 0, 'activity_date_time' => $params['start_date'], 'caseID' => $caseId, 'caseType' => $caseType, 'activityTypeName' => 'Change Case Start Date', 'activitySetName' => 'standard_timeline', 'resetTimeline' => 1);
     $xmlProcessor->run($caseType, $xmlProcessorParams);
     // 2.5 Update open case activity date
     // Multiple steps since revisioned
     if ($form->openCaseActivityId) {
         $abao = new CRM_Activity_BAO_Activity();
         $oldParams = array('id' => $form->openCaseActivityId);
         $oldActivityDefaults = array();
         $oldActivity = $abao->retrieve($oldParams, $oldActivityDefaults);
         // save the old values
         require_once 'api/v3/utils.php';
         $openCaseParams = array();
         //@todo calling api functions directly is not supported
         _civicrm_api3_object_to_array($oldActivity, $openCaseParams);
         // update existing revision
         $oldParams = array('id' => $form->openCaseActivityId, 'is_current_revision' => 0);
         $oldActivity = new CRM_Activity_DAO_Activity();
         $oldActivity->copyValues($oldParams);
         $oldActivity->save();
         // change some params for the new one
         unset($openCaseParams['id']);
         $openCaseParams['activity_date_time'] = $params['start_date'];
         $openCaseParams['target_contact_id'] = $oldActivityDefaults['target_contact'];
         $openCaseParams['assignee_contact_id'] = $oldActivityDefaults['assignee_contact'];
         $session = CRM_Core_Session::singleton();
         $openCaseParams['source_contact_id'] = $session->get('userID');
         // original_id always refers to the first activity, so only update if null (i.e. this is the second revision)
         $openCaseParams['original_id'] = $openCaseParams['original_id'] ? $openCaseParams['original_id'] : $form->openCaseActivityId;
         $newActivity = CRM_Activity_BAO_Activity::create($openCaseParams);
         if (is_a($newActivity, 'CRM_Core_Error')) {
             CRM_Core_Error::fatal('Unable to update Open Case activity');
         } else {
             // Create linkage to case
             $caseActivityParams = array('activity_id' => $newActivity->id, 'case_id' => $caseId);
             CRM_Case_BAO_Case::processCaseActivity($caseActivityParams);
             $caseActivityParams = array('activityID' => $form->openCaseActivityId, 'mainActivityId' => $newActivity->id);
             CRM_Activity_BAO_Activity::copyExtendedActivityData($caseActivityParams);
         }
     }
     // 3.status msg
     $params['statusMsg'] = ts('Case Start Date changed successfully.');
 }
Example #27
0
 /**
  * Send email receipt.
  *
  * @param CRM_Core_Form $form
  *   Form object.
  * @param array $formValues
  * @param object $membership
  *   Object.
  *
  * @return bool
  *   true if mail was sent successfully
  */
 public static function emailReceipt(&$form, &$formValues, &$membership)
 {
     // retrieve 'from email id' for acknowledgement
     $receiptFrom = $formValues['from_email_address'];
     if (!empty($formValues['payment_instrument_id'])) {
         $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
         $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
     }
     // retrieve custom data
     $customFields = $customValues = array();
     if (property_exists($form, '_groupTree') && !empty($form->_groupTree)) {
         foreach ($form->_groupTree as $groupID => $group) {
             if ($groupID == 'info') {
                 continue;
             }
             foreach ($group['fields'] as $k => $field) {
                 $field['title'] = $field['label'];
                 $customFields["custom_{$k}"] = $field;
             }
         }
     }
     $members = array(array('member_id', '=', $membership->id, 0, 0));
     // check whether its a test drive
     if ($form->_mode == 'test') {
         $members[] = array('member_test', '=', 1, 0, 0);
     }
     CRM_Core_BAO_UFGroup::getValues($formValues['contact_id'], $customFields, $customValues, FALSE, $members);
     if ($form->_mode) {
         if (!empty($form->_params['billing_first_name'])) {
             $name = $form->_params['billing_first_name'];
         }
         if (!empty($form->_params['billing_middle_name'])) {
             $name .= " {$form->_params['billing_middle_name']}";
         }
         if (!empty($form->_params['billing_last_name'])) {
             $name .= " {$form->_params['billing_last_name']}";
         }
         $form->assign('billingName', $name);
         // assign the address formatted up for display
         $addressParts = array("street_address-{$form->_bltID}", "city-{$form->_bltID}", "postal_code-{$form->_bltID}", "state_province-{$form->_bltID}", "country-{$form->_bltID}");
         $addressFields = array();
         foreach ($addressParts as $part) {
             list($n, $id) = explode('-', $part);
             if (isset($form->_params['billing_' . $part])) {
                 $addressFields[$n] = $form->_params['billing_' . $part];
             }
         }
         $form->assign('address', CRM_Utils_Address::format($addressFields));
         $date = CRM_Utils_Date::format($form->_params['credit_card_exp_date']);
         $date = CRM_Utils_Date::mysqlToIso($date);
         $form->assign('credit_card_exp_date', $date);
         $form->assign('credit_card_number', CRM_Utils_System::mungeCreditCard($form->_params['credit_card_number']));
         $form->assign('credit_card_type', $form->_params['credit_card_type']);
         $form->assign('contributeMode', 'direct');
         $form->assign('isAmountzero', 0);
         $form->assign('is_pay_later', 0);
         $form->assign('isPrimary', 1);
     }
     $form->assign('module', 'Membership');
     $form->assign('contactID', $formValues['contact_id']);
     $form->assign('membershipID', CRM_Utils_Array::value('membership_id', $form->_params, CRM_Utils_Array::value('membership_id', $form->_defaultValues)));
     if (!empty($formValues['contribution_id'])) {
         $form->assign('contributionID', $formValues['contribution_id']);
     } elseif (isset($form->_onlinePendingContributionId)) {
         $form->assign('contributionID', $form->_onlinePendingContributionId);
     }
     if (!empty($formValues['contribution_status_id'])) {
         $form->assign('contributionStatusID', $formValues['contribution_status_id']);
         $form->assign('contributionStatus', CRM_Contribute_PseudoConstant::contributionStatus($formValues['contribution_status_id'], 'name'));
     }
     if (!empty($formValues['is_renew'])) {
         $form->assign('receiptType', 'membership renewal');
     } else {
         $form->assign('receiptType', 'membership signup');
     }
     $form->assign('receive_date', CRM_Utils_Date::processDate(CRM_Utils_Array::value('receive_date', $formValues)));
     $form->assign('formValues', $formValues);
     if (empty($lineItem)) {
         $form->assign('mem_start_date', CRM_Utils_Date::customFormat($membership->start_date, '%B %E%f, %Y'));
         if (!CRM_Utils_System::isNull($membership->end_date)) {
             $form->assign('mem_end_date', CRM_Utils_Date::customFormat($membership->end_date, '%B %E%f, %Y'));
         }
         $form->assign('membership_name', CRM_Member_PseudoConstant::membershipType($membership->membership_type_id));
     }
     $form->assign('customValues', $customValues);
     $isBatchProcess = is_a($form, 'CRM_Batch_Form_Entry');
     if (empty($form->_contributorDisplayName) || empty($form->_contributorEmail) || $isBatchProcess) {
         // in this case the form is being called statically from the batch editing screen
         // having one class in the form layer call another statically is not greate
         // & we should aim to move this function to the BAO layer in future.
         // however, we can assume that the contact_id passed in by the batch
         // function will be the recipient
         list($form->_contributorDisplayName, $form->_contributorEmail) = CRM_Contact_BAO_Contact_Location::getEmailDetails($formValues['contact_id']);
         if (empty($form->_receiptContactId) || $isBatchProcess) {
             $form->_receiptContactId = $formValues['contact_id'];
         }
     }
     $template = CRM_Core_Smarty::singleton();
     $taxAmt = $template->get_template_vars('dataArray');
     $eventTaxAmt = $template->get_template_vars('totalTaxAmount');
     $prefixValue = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
     $invoicing = CRM_Utils_Array::value('invoicing', $prefixValue);
     if ((!empty($taxAmt) || isset($eventTaxAmt)) && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
         $isEmailPdf = TRUE;
     } else {
         $isEmailPdf = FALSE;
     }
     list($mailSend, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_membership', 'valueName' => 'membership_offline_receipt', 'contactId' => $form->_receiptContactId, 'from' => $receiptFrom, 'toName' => $form->_contributorDisplayName, 'toEmail' => $form->_contributorEmail, 'PDFFilename' => ts('receipt') . '.pdf', 'isEmailPdf' => $isEmailPdf, 'contributionId' => $formValues['contribution_id'], 'isTest' => (bool) ($form->_action & CRM_Core_Action::PREVIEW)));
     return TRUE;
 }
Example #28
0
 /**
  * Process form submission.
  *
  * This function is also accessed by a unit test.
  */
 protected function submit()
 {
     $this->storeContactFields($this->_params);
     $this->beginPostProcess();
     $now = CRM_Utils_Date::getToday(NULL, 'YmdHis');
     $this->convertDateFieldsToMySQL($this->_params);
     $this->assign('receive_date', $this->_params['receive_date']);
     $this->processBillingAddress();
     list($userName) = CRM_Contact_BAO_Contact_Location::getEmailDetails(CRM_Core_Session::singleton()->get('userID'));
     $this->_params['total_amount'] = CRM_Utils_Array::value('total_amount', $this->_params, CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'minimum_fee'));
     $this->_membershipId = $this->_id;
     $customFieldsFormatted = CRM_Core_BAO_CustomField::postProcess($this->_params, $this->_id, 'Membership');
     if (empty($this->_params['financial_type_id'])) {
         $this->_params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_memType, 'financial_type_id');
     }
     $contributionRecurID = NULL;
     $this->assign('membershipID', $this->_id);
     $this->assign('contactID', $this->_contactID);
     $this->assign('module', 'Membership');
     $this->assign('receiptType', 'membership renewal');
     $this->_params['currencyID'] = CRM_Core_Config::singleton()->defaultCurrency;
     $this->_params['invoice_id'] = $this->_params['invoiceID'] = md5(uniqid(rand(), TRUE));
     if (!empty($this->_params['send_receipt'])) {
         $this->_params['receipt_date'] = $now;
         $this->assign('receipt_date', CRM_Utils_Date::mysqlToIso($this->_params['receipt_date']));
     } else {
         $this->_params['receipt_date'] = NULL;
     }
     if ($this->_mode) {
         $this->_params['register_date'] = $now;
         $this->_params['description'] = ts("Contribution submitted by a staff person using member's credit card for renewal");
         $this->_params['amount'] = $this->_params['total_amount'];
         // 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 passed params
         // so we copy stuff over to first_name etc.
         $paymentParams = $this->_params;
         if (!empty($this->_params['send_receipt'])) {
             $paymentParams['email'] = $this->_contributorEmail;
         }
         $paymentParams['contactID'] = $this->_contributorContactID;
         CRM_Core_Payment_Form::mapParams($this->_bltID, $this->_params, $paymentParams, TRUE);
         $payment = $this->_paymentProcessor['object'];
         if (!empty($this->_params['auto_renew'])) {
             $contributionRecurParams = $this->processRecurringContribution($paymentParams);
             $contributionRecurID = $contributionRecurParams['contributionRecurID'];
             $paymentParams = array_merge($paymentParams, $contributionRecurParams);
         }
         $result = $payment->doPayment($paymentParams);
         $this->_params = array_merge($this->_params, $result);
         $this->_params['contribution_status_id'] = $result['payment_status_id'];
         $this->_params['trxn_id'] = $result['trxn_id'];
         $this->_params['payment_instrument_id'] = 1;
         $this->_params['is_test'] = $this->_mode == 'live' ? 0 : 1;
         $this->set('params', $this->_params);
         $this->assign('trxn_id', $result['trxn_id']);
     }
     $renewalDate = !empty($this->_params['renewal_date']) ? $renewalDate = CRM_Utils_Date::processDate($this->_params['renewal_date']) : NULL;
     // check for test membership.
     $isTestMembership = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership', $this->_membershipId, 'is_test');
     // chk for renewal for multiple terms CRM-8750
     $numRenewTerms = 1;
     if (is_numeric(CRM_Utils_Array::value('num_terms', $this->_params))) {
         $numRenewTerms = $this->_params['num_terms'];
     }
     //if contribution status is pending then set pay later
     $this->_params['is_pay_later'] = FALSE;
     if ($this->_params['contribution_status_id'] == array_search('Pending', CRM_Contribute_PseudoConstant::contributionStatus())) {
         $this->_params['is_pay_later'] = 1;
     }
     // These variable sets prior to renewMembership may not be required for this form. They were in
     // a function this form shared with other forms.
     $membershipSource = NULL;
     if (!empty($this->_params['membership_source'])) {
         $membershipSource = $this->_params['membership_source'];
     }
     $isPending = $this->_params['contribution_status_id'] == 2 ? TRUE : FALSE;
     list($renewMembership) = CRM_Member_BAO_Membership::renewMembership($this->_contactID, $this->_params['membership_type_id'][1], $isTestMembership, $renewalDate, NULL, $customFieldsFormatted, $numRenewTerms, $this->_membershipId, $isPending, $contributionRecurID, $membershipSource, $this->_params['is_pay_later'], CRM_Utils_Array::value('campaign_id', $this->_params));
     $this->endDate = CRM_Utils_Date::processDate($renewMembership->end_date);
     $this->membershipTypeName = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $renewMembership->membership_type_id, 'name');
     if (!empty($this->_params['record_contribution']) || $this->_mode) {
         // set the source
         $this->_params['contribution_source'] = "{$this->membershipTypeName} Membership: Offline membership renewal (by {$userName})";
         //create line items
         $lineItem = array();
         $this->_params = $this->setPriceSetParameters($this->_params);
         CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $this->_params, $lineItem[$this->_priceSetId]);
         //CRM-11529 for quick config backoffice transactions
         //when financial_type_id is passed in form, update the
         //line items with the financial type selected in form
         if ($submittedFinancialType = CRM_Utils_Array::value('financial_type_id', $this->_params)) {
             foreach ($lineItem[$this->_priceSetId] as &$li) {
                 $li['financial_type_id'] = $submittedFinancialType;
             }
         }
         if (!empty($lineItem)) {
             $this->_params['lineItems'] = $lineItem;
             $this->_params['processPriceSet'] = TRUE;
         }
         //assign contribution contact id to the field expected by recordMembershipContribution
         if ($this->_contributorContactID != $this->_contactID) {
             $this->_params['contribution_contact_id'] = $this->_contributorContactID;
             if (!empty($this->_params['soft_credit_type_id'])) {
                 $this->_params['soft_credit'] = array('soft_credit_type_id' => $this->_params['soft_credit_type_id'], 'contact_id' => $this->_contactID);
             }
         }
         $this->_params['contact_id'] = $this->_contactID;
         //recordMembershipContribution receives params as a reference & adds one variable. This is
         // not a great pattern & ideally it would not receive as a reference. We assign our params as a
         // temporary variable to avoid e-notice & to make it clear to future refactorer that
         // this function is NOT reliant on that var being set
         $temporaryParams = array_merge($this->_params, array('membership_id' => $renewMembership->id));
         CRM_Member_BAO_Membership::recordMembershipContribution($temporaryParams);
     }
     if (!empty($this->_params['send_receipt'])) {
         $receiptFrom = $this->_params['from_email_address'];
         if (!empty($this->_params['payment_instrument_id'])) {
             $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
             $this->_params['paidBy'] = $paymentInstrument[$this->_params['payment_instrument_id']];
         }
         //get the group Tree
         $this->_groupTree = CRM_Core_BAO_CustomGroup::getTree('Membership', $this, $this->_id, FALSE, $this->_memType);
         // retrieve custom data
         $customFields = $customValues = $fo = array();
         foreach ($this->_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', '=', $this->_membershipId, 0, 0));
         // check whether its a test drive
         if ($this->_mode == 'test') {
             $members[] = array('member_test', '=', 1, 0, 0);
         }
         CRM_Core_BAO_UFGroup::getValues($this->_contactID, $customFields, $customValues, FALSE, $members);
         $this->assign_by_ref('formValues', $this->_params);
         if (!empty($this->_params['contribution_id'])) {
             $this->assign('contributionID', $this->_params['contribution_id']);
         }
         $this->assign('membership_name', CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $renewMembership->membership_type_id));
         $this->assign('customValues', $customValues);
         $this->assign('mem_start_date', CRM_Utils_Date::customFormat($renewMembership->start_date));
         $this->assign('mem_end_date', CRM_Utils_Date::customFormat($renewMembership->end_date));
         if ($this->_mode) {
             // 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) = explode('-', $part);
                 if (isset($this->_params['billing_' . $part])) {
                     $addressFields[$n] = $this->_params['billing_' . $part];
                 }
             }
             $this->assign('address', CRM_Utils_Address::format($addressFields));
             $this->assign('contributeMode', 'direct');
             $this->assign('isAmountzero', 0);
             $this->assign('is_pay_later', 0);
             $this->assign('isPrimary', 1);
             $this->assign('receipt_text_renewal', $this->_params['receipt_text']);
             if ($this->_mode == 'test') {
                 $this->assign('action', '1024');
             }
         }
         list($this->isMailSent) = CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_membership', 'valueName' => 'membership_offline_receipt', 'contactId' => $this->_receiptContactId, 'from' => $receiptFrom, 'toName' => $this->_contributorDisplayName, 'toEmail' => $this->_contributorEmail, 'isTest' => $this->_mode == 'test'));
     }
 }
Example #29
0
 /**
  * Assign the minimal set of variables to the template.
  */
 public function assignToTemplate()
 {
     //process only primary participant params
     $this->_params = $this->get('params');
     if (isset($this->_params[0])) {
         $params = $this->_params[0];
     }
     $name = '';
     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);
     $this->set('name', $name);
     $vars = array('amount', 'currencyID', 'credit_card_type', 'trxn_id', 'amount_level', 'receive_date');
     foreach ($vars as $v) {
         if (!empty($params[$v])) {
             if ($v == 'receive_date') {
                 $this->assign($v, CRM_Utils_Date::mysqlToIso($params[$v]));
             } else {
                 $this->assign($v, $params[$v]);
             }
         } elseif (CRM_Utils_Array::value('amount', $params) == 0) {
             $this->assign($v, CRM_Utils_Array::value($v, $params));
         }
     }
     // 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($params['billing_' . $part])) {
             $addressFields[$n] = CRM_Utils_Array::value('billing_' . $part, $params);
         }
     }
     $this->assign('address', CRM_Utils_Address::format($addressFields));
     // The concept of contributeMode is deprecated.
     if ($this->_contributeMode == 'direct' && empty($params['is_pay_later'])) {
         $date = CRM_Utils_Date::format(CRM_Utils_Array::value('credit_card_exp_date', $params));
         $date = CRM_Utils_Date::mysqlToIso($date);
         $this->assign('credit_card_exp_date', $date);
         $this->assign('credit_card_number', CRM_Utils_System::mungeCreditCard(CRM_Utils_Array::value('credit_card_number', $params)));
     }
     // get the email that the confirmation would have been sent to
     $session = CRM_Core_Session::singleton();
     // assign is_email_confirm to templates
     if (isset($this->_values['event']['is_email_confirm'])) {
         $this->assign('is_email_confirm', $this->_values['event']['is_email_confirm']);
     }
     // assign pay later stuff
     $params['is_pay_later'] = CRM_Utils_Array::value('is_pay_later', $params, FALSE);
     $this->assign('is_pay_later', $params['is_pay_later']);
     if ($params['is_pay_later']) {
         $this->assign('pay_later_text', $this->_values['event']['pay_later_text']);
         $this->assign('pay_later_receipt', $this->_values['event']['pay_later_receipt']);
     }
     // also assign all participantIDs to the template
     // useful in generating confirmation numbers if needed
     $this->assign('participantIDs', $this->_participantIDS);
 }
Example #30
0
 /**
  * Process payment after confirmation.
  *
  * @param CRM_Core_Form $form
  *   Form object.
  * @param array $paymentParams
  *   Array with payment related key.
  *   value pairs
  * @param int $contactID
  *   Contact id.
  * @param int $contributionTypeId
  *   Financial type id.
  * @param int|string $component component id
  * @param $isTest
  *
  * @throws CRM_Core_Exception
  * @throws Exception
  * @return array
  *   associated array
  *
  */
 public static function processConfirm(&$form, &$paymentParams, $contactID, $contributionTypeId, $component = 'contribution', $isTest)
 {
     CRM_Core_Payment_Form::mapParams($form->_bltID, $form->_params, $paymentParams, TRUE);
     $lineItems = $form->_lineItem;
     $isPaymentTransaction = self::isPaymentTransaction($form);
     $financialType = new CRM_Financial_DAO_FinancialType();
     $financialType->id = $contributionTypeId;
     $financialType->find(TRUE);
     if ($financialType->is_deductible) {
         $form->assign('is_deductible', TRUE);
         $form->set('is_deductible', TRUE);
     }
     // add some financial type details to the params list
     // if folks need to use it
     //CRM-15297 - contributionType is obsolete - pass financial type as well so people can deprecate it
     $paymentParams['financialType_name'] = $paymentParams['contributionType_name'] = $form->_params['contributionType_name'] = $financialType->name;
     //CRM-11456
     $paymentParams['financialType_accounting_code'] = $paymentParams['contributionType_accounting_code'] = $form->_params['contributionType_accounting_code'] = CRM_Financial_BAO_FinancialAccount::getAccountingCode($contributionTypeId);
     $paymentParams['contributionPageID'] = $form->_params['contributionPageID'] = $form->_values['id'];
     $paymentParams['contactID'] = $form->_params['contactID'] = $contactID;
     //fix for CRM-16317
     $form->_params['receive_date'] = date('YmdHis');
     $form->assign('receive_date', CRM_Utils_Date::mysqlToIso($form->_params['receive_date']));
     if ($isPaymentTransaction) {
         // Fix for CRM-14354. If the membership is recurring, don't create a
         // civicrm_contribution_recur record for the additional contribution
         // (i.e., the amount NOT associated with the membership). Temporarily
         // cache the is_recur values so we can process the additional gift as a
         // one-off payment.
         if (!empty($form->_values['is_recur'])) {
             if ($form->_membershipBlock['is_separate_payment'] && !empty($form->_params['auto_renew'])) {
                 $cachedFormValue = CRM_Utils_Array::value('is_recur', $form->_values);
                 $cachedParamValue = CRM_Utils_Array::value('is_recur', $paymentParams);
                 unset($form->_values['is_recur']);
                 unset($paymentParams['is_recur']);
             }
         }
         $contributionParams = array('contact_id' => $contactID, 'line_item' => $lineItems, 'is_test' => $isTest, 'campaign_id' => CRM_Utils_Array::value('campaign_id', $paymentParams, CRM_Utils_Array::value('campaign_id', $form->_values)), 'contribution_page_id' => $form->_id, 'source' => CRM_Utils_Array::value('source', $paymentParams, CRM_Utils_Array::value('description', $paymentParams)));
         $isMonetary = !empty($form->_values['is_monetary']);
         if ($isMonetary) {
             if (empty($paymentParams['is_pay_later'])) {
                 // @todo look up payment_instrument_id on payment processor table.
                 $contributionParams['payment_instrument_id'] = 1;
             }
         }
         $contribution = CRM_Contribute_Form_Contribution_Confirm::processFormContribution($form, $paymentParams, NULL, $contributionParams, $financialType, TRUE, TRUE, $form->_bltID);
         $paymentParams['contributionTypeID'] = $contributionTypeId;
         $paymentParams['item_name'] = $form->_params['description'];
         if ($contribution && $form->_values['is_recur'] && $contribution->contribution_recur_id) {
             $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
         }
         $paymentParams['qfKey'] = $form->controller->_key;
         if ($component == 'membership') {
             return array('contribution' => $contribution);
         }
         // restore cached values (part of fix for CRM-14354)
         if (!empty($cachedFormValue)) {
             $form->_values['is_recur'] = $cachedFormValue;
             $paymentParams['is_recur'] = $cachedParamValue;
         }
         $paymentParams['contributionID'] = $contribution->id;
         //CRM-15297 deprecate contributionTypeID
         $paymentParams['financialTypeID'] = $paymentParams['contributionTypeID'] = $contribution->financial_type_id;
         $paymentParams['contributionPageID'] = $contribution->contribution_page_id;
         if (isset($paymentParams['contribution_source'])) {
             $paymentParams['source'] = $paymentParams['contribution_source'];
         }
         if ($form->_values['is_recur'] && $contribution->contribution_recur_id) {
             $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id;
         }
         if ($form->_contributeMode && $form->_amount > 0.0) {
             try {
                 $payment = Civi\Payment\System::singleton()->getByProcessor($form->_paymentProcessor);
                 if ($form->_contributeMode == 'notify') {
                     // We want to get rid of this & make it generic - eg. by making payment processing the last thing
                     // and always calling it first.
                     $form->postProcessHook();
                 }
                 $result = $payment->doPayment($paymentParams);
                 $form->_params = array_merge($form->_params, $result);
                 $form->assign('trxn_id', CRM_Utils_Array::value('trxn_id', $result));
                 if (!empty($result['trxn_id'])) {
                     $contribution->trxn_id = $result['trxn_id'];
                 }
                 if (!empty($result['payment_status_id'])) {
                     $contribution->payment_status_id = $result['payment_status_id'];
                 }
                 $result['contribution'] = $contribution;
                 return $result;
             } catch (\Civi\Payment\Exception\PaymentProcessorException $e) {
                 // Clean up DB as appropriate.
                 if (!empty($paymentParams['contributionID'])) {
                     CRM_Contribute_BAO_Contribution::failPayment($paymentParams['contributionID'], $paymentParams['contactID'], $e->getMessage());
                 }
                 if (!empty($paymentParams['contributionRecurID'])) {
                     CRM_Contribute_BAO_ContributionRecur::deleteRecurContribution($paymentParams['contributionRecurID']);
                 }
                 $result['is_payment_failure'] = TRUE;
                 $result['error'] = $e;
                 return $result;
             }
         }
     }
     // Only pay later or unpaid should reach this point. The theory is that paylater should get a receipt now &
     // processor
     // transaction receipts should be outcome driven.
     $form->set('params', $form->_params);
     if (isset($paymentParams['contribution_source'])) {
         $form->_params['source'] = $paymentParams['contribution_source'];
     }
     // get the price set values for receipt.
     if ($form->_priceSetId && $form->_lineItem) {
         $form->_values['lineItem'] = $form->_lineItem;
         $form->_values['priceSetID'] = $form->_priceSetId;
     }
     $form->_values['contribution_id'] = $contribution->id;
     $form->_values['contribution_page_id'] = $contribution->contribution_page_id;
     CRM_Contribute_BAO_ContributionPage::sendMail($contactID, $form->_values, $contribution->is_test);
 }