/** * Evaluate the content of a single token. * * @param \Civi\Token\TokenRow $row * The record for which we want token values. * @param string $field * The name of the token field. * @param mixed $prefetch * Any data that was returned by the prefetch(). * @return mixed */ public function evaluateToken(\Civi\Token\TokenRow $row, $entity, $field, $prefetch = NULL) { $actionSearchResult = $row->context['actionSearchResult']; if ($field == 'location') { $loc = array(); $stateProvince = \CRM_Core_PseudoConstant::stateProvince(); $loc['street_address'] = $actionSearchResult->street_address; $loc['city'] = $actionSearchResult->city; $loc['state_province'] = \CRM_Utils_Array::value($actionSearchResult->state_province_id, $stateProvince); $loc['postal_code'] = $actionSearchResult->postal_code; //$entityTokenParams[$tokenEntity][$field] = \CRM_Utils_Address::format($loc); $row->tokens($entity, $field, \CRM_Utils_Address::format($loc)); } elseif ($field == 'info_url') { $row->tokens($entity, $field, \CRM_Utils_System::url('civicrm/event/info', 'reset=1&id=' . $actionSearchResult->event_id, TRUE, NULL, FALSE)); } elseif ($field == 'registration_url') { $row->tokens($entity, $field, \CRM_Utils_System::url('civicrm/event/register', 'reset=1&id=' . $actionSearchResult->event_id, TRUE, NULL, FALSE)); } elseif (in_array($field, array('start_date', 'end_date'))) { $row->tokens($entity, $field, \CRM_Utils_Date::customFormat($actionSearchResult->{$field})); } elseif ($field == 'balance') { if ($actionSearchResult->entityTable == 'civicrm_contact') { $balancePay = 'N/A'; } elseif (!empty($actionSearchResult->entityID)) { $info = \CRM_Contribute_BAO_Contribution::getPaymentInfo($actionSearchResult->entityID, 'event'); $balancePay = \CRM_Utils_Array::value('balance', $info); $balancePay = \CRM_Utils_Money::format($balancePay); } $row->tokens($entity, $field, $balancePay); } elseif ($field == 'fee_amount') { $row->tokens($entity, $field, \CRM_Utils_Money::format($actionSearchResult->{$field})); } elseif (isset($actionSearchResult->{$field})) { $row->tokens($entity, $field, $actionSearchResult->{$field}); } else { $row->tokens($entity, $field, ''); } }
/** * function that takes an address object and gets the latitude / longitude for this * address. Note that at a later stage, we could make this function also clean up * the address into a more valid format * * @param object $address * * @return boolean true if we modified the address, false otherwise * @static */ function format(&$values) { require_once 'CRM/Utils/Address.php'; // we need a valid zipcode, state and country, else we ignore if (!CRM_Utils_Array::value('postal_code', $values) && !CRM_Utils_Array::value('state_province', $values) && !CRM_Utils_Array::value('country', $values)) { return false; } if ($values['country'] != 'United States') { return false; } $string = CRM_Utils_Address::format($values); $string = str_replace("\n", ', ', $string); if (!$string) { return false; } $params = array(new XML_RPC_Value($string, 'string')); $message = new XML_RPC_Message('geocode', $params); $client = new XML_RPC_Client($GLOBALS['_CRM_UTILS_GEOCODE_RPC']['_uri'], $GLOBALS['_CRM_UTILS_GEOCODE_RPC']['_server']); $response = $client->send($message); if (!$response && !$response->faultCode()) { return false; } $data = XML_RPC_decode($response->value()); if (!CRM_Utils_Array::value(0, $data)) { return false; } $data = $data[0]; $values['geo_code_1'] = $data['lat']; $values['geo_code_2'] = $data['long']; return true; }
public function testAddressFormat() { $contact = $this->callAPISuccess('contact', 'create', array('first_name' => 'Micky', 'last_name' => 'mouse', 'contact_type' => 'Individual')); $address = $this->callAPISuccess('address', 'create', array('street_address' => '1 Happy Place', 'city' => 'Miami', 'state_province' => 'Flordia', 'country' => 'United States', 'postal_code' => 33101, 'contact_id' => $contact['id'], 'location_type_id' => 5, 'is_primary' => 1)); $addressDetails = $address['values'][$address['id']]; $countries = CRM_Core_PseudoConstant::country(); $addressDetails['country'] = $countries[$addressDetails['country_id']]; $formatted_address = CRM_Utils_Address::format($addressDetails, 'mailing_format', FALSE, TRUE); $this->assertTrue((bool) strstr($formatted_address, 'UNITED STATES')); }
public function updateConstructedNames() { require_once 'CRM/Utils/Address.php'; require_once 'CRM/Core/BAO/Preferences.php'; require_once 'CRM/Core/DAO.php'; require_once 'CRM/Core/PseudoConstant.php'; require_once 'CRM/Contact/BAO/Contact.php'; //handle individuals using settings in the system $query = "SELECT * FROM civicrm_contact WHERE contact_type = 'Individual';"; $dao = CRM_Core_DAO::executeQuery($query); $prefixes = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id'); $suffixes = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'suffix_id'); $tokens = array(); CRM_Utils_Hook::tokens($tokens); $tokenFields = array(); foreach ($tokens as $category => $catTokens) { foreach ($catTokens as $token) { $tokenFields[] = $token; } } //determine sort name construction $sortFormat = CRM_Core_BAO_Preferences::value('sort_name_format'); $sortFormat = str_replace('contact.', '', $sortFormat); //determine display name construction $displayFormat = CRM_Core_BAO_Preferences::value('display_name_format'); $displayFormat = str_replace('contact.', '', $displayFormat); while ($dao->fetch()) { $contactID = $dao->id; $params = array('first_name' => $dao->first_name, 'middle_name' => $dao->middle_name, 'last_name' => $dao->last_name, 'prefix_id' => $dao->prefix_id, 'suffix_id' => $dao->suffix_id); $params['individual_prefix'] = $prefixes[$dao->prefix_id]; $params['individual_suffix'] = $suffixes[$dao->suffix_id]; $sortName = CRM_Utils_Address::format($params, $sortFormat, FALSE, FALSE, TRUE, $tokenFields); $sortName = trim(CRM_Core_DAO::escapeString($sortName)); $displayName = CRM_Utils_Address::format($params, $displayFormat, FALSE, FALSE, TRUE, $tokenFields); $displayName = trim(CRM_Core_DAO::escapeString($displayName)); //check for email if (empty($sortName) || empty($displayName)) { $email = NULL; $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contactID); if (empty($email)) { $email = $contactID; } if (empty($sortName)) { $sortName = $email; } if (empty($displayName)) { $displayName = $email; } } //update record $updateQuery = "UPDATE civicrm_contact SET display_name = '{$displayName}', sort_name = '{$sortName}' WHERE id = {$contactID};"; CRM_Core_DAO::executeQuery($updateQuery); } //end indiv echo "\n Individuals recached... "; //set organizations $query = "UPDATE civicrm_contact\n\t\t SET display_name = organization_name,\n\t\t\t\t sort_name = organization_name\n\t\t\t WHERE contact_type = 'Organization';"; $dao = CRM_Core_DAO::executeQuery($query); echo "\n Organizations recached... "; //set households $query = "UPDATE civicrm_contact\n\t\t SET display_name = household_name,\n\t\t\t\t sort_name = household_name\n\t\t\t WHERE contact_type = 'Household';"; $dao = CRM_Core_DAO::executeQuery($query); echo "\n Households recached... "; }
/** * function to get the complete information for one or more events * * @param date $start get events with start date >= this date * @param integer $type get events on the a specific event type (by event_type_id) * @param integer $eventId return a single event - by event id * @param date $end also get events with end date >= this date * @param boolean $onlyPublic include public events only, default TRUE * * @return array $all array of all the events that are searched * @static * @access public */ static function &getCompleteInfo($start = NULL, $type = NULL, $eventId = NULL, $end = NULL, $onlyPublic = TRUE) { $publicCondition = NULL; if ($onlyPublic) { $publicCondition = " AND civicrm_event.is_public = 1"; } $dateCondition = ''; // if start and end date are NOT passed, return all events with start_date OR end_date >= today CRM-5133 if ($start) { // get events with start_date >= requested start $startDate = CRM_Utils_Type::escape($start, 'Date'); $dateCondition .= " AND ( civicrm_event.start_date >= {$startDate} )"; } if ($end) { // also get events with end_date <= requested end $endDate = CRM_Utils_Type::escape($end, 'Date'); $dateCondition .= " AND ( civicrm_event.end_date <= '{$endDate}' ) "; } // CRM-9421 and CRM-8620 Default mode for ical/rss feeds. No start or end filter passed. // Need to exclude old events with only start date // and not exclude events in progress (start <= today and end >= today). DGG if (empty($start) && empty($end)) { // get events with end date >= today, not sure of this logic // but keeping this for backward compatibility as per issue CRM-5133 $today = date("Y-m-d G:i:s"); $dateCondition .= " AND ( civicrm_event.end_date >= '{$today}' OR civicrm_event.start_date >= '{$today}' ) "; } if ($type) { $typeCondition = " AND civicrm_event.event_type_id = " . CRM_Utils_Type::escape($type, 'Integer'); } // Get the Id of Option Group for Event Types $optionGroupDAO = new CRM_Core_DAO_OptionGroup(); $optionGroupDAO->name = 'event_type'; $optionGroupId = NULL; if ($optionGroupDAO->find(TRUE)) { $optionGroupId = $optionGroupDAO->id; } $query = "\nSELECT\n civicrm_event.id as event_id,\n civicrm_email.email as email,\n civicrm_event.title as title,\n civicrm_event.summary as summary,\n civicrm_event.start_date as start,\n civicrm_event.end_date as end,\n civicrm_event.description as description,\n civicrm_event.is_show_location as is_show_location,\n civicrm_event.is_online_registration as is_online_registration,\n civicrm_event.registration_link_text as registration_link_text,\n civicrm_event.registration_start_date as registration_start_date,\n civicrm_event.registration_end_date as registration_end_date,\n civicrm_option_value.label as event_type,\n civicrm_address.name as address_name,\n civicrm_address.street_address as street_address,\n civicrm_address.supplemental_address_1 as supplemental_address_1,\n civicrm_address.supplemental_address_2 as supplemental_address_2,\n civicrm_address.city as city,\n civicrm_address.postal_code as postal_code,\n civicrm_address.postal_code_suffix as postal_code_suffix,\n civicrm_state_province.abbreviation as state,\n civicrm_country.name AS country\nFROM civicrm_event\nLEFT JOIN civicrm_loc_block ON civicrm_event.loc_block_id = civicrm_loc_block.id\nLEFT JOIN civicrm_address ON civicrm_loc_block.address_id = civicrm_address.id\nLEFT JOIN civicrm_state_province ON civicrm_address.state_province_id = civicrm_state_province.id\nLEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id\nLEFT JOIN civicrm_email ON civicrm_loc_block.email_id = civicrm_email.id\nLEFT JOIN civicrm_option_value ON (\n civicrm_event.event_type_id = civicrm_option_value.value AND\n civicrm_option_value.option_group_id = %1 )\nWHERE civicrm_event.is_active = 1\n AND (is_template = 0 OR is_template IS NULL)\n {$publicCondition}\n {$dateCondition}"; if (isset($typeCondition)) { $query .= $typeCondition; } if (isset($eventId)) { $query .= " AND civicrm_event.id ={$eventId} "; } $query .= " ORDER BY civicrm_event.start_date ASC"; $params = array(1 => array($optionGroupId, 'Integer')); $dao = CRM_Core_DAO::executeQuery($query, $params); $all = array(); $config = CRM_Core_Config::singleton(); $baseURL = parse_url($config->userFrameworkBaseURL); $url = "@" . $baseURL['host']; if (!empty($baseURL['path'])) { $url .= substr($baseURL['path'], 0, -1); } // check 'view event info' permission //@todo - per CRM-14626 we have resolved that 'view event info' means 'view ALL event info' // and passing in the specific permission here will short-circuit the evaluation of permission to // see specific events (doesn't seem relevant to this call // however, since this function is accessed only by a convoluted call from a joomla block function // it seems safer not to touch here. Suggestion is that CRM_Core_Permission::check(array or relevant permissions) would // be clearer & safer here $permissions = CRM_Core_Permission::event(CRM_Core_Permission::VIEW); // check if we're in shopping cart mode for events $enable_cart = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::EVENT_PREFERENCES_NAME, 'enable_cart'); if ($enable_cart) { } while ($dao->fetch()) { if (!empty($permissions) && in_array($dao->event_id, $permissions)) { $info = array(); $info['uid'] = "CiviCRM_EventID_{$dao->event_id}_" . md5($config->userFrameworkBaseURL) . $url; $info['title'] = $dao->title; $info['event_id'] = $dao->event_id; $info['summary'] = $dao->summary; $info['description'] = $dao->description; $info['start_date'] = $dao->start; $info['end_date'] = $dao->end; $info['contact_email'] = $dao->email; $info['event_type'] = $dao->event_type; $info['is_show_location'] = $dao->is_show_location; $info['is_online_registration'] = $dao->is_online_registration; $info['registration_link_text'] = $dao->registration_link_text; $info['registration_start_date'] = $dao->registration_start_date; $info['registration_end_date'] = $dao->registration_end_date; $address = ''; $addrFields = array('address_name' => $dao->address_name, 'street_address' => $dao->street_address, 'supplemental_address_1' => $dao->supplemental_address_1, 'supplemental_address_2' => $dao->supplemental_address_2, 'city' => $dao->city, 'state_province' => $dao->state, 'postal_code' => $dao->postal_code, 'postal_code_suffix' => $dao->postal_code_suffix, 'country' => $dao->country, 'county' => NULL); CRM_Utils_String::append($address, ', ', CRM_Utils_Address::format($addrFields)); $info['location'] = $address; $info['url'] = CRM_Utils_System::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id, TRUE, NULL, FALSE); if ($enable_cart) { $reg = CRM_Event_Cart_BAO_EventInCart::get_registration_link($dao->event_id); $info['registration_link'] = CRM_Utils_System::url($reg['path'], $reg['query'], TRUE); $info['registration_link_text'] = $reg['label']; } $all[] = $info; } } return $all; }
/** * 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; }
/** * Assign the minimal set of variables to the template. */ public function assignToTemplate() { $name = CRM_Utils_Array::value('billing_first_name', $this->_params); if (!empty($this->_params['billing_middle_name'])) { $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']) && !empty($this->_paymentProcessor['is_recur'])) { $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')); } // @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. 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 == "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 (!empty($this->_params['onbehalf_profile_id']) && !empty($this->_params['onbehalf'])) { $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 (!empty($this->_params['selectMembership'])) { $memFee = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $this->_params['selectMembership'], 'minimum_fee'); if ($memFee > 0.0) { $assignCCInfo = TRUE; } } // The concept of contributeMode is deprecated. // The payment processor object can provide info about the fields it shows. if ($this->_contributeMode == 'direct' && $assignCCInfo) { if ($this->_paymentProcessor && $this->_paymentProcessor['payment_type'] & CRM_Core_Payment::PAYMENT_TYPE_DIRECT_DEBIT) { $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']); } }
/** * 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; }
/** * Replace all the org-level tokens in $str * * @param string $str * The string with tokens to be replaced. * @param object $org * Associative array of org properties. * @param bool $html * Replace tokens with HTML or plain text. * * @param bool $escapeSmarty * * @return string * The processed string */ public static function &replaceOrgTokens($str, &$org, $html = FALSE, $escapeSmarty = FALSE) { self::$_tokens['org'] = array_merge(array_keys(CRM_Contact_BAO_Contact::importableFields('Organization')), array('address', 'display_name', 'checksum', 'contact_id')); $cv = NULL; foreach (self::$_tokens['org'] as $token) { // print "Getting token value for $token<br/><br/>"; if ($token == '') { continue; } // If the string doesn't contain this token, skip it. if (!self::token_match('org', $token, $str)) { continue; } // Construct value from $token and $contact $value = NULL; if ($cfID = CRM_Core_BAO_CustomField::getKeyID($token)) { // only generate cv if we need it if ($cv === NULL) { $cv = CRM_Core_BAO_CustomValue::getContactValues($org['contact_id']); } foreach ($cv as $cvFieldID => $value) { if ($cvFieldID == $cfID) { $value = CRM_Core_BAO_CustomOption::getOptionLabel($cfID, $value); break; } } } elseif ($token == 'checksum') { $cs = CRM_Contact_BAO_Contact_Utils::generateChecksum($org['contact_id']); $value = "cs={$cs}"; } elseif ($token == 'address') { // Build the location values array $loc = array(); $loc['display_name'] = CRM_Utils_Array::retrieveValueRecursive($org, 'display_name'); $loc['street_address'] = CRM_Utils_Array::retrieveValueRecursive($org, 'street_address'); $loc['city'] = CRM_Utils_Array::retrieveValueRecursive($org, 'city'); $loc['state_province'] = CRM_Utils_Array::retrieveValueRecursive($org, 'state_province'); $loc['postal_code'] = CRM_Utils_Array::retrieveValueRecursive($org, 'postal_code'); // Construct the address token $value = CRM_Utils_Address::format($loc); if ($html) { $value = str_replace("\n", '<br />', $value); } } else { $value = CRM_Utils_Array::retrieveValueRecursive($org, $token); } self::token_replace('org', $token, $value, $str, $escapeSmarty); } return $str; }
/** * process the form after the input has been submitted and validated * * @access public * * @return void */ public function postProcess() { $fv = $this->controller->exportValues($this->_name); $config = CRM_Core_Config::singleton(); $locName = NULL; //get the address format sequence from the config file $mailingFormat = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'mailing_format'); $sequence = CRM_Utils_Address::sequence($mailingFormat); foreach ($sequence as $v) { $address[$v] = 1; } if (array_key_exists('postal_code', $address)) { $address['postal_code_suffix'] = 1; } //build the returnproperties $returnProperties = array('display_name' => 1, 'contact_type' => 1); $mailingFormat = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'mailing_format'); $mailingFormatProperties = array(); if ($mailingFormat) { $mailingFormatProperties = self::getReturnProperties($mailingFormat); $returnProperties = array_merge($returnProperties, $mailingFormatProperties); } //we should not consider addressee for data exists, CRM-6025 if (array_key_exists('addressee', $mailingFormatProperties)) { unset($mailingFormatProperties['addressee']); } $customFormatProperties = array(); if (stristr($mailingFormat, 'custom_')) { foreach ($mailingFormatProperties as $token => $true) { if (substr($token, 0, 7) == 'custom_') { if (empty($customFormatProperties[$token])) { $customFormatProperties[$token] = $mailingFormatProperties[$token]; } } } } if (!empty($customFormatProperties)) { $returnProperties = array_merge($returnProperties, $customFormatProperties); } if (isset($fv['merge_same_address'])) { // we need first name/last name for summarising to avoid spillage $returnProperties['first_name'] = 1; $returnProperties['last_name'] = 1; } $individualFormat = FALSE; /* * CRM-8338: replace ids of household members with the id of their household * so we can merge labels by household. */ if (isset($fv['merge_same_household'])) { $this->mergeContactIdsByHousehold(); $individualFormat = TRUE; } //get the contacts information $params = array(); if (!empty($fv['location_type_id'])) { $locType = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); $locName = $locType[$fv['location_type_id']]; $location = array('location' => array("{$locName}" => $address)); $returnProperties = array_merge($returnProperties, $location); $params[] = array('location_type', '=', array($fv['location_type_id'] => 1), 0, 0); } else { $returnProperties = array_merge($returnProperties, $address); } $rows = array(); foreach ($this->_contactIds as $key => $contactID) { $params[] = array(CRM_Core_Form::CB_PREFIX . $contactID, '=', 1, 0, 0); } // fix for CRM-2651 if (!empty($fv['do_not_mail'])) { $params[] = array('do_not_mail', '=', 0, 0, 0); } // fix for CRM-2613 $params[] = array('is_deceased', '=', 0, 0, 0); $custom = array(); foreach ($returnProperties as $name => $dontCare) { $cfID = CRM_Core_BAO_CustomField::getKeyID($name); if ($cfID) { $custom[] = $cfID; } } //get the total number of contacts to fetch from database. $numberofContacts = count($this->_contactIds); $query = new CRM_Contact_BAO_Query($params, $returnProperties); $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts); $messageToken = CRM_Utils_Token::getTokens($mailingFormat); // also get all token values CRM_Utils_Hook::tokenValues($details[0], $this->_contactIds, NULL, $messageToken, 'CRM_Contact_Form_Task_Label'); $tokens = array(); CRM_Utils_Hook::tokens($tokens); $tokenFields = array(); foreach ($tokens as $category => $catTokens) { foreach ($catTokens as $token => $tokenName) { $tokenFields[] = $token; } } foreach ($this->_contactIds as $value) { foreach ($custom as $cfID) { if (isset($details[0][$value]["custom_{$cfID}"])) { $details[0][$value]["custom_{$cfID}"] = CRM_Core_BAO_CustomField::getDisplayValue($details[0][$value]["custom_{$cfID}"], $cfID, $details[1]); } } $contact = CRM_Utils_Array::value($value, $details['0']); if (is_a($contact, 'CRM_Core_Error')) { return NULL; } // we need to remove all the "_id" unset($contact['contact_id']); if ($locName && !empty($contact[$locName])) { // If location type is not primary, $contact contains // one more array as "$contact[$locName] = array( values... )" if (!$this->tokenIsFound($contact, $mailingFormatProperties, $tokenFields)) { continue; } unset($contact[$locName]); if (!empty($contact['county_id'])) { unset($contact['county_id']); } foreach ($contact as $field => $fieldValue) { $rows[$value][$field] = $fieldValue; } $valuesothers = array(); $paramsothers = array('contact_id' => $value); $valuesothers = CRM_Core_BAO_Location::getValues($paramsothers, $valuesothers); if (!empty($fv['location_type_id'])) { foreach ($valuesothers as $vals) { if (CRM_Utils_Array::value('location_type_id', $vals) == CRM_Utils_Array::value('location_type_id', $fv)) { foreach ($vals as $k => $v) { if (in_array($k, array('email', 'phone', 'im', 'openid'))) { if ($k == 'im') { $rows[$value][$k] = $v['1']['name']; } else { $rows[$value][$k] = $v['1'][$k]; } $rows[$value][$k . '_id'] = $v['1']['id']; } } } } } } else { if (!$this->tokenIsFound($contact, $mailingFormatProperties, $tokenFields)) { continue; } if (!empty($contact['addressee_display'])) { $contact['addressee_display'] = trim($contact['addressee_display']); } if (!empty($contact['addressee'])) { $contact['addressee'] = $contact['addressee_display']; } // now create the rows for generating mailing labels foreach ($contact as $field => $fieldValue) { $rows[$value][$field] = $fieldValue; } } } if (isset($fv['merge_same_address'])) { $this->mergeSameAddress($rows); $individualFormat = TRUE; } // format the addresses according to CIVICRM_ADDRESS_FORMAT (CRM-1327) foreach ($rows as $id => $row) { if ($commMethods = CRM_Utils_Array::value('preferred_communication_method', $row)) { $val = array_filter(explode(CRM_Core_DAO::VALUE_SEPARATOR, $commMethods)); $comm = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method'); $temp = array(); foreach ($val as $vals) { $temp[] = $comm[$vals]; } $row['preferred_communication_method'] = implode(', ', $temp); } $row['id'] = $id; $formatted = CRM_Utils_Address::format($row, 'mailing_format', FALSE, TRUE, $individualFormat, $tokenFields); // CRM-2211: UFPDF doesn't have bidi support; use the PECL fribidi package to fix it. // On Ubuntu (possibly Debian?) be aware of http://pecl.php.net/bugs/bug.php?id=12366 // Due to FriBidi peculiarities, this can't be called on // a multi-line string, hence the explode+implode approach. if (function_exists('fribidi_log2vis')) { $lines = explode("\n", $formatted); foreach ($lines as $i => $line) { $lines[$i] = fribidi_log2vis($line, FRIBIDI_AUTO, FRIBIDI_CHARSET_UTF8); } $formatted = implode("\n", $lines); } $rows[$id] = array($formatted); } //call function to create labels self::createLabel($rows, $fv['label_name']); CRM_Utils_System::civiExit(1); }
/** * function to get the complete information for one or more events * * @param date $start get events with start date >= this date * @param integer $type get events on the a specific event type (by event_type_id) * @param integer $eventId return a single event - by event id * @param date $end also get events with end date >= this date * * @return array $all array of all the events that are searched * @static * @access public */ static function &getCompleteInfo($start = null, $type = null, $eventId = null, $end = null) { // if start and end date are NOT passed, return all events with start_date OR end_date >= today CRM-5133 if ($start) { // get events with start_date >= requested start $startDate = CRM_Utils_Type::escape($start, 'Date'); } else { // get events with start date >= today $startDate = date("Ymd"); } if ($end) { // also get events with end_date >= requested end $endDate = CRM_Utils_Type::escape($end, 'Date'); } else { // OR also get events with end date >= today $endDate = date("Ymd"); } $dateCondition = "AND (civicrm_event.start_date >= {$startDate} OR civicrm_event.end_date >= {$endDate})"; if ($type) { $typeCondition = " AND civicrm_event.event_type_id = " . CRM_Utils_Type::escape($type, 'Integer'); } // Get the Id of Option Group for Event Types require_once 'CRM/Core/DAO/OptionGroup.php'; $optionGroupDAO = new CRM_Core_DAO_OptionGroup(); $optionGroupDAO->name = 'event_type'; $optionGroupId = null; if ($optionGroupDAO->find(true)) { $optionGroupId = $optionGroupDAO->id; } $query = "\nSELECT\n civicrm_event.id as event_id, \n civicrm_email.email as email, \n civicrm_event.title as title, \n civicrm_event.summary as summary, \n civicrm_event.start_date as start, \n civicrm_event.end_date as end, \n civicrm_event.description as description, \n civicrm_event.is_show_location as is_show_location, \n civicrm_event.is_online_registration as is_online_registration,\n civicrm_event.registration_link_text as registration_link_text,\n civicrm_event.registration_start_date as registration_start_date,\n civicrm_event.registration_end_date as registration_end_date,\n civicrm_option_value.label as event_type, \n civicrm_address.name as address_name, \n civicrm_address.street_address as street_address, \n civicrm_address.supplemental_address_1 as supplemental_address_1, \n civicrm_address.supplemental_address_2 as supplemental_address_2, \n civicrm_address.city as city, \n civicrm_address.postal_code as postal_code, \n civicrm_address.postal_code_suffix as postal_code_suffix, \n civicrm_state_province.abbreviation as state, \n civicrm_country.name AS country\nFROM civicrm_event\nLEFT JOIN civicrm_loc_block ON civicrm_event.loc_block_id = civicrm_loc_block.id\nLEFT JOIN civicrm_address ON civicrm_loc_block.address_id = civicrm_address.id\nLEFT JOIN civicrm_state_province ON civicrm_address.state_province_id = civicrm_state_province.id\nLEFT JOIN civicrm_country ON civicrm_address.country_id = civicrm_country.id\nLEFT JOIN civicrm_email ON civicrm_loc_block.email_id = civicrm_email.id\nLEFT JOIN civicrm_option_value ON (\n civicrm_event.event_type_id = civicrm_option_value.value AND\n civicrm_option_value.option_group_id = %1 )\nWHERE civicrm_event.is_active = 1 \n AND civicrm_event.is_public = 1\n AND (is_template = 0 OR is_template IS NULL)\n {$dateCondition}"; if (isset($typeCondition)) { $query .= $typeCondition; } if (isset($eventId)) { $query .= " AND civicrm_event.id ={$eventId} "; } $query .= " ORDER BY civicrm_event.start_date ASC"; $params = array(1 => array($optionGroupId, 'Integer')); $dao =& CRM_Core_DAO::executeQuery($query, $params); $all = array(); $config = CRM_Core_Config::singleton(); $baseURL = parse_url($config->userFrameworkBaseURL); $url = "@" . $baseURL['host']; if (CRM_Utils_Array::value('path', $baseURL)) { $url .= substr($baseURL['path'], 0, -1); } // check 'view event info' permission $permissions = CRM_Core_Permission::event(CRM_Core_Permission::VIEW); require_once 'CRM/Utils/String.php'; while ($dao->fetch()) { if (in_array($dao->event_id, $permissions)) { $info = array(); $info['uid'] = "CiviCRM_EventID_{$dao->event_id}_" . md5($config->userFrameworkBaseURL) . $url; $info['title'] = $dao->title; $info['event_id'] = $dao->event_id; $info['summary'] = $dao->summary; $info['description'] = $dao->description; $info['start_date'] = $dao->start; $info['end_date'] = $dao->end; $info['contact_email'] = $dao->email; $info['event_type'] = $dao->event_type; $info['is_show_location'] = $dao->is_show_location; $info['is_online_registration'] = $dao->is_online_registration; $info['registration_link_text'] = $dao->registration_link_text; $info['registration_start_date'] = $dao->registration_start_date; $info['registration_end_date'] = $dao->registration_end_date; $address = ''; $addrFields = array('address_name' => $dao->address_name, 'street_address' => $dao->street_address, 'supplemental_address_1' => $dao->supplemental_address_1, 'supplemental_address_2' => $dao->supplemental_address_2, 'city' => $dao->city, 'state_province' => $dao->state, 'postal_code' => $dao->postal_code, 'postal_code_suffix' => $dao->postal_code_suffix, 'country' => $dao->country, 'county' => null); require_once 'CRM/Utils/Address.php'; CRM_Utils_String::append($address, ', ', CRM_Utils_Address::format($addrFields)); $info['location'] = $address; $info['url'] = CRM_Utils_System::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id, true, null, false); $all[] = $info; } } return $all; }
/** * 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'); }
/** * @param $mappingID * @param $now * * @throws CRM_Core_Exception */ static function sendMailings($mappingID, $now) { $domainValues = CRM_Core_BAO_Domain::getNameAndEmail(); $fromEmailAddress = "{$domainValues['0']} <{$domainValues['1']}>"; $mapping = new CRM_Core_DAO_ActionMapping(); $mapping->id = $mappingID; $mapping->find(TRUE); $actionSchedule = new CRM_Core_DAO_ActionSchedule(); $actionSchedule->mapping_id = $mappingID; $actionSchedule->is_active = 1; $actionSchedule->find(FALSE); $tokenFields = array(); $session = CRM_Core_Session::singleton(); while ($actionSchedule->fetch()) { $extraSelect = $extraJoin = $extraWhere = $extraOn = ''; if ($actionSchedule->from_email) { $fromEmailAddress = "{$actionSchedule->from_name} <{$actionSchedule->from_email}>"; } if ($actionSchedule->record_activity) { if ($mapping->entity == 'civicrm_membership') { $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Membership Renewal Reminder', 'name'); } else { $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type', 'Reminder Sent', 'name'); } $activityStatusID = CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name'); } if ($mapping->entity == 'civicrm_activity') { $tokenEntity = 'activity'; $tokenFields = array('activity_id', 'activity_type', 'subject', 'details', 'activity_date_time'); $extraSelect = ', ov.label as activity_type, e.id as activity_id'; $extraJoin = "\nINNER JOIN civicrm_option_group og ON og.name = 'activity_type'\nINNER JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id"; $extraOn = ' AND e.is_current_revision = 1 AND e.is_deleted = 0 '; if ($actionSchedule->limit_to == 0) { $extraJoin = "\nLEFT JOIN civicrm_option_group og ON og.name = 'activity_type'\nLEFT JOIN civicrm_option_value ov ON e.activity_type_id = ov.value AND ov.option_group_id = og.id"; } } if ($mapping->entity == 'civicrm_participant') { $tokenEntity = 'event'; $tokenFields = array('event_type', 'title', 'event_id', 'start_date', 'end_date', 'summary', 'description', 'location', 'info_url', 'registration_url', 'fee_amount', 'contact_email', 'contact_phone', 'balance'); $extraSelect = ', ov.label as event_type, ev.title, ev.id as event_id, ev.start_date, ev.end_date, ev.summary, ev.description, address.street_address, address.city, address.state_province_id, address.postal_code, email.email as contact_email, phone.phone as contact_phone '; $extraJoin = "\nINNER JOIN civicrm_event ev ON e.event_id = ev.id\nINNER JOIN civicrm_option_group og ON og.name = 'event_type'\nINNER JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id\nLEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id\nLEFT JOIN civicrm_address address ON address.id = lb.address_id\nLEFT JOIN civicrm_email email ON email.id = lb.email_id\nLEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id\n"; if ($actionSchedule->limit_to == 0) { $extraJoin = "\nLEFT JOIN civicrm_event ev ON e.event_id = ev.id\nLEFT JOIN civicrm_option_group og ON og.name = 'event_type'\nLEFT JOIN civicrm_option_value ov ON ev.event_type_id = ov.value AND ov.option_group_id = og.id\nLEFT JOIN civicrm_loc_block lb ON lb.id = ev.loc_block_id\nLEFT JOIN civicrm_address address ON address.id = lb.address_id\nLEFT JOIN civicrm_email email ON email.id = lb.email_id\nLEFT JOIN civicrm_phone phone ON phone.id = lb.phone_id\n"; } } if ($mapping->entity == 'civicrm_membership') { $tokenEntity = 'membership'; $tokenFields = array('fee', 'id', 'join_date', 'start_date', 'end_date', 'status', 'type'); $extraSelect = ', mt.minimum_fee as fee, e.id as id , e.join_date, e.start_date, e.end_date, ms.name as status, mt.name as type'; $extraJoin = ' INNER JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id INNER JOIN civicrm_membership_status ms ON e.status_id = ms.id'; if ($actionSchedule->limit_to == 0) { $extraJoin = ' LEFT JOIN civicrm_membership_type mt ON e.membership_type_id = mt.id LEFT JOIN civicrm_membership_status ms ON e.status_id = ms.id'; } } if ($mapping->entity == 'civicrm_contact') { $tokenEntity = 'contact'; //TODO: get full list somewhere! $tokenFields = array('birth_date', 'last_name'); //TODO: is there anything to add here? } $entityJoinClause = "INNER JOIN {$mapping->entity} e ON e.id = reminder.entity_id"; if ($actionSchedule->limit_to == 0) { $entityJoinClause = "LEFT JOIN {$mapping->entity} e ON e.id = reminder.entity_id"; $extraWhere .= " AND (e.id = reminder.entity_id OR reminder.entity_table = 'civicrm_contact')"; } $entityJoinClause .= $extraOn; $query = "\nSELECT reminder.id as reminderID, reminder.contact_id as contactID, reminder.*, e.id as entityID, e.* {$extraSelect}\nFROM civicrm_action_log reminder\n{$entityJoinClause}\n{$extraJoin}\nWHERE reminder.action_schedule_id = %1 AND reminder.action_date_time IS NULL\n{$extraWhere}"; $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($actionSchedule->id, 'Integer'))); while ($dao->fetch()) { $entityTokenParams = array(); foreach ($tokenFields as $field) { if ($field == 'location') { $loc = array(); $stateProvince = CRM_Core_PseudoConstant::stateProvince(); $loc['street_address'] = $dao->street_address; $loc['city'] = $dao->city; $loc['state_province'] = CRM_Utils_Array::value($dao->state_province_id, $stateProvince); $loc['postal_code'] = $dao->postal_code; $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Address::format($loc); } elseif ($field == 'info_url') { $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System::url('civicrm/event/info', 'reset=1&id=' . $dao->event_id, TRUE, NULL, FALSE); } elseif ($field == 'registration_url') { $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_System::url('civicrm/event/register', 'reset=1&id=' . $dao->event_id, TRUE, NULL, FALSE); } elseif (in_array($field, array('start_date', 'end_date', 'join_date', 'activity_date_time'))) { $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Date::customFormat($dao->{$field}); } elseif ($field == 'balance') { $info = CRM_Contribute_BAO_Contribution::getPaymentInfo($dao->entityID, 'event'); $balancePay = CRM_Utils_Array::value('balance', $info); $balancePay = CRM_Utils_Money::format($balancePay); $entityTokenParams["{$tokenEntity}." . $field] = $balancePay; } elseif ($field == 'fee_amount') { $entityTokenParams["{$tokenEntity}." . $field] = CRM_Utils_Money::format($dao->{$field}); } else { $entityTokenParams["{$tokenEntity}." . $field] = $dao->{$field}; } } $isError = 0; $errorMsg = $toEmail = $toPhoneNumber = ''; if ($actionSchedule->mode == 'SMS' or $actionSchedule->mode == 'User_Preference') { $filters = array('is_deceased' => 0, 'is_deleted' => 0, 'do_not_sms' => 0); $toPhoneNumbers = CRM_Core_BAO_Phone::allPhones($dao->contactID, FALSE, 'Mobile', $filters); //to get primary mobile ph,if not get a first mobile phONE if (!empty($toPhoneNumbers)) { $toPhoneNumberDetails = reset($toPhoneNumbers); $toPhoneNumber = CRM_Utils_Array::value('phone', $toPhoneNumberDetails); //contact allows to send sms $toDoNotSms = 0; } } if ($actionSchedule->mode == 'Email' or $actionSchedule->mode == 'User_Preference') { $toEmail = CRM_Contact_BAO_Contact::getPrimaryEmail($dao->contactID); } if ($toEmail || !(empty($toPhoneNumber) or $toDoNotSms)) { $to['email'] = $toEmail; $to['phone'] = $toPhoneNumber; $result = CRM_Core_BAO_ActionSchedule::sendReminder($dao->contactID, $to, $actionSchedule->id, $fromEmailAddress, $entityTokenParams); if (!$result || is_a($result, 'PEAR_Error')) { // we could not send an email, for now we ignore, CRM-3406 $isError = 1; } } else { $isError = 1; $errorMsg = "Couldn\\'t find recipient\\'s email address."; } // update action log record $logParams = array('id' => $dao->reminderID, 'is_error' => $isError, 'message' => $errorMsg ? $errorMsg : "null", 'action_date_time' => $now); CRM_Core_BAO_ActionLog::create($logParams); // insert activity log record if needed if ($actionSchedule->record_activity) { $activityParams = array('subject' => $actionSchedule->title, 'details' => $actionSchedule->body_html, 'source_contact_id' => $session->get('userID') ? $session->get('userID') : $dao->contactID, 'target_contact_id' => $dao->contactID, 'activity_date_time' => date('YmdHis'), 'status_id' => $activityStatusID, 'activity_type_id' => $activityTypeID, 'source_record_id' => $dao->entityID); $activity = CRM_Activity_BAO_Activity::create($activityParams); } } $dao->free(); } }
/** * Process the form after the input has been submitted and validated. * * * @return void */ public function postProcess() { $formValues = $this->controller->exportValues($this->_name); $locationTypeID = $formValues['location_type_id']; $respectDoNotMail = CRM_Utils_Array::value('do_not_mail', $formValues); $labelName = $formValues['label_name']; $mergeSameAddress = CRM_Utils_Array::value('merge_same_address', $formValues); $mergeSameHousehold = CRM_Utils_Array::value('merge_same_household', $formValues); $isPerMembership = CRM_Utils_Array::value('per_membership', $formValues); if ($isPerMembership && ($mergeSameAddress || $mergeSameHousehold)) { // this shouldn't happen - perhaps is could if JS is disabled CRM_Core_Session::setStatus(ts('As you are printing one label per membership your merge settings are being ignored')); $mergeSameAddress = $mergeSameHousehold = FALSE; } // so no-one is tempted to refer to this again after relevant values are extracted unset($formValues); list($rows, $tokenFields) = CRM_Contact_Form_Task_LabelCommon::getRows($this->_contactIds, $locationTypeID, $respectDoNotMail, $mergeSameAddress, $mergeSameHousehold); $individualFormat = FALSE; if ($mergeSameAddress) { CRM_Core_BAO_Address::mergeSameAddress($rows); $individualFormat = TRUE; } if ($mergeSameHousehold) { $rows = CRM_Contact_Form_Task_LabelCommon::mergeSameHousehold($rows); $individualFormat = TRUE; } // format the addresses according to CIVICRM_ADDRESS_FORMAT (CRM-1327) foreach ((array) $rows as $id => $row) { if ($commMethods = CRM_Utils_Array::value('preferred_communication_method', $row)) { $val = array_filter(explode(CRM_Core_DAO::VALUE_SEPARATOR, $commMethods)); $comm = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method'); $temp = array(); foreach ($val as $vals) { $temp[] = $comm[$vals]; } $row['preferred_communication_method'] = implode(', ', $temp); } $row['id'] = $id; $formatted = CRM_Utils_Address::format($row, 'mailing_format', FALSE, TRUE, $individualFormat, $tokenFields); $rows[$id] = array($formatted); } if ($isPerMembership) { $labelRows = array(); $memberships = civicrm_api3('membership', 'get', array('id' => array('IN' => $this->_memberIds), 'return' => 'contact_id')); foreach ($memberships['values'] as $id => $membership) { if (isset($rows[$membership['contact_id']])) { $labelRows[$id] = $rows[$membership['contact_id']]; } } } else { $labelRows = $rows; } //call function to create labels CRM_Contact_Form_Task_LabelCommon::createLabel($labelRows, $labelName); CRM_Utils_System::civiExit(1); }
/** * 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; }
/** * Process the form. * * @return void */ public function postProcess() { $params = $this->controller->exportValues($this->_name); $status = NULL; // now set the values for the billing location. foreach ($this->_fields as $name => $value) { $fields[$name] = 1; } $fields["email-{$this->_bltID}"] = 1; $processorParams = array(); foreach ($params as $key => $val) { $key = str_replace('billing_', '', $key); list($key) = explode('-', $key); $processorParams[$key] = $val; } $processorParams['state_province'] = CRM_Core_PseudoConstant::stateProvince($params["billing_state_province_id-{$this->_bltID}"], FALSE); $processorParams['country'] = CRM_Core_PseudoConstant::country($params["billing_country_id-{$this->_bltID}"], FALSE); $processorParams['month'] = $processorParams['credit_card_exp_date']['M']; $processorParams['year'] = $processorParams['credit_card_exp_date']['Y']; $processorParams['subscriptionId'] = $this->_subscriptionDetails->subscription_id; $processorParams['amount'] = $this->_subscriptionDetails->amount; $updateSubscription = $this->_paymentProcessorObj->updateSubscriptionBillingInfo($message, $processorParams); if (is_a($updateSubscription, 'CRM_Core_Error')) { CRM_Core_Error::displaySessionError($updateSubscription); } elseif ($updateSubscription) { $ctype = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_subscriptionDetails->contact_id, 'contact_type'); $contact =& CRM_Contact_BAO_Contact::createProfileContact($params, $fields, $this->_subscriptionDetails->contact_id, NULL, NULL, $ctype); // build tpl params if ($this->_subscriptionDetails->membership_id) { $inputParams = array('id' => $this->_subscriptionDetails->membership_id); CRM_Member_BAO_Membership::getValues($inputParams, $tplParams); $tplParams = $tplParams[$this->_subscriptionDetails->membership_id]; $tplParams['membership_status'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus', $tplParams['status_id']); $tplParams['membershipType'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $tplParams['membership_type_id']); $status = ts('Billing details for your automatically renewed %1 membership have been updated.', array(1 => $tplParams['membershipType'])); $msgTitle = ts('Details Updated'); $msgType = 'success'; } else { $status = ts('Billing details for the recurring contribution of %1, every %2 %3 have been updated.', array(1 => $this->_subscriptionDetails->amount, 2 => $this->_subscriptionDetails->frequency_interval, 3 => $this->_subscriptionDetails->frequency_unit)); $msgTitle = ts('Details Updated'); $msgType = 'success'; $tplParams = array('recur_frequency_interval' => $this->_subscriptionDetails->frequency_interval, 'recur_frequency_unit' => $this->_subscriptionDetails->frequency_unit, 'amount' => $this->_subscriptionDetails->amount); } // format new address for display $addressParts = array("street_address", "city", "postal_code", "state_province", "country"); foreach ($addressParts as $part) { $addressParts[$part] = CRM_Utils_Array::value($part, $processorParams); } $tplParams['address'] = CRM_Utils_Address::format($addressParts); // format old address to store in activity details $this->_defaults["state_province-{$this->_bltID}"] = CRM_Core_PseudoConstant::stateProvince($this->_defaults["state_province-{$this->_bltID}"], FALSE); $this->_defaults["country-{$this->_bltID}"] = CRM_Core_PseudoConstant::country($this->_defaults["country-{$this->_bltID}"], FALSE); $addressParts = array("street_address", "city", "postal_code", "state_province", "country"); foreach ($addressParts as $part) { $key = "{$part}-{$this->_bltID}"; $addressParts[$part] = CRM_Utils_Array::value($key, $this->_defaults); } $this->_defaults['address'] = CRM_Utils_Address::format($addressParts); // format new billing name $name = $processorParams['first_name']; if (!empty($processorParams['middle_name'])) { $name .= " {$processorParams['middle_name']}"; } $name .= ' ' . $processorParams['last_name']; $name = trim($name); $tplParams['billingName'] = $name; // format old billing name $name = $this->_defaults['first_name']; if (!empty($this->_defaults['middle_name'])) { $name .= " {$this->_defaults['middle_name']}"; } $name .= ' ' . $this->_defaults['last_name']; $name = trim($name); $this->_defaults['billingName'] = $name; $message .= "\n<br/><br/>New Billing Name and Address\n<br/>==============================\n<br/>{$tplParams['billingName']}\n<br/>{$tplParams['address']}\n\n<br/><br/>Previous Billing Name and Address\n<br/>==================================\n<br/>{$this->_defaults['billingName']}\n<br/>{$this->_defaults['address']}"; $activityParams = array('source_contact_id' => $this->_subscriptionDetails->contact_id, 'activity_type_id' => CRM_Core_OptionGroup::getValue('activity_type', 'Update Recurring Contribution Billing Details', 'name'), 'subject' => ts('Recurring Contribution Billing Details Updated'), 'details' => $message, 'activity_date_time' => date('YmdHis'), 'status_id' => CRM_Core_OptionGroup::getValue('activity_status', 'Completed', 'name')); $session = CRM_Core_Session::singleton(); $cid = $session->get('userID'); if ($cid) { $activityParams['target_contact_id'][] = $activityParams['source_contact_id']; $activityParams['source_contact_id'] = $cid; } CRM_Activity_BAO_Activity::create($activityParams); // send notification if ($this->_subscriptionDetails->contribution_page_id) { CRM_Core_DAO::commonRetrieveAll('CRM_Contribute_DAO_ContributionPage', 'id', $this->_subscriptionDetails->contribution_page_id, $value, array('title', 'receipt_from_name', 'receipt_from_email')); $receiptFrom = '"' . CRM_Utils_Array::value('receipt_from_name', $value[$this->_subscriptionDetails->contribution_page_id]) . '" <' . $value[$this->_subscriptionDetails->contribution_page_id]['receipt_from_email'] . '>'; } else { $domainValues = CRM_Core_BAO_Domain::getNameAndEmail(); $receiptFrom = "{$domainValues['0']} <{$domainValues['1']}>"; } list($donorDisplayName, $donorEmail) = CRM_Contact_BAO_Contact::getContactDetails($this->_subscriptionDetails->contact_id); $tplParams['contact'] = array('display_name' => $donorDisplayName); $date = CRM_Utils_Date::format($processorParams['credit_card_exp_date']); $tplParams['credit_card_exp_date'] = CRM_Utils_Date::mysqlToIso($date); $tplParams['credit_card_number'] = CRM_Utils_System::mungeCreditCard($processorParams['credit_card_number']); $tplParams['credit_card_type'] = $processorParams['credit_card_type']; $sendTemplateParams = array('groupName' => $this->_subscriptionDetails->membership_id ? 'msg_tpl_workflow_membership' : 'msg_tpl_workflow_contribution', 'valueName' => $this->_subscriptionDetails->membership_id ? 'membership_autorenew_billing' : 'contribution_recurring_billing', 'contactId' => $this->_subscriptionDetails->contact_id, 'tplParams' => $tplParams, 'isTest' => $this->_subscriptionDetails->is_test, 'PDFFilename' => 'receipt.pdf', 'from' => $receiptFrom, 'toName' => $donorDisplayName, 'toEmail' => $donorEmail); list($sent) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams); } else { $status = ts('There was some problem updating the billing details.'); $msgTitle = ts('Update Error'); $msgType = 'error'; } $session = CRM_Core_Session::singleton(); $userID = $session->get('userID'); if ($userID && $status) { $session->setStatus($status, $msgTitle, $msgType); } elseif (!$userID) { if ($status) { CRM_Utils_System::setUFMessage($status); } $result = (int) ($updateSubscription && isset($ctype)); if (isset($tplParams)) { $session->set('resultParams', $tplParams); } return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contribute/subscriptionstatus', "reset=1&task=billing&result={$result}")); } }
/** * Function is used to format the individual contact values. * * @param array $params * (reference ) an assoc array of name/value pairs. * @param CRM $contact * Contact object. * * @return CRM_Contact_BAO_Contact */ public static function format(&$params, &$contact) { if (!self::dataExists($params)) { return NULL; } // "null" value for example is passed by dedupe merge in order to empty. // Display name computation shouldn't consider such values. foreach (array('first_name', 'middle_name', 'last_name', 'nick_name', 'formal_title') as $displayField) { if (CRM_Utils_Array::value($displayField, $params) == "null") { $params[$displayField] = ''; } } $sortName = $displayName = ''; $firstName = CRM_Utils_Array::value('first_name', $params, ''); $middleName = CRM_Utils_Array::value('middle_name', $params, ''); $lastName = CRM_Utils_Array::value('last_name', $params, ''); $nickName = CRM_Utils_Array::value('nick_name', $params, ''); $prefix_id = CRM_Utils_Array::value('prefix_id', $params, ''); $suffix_id = CRM_Utils_Array::value('suffix_id', $params, ''); $formalTitle = CRM_Utils_Array::value('formal_title', $params, ''); // get prefix and suffix names $prefix = $suffix = NULL; if ($prefix_id) { $params['individual_prefix'] = $prefix = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', 'prefix_id', $prefix_id); } if ($suffix_id) { $params['individual_suffix'] = $suffix = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', 'suffix_id', $suffix_id); } $params['is_deceased'] = CRM_Utils_Array::value('is_deceased', $params, FALSE); $individual = NULL; if ($contact->id) { $individual = new CRM_Contact_BAO_Contact(); $individual->id = $contact->id; if ($individual->find(TRUE)) { //lets allow to update single name field though preserveDBName //but if db having null value and params contain value, CRM-4330. $useDBNames = array(); foreach (array('last', 'middle', 'first', 'nick') as $name) { $dbName = "{$name}_name"; $value = $individual->{$dbName}; // the db has name values if ($value && !empty($params['preserveDBName'])) { $useDBNames[] = $name; } } foreach (array('prefix', 'suffix') as $name) { $dbName = "{$name}_id"; $value = $individual->{$dbName}; if ($value && !empty($params['preserveDBName'])) { $useDBNames[] = $name; } } if ($individual->formal_title && !empty($params['preserveDBName'])) { $useDBNames[] = 'formal_title'; } // CRM-4430 //1. preserve db name if want //2. lets get value from param if exists. //3. if not in params, lets get from db. foreach (array('last', 'middle', 'first', 'nick') as $name) { $phpName = "{$name}Name"; $dbName = "{$name}_name"; $value = $individual->{$dbName}; if (in_array($name, $useDBNames)) { $params[$dbName] = $value; $contact->{$dbName} = $value; ${$phpName} = $value; } elseif (array_key_exists($dbName, $params)) { ${$phpName} = $params[$dbName]; } elseif ($value) { ${$phpName} = $value; } } foreach (array('prefix', 'suffix') as $name) { $dbName = "{$name}_id"; $value = $individual->{$dbName}; if (in_array($name, $useDBNames)) { $params[$dbName] = $value; $contact->{$dbName} = $value; if ($value) { ${$name} = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', $dbName, $value); } else { ${$name} = NULL; } } elseif (array_key_exists($dbName, $params)) { // CRM-5278 if (!empty($params[$dbName])) { ${$name} = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', $dbName, $params[$dbName]); } } elseif ($value) { ${$name} = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', $dbName, $value); } } if (in_array('formal_title', $useDBNames)) { $params['formal_title'] = $individual->formal_title; $contact->formal_title = $individual->formal_title; $formalTitle = $individual->formal_title; } elseif (array_key_exists('formal_title', $params)) { $formalTitle = $params['formal_title']; } elseif ($individual->formal_title) { $formalTitle = $individual->formal_title; } } } //first trim before further processing. foreach (array('lastName', 'firstName', 'middleName') as $fld) { ${$fld} = trim(${$fld}); } if ($lastName || $firstName || $middleName) { // make sure we have values for all the name fields. $formatted = $params; $nameParams = array('first_name' => $firstName, 'middle_name' => $middleName, 'last_name' => $lastName, 'nick_name' => $nickName, 'individual_suffix' => $suffix, 'individual_prefix' => $prefix, 'prefix_id' => $prefix_id, 'suffix_id' => $suffix_id, 'formal_title' => $formalTitle); // make sure we have all the name fields. foreach ($nameParams as $name => $value) { if (empty($formatted[$name]) && $value) { $formatted[$name] = $value; } } $tokens = array(); CRM_Utils_Hook::tokens($tokens); $tokenFields = array(); foreach ($tokens as $catTokens) { foreach ($catTokens as $token => $label) { $tokenFields[] = $token; } } //build the sort name. $format = Civi::settings()->get('sort_name_format'); $sortName = CRM_Utils_Address::format($formatted, $format, FALSE, FALSE, TRUE, $tokenFields); $sortName = trim($sortName); //build the display name. $format = Civi::settings()->get('display_name_format'); $displayName = CRM_Utils_Address::format($formatted, $format, FALSE, FALSE, TRUE, $tokenFields); $displayName = trim($displayName); } //start further check for email. if (empty($sortName) || empty($displayName)) { $email = NULL; if (!empty($params['email']) && is_array($params['email'])) { foreach ($params['email'] as $emailBlock) { if (isset($emailBlock['is_primary'])) { $email = $emailBlock['email']; break; } } } $uniqId = CRM_Utils_Array::value('user_unique_id', $params); if (!$email && $contact->id) { $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contact->id); } } //now set the names. $names = array('displayName' => 'display_name', 'sortName' => 'sort_name'); foreach ($names as $value => $name) { if (empty(${$value})) { if ($email) { ${$value} = $email; } elseif ($uniqId) { ${$value} = $uniqId; } elseif (!empty($params[$name])) { ${$value} = $params[$name]; } elseif ($displayName) { ${$value} = $displayName; } } //finally if we could not pass anything lets keep db. if (!empty(${$value})) { $contact->{$name} = ${$value}; } } $format = CRM_Utils_Date::getDateFormat('birth'); if ($date = CRM_Utils_Array::value('birth_date', $params)) { if (in_array($format, array('dd-mm', 'mm/dd'))) { $separator = '/'; if ($format == 'dd-mm') { $separator = '-'; } $date = $date . $separator . '1902'; } elseif (in_array($format, array('yy-mm'))) { $date = $date . '-01'; } elseif (in_array($format, array('M yy'))) { $date = $date . '-01'; } elseif (in_array($format, array('yy'))) { $date = $date . '-01-01'; } $contact->birth_date = CRM_Utils_Date::processDate($date); } elseif ($contact->birth_date) { $contact->birth_date = CRM_Utils_Date::isoToMysql($contact->birth_date); } if ($date = CRM_Utils_Array::value('deceased_date', $params)) { if (in_array($format, array('dd-mm', 'mm/dd'))) { $separator = '/'; if ($format == 'dd-mm') { $separator = '-'; } $date = $date . $separator . '1902'; } elseif (in_array($format, array('yy-mm'))) { $date = $date . '-01'; } elseif (in_array($format, array('M yy'))) { $date = $date . '-01'; } elseif (in_array($format, array('yy'))) { $date = $date . '-01-01'; } $contact->deceased_date = CRM_Utils_Date::processDate($date); } elseif ($contact->deceased_date) { $contact->deceased_date = CRM_Utils_Date::isoToMysql($contact->deceased_date); } if ($middle_name = CRM_Utils_Array::value('middle_name', $params)) { $contact->middle_name = $middle_name; } return $contact; }
/** * Get array of return properties for address fields required for mailing label * @return array return properites for address e.g * array ( * - [street_address] => 1, * - [supplemental_address_1] => 1, * - [supplemental_address_2] => 1 * ) */ function getAddressReturnProperties() { $mailingFormat = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'mailing_format'); $addressFields = CRM_Utils_Address::sequence($mailingFormat); $addressReturnProperties = array_fill_keys($addressFields, 1); if (array_key_exists('postal_code', $addressReturnProperties)) { $addressReturnProperties['postal_code_suffix'] = 1; } return $addressReturnProperties; }
/** * Merge contacts with the Same address to get one shared label. * @param array $rows * Array[contact_id][contactDetails]. */ public static function mergeSameAddress(&$rows) { $uniqueAddress = array(); foreach (array_keys($rows) as $rowID) { // load complete address as array key $address = trim($rows[$rowID]['street_address']) . trim($rows[$rowID]['city']) . trim($rows[$rowID]['state_province']) . trim($rows[$rowID]['postal_code']) . trim($rows[$rowID]['country']); if (isset($rows[$rowID]['last_name'])) { $name = $rows[$rowID]['last_name']; } else { $name = $rows[$rowID]['display_name']; } // CRM-15120 $formatted = array('first_name' => $rows[$rowID]['first_name'], 'individual_prefix' => $rows[$rowID]['individual_prefix']); $format = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'display_name_format'); $firstNameWithPrefix = CRM_Utils_Address::format($formatted, $format, FALSE, FALSE, TRUE); $firstNameWithPrefix = trim($firstNameWithPrefix); // fill uniqueAddress array with last/first name tree if (isset($uniqueAddress[$address])) { $uniqueAddress[$address]['names'][$name][$firstNameWithPrefix]['first_name'] = $rows[$rowID]['first_name']; $uniqueAddress[$address]['names'][$name][$firstNameWithPrefix]['addressee_display'] = $rows[$rowID]['addressee_display']; // drop unnecessary rows unset($rows[$rowID]); // this is the first listing at this address } else { $uniqueAddress[$address]['ID'] = $rowID; $uniqueAddress[$address]['names'][$name][$firstNameWithPrefix]['first_name'] = $rows[$rowID]['first_name']; $uniqueAddress[$address]['names'][$name][$firstNameWithPrefix]['addressee_display'] = $rows[$rowID]['addressee_display']; } } foreach ($uniqueAddress as $address => $data) { // copy data back to $rows $count = 0; // one last name list per row foreach ($data['names'] as $last_name => $first_names) { // too many to list if ($count > 2) { break; } if (count($first_names) == 1) { $family = $first_names[current(array_keys($first_names))]['addressee_display']; } else { // collapse the tree to summarize $family = trim(implode(" & ", array_keys($first_names)) . " " . $last_name); } if ($count) { $processedNames .= "\n" . $family; } else { // build display_name string $processedNames = $family; } $count++; } $rows[$data['ID']]['addressee'] = $rows[$data['ID']]['addressee_display'] = $rows[$data['ID']]['display_name'] = $processedNames; } }
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); } }
/** * @deprecated */ public function addressSequence() { return CRM_Utils_Address::sequence(Civi::settings()->get('address_format')); }
/** * A function to build an array of information required by merge function and the merge UI. * * @param int $mainId * Main contact with whom merge has to happen. * @param int $otherId * Duplicate contact which would be deleted after merge operation. * * @return array|bool|int * 'main_loc_block' => Stores all location blocks associated with the 'main' contact */ public static function getRowsElementsAndInfo($mainId, $otherId) { $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9'; // Fetch contacts foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) { $params = array('contact_id' => $cid, 'version' => 3, 'return' => array_merge(array('display_name'), self::getContactFields())); $result = civicrm_api('contact', 'get', $params); if (empty($result['values'][$cid]['contact_type'])) { return FALSE; } ${$moniker} = $result['values'][$cid]; } $fields = CRM_Contact_DAO_Contact::fields(); // FIXME: there must be a better way foreach (array('main', 'other') as $moniker) { $contact =& ${$moniker}; $preferred_communication_method = CRM_Utils_array::value('preferred_communication_method', $contact); $value = empty($preferred_communication_method) ? array() : $preferred_communication_method; $specialValues[$moniker] = array('preferred_communication_method' => $value, 'communication_style_id' => $value); if (!empty($contact['preferred_communication_method'])) { // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct $prefCommList = is_array($specialValues[$moniker]['preferred_communication_method']) ? implode(CRM_Core_DAO::VALUE_SEPARATOR, $specialValues[$moniker]['preferred_communication_method']) : $specialValues[$moniker]['preferred_communication_method']; $specialValues[$moniker]['preferred_communication_method'] = CRM_Core_DAO::VALUE_SEPARATOR . $prefCommList . CRM_Core_DAO::VALUE_SEPARATOR; } $names = array('preferred_communication_method' => array('newName' => 'preferred_communication_method_display', 'groupName' => 'preferred_communication_method')); CRM_Core_OptionGroup::lookupValues($specialValues[$moniker], $names); if (!empty($contact['communication_style'])) { $specialValues[$moniker]['communication_style_id_display'] = $contact['communication_style']; } } static $optionValueFields = array(); if (empty($optionValueFields)) { $optionValueFields = CRM_Core_OptionValue::getFields(); } foreach ($optionValueFields as $field => $params) { $fields[$field]['title'] = $params['title']; } $compareFields = self::retrieveFields($main, $other); $rows = $elements = $relTableElements = $migrationInfo = array(); foreach ($compareFields['contact'] as $field) { if ($field == 'contact_sub_type') { // CRM-15681 don't display sub-types in UI continue; } foreach (array('main', 'other') as $moniker) { $contact =& ${$moniker}; $value = CRM_Utils_Array::value($field, $contact); if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) { $value = CRM_Core_DAO::VALUE_SEPARATOR . trim($specialValues[$moniker][$field], CRM_Core_DAO::VALUE_SEPARATOR) . CRM_Core_DAO::VALUE_SEPARATOR; } $label = isset($specialValues[$moniker]["{$field}_display"]) ? $specialValues[$moniker]["{$field}_display"] : $value; if (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_DATE) { if ($value) { $value = str_replace('-', '', $value); $label = CRM_Utils_Date::customFormat($label); } else { $value = "null"; } } elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) { if ($label === '0') { $label = ts('[ ]'); } if ($label === '1') { $label = ts('[x]'); } } elseif ($field == 'individual_prefix' || $field == 'prefix_id') { $label = CRM_Utils_Array::value('individual_prefix', $contact); $value = CRM_Utils_Array::value('prefix_id', $contact); $field = 'prefix_id'; } elseif ($field == 'individual_suffix' || $field == 'suffix_id') { $label = CRM_Utils_Array::value('individual_suffix', $contact); $value = CRM_Utils_Array::value('suffix_id', $contact); $field = 'suffix_id'; } elseif ($field == 'gender_id' && !empty($value)) { $genderOptions = civicrm_api3('contact', 'getoptions', array('field' => 'gender_id')); $label = $genderOptions['values'][$value]; } elseif ($field == 'current_employer_id' && !empty($value)) { $label = "{$value} (" . CRM_Contact_BAO_Contact::displayName($value) . ")"; } $rows["move_{$field}"][$moniker] = $label; if ($moniker == 'other') { //CRM-14334 if ($value === NULL || $value == '') { $value = 'null'; } if ($value === 0 or $value === '0') { $value = $qfZeroBug; } if (is_array($value) && empty($value[1])) { $value[1] = NULL; } // Display a checkbox to migrate, only if the values are different if ($value != $main[$field]) { $elements[] = array('advcheckbox', "move_{$field}", NULL, NULL, NULL, $value); } $migrationInfo["move_{$field}"] = $value; } } $rows["move_{$field}"]['title'] = $fields[$field]['title']; } // Handle location blocks. // @todo OpenID not in API yet, so is not supported here. // Set up useful information about the location blocks $locationBlocks = self::getLocationBlockInfo(); $locations = array('main' => array(), 'other' => array()); $mainLocBlock = array(); // @todo This could probably be defined and used earlier $mergeTargets = array('main' => $mainId, 'other' => $otherId); foreach ($locationBlocks as $blockName => $blockInfo) { // Collect existing fields from both 'main' and 'other' contacts first // This allows us to match up location/types when building the table rows foreach ($mergeTargets as $moniker => $cid) { $cnt = 1; $searchParams = array('version' => 3, 'contact_id' => $cid, 'options' => array('sort' => $blockInfo['sortString'])); $values = civicrm_api($blockName, 'get', $searchParams); if ($values['count']) { $cnt = 0; foreach ($values['values'] as $index => $value) { $locations[$moniker][$blockName][$cnt] = $value; // Fix address display $display = ''; if ($blockName == 'address') { CRM_Core_BAO_Address::fixAddress($value); $display = CRM_Utils_Address::format($value); $locations[$moniker][$blockName][$cnt]['display'] = $display; } // Add any 'main' contact block values to an array for the JS // @todo The JS should just access the main_details to find this info? if ($moniker == 'main') { if ($blockInfo['hasType']) { // Handle websites, no location type ID // @todo Remove the need for this specific 'if' if ($blockName == 'website') { $value['location_type_id'] = 0; } $mainLocBlock["main_" . $blockName . "_" . $value['location_type_id'] . "_" . $value[$blockInfo['hasType']]]['display'] = $value[$blockInfo['displayField']]; $mainLocBlock["main_" . $blockName . "_" . $value['location_type_id'] . "_" . $value[$blockInfo['hasType']]]['id'] = $value['id']; } else { // Get the correct display value for addresses // @todo Remove the need for this if... if ($blockName == 'address') { $mainLocBlock["main_" . $blockName . "_" . $value['location_type_id']]['display'] = $display; $mainLocBlock["main_" . $blockName . "_" . $value['location_type_id']]['id'] = $value['id']; } else { $mainLocBlock["main_" . $blockName . "_" . $value['location_type_id']]['display'] = $value[$blockInfo['displayField']]; $mainLocBlock["main_" . $blockName . "_" . $value['location_type_id']]['id'] = $value['id']; } } } $cnt++; } } } // Now, build the table rows appropriately, based off the information on // the 'other' contact if (!empty($locations['other']) && !empty($locations['other'][$blockName])) { foreach ($locations['other'][$blockName] as $count => $value) { $displayValue = $value[$blockInfo['displayField']]; // Add this value to the table rows $rows["move_location_{$blockName}_{$count}"]['other'] = $displayValue; // CRM-17556 Only display 'main' contact value if it's the same location + type // Look it up from main values... $lookupLocation = FALSE; if ($blockInfo['hasLocation']) { $lookupLocation = $value['location_type_id']; } $lookupType = FALSE; if ($blockInfo['hasType']) { $lookupType = $value[$blockInfo['hasType']]; } // Hold ID of main contact's matching block $mainContactBlockId = 0; if (!empty($locations['main'][$blockName])) { foreach ($locations['main'][$blockName] as $mainValueCheck) { // No location/type, or matching location and type if ((empty($lookupLocation) || $lookupLocation == $mainValueCheck['location_type_id']) && (empty($lookupType) || $lookupType == $mainValueCheck[$blockInfo['hasType']])) { // Set this value as the default against the 'other' contact value $rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']]; $mainContactBlockId = $mainValueCheck['id']; break; } } } // Add checkbox to migrate data from 'other' to 'main' $elements[] = array('advcheckbox', "move_location_{$blockName}_{$count}"); // Flag up this field to skipMerge function (@todo: do we need to?) $migrationInfo["move_location_{$blockName}_{$count}"] = 1; // Add a hidden field to store the ID of the target main contact block $elements[] = array('hidden', "location[{$blockName}][{$count}][mainContactBlockId]", $mainContactBlockId); // Setup variables $thisTypeId = FALSE; $thisLocId = FALSE; // Provide a select drop-down for the location's location type // eg: Home, Work... $js = NULL; if ($blockInfo['hasLocation']) { // Load the location options for this entity $locationOptions = civicrm_api3($blockName, 'getoptions', array('field' => 'location_type_id')); // JS lookup 'main' contact's location (if there are any) if (!empty($locations['main'][$blockName])) { $js = array('onChange' => "mergeBlock('{$blockName}', this, {$count}, 'locTypeId' );"); } $thisLocId = $value['location_type_id']; // Put this field's location type at the top of the list $tmpIdList = $locationOptions['values']; $defaultLocId = array($thisLocId => $tmpIdList[$thisLocId]); unset($tmpIdList[$thisLocId]); // Add the element $elements[] = array('select', "location[{$blockName}][{$count}][locTypeId]", NULL, $defaultLocId + $tmpIdList, $js); // Add the relevant information to the $migrationInfo // Keep location-type-id same as that of other-contact // @todo Check this logic out $migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId; if ($blockName != 'address') { $elements[] = array('advcheckbox', "location[{$blockName}][{$count}][operation]", NULL, ts('add new')); // always use add operation $migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1; } } // Provide a select drop-down for the location's type/provider // eg websites: Google+, Facebook... $js = NULL; if ($blockInfo['hasType']) { // Load the type options for this entity $typeOptions = civicrm_api3($blockName, 'getoptions', array('field' => $blockInfo['hasType'])); // CRM-17556 Set up JS lookup of 'main' contact's value by type if (!empty($locations['main'][$blockName])) { $js = array('onChange' => "mergeBlock('{$blockName}', this, {$count}, 'typeTypeId' );"); } $thisTypeId = $value[$blockInfo['hasType']]; // Put this field's location type at the top of the list $tmpIdList = $typeOptions['values']; $defaultTypeId = array($thisTypeId => $tmpIdList[$thisTypeId]); unset($tmpIdList[$thisTypeId]); // Add the element $elements[] = array('select', "location[{$blockName}][{$count}][typeTypeId]", NULL, $defaultTypeId + $tmpIdList, $js); // Add the information to the migrationInfo (@todo Why?) $migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $thisTypeId; } // Set the label for this row $rowTitle = $blockInfo['label'] . ' ' . ($count + 1); if (!empty($thisLocId)) { $rowTitle .= ' (' . $locationOptions['values'][$thisLocId] . ')'; } if (!empty($thisTypeId)) { $rowTitle .= ' (' . $typeOptions['values'][$thisTypeId] . ')'; } $rows["move_location_{$blockName}_{$count}"]['title'] = $rowTitle; } // End loop through 'other' locations of this type } // End if 'other' location for this type exists } // End loop through each location block entity // add the related tables and unset the ones that don't sport any of the duplicate contact's info $config = CRM_Core_Config::singleton(); $mainUfId = CRM_Core_BAO_UFMatch::getUFId($mainId); $mainUser = NULL; if ($mainUfId) { // d6 compatible if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) { $mainUser = user_load($mainUfId); } elseif ($config->userFramework == 'Joomla') { $mainUser = JFactory::getUser($mainUfId); } } $otherUfId = CRM_Core_BAO_UFMatch::getUFId($otherId); $otherUser = NULL; if ($otherUfId) { // d6 compatible if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) { $otherUser = user_load($otherUfId); } elseif ($config->userFramework == 'Joomla') { $otherUser = JFactory::getUser($otherUfId); } } $relTables = CRM_Dedupe_Merger::relTables(); $activeRelTables = CRM_Dedupe_Merger::getActiveRelTables($otherId); $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId); foreach ($relTables as $name => $null) { if (!in_array($name, $activeRelTables) && !($name == 'rel_table_users' && in_array($name, $activeMainRelTables))) { unset($relTables[$name]); continue; } $relTableElements[] = array('checkbox', "move_{$name}"); $migrationInfo["move_{$name}"] = 1; $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']); $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']); if ($name == 'rel_table_users') { $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']); $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']); $find = array('$ufid', '$ufname'); if ($mainUser) { $replace = array($mainUfId, $mainUser->name); $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']); } if ($otherUser) { $replace = array($otherUfId, $otherUser->name); $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']); } } if ($name == 'rel_table_memberships') { $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new')); $migrationInfo["operation"]["move_{$name}"]['add'] = 1; } } foreach ($relTables as $name => $null) { $relTables["move_{$name}"] = $relTables[$name]; unset($relTables[$name]); } // handle custom fields $mainTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $mainId, -1, CRM_Utils_Array::value('contact_sub_type', $main)); $otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $otherId, -1, CRM_Utils_Array::value('contact_sub_type', $other)); CRM_Core_DAO::freeResult(); foreach ($otherTree as $gid => $group) { $foundField = FALSE; if (!isset($group['fields'])) { continue; } foreach ($group['fields'] as $fid => $field) { if (in_array($fid, $compareFields['custom'])) { if (!$foundField) { $rows["custom_group_{$gid}"]['title'] = $group['title']; $foundField = TRUE; } if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) { foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) { $rows["move_custom_{$fid}"]['main'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid); } } $value = "null"; if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) { foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) { $rows["move_custom_{$fid}"]['other'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid); if ($values['data'] === 0 || $values['data'] === '0') { $values['data'] = $qfZeroBug; } $value = $values['data'] ? $values['data'] : $value; } } $rows["move_custom_{$fid}"]['title'] = $field['label']; $elements[] = array('advcheckbox', "move_custom_{$fid}", NULL, NULL, NULL, $value); $migrationInfo["move_custom_{$fid}"] = $value; } } } $result = array('rows' => $rows, 'elements' => $elements, 'rel_table_elements' => $relTableElements, 'main_loc_block' => $mainLocBlock, 'rel_tables' => $relTables, 'main_details' => $main, 'other_details' => $other, 'migration_info' => $migrationInfo); $result['main_details']['location_blocks'] = $locations['main']; $result['other_details']['location_blocks'] = $locations['other']; return $result; }
/** * Provide addressSequence * * @param * * @return string */ public function addressSequence() { $addressFormat = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'address_format'); return CRM_Utils_Address::sequence($addressFormat); }
/** * @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")); } }
/** * 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(' ', '', $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}")); } }
/** * A function to build an array of information required by merge function and the merge UI. * * @param int $mainId * Main contact with whom merge has to happen. * @param int $otherId * Duplicate contact which would be deleted after merge operation. * * @return array|bool|int */ public static function getRowsElementsAndInfo($mainId, $otherId) { $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9'; // Fetch contacts foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) { $params = array('contact_id' => $cid, 'version' => 3, 'return' => array_merge(array('display_name'), self::getContactFields())); $result = civicrm_api('contact', 'get', $params); if (empty($result['values'][$cid]['contact_type'])) { return FALSE; } ${$moniker} = $result['values'][$cid]; } static $fields = array(); if (empty($fields)) { $fields = CRM_Contact_DAO_Contact::fields(); CRM_Core_DAO::freeResult(); } // FIXME: there must be a better way foreach (array('main', 'other') as $moniker) { $contact =& ${$moniker}; $preferred_communication_method = CRM_Utils_array::value('preferred_communication_method', $contact); $value = empty($preferred_communication_method) ? array() : $preferred_communication_method; $specialValues[$moniker] = array('preferred_communication_method' => $value, 'communication_style_id' => $value); if (!empty($contact['preferred_communication_method'])) { // api 3 returns pref_comm_method as an array, which breaks the lookup; so we reconstruct $prefCommList = is_array($specialValues[$moniker]['preferred_communication_method']) ? implode(CRM_Core_DAO::VALUE_SEPARATOR, $specialValues[$moniker]['preferred_communication_method']) : $specialValues[$moniker]['preferred_communication_method']; $specialValues[$moniker]['preferred_communication_method'] = CRM_Core_DAO::VALUE_SEPARATOR . $prefCommList . CRM_Core_DAO::VALUE_SEPARATOR; } $names = array('preferred_communication_method' => array('newName' => 'preferred_communication_method_display', 'groupName' => 'preferred_communication_method')); CRM_Core_OptionGroup::lookupValues($specialValues[$moniker], $names); if (!empty($contact['communication_style'])) { $specialValues[$moniker]['communication_style_id_display'] = $contact['communication_style']; } } static $optionValueFields = array(); if (empty($optionValueFields)) { $optionValueFields = CRM_Core_OptionValue::getFields(); } foreach ($optionValueFields as $field => $params) { $fields[$field]['title'] = $params['title']; } $diffs = self::findDifferences($main, $other); $rows = $elements = $relTableElements = $migrationInfo = array(); $genders = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'); foreach ($diffs['contact'] as $field) { if ($field == 'contact_sub_type') { // CRM-15681 don't display sub-types in UI continue; } foreach (array('main', 'other') as $moniker) { $contact =& ${$moniker}; $value = CRM_Utils_Array::value($field, $contact); if (isset($specialValues[$moniker][$field]) && is_string($specialValues[$moniker][$field])) { $value = CRM_Core_DAO::VALUE_SEPARATOR . trim($specialValues[$moniker][$field], CRM_Core_DAO::VALUE_SEPARATOR) . CRM_Core_DAO::VALUE_SEPARATOR; } $label = isset($specialValues[$moniker]["{$field}_display"]) ? $specialValues[$moniker]["{$field}_display"] : $value; if (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_DATE) { if ($value) { $value = str_replace('-', '', $value); $label = CRM_Utils_Date::customFormat($label); } else { $value = "null"; } } elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) { if ($label === '0') { $label = ts('[ ]'); } if ($label === '1') { $label = ts('[x]'); } } elseif ($field == 'individual_prefix' || $field == 'prefix_id') { $label = CRM_Utils_Array::value('individual_prefix', $contact); $value = CRM_Utils_Array::value('prefix_id', $contact); $field = 'prefix_id'; } elseif ($field == 'individual_suffix' || $field == 'suffix_id') { $label = CRM_Utils_Array::value('individual_suffix', $contact); $value = CRM_Utils_Array::value('suffix_id', $contact); $field = 'suffix_id'; } elseif ($field == 'gender_id' && !empty($value)) { $label = $genders[$value]; } elseif ($field == 'current_employer_id' && !empty($value)) { $label = "{$value} (" . CRM_Contact_BAO_Contact::displayName($value) . ")"; } $rows["move_{$field}"][$moniker] = $label; if ($moniker == 'other') { //CRM-14334 if ($value === NULL || $value == '') { $value = 'null'; } if ($value === 0 or $value === '0') { $value = $qfZeroBug; } if (is_array($value) && empty($value[1])) { $value[1] = NULL; } $elements[] = array('advcheckbox', "move_{$field}", NULL, NULL, NULL, $value); $migrationInfo["move_{$field}"] = $value; } } $rows["move_{$field}"]['title'] = $fields[$field]['title']; } // handle location blocks. $locationBlocks = array('email', 'phone', 'address'); $locations = array(); foreach ($locationBlocks as $block) { foreach (array('main' => $mainId, 'other' => $otherId) as $moniker => $cid) { $cnt = 1; $values = civicrm_api($block, 'get', array('contact_id' => $cid, 'version' => 3)); $count = $values['count']; if ($count) { if ($count > $cnt) { foreach ($values['values'] as $value) { if ($block == 'address') { CRM_Core_BAO_Address::fixAddress($value); $display = CRM_Utils_Address::format($value); $locations[$moniker][$block][$cnt] = $value; $locations[$moniker][$block][$cnt]['display'] = $display; } else { $locations[$moniker][$block][$cnt] = $value; } $cnt++; } } else { $id = $values['id']; if ($block == 'address') { CRM_Core_BAO_Address::fixAddress($values['values'][$id]); $display = CRM_Utils_Address::format($values['values'][$id]); $locations[$moniker][$block][$cnt] = $values['values'][$id]; $locations[$moniker][$block][$cnt]['display'] = $display; } else { $locations[$moniker][$block][$cnt] = $values['values'][$id]; } } } } } $allLocationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); $mainLocBlock = $locBlockIds = array(); $locBlockIds['main'] = $locBlockIds['other'] = array(); foreach (array('Email', 'Phone', 'IM', 'OpenID', 'Address') as $block) { $name = strtolower($block); foreach (array('main', 'other') as $moniker) { $locIndex = CRM_Utils_Array::value($moniker, $locations); $blockValue = CRM_Utils_Array::value($name, $locIndex, array()); if (empty($blockValue)) { $locValue[$moniker][$name] = 0; $locLabel[$moniker][$name] = $locTypes[$moniker][$name] = array(); } else { $locValue[$moniker][$name] = TRUE; foreach ($blockValue as $count => $blkValues) { $fldName = $name; $locTypeId = $blkValues['location_type_id']; if ($name == 'im') { $fldName = 'name'; } if ($name == 'address') { $fldName = 'display'; } $locLabel[$moniker][$name][$count] = CRM_Utils_Array::value($fldName, $blkValues); $locTypes[$moniker][$name][$count] = $locTypeId; if ($moniker == 'main' && in_array($name, $locationBlocks)) { $mainLocBlock["main_{$name}{$locTypeId}"] = CRM_Utils_Array::value($fldName, $blkValues); $locBlockIds['main'][$name][$locTypeId] = $blkValues['id']; } else { $locBlockIds[$moniker][$name][$count] = $blkValues['id']; } } } } if ($locValue['other'][$name] != 0) { foreach ($locLabel['other'][$name] as $count => $value) { $locTypeId = $locTypes['other'][$name][$count]; $rows["move_location_{$name}_{$count}"]['other'] = $value; $rows["move_location_{$name}_{$count}"]['main'] = CRM_Utils_Array::value($count, $locLabel['main'][$name]); $rows["move_location_{$name}_{$count}"]['title'] = ts('%1:%2:%3', array(1 => $block, 2 => $count, 3 => $allLocationTypes[$locTypeId])); $elements[] = array('advcheckbox', "move_location_{$name}_{$count}"); $migrationInfo["move_location_{$name}_{$count}"] = 1; // make sure default location type is always on top $mainLocTypeId = CRM_Utils_Array::value($count, $locTypes['main'][$name], $locTypeId); $locTypeValues = $allLocationTypes; $defaultLocType = array($mainLocTypeId => $locTypeValues[$mainLocTypeId]); unset($locTypeValues[$mainLocTypeId]); // keep 1-1 mapping for address - location type. $js = NULL; if (in_array($name, $locationBlocks) && !empty($mainLocBlock)) { $js = array('onChange' => "mergeBlock('{$name}', this, {$count} );"); } $elements[] = array('select', "location[{$name}][{$count}][locTypeId]", NULL, $defaultLocType + $locTypeValues, $js); // keep location-type-id same as that of other-contact $migrationInfo['location'][$name][$count]['locTypeId'] = $locTypeId; if ($name != 'address') { $elements[] = array('advcheckbox', "location[{$name}][{$count}][operation]", NULL, ts('add new')); // always use add operation $migrationInfo['location'][$name][$count]['operation'] = 1; } } } } // add the related tables and unset the ones that don't sport any of the duplicate contact's info $config = CRM_Core_Config::singleton(); $mainUfId = CRM_Core_BAO_UFMatch::getUFId($mainId); $mainUser = NULL; if ($mainUfId) { // d6 compatible if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) { $mainUser = user_load($mainUfId); } elseif ($config->userFramework == 'Joomla') { $mainUser = JFactory::getUser($mainUfId); } } $otherUfId = CRM_Core_BAO_UFMatch::getUFId($otherId); $otherUser = NULL; if ($otherUfId) { // d6 compatible if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) { $otherUser = user_load($otherUfId); } elseif ($config->userFramework == 'Joomla') { $otherUser = JFactory::getUser($otherUfId); } } $relTables = CRM_Dedupe_Merger::relTables(); $activeRelTables = CRM_Dedupe_Merger::getActiveRelTables($otherId); $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId); foreach ($relTables as $name => $null) { if (!in_array($name, $activeRelTables) && !($name == 'rel_table_users' && in_array($name, $activeMainRelTables))) { unset($relTables[$name]); continue; } $relTableElements[] = array('checkbox', "move_{$name}"); $migrationInfo["move_{$name}"] = 1; $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']); $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']); if ($name == 'rel_table_users') { $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']); $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']); $find = array('$ufid', '$ufname'); if ($mainUser) { $replace = array($mainUfId, $mainUser->name); $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']); } if ($otherUser) { $replace = array($otherUfId, $otherUser->name); $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']); } } if ($name == 'rel_table_memberships') { $elements[] = array('checkbox', "operation[move_{$name}][add]", NULL, ts('add new')); $migrationInfo["operation"]["move_{$name}"]['add'] = 1; } } foreach ($relTables as $name => $null) { $relTables["move_{$name}"] = $relTables[$name]; unset($relTables[$name]); } // handle custom fields $mainTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $mainId, -1, CRM_Utils_Array::value('contact_sub_type', $main)); $otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], CRM_Core_DAO::$_nullObject, $otherId, -1, CRM_Utils_Array::value('contact_sub_type', $other)); CRM_Core_DAO::freeResult(); foreach ($otherTree as $gid => $group) { $foundField = FALSE; if (!isset($group['fields'])) { continue; } foreach ($group['fields'] as $fid => $field) { if (in_array($fid, $diffs['custom'])) { if (!$foundField) { $rows["custom_group_{$gid}"]['title'] = $group['title']; $foundField = TRUE; } if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) { foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) { $rows["move_custom_{$fid}"]['main'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values, $field, TRUE); } } $value = "null"; if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) { foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) { $rows["move_custom_{$fid}"]['other'] = CRM_Core_BAO_CustomGroup::formatCustomValues($values, $field, TRUE); if ($values['data'] === 0 || $values['data'] === '0') { $values['data'] = $qfZeroBug; } $value = $values['data'] ? $values['data'] : $value; } } $rows["move_custom_{$fid}"]['title'] = $field['label']; $elements[] = array('advcheckbox', "move_custom_{$fid}", NULL, NULL, NULL, $value); $migrationInfo["move_custom_{$fid}"] = $value; } } } $result = array('rows' => $rows, 'elements' => $elements, 'rel_table_elements' => $relTableElements, 'main_loc_block' => $mainLocBlock, 'rel_tables' => $relTables, 'main_details' => $main, 'other_details' => $other, 'migration_info' => $migrationInfo); $result['main_details']['loc_block_ids'] = $locBlockIds['main']; $result['other_details']['loc_block_ids'] = $locBlockIds['other']; return $result; }
/** * 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']); } }
/** * 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')); } }
/** * 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); }
/** * 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(' ', '', $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}")); } } }