/** * 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 __construct() { $this->_exposeContactID = $this->_emailField = FALSE; $this->_customGroupJoin = 'LEFT JOIN'; $this->_columns = array('civicrm_contact' => array('dao' => 'CRM_Contact_DAO_Contact', 'fields' => array('sort_name' => array('title' => ts('Name'), 'required' => TRUE), 'id' => array('no_display' => TRUE, 'required' => TRUE), 'gender' => array()), 'filters' => array('sort_name' => array('title' => ts('Name'), 'operator' => 'like'), 'id' => array('title' => ts('Contact ID'), 'no_display' => TRUE, 'type' => CRM_Utils_Type::T_INT), 'gender' => array()), 'order_bys' => array('sort_name' => array('title' => ts('Last Name, First Name'), 'default' => '1', 'default_weight' => '0', 'default_order' => 'ASC'), 'id' => array('title' => ts('Contact ID'), 'default' => '1', 'default_weight' => '1', 'default_order' => 'ASC')), 'grouping' => array('contact-fields' => ts('Personal Details'))), 'civicrm_email' => array('dao' => 'CRM_Core_DAO_Email', 'fields' => array('email' => array('default' => TRUE)), 'grouping' => 'contact-fields'), 'civicrm_phone' => array('dao' => 'CRM_Core_DAO_Phone', 'fields' => array('phone' => array('no_repeat' => TRUE)), 'grouping' => 'contact-fields'), 'civicrm_address' => array('dao' => 'CRM_Core_DAO_Address', 'fields' => array('city' => array('title' => ts('Work City')), 'postal_code' => array('title' => ts('Work Postal Code')), 'state_province_id' => array('title' => ts('Work State/Province')), 'country_id' => array('title' => ts('Work Country'))), 'filters' => array('city' => array('title' => ts('Work City')), 'postal_code' => array('title' => ts('Work Postal Code')), 'state_province_id' => array('title' => ts('Work State/Province'), 'type' => CRM_Utils_Type::T_INT, 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => CRM_Core_PseudoConstant::stateProvince()), 'country_id' => array('title' => ts('Work Country'), 'type' => CRM_Utils_Type::T_INT, 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => CRM_Core_PseudoConstant::country())), 'grouping' => 'contact-fields'), 'civicrm_group' => array('dao' => 'CRM_Contact_DAO_GroupContact', 'alias' => 'cgroup', 'filters' => array('gid' => array('name' => 'group_id', 'title' => ts('Group'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'group' => TRUE, 'options' => CRM_Core_PseudoConstant::group(), 'type' => CRM_Utils_Type::T_INT))), 'civicrm_hrjobcontract' => array('dao' => 'CRM_Hrjobcontract_DAO_HRJobContract', 'fields' => array('is_primary' => array('title' => ts('Job Is Primary?'), 'no_repeat' => TRUE, 'dbAlias' => 'hrjobcontract_civireport.is_primary')), 'filters' => array('is_primary' => array('title' => ts('Job Is Primary?'), 'default' => 1, 'type' => CRM_Utils_Type::T_INT, 'operatorType' => CRM_Report_Form::OP_SELECT, 'options' => array('' => ts('Any'), '0' => ts('No'), '1' => ts('Yes'))), 'current_employee' => array('default' => NULL, 'type' => CRM_Utils_Type::T_INT, 'operatorType' => CRM_Report_Form::OP_SELECT, 'options' => array('' => ts('ANY'), '0' => ts('No'), '1' => ts('Yes')), 'no_display' => TRUE)), 'grouping' => array('job-fields' => 'Job')), 'civicrm_hrjobcontract_revision' => array('dao' => 'CRM_Hrjobcontract_DAO_HRJobContractRevision', 'fields' => array('jobcontract_revision_id' => array('title' => ts('Revision ID'), 'no_repeat' => TRUE, 'name' => 'id', 'no_display' => TRUE), 'editor_uid' => array('title' => ts('Editor UID'), 'no_repeat' => TRUE, 'name' => 'editor_uid', 'no_display' => TRUE), 'created_date' => array('title' => ts('Created date'), 'no_repeat' => TRUE, 'name' => 'created_date', 'no_display' => TRUE), 'modified_date' => array('title' => ts('Modified date'), 'no_repeat' => TRUE, 'name' => 'modified_date', 'no_display' => TRUE), 'effective_date' => array('title' => ts('Effective date'), 'no_repeat' => TRUE, 'name' => 'effective_date', 'no_display' => TRUE), 'change_reason' => array('title' => ts('Change reason'), 'no_repeat' => TRUE, 'name' => 'change_reason', 'no_display' => TRUE), 'status' => array('title' => ts('Revision status'), 'no_repeat' => TRUE, 'name' => 'status', 'no_display' => TRUE)), 'grouping' => array('job-fields' => 'Job'), 'order_bys' => array('civicrm_hrjobcontract_revision_revision_id' => array('title' => ts('Revision Id'), 'dbAlias' => 'hrjobcontract_revision_civireport.id')), 'group_bys' => array('civicrm_hrjobcontract_revision_revision_id' => array('title' => ts('Revision Id'), 'dbAlias' => 'hrjobcontract_revision_civireport.id'))), 'civicrm_hrjobcontract_details' => array('dao' => 'CRM_Hrjobcontract_DAO_HRJobDetails', 'fields' => array('hrjobcontract_details_title' => array(), 'hrjobcontract_details_contract_type' => array(), 'hrjobcontract_details_location' => array(), 'hrjobcontract_details_position' => array(), 'hrjobcontract_details_period_start_date' => array(), 'hrjobcontract_details_period_end_date' => array()), 'filters' => array('hrjobcontract_details_title' => array(), 'hrjobcontract_details_contract_type' => array(), 'hrjobcontract_details_location' => array(), 'hrjobcontract_details_position' => array(), 'hrjobcontract_details_period_start_date' => array(), 'hrjobcontract_details_period_end_date' => array()), 'grouping' => array('job-fields' => 'Job')), 'civicrm_hrjobcontract_health' => array('dao' => 'CRM_Hrjobcontract_DAO_HRJobHealth', 'fields' => array('hrjobcontract_health_health_provider_life_insurance' => array(), 'hrjobcontract_health_life_insurance_plan_type' => array(), 'hrjobcontract_health_health_provider' => array(), 'hrjobcontract_health_health_plan_type' => array()), 'filters' => array('hrjobcontract_health_life_insurance_plan_type' => array(), 'hrjobcontract_health_health_plan_type' => array()), 'grouping' => array('job-fields' => 'Job')), 'civicrm_hrjobcontract_health_provider' => array('dao' => 'CRM_Contact_DAO_Contact', 'fields' => array('organization_name' => array('title' => ts('Job Healthcare Provider'), 'no_repeat' => TRUE, 'no_display' => TRUE, 'required' => TRUE), 'id' => array('no_display' => TRUE, 'required' => TRUE)), 'filters' => array('organization_name' => array('title' => ts('Job Healthcare Provider'), 'operatorType' => CRM_Report_Form::OP_STRING))), 'civicrm_hrjobcontract_health_life_provider' => array('dao' => 'CRM_Contact_DAO_Contact', 'fields' => array('display_name' => array('title' => ts('Job life insurance Provider'), 'no_repeat' => TRUE, 'no_display' => TRUE, 'required' => TRUE), 'id' => array('no_display' => TRUE, 'required' => TRUE)), 'filters' => array('display_name' => array('title' => ts('Job life insurance Provider'), 'operatorType' => CRM_Report_Form::OP_STRING))), 'civicrm_hrjobcontract_hour' => array('dao' => 'CRM_Hrjobcontract_DAO_HRJobHour', 'fields' => array('hrjobcontract_hour_hours_type' => array(), 'hrjobcontract_hour_hours_amount' => array(), 'hrjobcontract_hour_hours_unit' => array(), 'hrjobcontract_hour_hours_fte' => array()), 'filters' => array('hrjobcontract_hour_hours_type' => array(), 'hrjobcontract_hour_hours_amount' => array(), 'hrjobcontract_hour_hours_unit' => array(), 'hrjobcontract_hour_hours_fte' => array()), 'grouping' => array('job-fields' => 'Job')), 'civicrm_hrjobcontract_pay' => array('dao' => 'CRM_Hrjobcontract_DAO_HRJobPay', 'fields' => array('hrjobcontract_pay_is_paid' => array(), 'hrjobcontract_pay_pay_amount' => array(), 'hrjobcontract_pay_pay_unit' => array(), 'hrjobcontract_pay_pay_currency' => array(), 'hrjobcontract_pay_pay_annualized_est' => array()), 'filters' => array('hrjobcontract_pay_is_paid' => array(), 'hrjobcontract_pay_pay_amount' => array(), 'hrjobcontract_pay_pay_unit' => array(), 'hrjobcontract_pay_pay_annualized_est' => array()), 'grouping' => array('job-fields' => 'Job')), 'civicrm_hrjobcontract_pension' => array('dao' => 'CRM_Hrjobcontract_DAO_HRJobPension', 'fields' => array('hrjobcontract_pension_is_enrolled' => array()), 'filters' => array('hrjobcontract_pension_is_enrolled' => array()), 'grouping' => array('job-fields' => 'Job')), 'civicrm_hrjobcontract_role' => array('dao' => 'CRM_Hrjobcontract_DAO_HRJobRole', 'fields' => array('hrjobcontract_role_role_department' => array(), 'hrjobcontract_role_role_level_type' => array('name' => 'level_type', 'title' => ts('Role Level Types'), 'type' => CRM_Utils_Type::T_INT, 'grouping' => array('job-fields' => 'Job')), 'manager' => array('name' => 'manager_sort_name', 'title' => ts('Role Managers'), 'dbAlias' => 'manager.sort_name'), 'hrjob_role_manager_contact_id' => array('no_display' => TRUE, 'name' => 'manager_contact_id', 'title' => ts('Role Managers'), 'type' => CRM_Utils_Type::T_INT, 'grouping' => array('job-fields' => 'Job'))), 'filters' => array('hrjobcontract_role_role_department' => array(), 'hrjobcontract_role_role_level_type' => array()), 'grouping' => array('job-fields' => 'Job'))) + $this->addAddressFields(FALSE, TRUE); parent::__construct(); }
/** * @param $formValues * * @throws Exception */ public function __construct(&$formValues) { parent::__construct($formValues); // unset search profile and other search params if set unset($this->_formValues['uf_group_id']); unset($this->_formValues['component_mode']); unset($this->_formValues['operator']); if (!empty($this->_formValues)) { // add the country and state if (!empty($this->_formValues['country_id'])) { $this->_formValues['country'] = CRM_Core_PseudoConstant::country($this->_formValues['country_id']); } if (!empty($this->_formValues['state_province_id'])) { $this->_formValues['state_province'] = CRM_Core_PseudoConstant::stateProvince($this->_formValues['state_province_id']); } // use the address to get the latitude and longitude CRM_Utils_Geocode_Google::format($this->_formValues); if (!is_numeric(CRM_Utils_Array::value('geo_code_1', $this->_formValues)) || !is_numeric(CRM_Utils_Array::value('geo_code_2', $this->_formValues)) || !isset($this->_formValues['distance'])) { CRM_Core_Error::fatal(ts('Could not geocode input')); } $this->_latitude = $this->_formValues['geo_code_1']; $this->_longitude = $this->_formValues['geo_code_2']; if ($this->_formValues['prox_distance_unit'] == "miles") { $conversionFactor = 1609.344; } else { $conversionFactor = 1000; } $this->_distance = $this->_formValues['distance'] * $conversionFactor; } $this->_group = CRM_Utils_Array::value('group', $this->_formValues); $this->_tag = CRM_Utils_Array::value('tag', $this->_formValues); $this->_columns = array(ts('Name') => 'sort_name', ts('Street Address') => 'street_address', ts('City') => 'city', ts('Postal Code') => 'postal_code', ts('State') => 'state_province', ts('Country') => 'country'); }
function civicrm_pseudoconstant_stateProvince($params) { $stateProvince = CRM_Core_PseudoConstant::stateProvince(); $return = array('stateProvince' => $stateProvince); return $return; }
/** * create all common fields needed for a credit card or direct debit transaction * * @return void * @access protected */ protected function _setPaymentFields(&$form) { $bltID = $form->_bltID; $form->_fields['billing_first_name'] = array('htmlType' => 'text', 'name' => 'billing_first_name', 'title' => ts('Billing First Name'), 'cc_field' => true, 'attributes' => array('size' => 30, 'maxlength' => 60, 'autocomplete' => 'off'), 'is_required' => true); $form->_fields['billing_middle_name'] = array('htmlType' => 'text', 'name' => 'billing_middle_name', 'title' => ts('Billing Middle Name'), 'cc_field' => true, 'attributes' => array('size' => 30, 'maxlength' => 60, 'autocomplete' => 'off'), 'is_required' => false); $form->_fields['billing_last_name'] = array('htmlType' => 'text', 'name' => 'billing_last_name', 'title' => ts('Billing Last Name'), 'cc_field' => true, 'attributes' => array('size' => 30, 'maxlength' => 60, 'autocomplete' => 'off'), 'is_required' => true); $form->_fields["billing_street_address-{$bltID}"] = array('htmlType' => 'text', 'name' => "billing_street_address-{$bltID}", 'title' => ts('Street Address'), 'cc_field' => true, 'attributes' => array('size' => 30, 'maxlength' => 60, 'autocomplete' => 'off'), 'is_required' => true); $form->_fields["billing_city-{$bltID}"] = array('htmlType' => 'text', 'name' => "billing_city-{$bltID}", 'title' => ts('City'), 'cc_field' => true, 'attributes' => array('size' => 30, 'maxlength' => 60, 'autocomplete' => 'off'), 'is_required' => true); $form->_fields["billing_state_province_id-{$bltID}"] = array('htmlType' => 'select', 'name' => "billing_state_province_id-{$bltID}", 'title' => ts('State / Province'), 'cc_field' => true, 'attributes' => array('' => ts('- select -')) + CRM_Core_PseudoConstant::stateProvince(), 'is_required' => true); $form->_fields["billing_postal_code-{$bltID}"] = array('htmlType' => 'text', 'name' => "billing_postal_code-{$bltID}", 'title' => ts('Postal Code'), 'cc_field' => true, 'attributes' => array('size' => 30, 'maxlength' => 60, 'autocomplete' => 'off'), 'is_required' => true); $form->_fields["billing_country_id-{$bltID}"] = array('htmlType' => 'select', 'name' => "billing_country_id-{$bltID}", 'title' => ts('Country'), 'cc_field' => true, 'attributes' => array('' => ts('- select -')) + CRM_Core_PseudoConstant::country(), 'is_required' => true); }
/** * Prepare a set of search fields * * @param CRM_Core_Form $form modifiable * @return void */ function buildForm(&$form) { CRM_Utils_System::setTitle(ts('My Search Title')); $form->add('text', 'household_name', ts('Household Name'), TRUE); $stateProvince = array('' => ts('- any state/province -')) + CRM_Core_PseudoConstant::stateProvince(); $form->addElement('select', 'state_province_id', ts('State/Province'), $stateProvince); // Optionally define default search values $form->setDefaults(array('household_name' => '', 'state_province_id' => NULL)); /** * if you are using the standard template, this array tells the template what elements * are part of the search criteria */ $form->assign('elements', array('household_name', 'state_province_id')); }
/** * Validate a value against a CustomField type. * * @param string $type * The type of the data. * @param string $value * The data to be validated. * * @return bool * True if the value is of the specified type */ public static function typecheck($type, $value) { switch ($type) { case 'Memo': return TRUE; case 'String': return CRM_Utils_Rule::string($value); case 'Int': return CRM_Utils_Rule::integer($value); case 'Float': case 'Money': return CRM_Utils_Rule::numeric($value); case 'Date': if (is_numeric($value)) { return CRM_Utils_Rule::dateTime($value); } else { return CRM_Utils_Rule::date($value); } case 'Boolean': return CRM_Utils_Rule::boolean($value); case 'ContactReference': return CRM_Utils_Rule::validContact($value); case 'StateProvince': //fix for multi select state, CRM-3437 $valid = FALSE; $mulValues = explode(',', $value); foreach ($mulValues as $key => $state) { $valid = array_key_exists(strtolower(trim($state)), array_change_key_case(array_flip(CRM_Core_PseudoConstant::stateProvinceAbbreviation()), CASE_LOWER)) || array_key_exists(strtolower(trim($state)), array_change_key_case(array_flip(CRM_Core_PseudoConstant::stateProvince()), CASE_LOWER)); if (!$valid) { break; } } return $valid; case 'Country': //fix multi select country, CRM-3437 $valid = FALSE; $mulValues = explode(',', $value); foreach ($mulValues as $key => $country) { $valid = array_key_exists(strtolower(trim($country)), array_change_key_case(array_flip(CRM_Core_PseudoConstant::countryIsoCode()), CASE_LOWER)) || array_key_exists(strtolower(trim($country)), array_change_key_case(array_flip(CRM_Core_PseudoConstant::country()), CASE_LOWER)); if (!$valid) { break; } } return $valid; case 'Link': return CRM_Utils_Rule::url($value); } return FALSE; }
/** * Build form. * * @param CRM_Core_Form $form */ public function buildForm(&$form) { $form->add('text', 'household_name', ts('Household Name'), TRUE); $stateProvince = array('' => ts('- any state/province -')) + CRM_Core_PseudoConstant::stateProvince(); $form->addElement('select', 'state_province_id', ts('State/Province'), $stateProvince); /** * You can define a custom title for the search form */ $this->setTitle(ts('My Search Title')); /** * if you are using the standard template, this array tells the template what elements * are part of the search criteria */ $form->assign('elements', array('household_name', 'state_province_id')); }
/** * Function to actually build the form * * @return None * @access public */ function buildQuickForm() { $this->add('text', 'sort_name', ts('Name or email'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name')); // select for state province $stateProvince = array('' => ts('- any state/province -')) + CRM_Core_PseudoConstant::stateProvince(); $this->addElement('select', 'state_province', ts('State/Province'), $stateProvince); // select for country $country = array('' => ts('- any country -')) + CRM_Core_PseudoConstant::country(); $this->addElement('select', 'country', ts('Country'), $country); $this->addElement('date', 'birth_date', ts('Date of birth'), CRM_Core_SelectValues::date('birth')); $this->addElement('date', 'scheduled_date_time', ts('Date and Time'), CRM_Core_SelectValues::date('datetime')); $group = array('' => ts('- any group -')) + CRM_Core_PseudoConstant::group(); $this->addElement('select', 'group', ts('Groups'), $group); $this->addButtons(array(array('type' => 'refresh', 'name' => ts('Search'), 'isDefault' => true))); }
public function _populateOptionAndCustomGroup() { $dataValues = array('integer' => array(1, 2, 3), 'number' => array(10.11, 20.22, 30.33), 'string' => array(substr(sha1(rand()), 0, 4), substr(sha1(rand()), 0, 3), substr(sha1(rand()), 0, 2)), 'country' => array_rand(CRM_Core_PseudoConstant::country(FALSE, FALSE), 3), 'state_province' => array_rand(CRM_Core_PseudoConstant::stateProvince(FALSE, FALSE), 3), 'date' => NULL, 'contact' => NULL); foreach ($dataValues as $dataType => $values) { $this->optionGroup[$dataType] = array('values' => $values); if (!empty($values)) { $result = $this->callAPISuccess('OptionGroup', 'create', array('name' => "{$dataType}_group", 'api.option_value.create' => array('label' => "{$dataType} 1", 'value' => $values[0]), 'api.option_value.create.1' => array('label' => "{$dataType} 2", 'value' => $values[1]), 'api.option_value.create.2' => array('label' => "{$dataType} 3", 'value' => $values[2]))); $this->optionGroup[$dataType]['id'] = $result['id']; } elseif ($dataType == 'contact') { for ($i = 0; $i < 3; $i++) { $result = $this->callAPISuccess('Contact', 'create', array('contact_type' => 'Individual', 'email' => substr(sha1(rand()), 0, 7) . '@yahoo.com')); $this->optionGroup[$dataType]['values'][$i] = $result['id']; } } $this->ids[$dataType] = $this->entityCustomGroupWithSingleFieldCreate("{$dataType} Custom Group", 'Contacts'); } }
function buildForm(&$form) { /** * You can define a custom title for the search form */ $this->setTitle('List Employers for Individual Contacts'); /** * Define the search form fields here */ $form->add('text', 'sort_name', ts('Individual\'s Name (last, first)')); $stateProvince = array('' => ts('- any state/province -')) + CRM_Core_PseudoConstant::stateProvince(); $form->addElement('select', 'state_province_id', ts('Individual\'s Home State'), $stateProvince); /** * If you are using the sample template, this array tells the template fields to render * for the search form. */ $form->assign('elements', array('sort_name', 'state_province_id')); }
/** * This function is to get the state name based on the search criteria * @param string $fragment this is the search string * @param integer $countryId country id * * @return state id / state name depending on search criteria * @access public */ function getState($fragment = '', $countryId = 0) { $fraglen = strlen($fragment); if (!$countryId) { $states = CRM_Core_PseudoConstant::stateProvince(); } else { $queryString = "SELECT civicrm_state_province.id as civicrm_state_province_id \n FROM civicrm_country , civicrm_state_province \n WHERE civicrm_state_province.country_id = civicrm_country.id\n AND civicrm_country.id = " . CRM_Utils_Type::escape($countryId, 'Integer') . "\n AND civicrm_state_province.name ='" . CRM_Utils_Type::escape($fragment, 'String') . "'"; $DAOobj =& new CRM_Core_DAO(); $DAOobj->query($queryString); while ($DAOobj->fetch()) { return $DAOobj->civicrm_state_province_id; } } for ($i = $fraglen; $i > 0; $i--) { $matches = preg_grep('/^' . substr($fragment, 0, $i) . '/i', $states); if (count($matches) > 0) { $id = key($matches); $value = current($matches); $showState[$id] = $value; return $showState; } } return ''; }
function alterDisplay(&$rows) { // custom code to alter rows $checkList = array(); $entryFound = false; $display_flag = $prev_cid = $cid = 0; $contributionTypes = CRM_Contribute_PseudoConstant::contributionType(); foreach ($rows as $rowNum => $row) { if (!empty($this->_noRepeats) && $this->_outputMode != 'csv') { // don't repeat contact details if its same as the previous row if (array_key_exists('civicrm_contact_id', $row)) { if ($cid = $row['civicrm_contact_id']) { if ($rowNum == 0) { $prev_cid = $cid; } else { if ($prev_cid == $cid) { $display_flag = 1; $prev_cid = $cid; } else { $display_flag = 0; $prev_cid = $cid; } } if ($display_flag) { foreach ($row as $colName => $colVal) { if (in_array($colName, $this->_noRepeats)) { unset($rows[$rowNum][$colName]); } } } $entryFound = true; } } } // handle state province if (array_key_exists('civicrm_address_state_province_id', $row)) { if ($value = $row['civicrm_address_state_province_id']) { $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($value, false); $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail', "reset=1&force=1&" . "state_province_id_op=in&state_province_id_value={$value}", $this->_absoluteUrl, $this->_id); $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url; $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("List all contribution(s) for this State."); } $entryFound = true; } // handle country if (array_key_exists('civicrm_address_country_id', $row)) { if ($value = $row['civicrm_address_country_id']) { $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($value, false); $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail', "reset=1&force=1&" . "country_id_op=in&country_id_value={$value}", $this->_absoluteUrl, $this->_id); $rows[$rowNum]['civicrm_address_country_id_link'] = $url; $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("List all contribution(s) for this Country."); } $entryFound = true; } // convert display name to links if (array_key_exists('civicrm_contact_display_name', $row) && CRM_Utils_Array::value('civicrm_contact_display_name', $rows[$rowNum]) && array_key_exists('civicrm_contact_id', $row)) { $url = CRM_Utils_System::url("civicrm/contact/view", 'reset=1&cid=' . $row['civicrm_contact_id'], $this->_absoluteUrl); $rows[$rowNum]['civicrm_contact_display_name_link'] = $url; $rows[$rowNum]['civicrm_contact_display_name_hover'] = ts("View Contact Summary for this Contact."); } if ($value = CRM_Utils_Array::value('civicrm_contribution_contribution_type_id', $row)) { $rows[$rowNum]['civicrm_contribution_contribution_type_id'] = $contributionTypes[$value]; $entryFound = true; } // skip looking further in rows, if first row itself doesn't // have the column we need if (!$entryFound) { break; } $lastKey = $rowNum; } }
/** * Function to build the array for display the profile fields * * @param array $params key value. * @param int $gid profile Id * @param array $groupTitle Profile Group Title. * @param array $values formatted array of key value * * @return None * @access public */ function displayProfile(&$params, $gid, &$groupTitle, &$values) { if ($gid) { require_once 'CRM/Core/BAO/UFGroup.php'; require_once 'CRM/Profile/Form.php'; require_once 'CRM/Event/PseudoConstant.php'; $session = CRM_Core_Session::singleton(); $contactID = $session->get('userID'); if ($contactID) { if (CRM_Core_BAO_UFGroup::filterUFGroups($gid, $contactID)) { $fields = CRM_Core_BAO_UFGroup::getFields($gid, false, CRM_Core_Action::VIEW); } } else { $fields = CRM_Core_BAO_UFGroup::getFields($gid, false, CRM_Core_Action::ADD); } if (is_array($fields)) { // unset any email-* fields since we already collect it, CRM-2888 foreach (array_keys($fields) as $fieldName) { if (substr($fieldName, 0, 6) == 'email-') { unset($fields[$fieldName]); } } } foreach ($fields as $v) { if (CRM_Utils_Array::value('groupTitle', $v)) { $groupTitle['groupTitle'] = $v["groupTitle"]; break; } } $config = CRM_Core_Config::singleton(); require_once 'CRM/Core/PseudoConstant.php'; $locationTypes = $imProviders = array(); $locationTypes = CRM_Core_PseudoConstant::locationType(); $imProviders = CRM_Core_PseudoConstant::IMProvider(); //start of code to set the default values foreach ($fields as $name => $field) { $index = $field['title']; $customFieldName = null; if ($name === 'organization_name') { $values[$index] = $params[$name]; } if ('state_province' == substr($name, 0, 14)) { if ($params[$name]) { $values[$index] = CRM_Core_PseudoConstant::stateProvince($params[$name]); } else { $values[$index] = ''; } } else { if ('country' == substr($name, 0, 7)) { if ($params[$name]) { $values[$index] = CRM_Core_PseudoConstant::country($params[$name]); } else { $values[$index] = ''; } } else { if ('county' == substr($name, 0, 6)) { if ($params[$name]) { $values[$index] = CRM_Core_PseudoConstant::county($params[$name]); } else { $values[$index] = ''; } } else { if ('gender' == substr($name, 0, 6)) { $gender = CRM_Core_PseudoConstant::gender(); $values[$index] = $gender[$params[$name]]; } else { if ('individual_prefix' == substr($name, 0, 17)) { $prefix = CRM_Core_PseudoConstant::individualPrefix(); $values[$index] = $prefix[$params[$name]]; } else { if ('individual_suffix' == substr($name, 0, 17)) { $suffix = CRM_Core_PseudoConstant::individualSuffix(); $values[$index] = $suffix[$params[$name]]; } else { if (in_array($name, array('addressee', 'email_greeting', 'postal_greeting'))) { $filterCondition = array('greeting_type' => $name); $greeting =& CRM_Core_PseudoConstant::greeting($filterCondition); $values[$index] = $greeting[$params[$name]]; } else { if ($name === 'preferred_communication_method') { $communicationFields = CRM_Core_PseudoConstant::pcm(); $pref = array(); $compref = array(); $pref = $params[$name]; if (is_array($pref)) { foreach ($pref as $k => $v) { if ($v) { $compref[] = $communicationFields[$k]; } } } $values[$index] = implode(",", $compref); } else { if ($name == 'group') { require_once 'CRM/Contact/BAO/GroupContact.php'; $groups = CRM_Contact_BAO_GroupContact::getGroupList(); $title = array(); foreach ($params[$name] as $gId => $dontCare) { if ($dontCare) { $title[] = $groups[$gId]; } } $values[$index] = implode(', ', $title); } else { if ($name == 'tag') { require_once 'CRM/Core/BAO/EntityTag.php'; $entityTags = $params[$name]; $allTags =& CRM_Core_PseudoConstant::tag(); $title = array(); if (is_array($entityTags)) { foreach ($entityTags as $tagId => $dontCare) { $title[] = $allTags[$tagId]; } } $values[$index] = implode(', ', $title); } else { if ('participant_role_id' == $name) { $roles = CRM_Event_PseudoConstant::participantRole(); $values[$index] = $roles[$params[$name]]; } else { if ('participant_status_id' == $name) { $status = CRM_Event_PseudoConstant::participantStatus(); $values[$index] = $status[$params[$name]]; } else { if (strpos($name, '-') !== false) { list($fieldName, $id) = CRM_Utils_System::explode('-', $name, 2); $detailName = str_replace(' ', '_', $name); if (in_array($fieldName, array('state_province', 'country', 'county'))) { $values[$index] = $params[$detailName]; $idx = $detailName . '_id'; $values[$index] = $params[$idx]; } else { if ($fieldName == 'im') { $providerName = null; if ($providerId = $detailName . '-provider_id') { $providerName = CRM_Utils_Array::value($params[$providerId], $imProviders); } if ($providerName) { $values[$index] = $params[$detailName] . " (" . $providerName . ")"; } else { $values[$index] = $params[$detailName]; } } else { $values[$index] = $params[$detailName]; } } } else { if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') { if ($params[$name]) { $values[$index] = '[ x ]'; } } else { require_once 'CRM/Core/BAO/CustomField.php'; if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) { $query = "\nSELECT html_type, data_type\nFROM civicrm_custom_field\nWHERE id = {$cfID}\n"; $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray); $dao->fetch(); $htmlType = $dao->html_type; $dataType = $dao->data_type; if ($htmlType == 'File') { //$fileURL = CRM_Core_BAO_CustomField::getFileURL( $contactID, $cfID ); //$params[$index] = $values[$index] = $fileURL['file_url']; $values[$index] = $params[$index]; } else { if ($dao->data_type == 'Int' || $dao->data_type == 'Boolean') { $customVal = (int) $params[$name]; } else { if ($dao->data_type == 'Float') { $customVal = (double) $params[$name]; } else { if ($dao->data_type == 'Date') { $date = CRM_Utils_Date::format($params[$name], null, 'invalidDate'); if ($date != 'invalidDate') { $customVal = $date; } } else { $customVal = $params[$name]; } } } //take the custom field options $returnProperties = array($name => 1); require_once 'CRM/Contact/BAO/Query.php'; $query = new CRM_Contact_BAO_Query($params, $returnProperties, $fields); $options =& $query->_options; $displayValue = CRM_Core_BAO_CustomField::getDisplayValue($customVal, $cfID, $options); //Hack since we dont have function to check empty. //FIXME in 2.3 using crmIsEmptyArray() $customValue = true; if (is_array($customVal) && is_array($displayValue)) { $customValue = array_diff($customVal, $displayValue); } //use difference of arrays if (empty($customValue) || !$customValue) { $values[$index] = ''; } else { $values[$index] = $displayValue; } if (CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $cfID, 'is_search_range')) { $customFieldName = "{$name}_from"; } } } else { if ($name == 'home_URL' && !empty($params[$name])) { $url = CRM_Utils_System::fixURL($params[$name]); $values[$index] = "<a href=\"{$url}\">{$params[$name]}</a>"; } else { if (in_array($name, array('birth_date', 'deceased_date', 'participant_register_date'))) { require_once 'CRM/Utils/Date.php'; $values[$index] = CRM_Utils_Date::customFormat(CRM_Utils_Date::format($params[$name])); } else { $values[$index] = $params[$name]; } } } } } } } } } } } } } } } } } } } }
/** * Build the form * * @access public * * @return void */ function buildQuickForm($form, $proxSearch) { // is proximity search required (2) or optional (1)? $proxRequired = $proxSearch == 2 ? TRUE : FALSE; $form->assign('proximity_search', TRUE); $form->add('text', 'prox_street_address', ts('Street Address'), NULL, FALSE); $form->add('text', 'prox_city', ts('City'), NULL, FALSE); $form->add('text', 'prox_postal_code', ts('Postal Code'), NULL, FALSE); $defaults = self::setDefaultValues($form); if (CRM_Utils_Array::value('prox_country_id', $defaults)) { $stateProvince = array('' => ts('- select -')) + CRM_Core_PseudoConstant::stateProvinceForCountry($defaults['prox_country_id']); } else { $stateProvince = array('' => ts('- select -')) + CRM_Core_PseudoConstant::stateProvince(); } $form->add('select', 'prox_state_province_id', ts('State/Province'), $stateProvince, $proxRequired); $country = array('' => ts('- select -')) + CRM_Core_PseudoConstant::country(); $form->add('select', 'prox_country_id', ts('Country'), $country, $proxRequired); $form->add('text', 'prox_distance', ts('Distance'), NULL, $proxRequired); $proxUnits = array('km' => ts('km'), 'miles' => ts('miles')); $form->add('select', 'prox_distance_unit', ts('Units'), $proxUnits, $proxRequired); // prox_distance_unit // state country js, CRM-5233 $stateCountryMap = array(); $stateCountryMap[] = array('state_province' => 'prox_state_province_id', 'country' => 'prox_country_id'); CRM_Core_BAO_Address::addStateCountryMap($stateCountryMap); CRM_Core_BAO_Address::fixAllStateSelects($this, $defaults); $form->addFormRule(array('CRM_Contact_Form_Task_ProximityCommon', 'formRule'), $form); }
function alterStateProvinceID($value, &$row, $selectedfield, $criteriaFieldName) { $url = CRM_Utils_System::url(CRM_Utils_System::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl); $row[$selectedfield . '_link'] = $url; $row[$selectedfield . '_hover'] = ts("%1 for this state.", array(1 => $value)); $states = CRM_Core_PseudoConstant::stateProvince($value, FALSE); if (!is_array($states)) { return $states; } }
/** * Test case for resolveDefaults( ). * * Test all pseudoConstant, stateProvince, country. */ public function testResolveDefaults() { $params = array('prefix_id' => 3, 'suffix_id' => 2, 'gender_id' => 2, 'birth_date' => '1983-12-13'); $params['address'][1] = array('location_type_id' => 1, 'is_primary' => 1, 'country_id' => 1228, 'state_province_id' => 1004); CRM_Contact_BAO_Contact::resolveDefaults($params); //check the resolve values. $genders = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'); $this->assertEquals($genders[$params['gender_id']], $params['gender'], 'Check for gender.'); $prefix = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'prefix_id'); $this->assertEquals($prefix[$params['prefix_id']], $params['prefix'], 'Check for prefix.'); $suffix = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'suffix_id'); $this->assertEquals($suffix[$params['suffix_id']], $params['suffix'], 'Check for suffix.'); $this->assertEquals(CRM_Core_PseudoConstant::stateProvince($params['address'][1]['state_province_id']), $params['address'][1]['state_province'], 'Check for state province.'); $this->assertEquals(CRM_Core_PseudoConstant::country($params['address'][1]['country_id']), $params['address'][1]['country'], 'Check for country.'); }
function executePrintmode($rows) { //only get these last contribution related variables in print mode if selected on previous form if (array_key_exists('civicrm_contribution_cont_receive_date', $rows[0])) { $receiveDate = ', date_received DATE'; } if (array_key_exists('civicrm_contribution_cont_total_amount', $rows[0])) { $contAmount = ' , total_amount FLOAT'; } // Separate out fields and build a temporary table $tempTable = "WalkList_" . uniqid(); $sql = "CREATE TEMPORARY TABLE {$tempTable}" . " ( id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,\n street_name VARCHAR(255),\n s_street_number VARCHAR(32),\n i_street_number INT,\n odd TINYINT,\n apt_number VARCHAR(32),\n city VARCHAR(64),\n state VARCHAR(32),\n zip VARCHAR(32),\n name VARCHAR(255),\n phone VARCHAR(255),\n age INT,\n sex VARCHAR(16),\n lang CHAR(2),\n party CHAR(1),\n vh CHAR(1),\n contact_type VARCHAR(128),\n other_name VARCHAR(128),\n contact_id INT\n {$receiveDate} {$contAmount}\n )\n ENGINE=HEAP\n DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci"; CRM_Core_DAO::executeQuery($sql); $gender = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'); foreach ($rows as $key => $value) { $dob = $value['civicrm_contact_birth_date']; $age = empty($dob) ? 0 : $this->dob2age($dob); if (!empty($value['civicrm_contact_gender_id'])) { $sex = $gender[CRM_Utils_Array::value('civicrm_contact_gender_id', $value)]; } $sex = empty($sex) ? '' : $sex; $lang = strtoupper(substr($value[$this->_demoTable . '_' . $this->_demoLangCol], 0, 2)); $party = substr($value["{$this->_voterInfoTable}_{$this->_partyCol}"], 0, 1); $vh = substr($value["{$this->_voterInfoTable}_{$this->_vhCol}"], 0, 1); $contactType = $value[$this->_coreInfoTable . '_' . $this->_coreTypeCol]; $on = $value[$this->_coreInfoTable . '_' . $this->_coreOtherCol]; $otherName = empty($on) ? 0 : "'{$on}'"; $type = ''; if (!empty($contactType)) { $type = $this->hexOne2str($contactType); } $contact_id = (int) $value['civicrm_contact_id']; $state = ''; if (!empty($value['civicrm_address_state_province_id'])) { $state = CRM_Core_PseudoConstant::stateProvince($value['civicrm_address_state_province_id']); } $sStreetNumber = $value['civicrm_address_street_number']; $iStreetNumber = $value['civicrm_address_street_number'] ? (int) $value['civicrm_address_street_number'] : 0; $odd = $value['civicrm_address_street_number'] ? (int) $value['civicrm_address_street_number'] % 2 : 0; $apt_number = $value['civicrm_address_street_number'] ? $value['civicrm_address_street_number'] : ''; $phone_number = $value['civicrm_phone_phone'] ? $value['civicrm_phone_phone'] : ''; $query = "INSERT INTO {$tempTable} SET\n street_name = %1,\n s_street_number = %2,\n i_street_number = %3,\n odd = %4,\n apt_number = %5,\n city = %6,\n state = %7,\n zip = %8,\n name = %9,\n phone = %10,\n age = %11,\n sex = %12,\n lang = %13,\n party = %14,\n vh = %15,\n contact_type = %16,\n other_name = %17,\n contact_id = %18"; $params = array(1 => array($value['civicrm_address_street_name'] ? $value['civicrm_address_street_name'] : '', 'String'), 2 => array((string) $sStreetNumber, 'String'), 3 => array($iStreetNumber, 'Integer'), 4 => array($odd, 'Integer'), 5 => array((string) $apt_number, 'String'), 6 => array($value['civicrm_address_city'] ? $value['civicrm_address_city'] : '', 'String'), 7 => array((string) $state, 'String'), 8 => array($value['civicrm_address_postal_code'] ? $value['civicrm_address_postal_code'] : '', 'String'), 9 => array($value['civicrm_contact_display_name'] ? $value['civicrm_contact_display_name'] : '', 'String'), 10 => array((string) $phone_number, 'String'), 11 => array($age, 'Integer'), 12 => array((string) $sex, 'String'), 13 => array((string) $lang, 'String'), 14 => array((string) $party, 'String'), 15 => array((string) $vh, 'String'), 16 => array((string) $type, 'String'), 17 => array((string) $otherName, 'String'), 18 => array((string) $contact_id, 'Integer')); if (!empty($contAmount)) { $query .= ", total_amount = %19"; $total_amount = $value['civicrm_contribution_cont_total_amount'] ? $value['civicrm_contribution_cont_total_amount'] : 0; $params[19] = array($total_amount, 'Money'); } if (!empty($receiveDate)) { $query .= ",date_received = %20"; $date_received = $value['civicrm_contribution_cont_receive_date'] ? CRM_Utils_Date::isoToMysql($value['civicrm_contribution_cont_receive_date']) : NULL; $params[20] = array($date_received, 'Timestamp'); } CRM_Core_DAO::executeQuery($query, $params); } // With the data normalized and in a table, we can // retrieve it in the order we need to present it $query = "SELECT * FROM {$tempTable} ORDER BY state, city, zip,\n street_name, odd, i_street_number, apt_number"; $dao = CRM_Core_DAO::executeQuery($query); // Initialize output state $first = TRUE; $state = ''; $city = ''; $zip = ''; $street_name = ''; $odd = ''; $pageRow = 0; $reportDate = date('F j, Y'); $pdfRows = array(); $groupRows = array(); $groupCounts = 0; $pdfHeaders = array('s_street_number' => array('title' => 'STREET#'), 'apt_number' => array('title' => 'APT'), 'name' => array('title' => 'Name'), 'phone' => array('title' => 'PHONE'), 'age' => array('title' => 'AGE'), 'sex' => array('title' => 'SEX'), 'lang' => array('title' => 'Lang'), 'party' => array('title' => 'Party'), 'vh' => array('title' => 'VH'), 'contact_type' => array('title' => 'Constituent Type'), 'note' => array('title' => 'NOTES'), 'rcode' => array('title' => 'RESPONSE CODES'), 'status' => array('title' => 'STATUS'), 'contact_id' => array('title' => 'ID', 'class' => 'width=7%')); if (variable_get('civicrm_engage_groupbreak_street', "1") != 1) { $pdfHeaders['street_name']['title'] = 'Street'; } if ($receiveDate) { $pdfHeaders['date_received'] = array('title' => 'Last donation Date'); } if ($contAmount) { $pdfHeaders['total_amount'] = array('title' => 'Last donation'); } $groupInfo = array('date' => $reportDate, 'descr' => empty($this->_groupDescr) ? '' : "<br>Group {$this->_groupDescr}"); while ($dao->fetch()) { if (strtolower($state) != strtolower($dao->state) || variable_get('civicrm_engage_groupbreak_city', "1") == 1 && strtolower($city) != strtolower($dao->city) || variable_get('civicrm_engage_groupbreak_zip', "1") == 1 && strtolower($zip) != strtolower($dao->zip) || variable_get('civicrm_engage_groupbreak_street', "1") == 1 && strtolower($street_name) != strtolower($dao->street_name) || variable_get('civicrm_engage_groupbreak_odd_even', "1") == 1 && $odd != $dao->odd || $pageRow > variable_get('civicrm_engage_lines_per_group', "6") - 1) { $state = $dao->state; $city = $dao->city; $zip = $dao->zip; $street_name = $dao->street_name; $odd = $dao->odd; $pageRow = 0; $groupRow['city_zip'] = ''; $groupRow['org'] = $this->_orgName; if (variable_get('civicrm_engage_groupbreak_street', "1") == 1) { $groupRow['street_name'] = $street_name; } if (variable_get('civicrm_engage_groupbreak_city', "1") == 1) { $groupRow['city_zip'] .= $city . ', '; } $groupRow['city_zip'] .= $state; //don't give zip or odd-even if not grouped on if (variable_get('civicrm_engage_groupbreak_zip', "1") == 1) { $groupRow['city_zip'] .= ' ' . $zip; } if (variable_get('civicrm_engage_groupbreak_odd_even', "1") == 1) { $groupRow['odd'] = $odd ? 'Odd' : 'Even'; } $groupCounts++; $groupRows[$groupCounts] = $groupRow; } // if admin settings have been defined to specify not to canvas people for a period change date to specified text if (variable_get('civicrm_engage_no_canvas_period', "0") > 0 && $dao->date_received > 0 && (strtotime("now") - strtotime($dao->date_received)) / 60 / 60 / 24 / 30 < variable_get('civicrm_engage_no_canvas_period', "0")) { $dao->date_received = variable_get('civicrm_engage_no_canvass_text', "Do Not Canvass"); } $pdfRow = array(); foreach ($pdfHeaders as $k => $v) { if (property_exists($dao, $k)) { if ($k == 'name' && $dao->other_name) { $pdfRow[$k] = $dao->{$k} . "<br />" . $dao->other_name; continue; } $pdfRow[$k] = $dao->{$k}; } else { $pdfRow[$k] = ""; } } $pdfRows[$groupCounts][] = $pdfRow; $pageRow++; } if (variable_get('civicrm_engage_group_per_page', "1")) { $this->assign('newgroupdiv', 'class="page"'); } $this->assign('pageTotal', $groupCounts); $this->assign('pdfHeaders', $pdfHeaders); $this->assign('groupInfo', $groupInfo); $this->assign('pdfRows', $pdfRows); $this->assign('groupRows', $groupRows); }
/** * Alter display of rows. * * Iterate through the rows retrieved via SQL and make changes for display purposes, * such as rendering contacts as links. * * @param array $rows * Rows generated by SQL, with an array for each row. */ public function alterDisplay(&$rows) { list($from1, $to1) = $this->getFromTo(CRM_Utils_Array::value("receive_date1_relative", $this->_params), CRM_Utils_Array::value("receive_date1_from", $this->_params), CRM_Utils_Array::value("receive_date1_to", $this->_params)); list($from2, $to2) = $this->getFromTo(CRM_Utils_Array::value("receive_date2_relative", $this->_params), CRM_Utils_Array::value("receive_date2_from", $this->_params), CRM_Utils_Array::value("receive_date2_to", $this->_params)); $dateUrl = ""; if ($from1) { $dateUrl .= "receive_date1_from={$from1}&"; } if ($to1) { $dateUrl .= "receive_date1_to={$to1}&"; } if ($from2) { $dateUrl .= "receive_date2_from={$from2}&"; } if ($to2) { $dateUrl .= "receive_date2_to={$to2}&"; } foreach ($rows as $rowNum => $row) { // handle country if (array_key_exists('address_civireport_country_id', $row)) { if ($value = $row['address_civireport_country_id']) { $rows[$rowNum]['address_civireport_country_id'] = CRM_Core_PseudoConstant::country($value, FALSE); $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail', "reset=1&force=1&" . "country_id_op=in&country_id_value={$value}&" . "{$dateUrl}", $this->_absoluteUrl, $this->_id, $this->_drilldownReport); $rows[$rowNum]['address_civireport_country_id_link'] = $url; $rows[$rowNum]['address_civireport_country_id_hover'] = ts("View contributions for this Country."); } } // handle state province if (array_key_exists('address_civireport_state_province_id', $row)) { if ($value = $row['address_civireport_state_province_id']) { $rows[$rowNum]['address_civireport_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($value, FALSE); $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail', "reset=1&force=1&" . "state_province_id_op=in&state_province_id_value={$value}&" . "{$dateUrl}", $this->_absoluteUrl, $this->_id, $this->_drilldownReport); $rows[$rowNum]['address_civireport_state_province_id_link'] = $url; $rows[$rowNum]['address_civireport_state_province_id_hover'] = ts("View repeatDetails for this state."); } } // convert display name to links if (array_key_exists('contact_civireport_sort_name', $row) && array_key_exists('contact_civireport_id', $row)) { $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail', 'reset=1&force=1&id_op=eq&id_value=' . $row['contact_civireport_id'], $this->_absoluteUrl, $this->_id, $this->_drilldownReport); $rows[$rowNum]['contact_civireport_sort_name_link'] = $url; $rows[$rowNum]['contact_civireport_sort_name_hover'] = ts("View Contribution details for this contact"); } } // foreach ends }
function alterDisplay(&$rows) { // custom code to alter rows $genderList = CRM_Core_PseudoConstant::gender(); $entryFound = false; foreach ($rows as $rowNum => $row) { // handle state province if (array_key_exists('civicrm_address_state_province_id', $row)) { if ($value = $row['civicrm_address_state_province_id']) { $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($value); } $entryFound = true; } // handle country if (array_key_exists('civicrm_address_country_id', $row)) { if ($value = $row['civicrm_address_country_id']) { $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($value); } $entryFound = true; } // Handle contactType if (!empty($row[$this->_coreInfoTable . '_' . $this->_coreTypeCol])) { $rows[$rowNum][$this->_coreInfoTable . '_' . $this->_coreTypeCol] = $this->type2str($rows[$rowNum][$this->_coreInfoTable . '_' . $this->_coreTypeCol]); $entryFound = true; } // date of birth to age if (!empty($row['civicrm_contact_birth_date'])) { $rows[$rowNum]['civicrm_contact_birth_date'] = $this->dob2age($row['civicrm_contact_birth_date']); $entryFound = true; } // gender label if (!empty($row['civicrm_contact_gender_id'])) { $rows[$rowNum]['civicrm_contact_gender_id'] = $genderList[$row['civicrm_contact_gender_id']]; $entryFound = true; } if ($this->_outputMode != 'html' && !empty($row[$this->_coreInfoTable . '_' . $this->_coreOtherCol])) { $rows[$rowNum]['civicrm_contact_display_name'] .= "<br />" . $row[$this->_coreInfoTable . '_' . $this->_coreOtherCol]; $entryFound = true; } // skip looking further in rows, if first row itself doesn't // have the column we need if (!$entryFound) { break; } } $columnOrder = array('civicrm_phone_phone', 'civicrm_contact_display_name', 'civicrm_address_street_address', 'civicrm_contact_birth_date', 'civicrm_contact_gender_id', $this->_demoTable . '_' . $this->_demoLangCol, $this->_coreInfoTable . '_' . $this->_coreTypeCol, 'civicrm_contact_id'); if ($this->_outputMode == 'print' || $this->_outputMode == 'pdf') { $this->_columnHeaders = array('civicrm_phone_phone' => array('title' => 'PHONE', 'type' => CRM_Utils_Type::T_STRING, 'class' => 'width=68'), 'civicrm_contact_display_name' => array('title' => 'NAME', 'type' => CRM_Utils_Type::T_STRING, 'class' => 'width=83'), 'civicrm_address_street_address' => array('title' => 'ADDRESS', 'type' => CRM_Utils_Type::T_STRING, 'class' => 'width=117'), 'civicrm_contact_birth_date' => array('title' => 'AGE', 'type' => CRM_Utils_Type::T_STRING, 'class' => 'width=25'), 'civicrm_contact_gender_id' => array('title' => 'SEX', 'type' => CRM_Utils_Type::T_STRING, 'class' => 'width=18'), $this->_demoTable . '_' . $this->_demoLangCol => array('title' => 'Lang', 'type' => CRM_Utils_Type::T_STRING, 'class' => 'width=27'), $this->_coreInfoTable . '_' . $this->_coreTypeCol => array('title' => 'Contact Type', 'type' => CRM_Utils_Type::T_STRING, 'class' => 'width=48'), 'notes' => array('title' => 'NOTES', 'type' => CRM_Utils_Type::T_STRING, 'class' => 'width=48'), 'response_codes' => array('title' => 'RESPONSE CODES', 'type' => CRM_Utils_Type::T_STRING, 'class' => 'width=91'), 'status' => array('title' => 'STATUS', 'type' => CRM_Utils_Type::T_STRING, 'class' => 'width=70'), 'civicrm_contact_id' => array('title' => 'ID', 'type' => CRM_Utils_Type::T_STRING, 'class' => 'width=100')); $newRows = array(); foreach ($columnOrder as $col) { foreach ($rows as $rowNum => $row) { $newRows[$rowNum][$col] = $row[$col]; $newRows[$rowNum]['notes'] = ' '; $newRows[$rowNum]['status'] = 'NH MV D WN'; $newRows[$rowNum]['response_codes'] = ' Q1 Y N U D<br /> Q2 Y N U D<br /> Q3 Y N U D<br /> Q4 Y N U D'; } } $rows = $newRows; $this->assign('pageTotal', ceil(count($newRows) / 7)); } else { // make sure column order is same as in print mode $tempHeaders = $this->_columnHeaders; $this->_columnHeaders = array(); foreach ($columnOrder as $col) { if (array_key_exists($col, $tempHeaders)) { $this->_columnHeaders[$col] = $tempHeaders[$col]; unset($tempHeaders[$col]); } } $this->_columnHeaders = $this->_columnHeaders + $tempHeaders; } }
function alterDisplay(&$rows) { // custom code to alter rows $entryFound = FALSE; foreach ($rows as $rowNum => $row) { // make count columns point to detail report // convert display name to links if (array_key_exists('civicrm_contact_sort_name', $row) && array_key_exists('civicrm_contact_id', $row)) { $url = CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $row['civicrm_contact_id'], $this->_absoluteUrl); $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url; $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contact details for this contact."); $entryFound = TRUE; } // handle gender if (array_key_exists('civicrm_contact_gender_id', $row)) { if ($value = $row['civicrm_contact_gender_id']) { $rows[$rowNum]['civicrm_contact_gender_id'] = $this->_genders[$value]; } $entryFound = TRUE; } // handle country if (array_key_exists('civicrm_address_country_id', $row)) { if ($value = $row['civicrm_address_country_id']) { $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($value, FALSE); } $entryFound = TRUE; } if (array_key_exists('civicrm_address_state_province_id', $row)) { if ($value = $row['civicrm_address_state_province_id']) { $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($value, FALSE); } $entryFound = TRUE; } // handle custom fields foreach ($row as $k => $r) { if (substr($k, 0, 13) == 'civicrm_value' || substr($k, 0, 12) == 'custom_value') { if ($r || $r == '0') { if ($newval = $this->getCustomFieldLabel($k, $r)) { $rows[$rowNum][$k] = $newval; } } $entryFound = TRUE; } } // skip looking further in rows, if first row itself doesn't // have the column we need if (!$entryFound) { break; } } }
/** * Given the list of params in the params array, fetch the object * and store the values in the values array * * @param array $entityBlock * Associated array of fields. * @param bool $microformat * If microformat output is required. * @param int|string $fieldName conditional field name * * @return array * array with address fields */ public static function &getValues($entityBlock, $microformat = FALSE, $fieldName = 'contact_id') { if (empty($entityBlock)) { return NULL; } $addresses = array(); $address = new CRM_Core_BAO_Address(); if (empty($entityBlock['entity_table'])) { $address->{$fieldName} = CRM_Utils_Array::value($fieldName, $entityBlock); } else { $addressIds = array(); $addressIds = self::allEntityAddress($entityBlock); if (!empty($addressIds[1])) { $address->id = $addressIds[1]; } else { return $addresses; } } //get primary address as a first block. $address->orderBy('is_primary desc, id'); $address->find(); $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); $count = 1; while ($address->fetch()) { // deprecate reference. if ($count > 1) { foreach (array('state', 'state_name', 'country', 'world_region') as $fld) { if (isset($address->{$fld})) { unset($address->{$fld}); } } } $stree = $address->street_address; $values = array(); CRM_Core_DAO::storeValues($address, $values); // add state and country information: CRM-369 if (!empty($address->location_type_id)) { $values['location_type'] = CRM_Utils_Array::value($address->location_type_id, $locationTypes); } if (!empty($address->state_province_id)) { $address->state = CRM_Core_PseudoConstant::stateProvinceAbbreviation($address->state_province_id, FALSE); $address->state_name = CRM_Core_PseudoConstant::stateProvince($address->state_province_id, FALSE); } if (!empty($address->country_id)) { $address->country = CRM_Core_PseudoConstant::country($address->country_id); //get world region $regionId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Country', $address->country_id, 'region_id'); $address->world_region = CRM_Core_PseudoConstant::worldregion($regionId); } $address->addDisplay($microformat); $values['display'] = $address->display; $values['display_text'] = $address->display_text; if (is_numeric($address->master_id)) { $values['use_shared_address'] = 1; } $addresses[$count] = $values; //unset is_primary after first block. Due to some bug in earlier version //there might be more than one primary blocks, hence unset is_primary other than first if ($count > 1) { unset($addresses[$count]['is_primary']); } $count++; } return $addresses; }
/** * format common params data to proper format to store. * * @param array $params contain record values. * @param array $formatted array of formatted data. * @param array $contactFields contact DAO fields. * @static */ function formatCommonData($params, &$formatted, &$contactFields) { $csType = array(CRM_Utils_Array::value('contact_type', $formatted)); //CRM-5125 //add custom fields for contact sub type if (!empty($this->_contactSubType)) { $csType = $this->_contactSubType; } if ($relCsType = CRM_Utils_Array::value('contact_sub_type', $formatted)) { $csType = $relCsType; } $customFields = CRM_Core_BAO_CustomField::getFields($formatted['contact_type'], false, false, $csType); //if a Custom Email Greeting, Custom Postal Greeting or Custom Addressee is mapped, and no "Greeting / Addressee Type ID" is provided, then automatically set the type = Customized, CRM-4575 $elements = array('email_greeting_custom' => 'email_greeting', 'postal_greeting_custom' => 'postal_greeting', 'addressee_custom' => 'addressee'); foreach ($elements as $k => $v) { if (array_key_exists($k, $params) && !array_key_exists($v, $params)) { $label = key(CRM_Core_OptionGroup::values($v, true, null, null, 'AND v.name = "Customized"')); $params[$v] = $label; } } //format date first $session =& CRM_Core_Session::singleton(); $dateType = $session->get("dateTypes"); foreach ($params as $key => $val) { if ($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) { //we should not update Date to null, CRM-4062 if ($val && $customFields[$customFieldID]['data_type'] == 'Date') { self::formatCustomDate($params, $formatted, $dateType, $key); unset($params[$key]); } else { if ($customFields[$customFieldID]['data_type'] == 'Boolean') { $params[$key] = CRM_Utils_String::strtoboolstr($val); } } } if ($key == 'birth_date' && $val) { CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key); } else { if ($key == 'deceased_date' && $val) { CRM_Utils_Date::convertToDefaultDate($params, $dateType, $key); } else { if ($key == 'is_deceased' && $val) { $params[$key] = CRM_Utils_String::strtoboolstr($val); } else { if ($key == 'gender') { //CRM-4360 $params[$key] = $this->checkGender($val); } } } } } //now format custom data. foreach ($params as $key => $field) { if ($field == null || $field === '') { continue; } if (is_array($field)) { foreach ($field as $value) { $break = false; if (is_array($value)) { foreach ($value as $name => $testForEmpty) { // check if $value does not contain IM provider or phoneType if (($name !== 'phone_type_id' || $name !== 'provider_id') && ($testForEmpty === '' || $testForEmpty == null)) { $break = true; break; } } } else { $break = true; } if (!$break) { _civicrm_add_formatted_param($value, $formatted); } } continue; } $formatValues = array($key => $field); if ($key !== 'preferred_communication_method' && array_key_exists($key, $contactFields)) { // due to merging of individual table and // contact table, we need to avoid // preferred_communication_method forcefully $formatValues['contact_type'] = $formatted['contact_type']; } if ($key == 'id' && isset($field)) { $formatted[$key] = $field; } _civicrm_add_formatted_param($formatValues, $formatted); //Handling Custom Data if (($customFieldID = CRM_Core_BAO_CustomField::getKeyID($key)) && array_key_exists($customFieldID, $customFields)) { //get the html type. $type = $customFields[$customFieldID]['html_type']; switch ($type) { case 'CheckBox': case 'AdvMulti-Select': case 'Multi-Select': $mulValues = explode(',', $field); $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, true); $formatted[$key] = array(); foreach ($mulValues as $v1) { foreach ($customOption as $v2) { if (strtolower($v2['label']) == strtolower(trim($v1)) || strtolower($v2['value']) == strtolower(trim($v1))) { if ($type == 'CheckBox') { $formatted[$key][$v2['value']] = 1; } else { $formatted[$key][] = $v2['value']; } } } } break; case 'Select': case 'Radio': $customOption = CRM_Core_BAO_CustomOption::getCustomOption($customFieldID, true); foreach ($customOption as $v2) { if (strtolower($v2['label']) == strtolower(trim($field)) || strtolower($v2['value']) == strtolower(trim($field))) { $formatted[$key] = $v2['value']; } } break; case 'Multi-Select State/Province': $mulValues = explode(',', $field); $stateAbbr = CRM_Core_PseudoConstant::stateProvinceAbbreviation(); $stateName = CRM_Core_PseudoConstant::stateProvince(); $formatted[$key] = $stateValues = array(); foreach ($mulValues as $values) { if ($val = CRM_Utils_Array::key($values, $stateAbbr)) { $formatted[$key][] = $val; } else { if ($val = CRM_Utils_Array::key($values, $stateName)) { $formatted[$key][] = $val; } } } break; case 'Multi-Select Country': $config =& CRM_Core_Config::singleton(); $limitCodes = $config->countryLimit(); $mulValues = explode(',', $field); $formatted[$key] = array(); CRM_Core_PseudoConstant::populate($countryNames, 'CRM_Core_DAO_Country', true, 'name', 'is_active'); CRM_Core_PseudoConstant::populate($countryIsoCodes, 'CRM_Core_DAO_Country', true, 'iso_code'); foreach ($mulValues as $values) { if ($val = CRM_Utils_Array::key($values, $countryNames)) { $formatted[$key][] = $val; } else { if ($val = CRM_Utils_Array::key($values, $countryIsoCodes)) { $formatted[$key][] = $val; } else { if ($val = CRM_Utils_Array::key($values, $limitCodes)) { $formatted[$key][] = $val; } } } } break; } } } // check for primary location type, whether it is already present for the contact or not, CRM-4423 if (CRM_Utils_Array::value('id', $formatted) && isset($formatted['location'])) { $primaryLocationTypeId = CRM_Contact_BAO_Contact::getPrimaryLocationType($formatted['id'], true); if (isset($primaryLocationTypeId)) { foreach ($formatted['location'] as $loc => $details) { if ($primaryLocationTypeId == CRM_Utils_Array::value('location_type_id', $details)) { $formatted['location'][$loc]['is_primary'] = 1; break; } else { $formatted['location'][$loc]['is_primary'] = 0; } } } } // parse street address, CRM-5450 if ($this->_parseStreetAddress) { require_once 'CRM/Core/BAO/Address.php'; if (array_key_exists('address', $formatted) && is_array($formatted['address'])) { foreach ($formatted['address'] as $instance => &$address) { $streetAddress = CRM_Utils_Array::value('street_address', $address); if (empty($streetAddress)) { continue; } // parse address field. $parsedFields = CRM_Core_BAO_Address::parseStreetAddress($streetAddress); //street address consider to be parsed properly, //If we get street_name and street_number. if (!CRM_Utils_Array::value('street_name', $parsedFields) || !CRM_Utils_Array::value('street_number', $parsedFields)) { $parsedFields = array_fill_keys(array_keys($parsedFields), ''); } // merge parse address w/ main address block. $address = array_merge($address, $parsedFields); } } } }
/** * @param $rows */ function alterDisplay(&$rows) { $entryFound = FALSE; $activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE); foreach ($rows as $rowNum => $row) { if (array_key_exists('civicrm_case_status_id', $row)) { if ($value = $row['civicrm_case_status_id']) { $rows[$rowNum]['civicrm_case_status_id'] = $this->case_statuses[$value]; $entryFound = TRUE; } } if (array_key_exists('civicrm_case_case_type_id', $row)) { if ($value = str_replace(CRM_Core_DAO::VALUE_SEPARATOR, '', $row['civicrm_case_case_type_id'])) { $rows[$rowNum]['civicrm_case_case_type_id'] = $this->case_types[$value]; $entryFound = TRUE; } } if (array_key_exists('civicrm_case_subject', $row)) { if ($value = $row['civicrm_case_subject']) { $caseId = $row['civicrm_case_id']; $contactId = $row['civicrm_contact_id']; $rows[$rowNum]['civicrm_case_subject'] = "<a href= 'javascript:viewCase( {$caseId},{$contactId} );'>{$value}</a>"; $rows[$rowNum]['civicrm_case_subject_hover'] = ts('View Details of Case.'); $entryFound = TRUE; } } if (array_key_exists('civicrm_relationship_case_role', $row)) { if ($value = $row['civicrm_relationship_case_role']) { $caseRoles = explode(',', $value); foreach ($caseRoles as $num => $caseRole) { $caseRoles[$num] = $this->rel_types[$caseRole]; } $rows[$rowNum]['civicrm_relationship_case_role'] = implode('; ', $caseRoles); } $entryFound = TRUE; } if (array_key_exists('civicrm_address_country_id', $row)) { if ($value = $row['civicrm_address_country_id']) { $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($value, FALSE); } $entryFound = TRUE; } if (array_key_exists('civicrm_address_state_province_id', $row)) { if ($value = $row['civicrm_address_state_province_id']) { $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($value, FALSE); } $entryFound = TRUE; } if (array_key_exists('civicrm_activity_last_completed_last_completed_activity_subject', $row) && empty($row['civicrm_activity_last_completed_last_completed_activity_subject'])) { $rows[$rowNum]['civicrm_activity_last_completed_last_completed_activity_subject'] = ts('(No Subject)'); $entryFound = TRUE; } if (array_key_exists('civicrm_contact_client_sort_name', $row) && array_key_exists('civicrm_contact_id', $row)) { $url = CRM_Utils_System::url("civicrm/contact/view", 'reset=1&cid=' . $row['civicrm_contact_id'], $this->_absoluteUrl); $rows[$rowNum]['civicrm_contact_client_sort_name_link'] = $url; $rows[$rowNum]['civicrm_contact_client_sort_name_hover'] = ts("View Contact Summary for this Contact"); $entryFound = TRUE; } if (array_key_exists('civicrm_activity_last_completed_last_completed_activity_type', $row)) { if ($value = $row['civicrm_activity_last_completed_last_completed_activity_type']) { $rows[$rowNum]['civicrm_activity_last_completed_last_completed_activity_type'] = $activityTypes[$value]; } $entryFound = TRUE; } if (array_key_exists('case_activity_all_dates', $row)) { if ($value = $row['case_activity_all_dates']) { $activityDates = explode(',', $value); foreach ($activityDates as $num => $activityDate) { $activityDates[$num] = CRM_Utils_Date::customFormat($activityDate); } $rows[$rowNum]['case_activity_all_dates'] = implode('; ', $activityDates); } $entryFound = TRUE; } if (array_key_exists('civicrm_case_is_deleted', $row)) { $value = $row['civicrm_case_is_deleted']; $rows[$rowNum]['civicrm_case_is_deleted'] = $this->deleted_labels[$value]; $entryFound = TRUE; } if (!$entryFound) { break; } } }
function alterRow(&$row) { foreach ($this->_options as $fieldID => $values) { $customVal = $valueSeparatedArray = array(); if (in_array($values['attributes']['html_type'], array('Radio', 'Select', 'Autocomplete-Select'))) { if ($values['attributes']['data_type'] == 'ContactReference' && $row["custom_{$fieldID}"]) { $row["custom_{$fieldID}"] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', (int) $row["custom_{$fieldID}"], 'display_name'); } elseif ($row["custom_{$fieldID}"] && array_key_exists($row["custom_{$fieldID}"], $values)) { $row["custom_{$fieldID}"] = $values[$row["custom_{$fieldID}"]]; } } elseif (in_array($values['attributes']['html_type'], array('CheckBox', 'Multi-Select', 'AdvMulti-Select'))) { $valueSeparatedArray = array_filter(explode(CRM_Core_DAO::VALUE_SEPARATOR, $row["custom_{$fieldID}"])); foreach ($valueSeparatedArray as $val) { $customVal[] = $values[$val]; } $row["custom_{$fieldID}"] = implode(', ', $customVal); } elseif (in_array($values['attributes']['html_type'], array('Multi-Select State/Province', 'Select State/Province'))) { $valueSeparatedArray = array_filter(explode(CRM_Core_DAO::VALUE_SEPARATOR, $row["custom_{$fieldID}"])); $stateName = CRM_Core_PseudoConstant::stateProvince(); foreach ($valueSeparatedArray as $val) { $customVal[] = $stateName[$val]; } $row["custom_{$fieldID}"] = implode(', ', $customVal); } elseif (in_array($values['attributes']['html_type'], array('Multi-Select Country', 'Select Country'))) { $valueSeparatedArray = array_filter(explode(CRM_Core_DAO::VALUE_SEPARATOR, $row["custom_{$fieldID}"])); CRM_Core_PseudoConstant::populate($countryNames, 'CRM_Core_DAO_Country', TRUE, 'name', 'is_active'); foreach ($valueSeparatedArray as $val) { $customVal[] = $countryNames[$val]; } $row["custom_{$fieldID}"] = implode(', ', $customVal); } } }
static function fixStateSelect(&$form, $countryElementName, $stateElementName, $countyElementName, $countryDefaultValue, $stateDefaultValue = NULL) { $countryID = $stateID = NULL; if (isset($form->_elementIndex[$countryElementName])) { //get the country id to load states - //first check for submitted value, //then check for user passed value. //finally check for element default val. $submittedVal = $form->getSubmitValue($countryElementName); if ($submittedVal) { $countryID = $submittedVal; } elseif ($countryDefaultValue) { $countryID = $countryDefaultValue; } else { $countryID = CRM_Utils_Array::value(0, $form->getElementValue($countryElementName)); } } $stateTitle = ts('State/Province'); if (isset($form->_fields[$stateElementName]['title'])) { $stateTitle = $form->_fields[$stateElementName]['title']; } if (isset($form->_elementIndex[$stateElementName])) { $submittedValState = $form->getSubmitValue($stateElementName); if ($submittedValState) { $stateID = $submittedValState; } elseif ($stateDefaultValue) { $stateID = $stateDefaultValue; } else { $stateID = CRM_Utils_Array::value(0, $form->getElementValue($stateElementName)); } } if (isset($form->_elementIndex[$stateElementName])) { if ($countryID) { $stateProvinces = CRM_Core_PseudoConstant::stateProvinceForCountry($countryID); } else { $stateProvinces = CRM_Core_PseudoConstant::stateProvince(); } $stateSelect =& $form->addElement('select', $stateElementName, $stateTitle, array('' => ts('- select -')) + $stateProvinces); } if (isset($form->_elementIndex[$stateElementName]) && isset($form->_elementIndex[$countyElementName])) { if ($stateID) { $counties = CRM_Core_PseudoConstant::countyForState($stateID); } else { $counties = CRM_Core_PseudoConstant::county(); } $form->addElement('select', $countyElementName, ts('County'), array('' => ts('- select -')) + $counties); } // CRM-7296 freeze the select for state if address is shared with household // CRM-9070 freeze the select for state if it is view only if (isset($form->_fields) && !empty($form->_fields[$stateElementName]) && (!empty($form->_fields[$stateElementName]['is_shared']) || !empty($form->_fields[$stateElementName]['is_view']))) { $stateSelect->freeze(); } }
/** * Alter display of rows. * * Iterate through the rows retrieved via SQL and make changes for display purposes, * such as rendering contacts as links. * * @param array $rows * Rows generated by SQL, with an array for each row. */ public function alterDisplay(&$rows) { $entryFound = FALSE; $eventType = CRM_Core_OptionGroup::values('event_type'); $financialTypes = CRM_Contribute_PseudoConstant::financialType(); $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus(); $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument(); foreach ($rows as $rowNum => $row) { // make count columns point to detail report // convert display name to links if (array_key_exists('civicrm_participant_event_id', $row)) { $eventId = $row['civicrm_participant_event_id']; if ($eventId) { $rows[$rowNum]['civicrm_participant_event_id'] = CRM_Event_PseudoConstant::event($eventId, FALSE); $url = CRM_Report_Utils_Report::getNextUrl('event/income', 'reset=1&force=1&id_op=in&id_value=' . $eventId, $this->_absoluteUrl, $this->_id, $this->_drilldownReport); $rows[$rowNum]['civicrm_participant_event_id_link'] = $url; $rows[$rowNum]['civicrm_participant_event_id_hover'] = ts("View Event Income Details for this Event"); } $entryFound = TRUE; } // handle event type id $this->_initBasicRow($rows, $entryFound, $row, 'civicrm_event_event_type_id', $rowNum, $eventType); // handle participant status id if (array_key_exists('civicrm_participant_status_id', $row)) { $statusId = $row['civicrm_participant_status_id']; if ($statusId) { $rows[$rowNum]['civicrm_participant_status_id'] = CRM_Event_PseudoConstant::participantStatus($statusId, FALSE, 'label'); } $entryFound = TRUE; } // handle participant role id if (array_key_exists('civicrm_participant_role_id', $row)) { $roleId = $row['civicrm_participant_role_id']; if ($roleId) { $roles = explode(CRM_Core_DAO::VALUE_SEPARATOR, $roleId); $roleId = array(); foreach ($roles as $role) { $roleId[$role] = CRM_Event_PseudoConstant::participantRole($role, FALSE); } $rows[$rowNum]['civicrm_participant_role_id'] = implode(', ', $roleId); } $entryFound = TRUE; } // Handel value seperator in Fee Level if (array_key_exists('civicrm_participant_participant_fee_level', $row)) { $feeLevel = $row['civicrm_participant_participant_fee_level']; if ($feeLevel) { CRM_Event_BAO_Participant::fixEventLevel($feeLevel); $rows[$rowNum]['civicrm_participant_participant_fee_level'] = $feeLevel; } $entryFound = TRUE; } // Convert display name to link $displayName = CRM_Utils_Array::value('civicrm_contact_sort_name_linked', $row); $cid = CRM_Utils_Array::value('civicrm_contact_id', $row); $id = CRM_Utils_Array::value('civicrm_participant_participant_record', $row); if ($displayName && $cid && $id) { $url = CRM_Report_Utils_Report::getNextUrl('contact/detail', "reset=1&force=1&id_op=eq&id_value={$cid}", $this->_absoluteUrl, $this->_id, $this->_drilldownReport); $viewUrl = CRM_Utils_System::url("civicrm/contact/view/participant", "reset=1&id={$id}&cid={$cid}&action=view&context=participant"); $contactTitle = ts('View Contact Details'); $participantTitle = ts('View Participant Record'); $rows[$rowNum]['civicrm_contact_sort_name_linked'] = "<a title='{$contactTitle}' href={$url}>{$displayName}</a>"; if ($this->_outputMode !== 'csv') { $rows[$rowNum]['civicrm_contact_sort_name_linked'] .= "<span style='float: right;'><a title='{$participantTitle}' href={$viewUrl}>" . ts('View') . "</a></span>"; } $entryFound = TRUE; } // Handle country id if (array_key_exists('civicrm_address_country_id', $row)) { $countryId = $row['civicrm_address_country_id']; if ($countryId) { $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($countryId, TRUE); } $entryFound = TRUE; } // Handle state/province id if (array_key_exists('civicrm_address_state_province_id', $row)) { $provinceId = $row['civicrm_address_state_province_id']; if ($provinceId) { $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($provinceId, TRUE); } $entryFound = TRUE; } // Handle employer id if (array_key_exists('civicrm_contact_employer_id', $row)) { $employerId = $row['civicrm_contact_employer_id']; if ($employerId) { $rows[$rowNum]['civicrm_contact_employer_id'] = CRM_Contact_BAO_Contact::displayName($employerId); $url = CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $employerId, $this->_absoluteUrl); $rows[$rowNum]['civicrm_contact_employer_id_link'] = $url; $rows[$rowNum]['civicrm_contact_employer_id_hover'] = ts('View Contact Summary for this Contact.'); } } // Convert campaign_id to campaign title $this->_initBasicRow($rows, $entryFound, $row, 'civicrm_participant_campaign_id', $rowNum, $this->activeCampaigns); // handle contribution status $this->_initBasicRow($rows, $entryFound, $row, 'civicrm_contribution_contribution_status_id', $rowNum, $contributionStatus); // handle payment instrument $this->_initBasicRow($rows, $entryFound, $row, 'civicrm_contribution_payment_instrument_id', $rowNum, $paymentInstruments); // handle financial type $this->_initBasicRow($rows, $entryFound, $row, 'civicrm_contribution_financial_type_id', $rowNum, $financialTypes); $entryFound = $this->alterDisplayContactFields($row, $rows, $rowNum, 'event/participantListing', 'View Event Income Details') ? TRUE : $entryFound; // display birthday in the configured custom format if (array_key_exists('civicrm_contact_birth_date', $row)) { $birthDate = $row['civicrm_contact_birth_date']; if ($birthDate) { $rows[$rowNum]['civicrm_contact_birth_date'] = CRM_Utils_Date::customFormat($birthDate, '%Y%m%d'); } $entryFound = TRUE; } // skip looking further in rows, if first row itself doesn't // have the column we need if (!$entryFound) { break; } } }
/** * where / qill clause for state/province AND country (if present) * * @return void * @access public */ function stateProvince(&$values, $status = NULL) { list($name, $op, $value, $grouping, $wildcard) = $values; if (!is_array($value)) { // force the state to be an array $value = array($value); } // check if the values are ids OR names of the states $inputFormat = 'id'; foreach ($value as $v) { if (!is_numeric($v)) { $inputFormat = 'name'; break; } } $names = array(); if ($inputFormat == 'id') { $stateClause = 'civicrm_state_province.id IN (' . implode(',', $value) . ')'; $stateProvince = CRM_Core_PseudoConstant::stateProvince(); foreach ($value as $id) { $names[] = CRM_Utils_Array::value($id, $stateProvince); } } else { $inputClause = array(); foreach ($value as $name) { $name = trim($name); $inputClause[] = "'{$name}'"; } $stateClause = 'civicrm_state_province.name IN (' . implode(',', $inputClause) . ')'; $names = $value; } $this->_tables['civicrm_state_province'] = 1; $this->_whereTables['civicrm_state_province'] = 1; $countryValues = $this->getWhereValues('country', $grouping); list($countryClause, $countryQill) = $this->country($countryValues, TRUE); if ($countryClause) { $clause = "( {$stateClause} AND {$countryClause} )"; } else { $clause = $stateClause; } $this->_where[$grouping][] = $clause; if (!$status) { $this->_qill[$grouping][] = ts('State/Province') . ' - ' . implode(' ' . ts('or') . ' ', $names) . $countryQill; } else { return implode(' ' . ts('or') . ' ', $names) . $countryQill; } }
/** * Get the list the export fields. * * @param int $selectAll * User preference while export. * @param array $ids * Contact ids. * @param array $params * Associated array of fields. * @param string $order * Order by clause. * @param array $fields * Associated array of fields. * @param array $moreReturnProperties * Additional return fields. * @param int $exportMode * Export mode. * @param string $componentClause * Component clause. * @param string $componentTable * Component table. * @param bool $mergeSameAddress * Merge records if they have same address. * @param bool $mergeSameHousehold * Merge records if they belong to the same household. * * @param array $exportParams * @param string $queryOperator * */ public static function exportComponents($selectAll, $ids, $params, $order = NULL, $fields = NULL, $moreReturnProperties = NULL, $exportMode = CRM_Export_Form_Select::CONTACT_EXPORT, $componentClause = NULL, $componentTable = NULL, $mergeSameAddress = FALSE, $mergeSameHousehold = FALSE, $exportParams = array(), $queryOperator = 'AND') { $headerRows = $returnProperties = array(); $primary = $paymentFields = $selectedPaymentFields = FALSE; $origFields = $fields; $relationField = NULL; $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'); $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'); $contactRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE, 'name', FALSE); $queryMode = self::getQueryMode($exportMode); if ($fields) { //construct return properties $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); $locationTypeFields = array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2', 'state_province', 'country', 'phone', 'email', 'im'); foreach ($fields as $key => $value) { $phoneTypeId = $imProviderId = NULL; $relationshipTypes = $fieldName = CRM_Utils_Array::value(1, $value); if (!$fieldName) { continue; } // get phoneType id and IM service provider id separately if ($fieldName == 'phone') { $phoneTypeId = CRM_Utils_Array::value(3, $value); } elseif ($fieldName == 'im') { $imProviderId = CRM_Utils_Array::value(3, $value); } if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) { if (!empty($value[2])) { $relationField = CRM_Utils_Array::value(2, $value); if (trim(CRM_Utils_Array::value(3, $value))) { $relLocTypeId = CRM_Utils_Array::value(3, $value); } else { $relLocTypeId = 'Primary'; } if ($relationField == 'phone') { $relPhoneTypeId = CRM_Utils_Array::value(4, $value); } elseif ($relationField == 'im') { $relIMProviderId = CRM_Utils_Array::value(4, $value); } } elseif (!empty($value[4])) { $relationField = CRM_Utils_Array::value(4, $value); $relLocTypeId = CRM_Utils_Array::value(5, $value); if ($relationField == 'phone') { $relPhoneTypeId = CRM_Utils_Array::value(6, $value); } elseif ($relationField == 'im') { $relIMProviderId = CRM_Utils_Array::value(6, $value); } } } $contactType = CRM_Utils_Array::value(0, $value); $locTypeId = CRM_Utils_Array::value(2, $value); if ($relationField) { if (in_array($relationField, $locationTypeFields) && is_numeric($relLocTypeId)) { if ($relPhoneTypeId) { $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1; } elseif ($relIMProviderId) { $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1; } else { $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1; } $relPhoneTypeId = $relIMProviderId = NULL; } else { $returnProperties[$relationshipTypes][$relationField] = 1; } } elseif (is_numeric($locTypeId)) { if ($phoneTypeId) { $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1; } elseif ($imProviderId) { $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1; } else { $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1; } } else { //hack to fix component fields //revert mix of event_id and title if ($fieldName == 'event_id') { $returnProperties['event_id'] = 1; } elseif ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT && array_key_exists($fieldName, self::componentPaymentFields())) { $selectedPaymentFields = TRUE; $paymentTableId = 'participant_id'; $returnProperties[$fieldName] = 1; } else { $returnProperties[$fieldName] = 1; } } } $returnProperties[self::defaultReturnProperty($exportMode)] = 1; } else { $primary = TRUE; $fields = CRM_Contact_BAO_Contact::exportableFields('All', TRUE, TRUE); foreach ($fields as $key => $var) { if ($key && substr($key, 0, 6) != 'custom') { //for CRM=952 $returnProperties[$key] = 1; } } if ($primary) { $returnProperties['location_type'] = 1; $returnProperties['im_provider'] = 1; $returnProperties['phone_type_id'] = 1; $returnProperties['provider_id'] = 1; $returnProperties['current_employer'] = 1; } $extraReturnProperties = array(); $paymentFields = FALSE; switch ($queryMode) { case CRM_Contact_BAO_Query::MODE_EVENT: $paymentFields = TRUE; $paymentTableId = 'participant_id'; break; case CRM_Contact_BAO_Query::MODE_MEMBER: $paymentFields = TRUE; $paymentTableId = 'membership_id'; break; case CRM_Contact_BAO_Query::MODE_PLEDGE: $extraReturnProperties = CRM_Pledge_BAO_Query::extraReturnProperties($queryMode); $paymentFields = TRUE; $paymentTableId = 'pledge_payment_id'; break; case CRM_Contact_BAO_Query::MODE_CASE: $extraReturnProperties = CRM_Case_BAO_Query::extraReturnProperties($queryMode); break; } if ($queryMode != CRM_Contact_BAO_Query::MODE_CONTACTS) { $componentReturnProperties = CRM_Contact_BAO_Query::defaultReturnProperties($queryMode); if ($queryMode == CRM_Contact_BAO_Query::MODE_CONTRIBUTE) { // soft credit columns are not automatically populated, because contribution search doesn't require them by default $componentReturnProperties = array_merge($componentReturnProperties, CRM_Contribute_BAO_Query::softCreditReturnProperties(TRUE)); } $returnProperties = array_merge($returnProperties, $componentReturnProperties); if (!empty($extraReturnProperties)) { $returnProperties = array_merge($returnProperties, $extraReturnProperties); } // unset non exportable fields for components $nonExpoFields = array('groups', 'tags', 'notes', 'contribution_status_id', 'pledge_status_id', 'pledge_payment_status_id'); foreach ($nonExpoFields as $value) { unset($returnProperties[$value]); } } } if ($mergeSameAddress) { //make sure the addressee fields are selected //while using merge same address feature $returnProperties['addressee'] = 1; $returnProperties['postal_greeting'] = 1; $returnProperties['email_greeting'] = 1; $returnProperties['street_name'] = 1; $returnProperties['household_name'] = 1; $returnProperties['street_address'] = 1; $returnProperties['city'] = 1; $returnProperties['state_province'] = 1; // some columns are required for assistance incase they are not already present $exportParams['merge_same_address']['temp_columns'] = array(); $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id'); foreach ($tempColumns as $column) { if (!array_key_exists($column, $returnProperties)) { $returnProperties[$column] = 1; $column = $column == 'id' ? 'civicrm_primary_id' : $column; $exportParams['merge_same_address']['temp_columns'][$column] = 1; } } } if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) { // If an Additional Group is selected, then all contacts in that group are // added to the export set (filtering out duplicates). $query = "\nINSERT INTO {$componentTable} SELECT distinct gc.contact_id FROM civicrm_group_contact gc WHERE gc.group_id = {$exportParams['additional_group']} ON DUPLICATE KEY UPDATE {$componentTable}.contact_id = gc.contact_id"; CRM_Core_DAO::executeQuery($query); } if ($moreReturnProperties) { // fix for CRM-7066 if (!empty($moreReturnProperties['group'])) { unset($moreReturnProperties['group']); $moreReturnProperties['groups'] = 1; } $returnProperties = array_merge($returnProperties, $moreReturnProperties); } $exportParams['postal_mailing_export']['temp_columns'] = array(); if ($exportParams['exportOption'] == 2 && isset($exportParams['postal_mailing_export']) && CRM_Utils_Array::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1) { $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1'); foreach ($postalColumns as $column) { if (!array_key_exists($column, $returnProperties)) { $returnProperties[$column] = 1; $exportParams['postal_mailing_export']['temp_columns'][$column] = 1; } } } // rectify params to what proximity search expects if there is a value for prox_distance // CRM-7021 if (!empty($params)) { CRM_Contact_BAO_ProximityQuery::fixInputParams($params); } $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL, FALSE, FALSE, $queryMode, FALSE, TRUE, TRUE, NULL, $queryOperator); //sort by state //CRM-15301 $query->_sort = $order; list($select, $from, $where, $having) = $query->query(); if ($mergeSameHousehold == 1) { if (!$returnProperties['id']) { $returnProperties['id'] = 1; } //also merge Head of Household $relationKeyMOH = CRM_Utils_Array::key('Household Member of', $contactRelationshipTypes); $relationKeyHOH = CRM_Utils_Array::key('Head of Household for', $contactRelationshipTypes); foreach ($returnProperties as $key => $value) { if (!array_key_exists($key, $contactRelationshipTypes)) { $returnProperties[$relationKeyMOH][$key] = $value; $returnProperties[$relationKeyHOH][$key] = $value; } } unset($returnProperties[$relationKeyMOH]['location_type']); unset($returnProperties[$relationKeyMOH]['im_provider']); unset($returnProperties[$relationKeyHOH]['location_type']); unset($returnProperties[$relationKeyHOH]['im_provider']); } $allRelContactArray = $relationQuery = array(); foreach ($contactRelationshipTypes as $rel => $dnt) { if ($relationReturnProperties = CRM_Utils_Array::value($rel, $returnProperties)) { $allRelContactArray[$rel] = array(); // build Query for each relationship $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties, NULL, FALSE, FALSE, $queryMode); list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query(); list($id, $direction) = explode('_', $rel, 2); // identify the relationship direction $contactA = 'contact_id_a'; $contactB = 'contact_id_b'; if ($direction == 'b_a') { $contactA = 'contact_id_b'; $contactB = 'contact_id_a'; } if ($exportMode == CRM_Export_Form_Select::CONTACT_EXPORT) { $relIDs = $ids; } elseif ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) { $sourceID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source'); $query = "SELECT contact_id FROM civicrm_activity_contact\n WHERE activity_id IN ( " . implode(',', $ids) . ") AND\n record_type_id = {$sourceID}"; $dao = CRM_Core_DAO::executeQuery($query); while ($dao->fetch()) { $relIDs[] = $dao->contact_id; } } else { $component = self::exportComponent($exportMode); if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) { $relIDs = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($ids); } else { $relIDs = CRM_Core_DAO::getContactIDsFromComponent($ids, $component); } } $relationshipJoin = $relationshipClause = ''; if (!$selectAll && $componentTable) { $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}"; } elseif (!empty($relIDs)) { $relID = implode(',', $relIDs); $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )"; } $relationFrom = " {$relationFrom}\n INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}\n {$relationshipJoin} "; //check for active relationship status only $today = date('Ymd'); $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )"; $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}"; $relationGroupBy = " GROUP BY crel.{$contactA}"; $relationSelect = "{$relationSelect}, {$contactA} as refContact "; $relationQueryString = "{$relationSelect} {$relationFrom} {$relationWhere} {$relationHaving} {$relationGroupBy}"; $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString); while ($allRelContactDAO->fetch()) { //FIX Me: Migrate this to table rather than array // build the array of all related contacts $allRelContactArray[$rel][$allRelContactDAO->refContact] = clone $allRelContactDAO; } $allRelContactDAO->free(); } } // make sure the groups stuff is included only if specifically specified // by the fields param (CRM-1969), else we limit the contacts outputted to only // ones that are part of a group if (!empty($returnProperties['groups'])) { $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )"; $newClause = " ( {$oldClause} AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )"; // total hack for export, CRM-3618 $from = str_replace($oldClause, $newClause, $from); } if (!$selectAll && $componentTable) { $from .= " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = contact_a.id "; } elseif ($componentClause) { if (empty($where)) { $where = "WHERE {$componentClause}"; } else { $where .= " AND {$componentClause}"; } } // CRM-13982 - check if is deleted $excludeTrashed = TRUE; foreach ($params as $value) { if ($value[0] == 'contact_is_deleted') { $excludeTrashed = FALSE; } } $trashClause = $excludeTrashed ? "contact_a.is_deleted != 1" : "( 1 )"; if (empty($where)) { $where = "WHERE {$trashClause}"; } else { $where .= " AND {$trashClause}"; } $queryString = "{$select} {$from} {$where} {$having}"; $groupBy = ""; if (!empty($returnProperties['tags']) || !empty($returnProperties['groups']) || CRM_Utils_Array::value('notes', $returnProperties) || $queryMode & CRM_Contact_BAO_Query::MODE_CONTACTS && $query->_useGroupBy) { $groupBy = " GROUP BY contact_a.id"; } switch ($exportMode) { case CRM_Export_Form_Select::CONTRIBUTE_EXPORT: $groupBy = 'GROUP BY civicrm_contribution.id'; if (CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled()) { // especial group by when soft credit columns are included $groupBy = 'GROUP BY contribution_search_scredit_combined.id, contribution_search_scredit_combined.scredit_id'; } break; case CRM_Export_Form_Select::EVENT_EXPORT: $groupBy = 'GROUP BY civicrm_participant.id'; break; case CRM_Export_Form_Select::MEMBER_EXPORT: $groupBy = " GROUP BY civicrm_membership.id"; break; } if ($queryMode & CRM_Contact_BAO_Query::MODE_ACTIVITY) { $groupBy = " GROUP BY civicrm_activity.id "; } $queryString .= $groupBy; // always add contact_a.id to the ORDER clause // so the order is deterministic //CRM-15301 if (strpos('contact_a.id', $order) === FALSE) { $order .= ", contact_a.id"; } if ($order) { list($field, $dir) = explode(' ', $order, 2); $field = trim($field); if (!empty($returnProperties[$field])) { //CRM-15301 $queryString .= " ORDER BY {$order}"; } } $multipleSelectFields = array('preferred_communication_method' => 1); $addPaymentHeader = FALSE; $paymentDetails = array(); if ($paymentFields || $selectedPaymentFields) { // get payment related in for event and members $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids); //get all payment headers. // If we haven't selected specific payment fields, load in all the // payment headers. if (!$selectedPaymentFields) { $paymentHeaders = self::componentPaymentFields(); if (!empty($paymentDetails)) { $addPaymentHeader = TRUE; } } else { $paymentHeaders = array(); } $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL); } $componentDetails = $headerRows = $sqlColumns = array(); $setHeader = TRUE; $rowCount = self::EXPORT_ROW_COUNT; $offset = 0; // we write to temp table often to avoid using too much memory $tempRowCount = 100; $count = -1; // for CRM-3157 purposes $i18n = CRM_Core_I18n::singleton(); $outputColumns = array(); //@todo - it would be clearer to start defining output columns earlier in this function rather than stick with return properties until this point // as the array is not actually 'returnProperties' after the sql query is formed - making the alterations to it confusing foreach ($returnProperties as $key => $value) { $outputColumns[$key] = $value; } while (1) { $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}"; $dao = CRM_Core_DAO::executeQuery($limitQuery); if ($dao->N <= 0) { break; } while ($dao->fetch()) { $count++; $row = array(); //convert the pseudo constants // CRM-14398 there is problem in this architecture that is not easily solved. For now we are using the cloned // temporary iterationDAO object to get around it. // the issue is that the convertToPseudoNames function is adding additional properties (e.g for campaign) to the DAO object // these additional properties are NOT reset when the $dao cycles through the while loop // nor are they overwritten as they are not in the loop // the convertToPseudoNames will not adequately over-write them either as it doesn't 'kick-in' unless the // relevant property is set. // It may be that a long-term fix could be introduced there - however, it's probably necessary to figure out how to test the // export class before tackling a better architectural fix $iterationDAO = clone $dao; $query->convertToPseudoNames($iterationDAO); //first loop through output columns so that we return what is required, and in same order. $relationshipField = 0; foreach ($outputColumns as $field => $value) { //we should set header only once if ($setHeader) { $sqlDone = FALSE; // Split campaign into 2 fields for id and title if (substr($field, -14) == 'campaign_title') { $headerRows[] = ts('Campaign Title'); } elseif (substr($field, -11) == 'campaign_id') { $headerRows[] = ts('Campaign ID'); } elseif (isset($query->_fields[$field]['title'])) { $headerRows[] = $query->_fields[$field]['title']; } elseif ($field == 'phone_type_id') { $headerRows[] = ts('Phone Type'); } elseif ($field == 'provider_id') { $headerRows[] = ts('IM Service Provider'); } elseif (is_array($value) && $field == 'location') { // fix header for location type case foreach ($value as $ltype => $val) { foreach (array_keys($val) as $fld) { $type = explode('-', $fld); $hdr = "{$ltype}-" . $query->_fields[$type[0]]['title']; if (!empty($type[1])) { if (CRM_Utils_Array::value(0, $type) == 'phone') { $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes); } elseif (CRM_Utils_Array::value(0, $type) == 'im') { $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders); } } $headerRows[] = $hdr; self::sqlColumnDefn($query, $sqlColumns, $hdr); } $sqlDone = TRUE; } } elseif (substr($field, 0, 5) == 'case_') { if ($query->_fields['case'][$field]['title']) { $headerRows[] = $query->_fields['case'][$field]['title']; } elseif ($query->_fields['activity'][$field]['title']) { $headerRows[] = $query->_fields['activity'][$field]['title']; } } elseif (array_key_exists($field, $contactRelationshipTypes)) { $relName = $field; foreach ($value as $relationField => $relationValue) { // below block is same as primary block (duplicate) if (isset($relationQuery[$field]->_fields[$relationField]['title'])) { if ($relationQuery[$field]->_fields[$relationField]['name'] == 'name') { $headerName = $field . '-' . $relationField; } else { if ($relationField == 'current_employer') { $headerName = $field . '-' . 'current_employer'; } else { $headerName = $field . '-' . $relationQuery[$field]->_fields[$relationField]['name']; } } $headerRows[] = $headerName; self::sqlColumnDefn($query, $sqlColumns, $headerName); } elseif ($relationField == 'phone_type_id') { $headerName = $field . '-' . 'Phone Type'; $headerRows[] = $headerName; self::sqlColumnDefn($query, $sqlColumns, $headerName); } elseif ($relationField == 'provider_id') { $headerName = $field . '-' . 'Im Service Provider'; $headerRows[] = $headerName; self::sqlColumnDefn($query, $sqlColumns, $headerName); } elseif ($relationField == 'state_province_id') { $headerName = $field . '-' . 'state_province_id'; $headerRows[] = $headerName; self::sqlColumnDefn($query, $sqlColumns, $headerName); } elseif (is_array($relationValue) && $relationField == 'location') { // fix header for location type case foreach ($relationValue as $ltype => $val) { foreach (array_keys($val) as $fld) { $type = explode('-', $fld); $hdr = "{$ltype}-" . $relationQuery[$field]->_fields[$type[0]]['title']; if (!empty($type[1])) { if (CRM_Utils_Array::value(0, $type) == 'phone') { $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes); } elseif (CRM_Utils_Array::value(0, $type) == 'im') { $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders); } } $headerName = $field . '-' . $hdr; $headerRows[] = $headerName; self::sqlColumnDefn($query, $sqlColumns, $headerName); } } } } } elseif ($selectedPaymentFields && array_key_exists($field, self::componentPaymentFields())) { $headerRows[] = CRM_Utils_Array::value($field, self::componentPaymentFields()); } else { $headerRows[] = $field; } if (!$sqlDone) { self::sqlColumnDefn($query, $sqlColumns, $field); } } // add im_provider to $dao object if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) { $iterationDAO->im_provider = $iterationDAO->provider_id; } //build row values (data) $fieldValue = NULL; if (property_exists($iterationDAO, $field)) { $fieldValue = $iterationDAO->{$field}; // to get phone type from phone type id if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) { $fieldValue = $phoneTypes[$fieldValue]; } elseif ($field == 'provider_id' || $field == 'im_provider') { $fieldValue = CRM_Utils_Array::value($fieldValue, $imProviders); } elseif ($field == 'master_id') { $masterAddressId = NULL; if (isset($iterationDAO->master_id)) { $masterAddressId = $iterationDAO->master_id; } // get display name of contact that address is shared. $fieldValue = CRM_Contact_BAO_Contact::getMasterDisplayName($masterAddressId, $iterationDAO->contact_id); } } if ($field == 'id') { $row[$field] = $iterationDAO->contact_id; // special case for calculated field } elseif ($field == 'source_contact_id') { $row[$field] = $iterationDAO->contact_id; } elseif ($field == 'pledge_balance_amount') { $row[$field] = $iterationDAO->pledge_amount - $iterationDAO->pledge_total_paid; // special case for calculated field } elseif ($field == 'pledge_next_pay_amount') { $row[$field] = $iterationDAO->pledge_next_pay_amount + $iterationDAO->pledge_outstanding_amount; } elseif (is_array($value) && $field == 'location') { // fix header for location type case foreach ($value as $ltype => $val) { foreach (array_keys($val) as $fld) { $type = explode('-', $fld); $fldValue = "{$ltype}-" . $type[0]; // CRM-14076 - fix label to work as the query object expects // FIXME: We should not be using labels as keys! $daoField = CRM_Utils_String::munge($ltype) . '-' . $type[0]; if (!empty($type[1])) { $fldValue .= "-" . $type[1]; $daoField .= "-" . $type[1]; } // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context) switch ($fld) { case 'country': case 'world_region': $row[$fldValue] = $i18n->crm_translate($iterationDAO->{$daoField}, array('context' => 'country')); break; case 'state_province': $row[$fldValue] = $i18n->crm_translate($iterationDAO->{$daoField}, array('context' => 'province')); break; case 'im_provider': $imFieldvalue = $daoField . "-provider_id"; $row[$fldValue] = CRM_Utils_Array::value($iterationDAO->{$imFieldvalue}, $imProviders); break; default: $row[$fldValue] = $iterationDAO->{$daoField}; break; } } } } elseif (array_key_exists($field, $contactRelationshipTypes)) { $relDAO = CRM_Utils_Array::value($iterationDAO->contact_id, $allRelContactArray[$field]); $relationQuery[$field]->convertToPseudoNames($relDAO); foreach ($value as $relationField => $relationValue) { if (is_object($relDAO) && property_exists($relDAO, $relationField)) { $fieldValue = $relDAO->{$relationField}; if ($relationField == 'phone_type_id') { $fieldValue = $phoneTypes[$relationValue]; } elseif ($relationField == 'provider_id') { $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders); } elseif (is_object($relDAO) && in_array($relationField, array('email_greeting', 'postal_greeting', 'addressee'))) { //special case for greeting replacement $fldValue = "{$relationField}_display"; $fieldValue = $relDAO->{$fldValue}; } } elseif (is_object($relDAO) && $relationField == 'state_province') { $fieldValue = CRM_Core_PseudoConstant::stateProvince($relDAO->state_province_id); } elseif (is_object($relDAO) && $relationField == 'country') { $fieldValue = CRM_Core_PseudoConstant::country($relDAO->country_id); } else { $fieldValue = ''; } $field = $field . '_'; if (array_key_exists($relationField, $multipleSelectFields)) { $param = array($relationField => $fieldValue); $names = array($relationField => array('newName' => $relationField, 'groupName' => $relationField)); CRM_Core_OptionGroup::lookupValues($param, $names, FALSE); $fieldValue = $param[$relationField]; } if (is_object($relDAO) && $relationField == 'id') { $row[$field . $relationField] = $relDAO->contact_id; } elseif (is_array($relationValue) && $relationField == 'location') { foreach ($relationValue as $ltype => $val) { foreach (array_keys($val) as $fld) { $type = explode('-', $fld); $fldValue = "{$ltype}-" . $type[0]; if (!empty($type[1])) { $fldValue .= "-" . $type[1]; } // CRM-3157: localise country, region (both have ‘country’ context) // and state_province (‘province’ context) switch (TRUE) { case !is_object($relDAO): $row[$field . '_' . $fldValue] = ''; break; case in_array('country', $type): case in_array('world_region', $type): $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->{$fldValue}, array('context' => 'country')); break; case in_array('state_province', $type): $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->{$fldValue}, array('context' => 'province')); break; default: $row[$field . '_' . $fldValue] = $relDAO->{$fldValue}; break; } } } } elseif (isset($fieldValue) && $fieldValue != '') { //check for custom data if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) { $row[$field . $relationField] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID, $relationQuery[$field]->_options); } else { //normal relationship fields // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context) switch ($relationField) { case 'country': case 'world_region': $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'country')); break; case 'state_province': $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'province')); break; default: $row[$field . $relationField] = $fieldValue; break; } } } else { // if relation field is empty or null $row[$field . $relationField] = ''; } } } elseif (isset($fieldValue) && $fieldValue != '') { //check for custom data if ($cfID = CRM_Core_BAO_CustomField::getKeyID($field)) { $row[$field] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID, $query->_options); } elseif (array_key_exists($field, $multipleSelectFields)) { //option group fixes $paramsNew = array($field => $fieldValue); if ($field == 'test_tutoring') { $name = array($field => array('newName' => $field, 'groupName' => 'test')); // for readers group } elseif (substr($field, 0, 4) == 'cmr_') { $name = array($field => array('newName' => $field, 'groupName' => substr($field, 0, -3))); } else { $name = array($field => array('newName' => $field, 'groupName' => $field)); } CRM_Core_OptionGroup::lookupValues($paramsNew, $name, FALSE); $row[$field] = $paramsNew[$field]; } elseif (in_array($field, array('email_greeting', 'postal_greeting', 'addressee'))) { //special case for greeting replacement $fldValue = "{$field}_display"; $row[$field] = $iterationDAO->{$fldValue}; } else { //normal fields with a touch of CRM-3157 switch ($field) { case 'country': case 'world_region': $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'country')); break; case 'state_province': $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'province')); break; case 'gender': case 'preferred_communication_method': case 'preferred_mail_format': case 'communication_style': $row[$field] = $i18n->crm_translate($fieldValue); break; default: $row[$field] = $fieldValue; break; } } } elseif ($selectedPaymentFields && array_key_exists($field, self::componentPaymentFields())) { $paymentData = CRM_Utils_Array::value($iterationDAO->{$paymentTableId}, $paymentDetails); $payFieldMapper = array('componentPaymentField_total_amount' => 'total_amount', 'componentPaymentField_contribution_status' => 'contribution_status', 'componentPaymentField_payment_instrument' => 'pay_instru', 'componentPaymentField_transaction_id' => 'trxn_id', 'componentPaymentField_received_date' => 'receive_date'); $row[$field] = CRM_Utils_Array::value($payFieldMapper[$field], $paymentData, ''); } else { // if field is empty or null $row[$field] = ''; } } // add payment headers if required if ($addPaymentHeader && $paymentFields) { $headerRows = array_merge($headerRows, $paymentHeaders); foreach (array_keys($paymentHeaders) as $paymentHdr) { self::sqlColumnDefn($query, $sqlColumns, $paymentHdr); } } if ($setHeader) { $exportTempTable = self::createTempTable($sqlColumns); } //build header only once $setHeader = FALSE; // If specific payment fields have been selected for export, payment // data will already be in $row. Otherwise, add payment related // information, if appropriate. if ($addPaymentHeader) { if (!$selectedPaymentFields) { if ($paymentFields) { $paymentData = CRM_Utils_Array::value($row[$paymentTableId], $paymentDetails); if (!is_array($paymentData) || empty($paymentData)) { $paymentData = $nullContributionDetails; } $row = array_merge($row, $paymentData); } elseif (!empty($paymentDetails)) { $row = array_merge($row, $nullContributionDetails); } } } //remove organization name for individuals if it is set for current employer if (!empty($row['contact_type']) && $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)) { $row['organization_name'] = ''; } // add component info // write the row to a file $componentDetails[] = $row; // output every $tempRowCount rows if ($count % $tempRowCount == 0) { self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns); $componentDetails = array(); } } $dao->free(); $offset += $rowCount; } if ($exportTempTable) { self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns); // do merge same address and merge same household processing if ($mergeSameAddress) { self::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams); } // merge the records if they have corresponding households if ($mergeSameHousehold) { self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyMOH); self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyHOH); } // fix the headers for rows with relationship type if (!empty($relName)) { self::manipulateHeaderRows($headerRows, $contactRelationshipTypes); } // if postalMailing option is checked, exclude contacts who are deceased, have // "Do not mail" privacy setting, or have no street address if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) && $exportParams['postal_mailing_export']['postal_mailing_export'] == 1) { self::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode); } // call export hook CRM_Utils_Hook::export($exportTempTable, $headerRows, $sqlColumns, $exportMode); // now write the CSV file self::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode); // delete the export temp table and component table $sql = "DROP TABLE IF EXISTS {$exportTempTable}"; CRM_Core_DAO::executeQuery($sql); CRM_Utils_System::civiExit(); } else { CRM_Core_Error::fatal(ts('No records to export')); } }
/** * @param $rows */ function alterDisplay(&$rows) { // custom code to alter rows $entryFound = FALSE; foreach ($rows as $rowNum => $row) { // make count columns point to detail report // convert sort name to links if (array_key_exists('civicrm_contact_sort_name', $row) && array_key_exists('civicrm_contact_id', $row)) { $url = CRM_Report_Utils_Report::getNextUrl('contact/detail', 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'], $this->_absoluteUrl, $this->_id, $this->_drilldownReport); $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url; $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Constituent Detail Report for this contact."); $entryFound = TRUE; } if (array_key_exists('civicrm_address_state_province_id', $row)) { if ($value = $row['civicrm_address_state_province_id']) { $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($value, FALSE); } $entryFound = TRUE; } // skip looking further in rows, if first row itself doesn't // have the column we need if (!$entryFound) { break; } } }