function __construct() { $contact_type = CRM_Contact_BAO_ContactType::getSelectElements(false, true, '_'); $this->_columns = array('civicrm_contact' => array('dao' => 'CRM_Contact_DAO_Contact', 'fields' => array('display_name_a' => array('title' => ts('Contact A'), 'name' => 'display_name', 'required' => true), 'id' => array('no_display' => true, 'required' => true)), 'filters' => array('sort_name_a' => array('title' => ts('Contact A'), 'name' => 'sort_name', 'operator' => 'like', 'type' => CRM_Report_Form::OP_STRING)), 'grouping' => 'conact_a_fields'), 'civicrm_contact_b' => array('dao' => 'CRM_Contact_DAO_Contact', 'alias' => 'contact_b', 'fields' => array('display_name_b' => array('title' => ts('Contact B'), 'name' => 'display_name', 'required' => true), 'id' => array('no_display' => true, 'required' => true)), 'filters' => array('sort_name_b' => array('title' => ts('Contact B'), 'name' => 'sort_name', 'operator' => 'like', 'type' => CRM_Report_Form::OP_STRING)), 'grouping' => 'conact_b_fields'), 'civicrm_email' => array('dao' => 'CRM_Core_DAO_Email', 'fields' => array('email_a' => array('title' => ts('Email of Contact A'), 'name' => 'email')), 'grouping' => 'conact_a_fields'), 'civicrm_email_b' => array('dao' => 'CRM_Core_DAO_Email', 'alias' => 'email_b', 'fields' => array('email_b' => array('title' => ts('Email of Contact B'), 'name' => 'email')), 'grouping' => 'conact_b_fields'), 'civicrm_relationship_type' => array('dao' => 'CRM_Contact_DAO_RelationshipType', 'fields' => array('label_a_b' => array('title' => ts('Relationship A-B '), 'default' => true), 'label_b_a' => array('title' => ts('Relationship B-A '), 'default' => true)), 'filters' => array('contact_type_a' => array('title' => ts('Contact Type A'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => $contact_type, 'type' => CRM_Utils_Type::T_STRING), 'contact_type_b' => array('title' => ts('Contact Type B'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => $contact_type, 'type' => CRM_Utils_Type::T_STRING)), 'grouping' => 'relation-fields'), 'civicrm_relationship' => array('dao' => 'CRM_Contact_DAO_Relationship', 'fields' => array('start_date' => array('title' => ts('Relationship Start Date')), 'end_date' => array('title' => ts('Relationship End Date')), 'description' => array('title' => ts('Description'))), 'filters' => array('is_active' => array('title' => ts('Relationship Status'), 'operatorType' => CRM_Report_Form::OP_SELECT, 'options' => array('' => '- Any -', 1 => 'Active', 0 => 'Inactive'), 'type' => CRM_Utils_Type::T_INT), 'relationship_type_id' => array('title' => ts('Relationship'), 'operatorType' => CRM_Report_Form::OP_SELECT, 'options' => array('' => '- any relationship type -') + CRM_Contact_BAO_Relationship::getContactRelationshipType(null, 'null', null, null, true), 'type' => CRM_Utils_Type::T_INT)), 'grouping' => 'relation-fields'), 'civicrm_address' => array('dao' => 'CRM_Core_DAO_Address', 'filters' => array('country_id' => array('title' => ts('Country'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => CRM_Core_PseudoConstant::country()), 'state_province_id' => array('title' => ts('State/Province'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => CRM_Core_PseudoConstant::stateProvince())), 'grouping' => 'contact-fields'), 'civicrm_group' => array('dao' => 'CRM_Contact_DAO_Group', '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())))); $this->_tagFilter = true; parent::__construct(); }
/** * Class constructor. */ public function __construct() { $contact_type = CRM_Contact_BAO_ContactType::getSelectElements(FALSE, TRUE, '_'); $this->_columns = array('civicrm_contact' => array('dao' => 'CRM_Contact_DAO_Contact', 'fields' => array('sort_name_a' => array('title' => ts('Contact A'), 'name' => 'sort_name', 'required' => TRUE), 'id' => array('no_display' => TRUE, 'required' => TRUE), 'contact_type_a' => array('title' => ts('Contact Type (Contact A)'), 'name' => 'contact_type'), 'contact_sub_type_a' => array('title' => ts('Contact Subtype (Contact A)'), 'name' => 'contact_sub_type')), 'filters' => array('sort_name_a' => array('title' => ts('Contact A'), 'name' => 'sort_name', 'operator' => 'like', 'type' => CRM_Report_Form::OP_STRING), 'contact_type_a' => array('title' => ts('Contact Type A'), 'name' => 'contact_type', 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => $contact_type, 'type' => CRM_Utils_Type::T_STRING)), 'grouping' => 'contact_a_fields'), 'civicrm_contact_b' => array('dao' => 'CRM_Contact_DAO_Contact', 'alias' => 'contact_b', 'fields' => array('sort_name_b' => array('title' => ts('Contact B'), 'name' => 'sort_name', 'required' => TRUE), 'id' => array('no_display' => TRUE, 'required' => TRUE), 'contact_type_b' => array('title' => ts('Contact Type (Contact B)'), 'name' => 'contact_type'), 'contact_sub_type_b' => array('title' => ts('Contact Subtype (Contact B)'), 'name' => 'contact_sub_type')), 'filters' => array('sort_name_b' => array('title' => ts('Contact B'), 'name' => 'sort_name', 'operator' => 'like', 'type' => CRM_Report_Form::OP_STRING), 'contact_type_b' => array('title' => ts('Contact Type B'), 'name' => 'contact_type', 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => $contact_type, 'type' => CRM_Utils_Type::T_STRING)), 'grouping' => 'contact_b_fields'), 'civicrm_email' => array('dao' => 'CRM_Core_DAO_Email', 'fields' => array('email_a' => array('title' => ts('Email (Contact A)'), 'name' => 'email')), 'grouping' => 'contact_a_fields'), 'civicrm_email_b' => array('dao' => 'CRM_Core_DAO_Email', 'alias' => 'email_b', 'fields' => array('email_b' => array('title' => ts('Email (Contact B)'), 'name' => 'email')), 'grouping' => 'contact_b_fields'), 'civicrm_phone' => array('dao' => 'CRM_Core_DAO_Phone', 'alias' => 'phone_a', 'fields' => array('phone_a' => array('title' => ts('Phone (Contact A)'), 'name' => 'phone'), 'phone_ext_a' => array('title' => ts('Phone Ext (Contact A)'), 'name' => 'phone_ext')), 'grouping' => 'contact_a_fields'), 'civicrm_phone_b' => array('dao' => 'CRM_Core_DAO_Phone', 'alias' => 'phone_b', 'fields' => array('phone_b' => array('title' => ts('Phone (Contact B)'), 'name' => 'phone'), 'phone_ext_b' => array('title' => ts('Phone Ext (Contact B)'), 'name' => 'phone_ext')), 'grouping' => 'contact_b_fields'), 'civicrm_relationship_type' => array('dao' => 'CRM_Contact_DAO_RelationshipType', 'fields' => array('label_a_b' => array('title' => ts('Relationship A-B '), 'default' => TRUE), 'label_b_a' => array('title' => ts('Relationship B-A '), 'default' => TRUE)), 'grouping' => 'relation-fields'), 'civicrm_relationship' => array('dao' => 'CRM_Contact_DAO_Relationship', 'fields' => array('start_date' => array('title' => ts('Relationship Start Date')), 'end_date' => array('title' => ts('Relationship End Date')), 'description' => array('title' => ts('Description')), 'relationship_id' => array('title' => ts('Rel ID'), 'name' => 'id')), 'filters' => array('is_active' => array('title' => ts('Relationship Status'), 'operatorType' => CRM_Report_Form::OP_SELECT, 'options' => array('' => '- Any -', 1 => 'Active', 0 => 'Inactive'), 'type' => CRM_Utils_Type::T_INT), 'is_valid' => array('title' => ts('Relationship Dates Validity'), 'operatorType' => CRM_Report_Form::OP_SELECT, 'options' => array(NULL => ts('- Any -'), 1 => ts('Not expired'), 0 => ts('Expired')), 'type' => CRM_Utils_Type::T_INT), 'relationship_type_id' => array('title' => ts('Relationship'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, NULL, TRUE), 'type' => CRM_Utils_Type::T_INT), 'start_date' => array('title' => ts('Start Date'), 'type' => CRM_Utils_Type::T_DATE), 'end_date' => array('title' => ts('End Date'), 'type' => CRM_Utils_Type::T_DATE)), 'grouping' => 'relation-fields'), 'civicrm_address' => array('dao' => 'CRM_Core_DAO_Address', 'filters' => array('country_id' => array('title' => ts('Country'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => CRM_Core_PseudoConstant::country()), 'state_province_id' => array('title' => ts('State/Province'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => CRM_Core_PseudoConstant::stateProvince())), 'grouping' => 'contact-fields')); $this->_groupFilter = TRUE; $this->_tagFilter = TRUE; parent::__construct(); }
/** * @param CRM_Core_Form $form */ public static function basic(&$form) { $form->addElement('hidden', 'hidden_basic', 1); // text for sort_name $form->addElement('text', 'target_name', ts('Target Contact'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name')); $allRelationshipType = array(); $allRelationshipType = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE); $form->add('select', 'relationship_type_id', ts('Relationship Type'), array('' => ts('- select -')) + $allRelationshipType, FALSE, array('class' => 'crm-select2', 'multiple' => 'multiple')); // relation status $relStatusOption = array(ts('Active'), ts('Inactive'), ts('All')); $form->addRadio('is_active', ts('Relationship Status'), $relStatusOption); $form->setDefaults(array('is_active' => 0)); CRM_Core_Form_Date::buildDateRange($form, 'start_date', 1, '_low', '_high', ts('From:'), FALSE, FALSE); CRM_Core_Form_Date::buildDateRange($form, 'end_date', 1, '_low', '_high', ts('From:'), FALSE, FALSE); }
/** * Test the function that extracts the arrays used to structure the output. * * The keys in the output fields array should by matched by field aliases in the sql query (with * exceptions of course - currently country is one - although maybe a future refactor can change that!). * * We are trying to move towards simpler processing in the per row iteration as that may be * repeated 100,000 times and in general we should simply be able to match the query fields to * our expected rows & do a little pseudoconstant mapping. */ public function testGetExportStructureArrays() { // This is how return properties are formatted internally within the function for passing to the BAO query. $returnProperties = array('first_name' => 1, 'last_name' => 1, 'receive_date' => 1, 'contribution_source' => 1, 'location' => array('Home' => array('street_address' => 1, 'city' => 1, 'country' => 1, 'email' => 1, 'im-1' => 1, 'im_provider' => 1, 'phone-1' => 1)), 'phone' => 1, 'trxn_id' => 1, 'contribution_id' => 1); $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); $query = new CRM_Contact_BAO_Query(array(), $returnProperties, NULL, FALSE, FALSE, CRM_Contact_BAO_Query::MODE_CONTRIBUTE, FALSE, TRUE, TRUE, NULL, 'AND'); list($select) = $query->query(); $pattern = '/as `?([^`,]*)/'; $queryFieldAliases = array(); preg_match_all($pattern, $select, $queryFieldAliases, PREG_PATTERN_ORDER); list($outputFields) = CRM_Export_BAO_Export::getExportStructureArrays($returnProperties, $query, $phoneTypes, $imProviders, $contactRelationshipTypes, '', array()); foreach (array_keys($outputFields) as $fieldAlias) { if ($fieldAlias == 'Home-country') { $this->assertTrue(in_array($fieldAlias . '_id', $queryFieldAliases[1]), 'Country is subject to some funky translate so we make sure country id is present'); } else { $this->assertTrue(in_array($fieldAlias, $queryFieldAliases[1]), 'looking for field ' . $fieldAlias . ' in generaly the alias fields need to match the outputfields'); } } }
static function relationship(&$form) { $form->add('hidden', 'hidden_relationship', 1); require_once 'CRM/Contact/BAO/Relationship.php'; require_once 'CRM/Core/PseudoConstant.php'; $relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(null, 'null', null, 'Individual'); $relTypeOrg = CRM_Contact_BAO_Relationship::getContactRelationshipType(null, 'null', null, 'Organization'); $relTypeHou = CRM_Contact_BAO_Relationship::getContactRelationshipType(null, 'null', null, 'Household'); $allRelationshipType = array(); $allRelationshipType = array_merge($relTypeInd, $relTypeOrg); $allRelationshipType = array_merge($allRelationshipType, $relTypeHou); $form->addElement('select', 'relation_type_id', ts('Relationship Type'), array('' => ts('- select -')) + $allRelationshipType); $form->addElement('text', 'relation_target_name', ts('Target Contact'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name')); $relStatusOption = array(ts('Active '), ts('Inactive '), ts('All')); $form->addRadio('relation_status', ts('Relationship Status'), $relStatusOption); $form->setDefaults(array('relation_status' => 0)); // add all the custom searchable fields require_once 'CRM/Core/BAO/CustomGroup.php'; $relationship = array('Relationship'); $groupDetails = CRM_Core_BAO_CustomGroup::getGroupDetail(null, true, $relationship); if ($groupDetails) { require_once 'CRM/Core/BAO/CustomField.php'; $form->assign('relationshipGroupTree', $groupDetails); foreach ($groupDetails as $group) { foreach ($group['fields'] as $field) { $fieldId = $field['id']; $elementName = 'custom_' . $fieldId; CRM_Core_BAO_CustomField::addQuickFormElement($form, $elementName, $fieldId, false, false, true); } } } }
/** * Function to 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 $associated array of fields * @param array $moreReturnProperties additional return fields * @param int $exportMode export mode * @param string $componentClause component clause * * @static * @access public */ static function exportComponents($selectAll, $ids, $params, $order = null, $fields = null, $moreReturnProperties = null, $exportMode = CRM_Export_Form_Select::CONTACT_EXPORT, $componentClause = null) { $headerRows = array(); $primary = false; $returnProperties = array(); $origFields = $fields; $queryMode = null; $paymentFields = false; $phoneTypes = CRM_Core_PseudoConstant::phoneType(); $imProviders = CRM_Core_PseudoConstant::IMProvider(); $contactRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(null, null, null, null, true, 'label', false); $queryMode = CRM_Contact_BAO_Query::MODE_CONTACTS; switch ($exportMode) { case CRM_Export_Form_Select::CONTRIBUTE_EXPORT: $queryMode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE; break; case CRM_Export_Form_Select::EVENT_EXPORT: $queryMode = CRM_Contact_BAO_Query::MODE_EVENT; break; case CRM_Export_Form_Select::MEMBER_EXPORT: $queryMode = CRM_Contact_BAO_Query::MODE_MEMBER; break; case CRM_Export_Form_Select::PLEDGE_EXPORT: $queryMode = CRM_Contact_BAO_Query::MODE_PLEDGE; break; case CRM_Export_Form_Select::CASE_EXPORT: $queryMode = CRM_Contact_BAO_Query::MODE_CASE; break; case CRM_Export_Form_Select::GRANT_EXPORT: $queryMode = CRM_Contact_BAO_Query::MODE_GRANT; break; } require_once 'CRM/Core/BAO/CustomField.php'; if ($fields) { //construct return properties $locationTypes =& CRM_Core_PseudoConstant::locationType(); $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 = null; $imProviderId = null; $relationshipTypes = $fieldName = CRM_Utils_Array::value(1, $value); if (!$fieldName) { continue; } // get phoneType id and IM service provider id seperately if ($fieldName == 'phone') { $phoneTypeId = CRM_Utils_Array::value(3, $value); } else { if ($fieldName == 'im') { $imProviderId = CRM_Utils_Array::value(3, $value); } } if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) { if (CRM_Utils_Array::value(2, $value)) { $relationField = CRM_Utils_Array::value(2, $value); if (trim(CRM_Utils_Array::value(3, $value))) { $relLocTypeId = CRM_Utils_Array::value(3, $value); } else { $relLocTypeId = 1; } if ($relationField == 'phone') { $relPhoneTypeId = CRM_Utils_Array::value(4, $value); } else { if ($relationField == 'im') { $relIMProviderId = CRM_Utils_Array::value(4, $value); } } } else { if (CRM_Utils_Array::value(4, $value)) { $relationField = CRM_Utils_Array::value(4, $value); $relLocTypeId = CRM_Utils_Array::value(5, $value); if ($relationField == 'phone') { $relPhoneTypeId = CRM_Utils_Array::value(6, $value); } else { if ($relationField == 'im') { $relIMProviderId = CRM_Utils_Array::value(6, $value); } } } } } $contactType = CRM_Utils_Array::value(0, $value); $locTypeId = CRM_Utils_Array::value(2, $value); $phoneTypeId = CRM_Utils_Array::value(3, $value); if ($relationField) { if (in_array($relationField, $locationTypeFields)) { if ($relPhoneTypeId) { $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1; } else { if ($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; } } else { if (is_numeric($locTypeId)) { if ($phoneTypeId) { $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1; } else { if (isset($imProviderId)) { //build returnProperties for IM service provider $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1; } else { $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1; } } } else { //hack to fix component fields if ($fieldName == 'event_id') { $returnProperties['event_title'] = 1; } else { $returnProperties[$fieldName] = 1; } } } } // hack to add default returnproperty based on export mode if ($exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT) { $returnProperties['contribution_id'] = 1; } else { if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) { $returnProperties['participant_id'] = 1; } else { if ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) { $returnProperties['membership_id'] = 1; } else { if ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) { $returnProperties['pledge_id'] = 1; } else { if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) { $returnProperties['case_id'] = 1; } else { if ($exportMode == CRM_Export_Form_Select::GRANT_EXPORT) { $returnProperties['grant_id'] = 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: require_once 'CRM/Pledge/BAO/Query.php'; $extraReturnProperties = CRM_Pledge_BAO_Query::extraReturnProperties($queryMode); $paymentFields = true; $paymentTableId = "pledge_payment_id"; break; case CRM_Contact_BAO_Query::MODE_CASE: require_once 'CRM/Case/BAO/Query.php'; $extraReturnProperties = CRM_Case_BAO_Query::extraReturnProperties($queryMode); break; } if ($queryMode != CRM_Contact_BAO_Query::MODE_CONTACTS) { $componentReturnProperties =& CRM_Contact_BAO_Query::defaultReturnProperties($queryMode); $returnProperties = array_merge($returnProperties, $componentReturnProperties); if (!empty($extraReturnProperties)) { $returnProperties = array_merge($returnProperties, $extraReturnProperties); } // unset groups, tags, notes for components foreach (array('groups', 'tags', 'notes') as $value) { unset($returnProperties[$value]); } } } if ($moreReturnProperties) { $returnProperties = array_merge($returnProperties, $moreReturnProperties); } $query =& new CRM_Contact_BAO_Query(0, $returnProperties, null, false, false, $queryMode); list($select, $from, $where) = $query->query(); $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(0, $relationReturnProperties, null, false, false, $queryMode); list($relationSelect, $relationFrom, $relationWhere) = $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'; } $relIDs = implode(',', $ids); $relSQL = "SELECT {$contactB} as relContact,{$contactA} as refContact FROM civicrm_relationship \n WHERE relationship_type_id = {$id} AND\n {$contactA} IN ({$relIDs})\n GROUP BY {$contactA}"; // Get the related contacts $relContactDAO = CRM_Core_DAO::executeQuery($relSQL); $relContactArray = array(); while ($relContactDAO->fetch()) { $relContactArray[$relContactDAO->refContact] = $relContactDAO->relContact; } $uniqueContacts = array_unique($relContactArray); if (!empty($uniqueContacts)) { $relationWhere = " WHERE contact_a.id IN (" . implode(',', $uniqueContacts) . ") GROUP BY contact_id"; $relationQueryString = "{$relationSelect} {$relationFrom} {$relationWhere}"; $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString); while ($allRelContactDAO->fetch()) { foreach ($relContactArray as $k => $v) { if ($allRelContactDAO->contact_id == $v) { //$allRelContactArray[$rel][$k] = array(); // build the array of all related contacts $allRelContactArray[$rel][$k] = clone $allRelContactDAO; } } } } } } // 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 (CRM_Utils_Array::value('groups', $returnProperties)) { $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 ($componentClause) { if (empty($where)) { $where = "WHERE {$componentClause}"; } else { $where .= " AND {$componentClause}"; } } $queryString = "{$select} {$from} {$where}"; if (CRM_Utils_Array::value('tags', $returnProperties) || CRM_Utils_Array::value('groups', $returnProperties) || CRM_Utils_Array::value('notes', $returnProperties) || $query->_useGroupBy) { $queryString .= " GROUP BY contact_a.id"; } if ($order) { list($field, $dir) = explode(' ', $order, 2); $field = trim($field); if (CRM_Utils_Array::value($field, $returnProperties)) { $queryString .= " ORDER BY {$order}"; } } //hack for student data require_once 'CRM/Core/OptionGroup.php'; $multipleSelectFields = array('preferred_communication_method' => 1); if (CRM_Core_Permission::access('Quest')) { require_once 'CRM/Quest/BAO/Student.php'; $studentFields = array(); $studentFields = CRM_Quest_BAO_Student::$multipleSelectFields; $multipleSelectFields = array_merge($multipleSelectFields, $studentFields); } $dao =& CRM_Core_DAO::executeQuery($queryString, CRM_Core_DAO::$_nullArray); $header = false; $addPaymentHeader = false; if ($paymentFields) { $addPaymentHeader = true; //special return properties for event and members $paymentHeaders = array(ts('Total Amount'), ts('Contribution Status'), ts('Received Date'), ts('Payment Instrument'), ts('Transaction ID')); // get payment related in for event and members require_once 'CRM/Contribute/BAO/Contribution.php'; $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids); } $componentDetails = $headerRows = array(); $setHeader = true; while ($dao->fetch()) { $row = array(); //first loop through returnproperties so that we return what is required, and in same order. $relationshipField = 0; foreach ($returnProperties as $field => $value) { //we should set header only once if ($setHeader) { if (isset($query->_fields[$field]['title'])) { $headerRows[] = $query->_fields[$field]['title']; } else { if ($field == 'phone_type_id') { $headerRows[] = 'Phone Type'; } else { if ($field == 'provider_id') { $headerRows[] = 'Im Service Provider'; } else { if (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 (CRM_Utils_Array::value(1, $type)) { if (CRM_Utils_Array::value(0, $type) == 'phone') { $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes); } else { if (CRM_Utils_Array::value(0, $type) == 'im') { $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders); } } } $headerRows[] = $hdr; } } } else { if (substr($field, 0, 5) == 'case_') { if ($query->_fields['case'][$field]['title']) { $headerRows[] = $query->_fields['case'][$field]['title']; } else { if ($query->_fields['activity'][$field]['title']) { $headerRows[] = $query->_fields['activity'][$field]['title']; } } } else { if (array_key_exists($field, $contactRelationshipTypes)) { $relName = CRM_Utils_Array::value($field, $contactRelationshipTypes); foreach ($value as $relationField => $relationValue) { // below block is same as primary block (duplicate) if (isset($relationQuery[$field]->_fields[$relationField]['title'])) { $headerRows[] = $relName . '-' . $relationQuery[$field]->_fields[$relationField]['title']; } else { if ($relationField == 'phone_type_id') { $headerRows[] = $relName . '-' . 'Phone Type'; } else { if ($relationField == 'provider_id') { $headerRows[] = $relName . '-' . 'Im Service Provider'; } else { if (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 (CRM_Utils_Array::value(1, $type)) { if (CRM_Utils_Array::value(0, $type) == 'phone') { $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes); } else { if (CRM_Utils_Array::value(0, $type) == 'im') { $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders); } } } $headerRows[] = $relName . '-' . $hdr; } } } } } } } } else { $headerRows[] = $field; } } } } } } } //build row values (data) if (property_exists($dao, $field)) { $fieldValue = $dao->{$field}; // to get phone type from phone type id if ($field == 'phone_type_id') { $fieldValue = $phoneTypes[$fieldValue]; } else { if ($field == 'provider_id') { $fieldValue = CRM_Utils_Array::value($fieldValue, $imProviders); } } } else { $fieldValue = ''; } if ($field == 'id') { $row[$field] = $dao->contact_id; } else { if ($field == 'pledge_balance_amount') { //special case for calculated field $row[$field] = $dao->pledge_amount - $dao->pledge_total_paid; } else { if ($field == 'pledge_next_pay_amount') { //special case for calculated field $row[$field] = $dao->pledge_next_pay_amount + $dao->pledge_outstanding_amount; } else { if (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]; if (CRM_Utils_Array::value(1, $type)) { $fldValue .= "-" . $type[1]; } $row[$fldValue] = $dao->{$fldValue}; } } } else { if (array_key_exists($field, $contactRelationshipTypes)) { $relDAO = $allRelContactArray[$field][$dao->contact_id]; foreach ($value as $relationField => $relationValue) { if (is_object($relDAO) && property_exists($relDAO, $relationField)) { $fieldValue = $relDAO->{$relationField}; if ($relationField == 'phone_type_id') { $fieldValue = $phoneTypes[$relationValue]; } else { if ($relationField == 'provider_id') { $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders); } } } else { $fieldValue = ''; } if ($relationField == 'id') { $row[$field . $relationField] = $relDAO->contact_id; } else { if (is_array($relationValue) && $relationField == 'location') { foreach ($relationValue as $ltype => $val) { foreach (array_keys($val) as $fld) { $type = explode('-', $fld); $fldValue = "{$ltype}-" . $type[0]; if (CRM_Utils_Array::value(1, $type)) { $fldValue .= "-" . $type[1]; } $row[$field . $fldValue] = $relDAO->{$fldValue}; } } } else { if (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 { if (in_array($relationField, array('email_greeting', 'postal_greeting', 'addressee'))) { //special case for greeting replacement $fldValue = "{$relationField}_display"; $row[$field . $relationField] = $relDAO->{$fldValue}; } else { //normal relationship fields $row[$field . $relationField] = $fieldValue; } } } else { // if relation field is empty or null $row[$field . $relationField] = ''; } } } } } else { if (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); } else { if (array_key_exists($field, $multipleSelectFields)) { //option group fixes $paramsNew = array($field => $fieldValue); if ($field == 'test_tutoring') { $name = array($field => array('newName' => $field, 'groupName' => 'test')); } else { if (substr($field, 0, 4) == 'cmr_') { //for readers group $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]; } else { if (in_array($field, array('email_greeting', 'postal_greeting', 'addressee'))) { //special case for greeting replacement $fldValue = "{$field}_display"; $row[$field] = $dao->{$fldValue}; } else { //normal fields $row[$field] = $fieldValue; } } } } else { // if field is empty or null $row[$field] = ''; } } } } } } } //build header only once $setHeader = false; // add payment headers if required if ($addPaymentHeader && $paymentFields) { $headerRows = array_merge($headerRows, $paymentHeaders); $addPaymentHeader = false; } // add payment related information if ($paymentFields && isset($paymentDetails[$row[$paymentTableId]])) { $row = array_merge($row, $paymentDetails[$row[$paymentTableId]]); } //remove organization name for individuals if it is set for current employer if (CRM_Utils_Array::value('contact_type', $row) && $row['contact_type'] == 'Individual') { $row['organization_name'] = ''; } // CRM-3157: localise the output // FIXME: we should move this to multilingual stack some day require_once 'CRM/Core/I18n.php'; $i18n =& CRM_Core_I18n::singleton(); $translatable = array('preferred_communication_method', 'preferred_mail_format', 'gender', 'state_province', 'country', 'world_region'); foreach ($translatable as $column) { if (isset($row[$column]) and $row[$column]) { $row[$column] = $i18n->translate($row[$column]); } } // add component info $componentDetails[] = $row; } require_once 'CRM/Core/Report/Excel.php'; CRM_Core_Report_Excel::writeCSVFile(self::getExportFileName('csv', $exportMode), $headerRows, $componentDetails); exit; }
/** * Build the form object. */ public function buildQuickForm() { if ($this->_action & CRM_Core_Action::DELETE) { $this->addButtons(array(array('type' => 'next', 'name' => ts('Delete'), 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Cancel')))); return; } // Select list $relationshipList = CRM_Contact_BAO_Relationship::getContactRelationshipType($this->_contactId, $this->_rtype, $this->_relationshipId); // Metadata needed on clientside $this->assign('relationshipData', self::getRelationshipTypeMetadata($relationshipList)); foreach ($this->_allRelationshipNames as $id => $vals) { if ($vals['name_a_b'] === 'Employee of') { $this->assign('employmentRelationship', $id); break; } } $this->addField('relationship_type_id', array('options' => array('' => ts('- select -')) + $relationshipList, 'class' => 'huge', 'placeholder' => '- select -'), TRUE); $label = $this->_action & CRM_Core_Action::ADD ? ts('Contact(s)') : ts('Contact'); $contactField = $this->addField('related_contact_id', array('label' => $label, 'name' => 'contact_id_b', 'multiple' => TRUE, 'create' => TRUE), TRUE); // This field cannot be updated if ($this->_action & CRM_Core_Action::UPDATE) { $contactField->freeze(); } $this->add('advcheckbox', 'is_current_employer', $this->_contactType == 'Organization' ? ts('Current Employee') : ts('Current Employer')); $this->addField('start_date', array('label' => ts('Start Date'), 'formatType' => 'searchDate')); $this->addField('end_date', array('label' => ts('End Date'), 'formatType' => 'searchDate')); $this->addField('is_active', array('label' => ts('Enabled?'), 'type' => 'advcheckbox')); $this->addField('is_permission_a_b'); $this->addField('is_permission_b_a'); $this->addField('description', array('label' => ts('Description'))); CRM_Contact_Form_Edit_Notes::buildQuickForm($this); if ($this->_action & CRM_Core_Action::VIEW) { $this->addButtons(array(array('type' => 'cancel', 'name' => ts('Done')))); } else { // make this form an upload since we don't know if the custom data injected dynamically is of type file etc. $this->addButtons(array(array('type' => 'upload', 'name' => ts('Save Relationship'), 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Cancel')))); } }
/** * the initializer code, called before the processing * * @return void * @access public */ function init() { require_once 'CRM/Contact/BAO/Contact.php'; $fields =& CRM_Contact_BAO_Contact::importableFields($this->_contactType); //CRM-5125 //supporting import for contact subtypes if (!empty($this->_contactSubType)) { //custom fields for sub type $subTypeFields = CRM_Core_BAO_CustomField::getFieldsForImport($this->_contactSubType); if (!empty($subTypeFields)) { foreach ($subTypeFields as $customSubTypeField => $details) { $fields[$customSubTypeField] = $details; } } } //Relationship importables $this->_relationships = $relations = CRM_Contact_BAO_Relationship::getContactRelationshipType(null, null, null, $this->_contactType, false, 'label', true, $this->_contactSubType); asort($relations); foreach ($relations as $key => $var) { list($type) = explode('_', $key); $relationshipType[$key]['title'] = $var; $relationshipType[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/'; $relationshipType[$key]['import'] = true; $relationshipType[$key]['relationship_type_id'] = $type; $relationshipType[$key]['related'] = true; } if (!empty($relationshipType)) { $fields = array_merge($fields, array('related' => array('title' => ts('- related contact info -'))), $relationshipType); } foreach ($fields as $name => $field) { $this->addField($name, $field['title'], CRM_Utils_Array::value('type', $field), CRM_Utils_Array::value('headerPattern', $field), CRM_Utils_Array::value('dataPattern', $field), CRM_Utils_Array::value('hasLocationType', $field)); } $this->_newContacts = array(); $this->setActiveFields($this->_mapperKeys); $this->setActiveFieldLocationTypes($this->_mapperLocType); $this->setActiveFieldPhoneTypes($this->_mapperPhoneType); //set active fields of IM provider of contact $this->setActiveFieldImProviders($this->_mapperImProvider); //related info $this->setActiveFieldRelated($this->_mapperRelated); $this->setActiveFieldRelatedContactType($this->_mapperRelatedContactType); $this->setActiveFieldRelatedContactDetails($this->_mapperRelatedContactDetails); $this->setActiveFieldRelatedContactLocType($this->_mapperRelatedContactLocType); $this->setActiveFieldRelatedContactPhoneType($this->_mapperRelatedContactPhoneType); //set active fields of IM provider of related contact $this->setActiveFieldRelatedContactImProvider($this->_mapperRelatedContactImProvider); $this->_phoneIndex = -1; $this->_emailIndex = -1; $this->_firstNameIndex = -1; $this->_lastNameIndex = -1; $this->_householdNameIndex = -1; $this->_organizationNameIndex = -1; $this->_externalIdentifierIndex = -1; $index = 0; foreach ($this->_mapperKeys as $key) { if (substr($key, 0, 5) == 'email' && substr($key, 0, 14) != 'email_greeting') { $this->_emailIndex = $index; $this->_allEmails = array(); } if (substr($key, 0, 5) == 'phone') { $this->_phoneIndex = $index; } if ($key == 'first_name') { $this->_firstNameIndex = $index; } if ($key == 'last_name') { $this->_lastNameIndex = $index; } if ($key == 'household_name') { $this->_householdNameIndex = $index; } if ($key == 'organization_name') { $this->_organizationNameIndex = $index; } if ($key == 'external_identifier') { $this->_externalIdentifierIndex = $index; $this->_allExternalIdentifiers = array(); } $index++; } $this->_updateWithId = false; if (in_array('id', $this->_mapperKeys) || $this->_externalIdentifierIndex >= 0 && in_array($this->_onDuplicate, array(CRM_Import_Parser::DUPLICATE_UPDATE, CRM_Import_Parser::DUPLICATE_FILL))) { $this->_updateWithId = true; } require_once 'CRM/Core/BAO/Preferences.php'; $this->_parseStreetAddress = CRM_Utils_Array::value('street_address_parsing', CRM_Core_BAO_Preferences::valueOptions('address_options'), false); }
/** * where / qill clause for relationship * * @return void * @access public */ function relationship(&$values) { list($name, $op, $value, $grouping, $wildcard) = $values; // also get values array for relation_target_name // for relatinship search we always do wildcard $targetName = $this->getWhereValues('relation_target_name', $grouping); $relStatus = $this->getWhereValues('relation_status', $grouping); $targetGroup = $this->getWhereValues('relation_target_group', $grouping); $nameClause = $name = NULL; if ($targetName) { $name = trim($targetName[2]); if (substr($name, 0, 1) == '"' && substr($name, -1, 1) == '"') { $name = substr($name, 1, -1); $name = strtolower(CRM_Core_DAO::escapeString($name)); $nameClause = "= '{$name}'"; } else { $name = strtolower(CRM_Core_DAO::escapeString($name)); $nameClause = "LIKE '%{$name}%'"; } } $rel = explode('_', $value); self::$_relType = $rel[1]; $params = array('id' => $rel[0]); $rTypeValues = array(); $rType = CRM_Contact_BAO_RelationshipType::retrieve($params, $rTypeValues); if (!$rType) { return; } if ($rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) { self::$_relType = 'reciprocal'; } if ($nameClause) { $this->_where[$grouping][] = "( contact_b.sort_name {$nameClause} AND contact_b.id != contact_a.id )"; } $relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Individual'); $relTypeOrg = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Organization'); $relTypeHou = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Household'); $allRelationshipType = array(); $allRelationshipType = array_merge($relTypeInd, $relTypeOrg); $allRelationshipType = array_merge($allRelationshipType, $relTypeHou); if ($nameClause || !$targetGroup) { $this->_qill[$grouping][] = "{$allRelationshipType[$value]} {$name}"; } //check to see if the target contact is in specified group if ($targetGroup) { //add contacts from static groups $this->_tables['civicrm_relationship_group_contact'] = $this->_whereTables['civicrm_relationship_group_contact'] = " LEFT JOIN civicrm_group_contact civicrm_relationship_group_contact ON civicrm_relationship_group_contact.contact_id = contact_b.id"; $groupWhere[] = "( civicrm_relationship_group_contact.group_id IN (" . implode(",", $targetGroup[2]) . ") )"; //add contacts from saved searches $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b"); //set the group where clause if ($ssWhere) { $groupWhere[] = "( " . $ssWhere . " )"; } $this->_where[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )"; //Get the names of the target groups for the qill $groupNames =& CRM_Core_PseudoConstant::group(); $qillNames = array(); foreach ($targetGroup[2] as $groupId) { if (array_key_exists($groupId, $groupNames)) { $qillNames[] = $groupNames[$groupId]; } } $this->_qill[$grouping][] = "{$allRelationshipType[$value]} ( " . implode(", ", $qillNames) . " )"; } //check for active, inactive and all relation status $today = date('Ymd'); if ($relStatus[2] == 0) { $this->_where[$grouping][] = "(\ncivicrm_relationship.is_active = 1 AND\n( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND\n( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )\n)"; $this->_qill[$grouping][] = ts('Relationship - Active'); } elseif ($relStatus[2] == 1) { $this->_where[$grouping][] = "(\ncivicrm_relationship.is_active = 0 OR\ncivicrm_relationship.end_date < {$today} OR\ncivicrm_relationship.start_date > {$today}\n)"; $this->_qill[$grouping][] = ts('Relationship - Inactive'); } $this->_where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rel[0]; $this->_tables['civicrm_relationship'] = $this->_whereTables['civicrm_relationship'] = 1; $this->_useDistinct = TRUE; }
/** * Where / qill clause for relationship. * * @param array $values */ public function relationship(&$values) { list($name, $op, $value, $grouping, $wildcard) = $values; if ($this->_relationshipValuesAdded) { return; } // also get values array for relation_target_name // for relationship search we always do wildcard $relationType = $this->getWhereValues('relation_type_id', $grouping); $targetName = $this->getWhereValues('relation_target_name', $grouping); $relStatus = $this->getWhereValues('relation_status', $grouping); $relPermission = $this->getWhereValues('relation_permission', $grouping); $targetGroup = $this->getWhereValues('relation_target_group', $grouping); $nameClause = $name = NULL; if ($targetName) { $name = trim($targetName[2]); if (substr($name, 0, 1) == '"' && substr($name, -1, 1) == '"') { $name = substr($name, 1, -1); $name = strtolower(CRM_Core_DAO::escapeString($name)); $nameClause = "= '{$name}'"; } else { $name = strtolower(CRM_Core_DAO::escapeString($name)); $nameClause = "LIKE '%{$name}%'"; } } $rTypeValues = array(); if (!empty($relationType)) { $rel = explode('_', $relationType[2]); self::$_relType = $rel[1]; $params = array('id' => $rel[0]); $rType = CRM_Contact_BAO_RelationshipType::retrieve($params, $rTypeValues); } if (!empty($rTypeValues) && $rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) { // if we don't know which end of the relationship we are dealing with we'll create a temp table //@todo unless we are dealing with a target group self::$_relType = 'reciprocal'; } // if we are creating a temp table we build our own where for the relationship table $relationshipTempTable = NULL; if (self::$_relType == 'reciprocal' && empty($targetGroup)) { $where = array(); self::$_relationshipTempTable = $relationshipTempTable = CRM_Core_DAO::createTempTableName('civicrm_rel'); if ($nameClause) { $where[$grouping][] = " sort_name {$nameClause} "; } } else { $where =& $this->_where; if ($nameClause) { $where[$grouping][] = "( contact_b.sort_name {$nameClause} AND contact_b.id != contact_a.id )"; } } $allRelationshipType = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, NULL, TRUE); if ($nameClause || !$targetGroup) { if (!empty($relationType)) { $this->_qill[$grouping][] = $allRelationshipType[$relationType[2]] . " {$name}"; } else { $this->_qill[$grouping][] = $name; } } //check to see if the target contact is in specified group if ($targetGroup) { //add contacts from static groups $this->_tables['civicrm_relationship_group_contact'] = $this->_whereTables['civicrm_relationship_group_contact'] = " LEFT JOIN civicrm_group_contact civicrm_relationship_group_contact ON civicrm_relationship_group_contact.contact_id = contact_b.id AND civicrm_relationship_group_contact.status = 'Added'"; $groupWhere[] = "( civicrm_relationship_group_contact.group_id IN (" . implode(",", $targetGroup[2]) . ") ) "; //add contacts from saved searches $ssWhere = $this->addGroupContactCache($targetGroup[2], "civicrm_relationship_group_contact_cache", "contact_b", $op); //set the group where clause if ($ssWhere) { $groupWhere[] = "( " . $ssWhere . " )"; } $this->_where[$grouping][] = "( " . implode(" OR ", $groupWhere) . " )"; //Get the names of the target groups for the qill $groupNames = CRM_Core_PseudoConstant::group(); $qillNames = array(); foreach ($targetGroup[2] as $groupId) { if (array_key_exists($groupId, $groupNames)) { $qillNames[] = $groupNames[$groupId]; } } if (!empty($relationType)) { $this->_qill[$grouping][] = $allRelationshipType[$relationType[2]] . " ( " . implode(", ", $qillNames) . " )"; } else { $this->_qill[$grouping][] = implode(", ", $qillNames); } } // Note we do not currently set mySql to handle timezones, so doing this the old-fashioned way $today = date('Ymd'); //check for active, inactive and all relation status if ($relStatus[2] == 0) { $where[$grouping][] = "(\ncivicrm_relationship.is_active = 1 AND\n( civicrm_relationship.end_date IS NULL OR civicrm_relationship.end_date >= {$today} ) AND\n( civicrm_relationship.start_date IS NULL OR civicrm_relationship.start_date <= {$today} )\n)"; $this->_qill[$grouping][] = ts('Relationship - Active and Current'); } elseif ($relStatus[2] == 1) { $where[$grouping][] = "(\ncivicrm_relationship.is_active = 0 OR\ncivicrm_relationship.end_date < {$today} OR\ncivicrm_relationship.start_date > {$today}\n)"; $this->_qill[$grouping][] = ts('Relationship - Inactive or not Current'); } $onlyDeleted = 0; if (in_array(array('deleted_contacts', '=', '1', '0', '0'), $this->_params)) { $onlyDeleted = 1; } $where[$grouping][] = "(contact_b.is_deleted = {$onlyDeleted})"; //check for permissioned, non-permissioned and all permissioned relations if ($relPermission[2] == 1) { $where[$grouping][] = "(\ncivicrm_relationship.is_permission_a_b = 1\n)"; $this->_qill[$grouping][] = ts('Relationship - Permissioned'); } elseif ($relPermission[2] == 2) { //non-allowed permission relationship. $where[$grouping][] = "(\ncivicrm_relationship.is_permission_a_b = 0\n)"; $this->_qill[$grouping][] = ts('Relationship - Non-permissioned'); } $this->addRelationshipDateClauses($grouping, $where); if (!empty($relationType) && !empty($rType) && isset($rType->id)) { $where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rType->id; } $this->_tables['civicrm_relationship'] = $this->_whereTables['civicrm_relationship'] = 1; $this->_useDistinct = TRUE; $this->_relationshipValuesAdded = TRUE; // it could be a or b, using an OR creates an unindexed join - better to create a temp table & // join on that, // @todo creating a temp table could be expanded to group filter // as even creating a temp table of all relationships is much much more efficient than // an OR in the join if ($relationshipTempTable) { $whereClause = ''; if (!empty($where[$grouping])) { $whereClause = ' WHERE ' . implode(' AND ', $where[$grouping]); $whereClause = str_replace('contact_b', 'c', $whereClause); } $sql = "\n CREATE TEMPORARY TABLE {$relationshipTempTable}\n (SELECT contact_id_b as contact_id, civicrm_relationship.id\n FROM civicrm_relationship\n INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_a = c.id\n {$whereClause} )\n UNION\n (SELECT contact_id_a as contact_id, civicrm_relationship.id\n FROM civicrm_relationship\n INNER JOIN civicrm_contact c ON civicrm_relationship.contact_id_b = c.id\n {$whereClause} )\n "; CRM_Core_DAO::executeQuery($sql); } }
/** * Function to build the form * * @return None * @access public */ public function buildQuickForm() { parent::buildQuickForm(); if ($this->_action & CRM_Core_Action::DELETE) { return; } $this->applyFilter('__ALL__', 'trim'); $this->add('text', 'name', ts('Name'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'name'), TRUE); $this->addRule('name', ts('A membership type with this name already exists. Please select another name.'), 'objectExists', array('CRM_Member_DAO_MembershipType', $this->_id)); $this->add('text', 'description', ts('Description'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'description')); $this->add('text', 'minimum_fee', ts('Minimum Fee'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'minimum_fee')); $this->addRule('minimum_fee', ts('Please enter a monetary value for the Minimum Fee.'), 'money'); $this->addElement('select', 'duration_unit', ts('Duration') . ' ', CRM_Core_SelectValues::unitList('duration'), array('onchange' => 'showHidePeriodSettings()')); //period type $this->addElement('select', 'period_type', ts('Period Type'), CRM_Core_SelectValues::periodType(), array('onchange' => 'showHidePeriodSettings()')); $this->add('text', 'duration_interval', ts('Duration Interval'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'duration_interval')); $memberOrg =& $this->add('text', 'member_org', ts('Membership Organization'), 'size=30 maxlength=120'); //start day $this->add('date', 'fixed_period_start_day', ts('Fixed Period Start Day'), CRM_Core_SelectValues::date(NULL, 'M d'), FALSE); $msgTemplates = CRM_Core_BAO_MessageTemplates::getMessageTemplates(FALSE); $hasMsgTemplates = FALSE; if (!empty($msgTemplates)) { $hasMsgTemplates = TRUE; } //Auto-renew Option $paymentProcessor = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, 'is_recur = 1'); $isAuthorize = FALSE; $options = array(); $allowAutoRenewMsg = FALSE; if (is_array($paymentProcessor) && !empty($paymentProcessor)) { $isAuthorize = TRUE; $options = array(ts('No auto-renew option'), ts('Give option, but not required'), ts('Auto-renew required ')); if ($hasMsgTemplates) { $allowAutoRenewMsg = TRUE; $autoRenewReminderMsg = $this->add('select', 'autorenewal_msg_id', ts('Auto-renew Reminder Message'), array('' => ts('- select -')) + $msgTemplates); } } $this->addRadio('auto_renew', ts('Auto-renew Option'), $options, array('onclick' => "setReminder(this.value);")); $this->assign('authorize', $isAuthorize); $this->assign('allowAutoRenewMsg', $allowAutoRenewMsg); //rollover day $this->add('date', 'fixed_period_rollover_day', ts('Fixed Period Rollover Day'), CRM_Core_SelectValues::date(NULL, 'M d'), FALSE); // required in form rule $this->add('hidden', 'action', $this->_action); $this->add('select', 'contribution_type_id', ts('Contribution Type'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::contributionType()); $relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE); if (is_array($relTypeInd)) { asort($relTypeInd); } $memberRel =& $this->add('select', 'relationship_type_id', ts('Relationship Type'), array('' => ts('- select -')) + $relTypeInd); $memberRel->setMultiple(TRUE); $this->add('select', 'visibility', ts('Visibility'), CRM_Core_SelectValues::memberVisibility()); $this->add('text', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'weight')); $this->add('checkbox', 'is_active', ts('Enabled?')); if ($hasMsgTemplates) { $reminderMsg = $this->add('select', 'renewal_msg_id', ts('Renewal Reminder Message'), array('' => ts('- select -')) + $msgTemplates); } $this->assign('hasMsgTemplates', $hasMsgTemplates); $reminderDay =& $this->add('text', 'renewal_reminder_day', ts('Renewal Reminder Day'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'renewal_reminder_day')); $searchRows = $this->get('searchRows'); $searchCount = $this->get('searchCount'); $searchDone = $this->get('searchDone'); if ($searchRows) { $checkBoxes = array(); $chekFlag = 0; foreach ($searchRows as $id => $row) { $checked = ''; if (!$chekFlag) { $checked = array('checked' => NULL); $chekFlag++; } $checkBoxes[$id] = $this->createElement('radio', NULL, NULL, NULL, $id, $checked); } $this->addGroup($checkBoxes, 'contact_check'); $this->assign('searchRows', $searchRows); } $this->assign('searchCount', $searchCount); $this->assign('searchDone', $searchDone); if ($searchDone) { $searchBtn = ts('Search Again'); } elseif ($this->_action & CRM_Core_Action::UPDATE) { $searchBtn = ts('Change'); } else { $searchBtn = ts('Search'); } $membershipRecords = FALSE; if ($this->_action & CRM_Core_Action::UPDATE) { $membershipType = new CRM_Member_BAO_Membership(); $membershipType->membership_type_id = $this->_id; if ($membershipType->find(TRUE)) { $membershipRecords = TRUE; $memberRel->freeze(); } $memberOrg->freeze(); if ($searchDone) { $memberOrg->unfreeze(); } } $this->assign('membershipRecordsExists', $membershipRecords); if ($this->_action & CRM_Core_Action::UPDATE && $reminderDay) { $renewMessage = array(); $returnProperties = array('renewal_msg_id', 'renewal_reminder_day'); CRM_Core_DAO::commonRetrieveAll('CRM_Member_DAO_MembershipType', 'id', $this->_id, $renewMessage, $returnProperties); if (CRM_Utils_Array::value('renewal_msg_id', $renewMessage[$this->_id]) && CRM_Utils_Array::value('renewal_reminder_day', $renewMessage[$this->_id]) && $membershipRecords) { $reminderMsg = $this->add('select', 'renewal_msg_id', ts('Renewal Reminder Message'), array('' => ts('- select -')) + $msgTemplates); $reminderDay->freeze(); } } $this->addElement('submit', $this->getButtonName('refresh'), $searchBtn, array('class' => 'form-submit')); $this->addFormRule(array('CRM_Member_Form_MembershipType', 'formRule')); $this->assign('membershipTypeId', $this->_id); }
function clauseComponent() { $selectedContacts = implode(',', $this->_contactSelected); $contribution = $membership = $participant = null; $eligibleResult = $rows = $tempArray = array(); foreach ($this->_component as $val) { if (CRM_Utils_Array::value($val, $this->_selectComponent) && ($val != 'activity_civireport' && $val != 'relationship_civireport')) { $sql = "{$this->_selectComponent[$val]} {$this->_formComponent[$val]} \n WHERE {$this->_aliases['civicrm_contact']}.id IN ( {$selectedContacts} )\n GROUP BY {$this->_aliases['civicrm_contact']}.id,{$val}.id "; $dao = CRM_Core_DAO::executeQuery($sql); while ($dao->fetch()) { $countRecord = 0; $eligibleResult[$val] = $val; $CC = "civicrm_" . substr_replace($val, '', -11, 11) . "_contact_id"; $row = array(); foreach ($this->_columnHeadersComponent[$val] as $key => $value) { $countRecord++; $row[$key] = $dao->{$key}; } //if record exist for component(except contact_id) //since contact_id is selected for every component if ($countRecord > 1) { $rows[$dao->{$CC}][$val][] = $row; } $tempArray[$dao->{$CC}] = $dao->{$CC}; } } } if (CRM_Utils_Array::value('relationship_civireport', $this->_selectComponent)) { require_once 'CRM/Contact/BAO/Relationship.php'; $relTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(null, 'null', null, null, true); $val = 'relationship_civireport'; $eligibleResult[$val] = $val; $sql = "{$this->_selectComponent[$val]},{$this->_aliases['civicrm_contact']}.display_name as contact_b_name, contact_a.id as contact_a_id , contact_a.display_name as contact_a_name {$this->_formComponent[$val]} \n WHERE ({$this->_aliases['civicrm_contact']}.id IN ( {$selectedContacts} )\n OR \n contact_a.id IN ( {$selectedContacts} ) ) AND\n {$this->_aliases['civicrm_relationship']}.is_active = 1\n GROUP BY {$this->_aliases['civicrm_relationship']}.id"; $dao = CRM_Core_DAO::executeQuery($sql); while ($dao->fetch()) { foreach ($this->_columnHeadersComponent[$val] as $key => $value) { if ($key == 'civicrm_relationship_contact_id_b') { $row[$key] = $dao->contact_b_name; continue; } $row[$key] = $dao->{$key}; } $relTitle = "" . $dao->civicrm_relationship_relationship_type_id . "_a_b"; $row['civicrm_relationship_relationship_type_id'] = $relTypes[$relTitle]; $rows[$dao->contact_a_id][$val][] = $row; $row['civicrm_relationship_contact_id_b'] = $dao->contact_a_name; $relTitle = "" . $dao->civicrm_relationship_relationship_type_id . "_b_a"; if (isset($relTypes[$relTitle])) { $row['civicrm_relationship_relationship_type_id'] = $relTypes[$relTitle]; } $rows[$dao->civicrm_relationship_contact_id_b][$val][] = $row; } } if (CRM_Utils_Array::value('activity_civireport', $this->_selectComponent)) { $componentClause = "civicrm_option_value.component_id IS NULL"; $componentsIn = null; $compInfo = CRM_Core_Component::getEnabledComponents(); foreach ($compInfo as $compObj) { if ($compObj->info['showActivitiesInCore']) { $componentsIn = $componentsIn ? $componentsIn . ', ' . $compObj->componentID : $compObj->componentID; } } if ($componentsIn) { $componentClause = "( {$componentClause} OR \n civicrm_option_value.component_id IN ({$componentsIn}) )"; } $val = 'activity_civireport'; $eligibleResult[$val] = $val; $sql = "{$this->_selectComponent[$val]} , \n sourceContact.display_name as added_by {$this->_formComponent[$val]}\n\n WHERE ( {$this->_aliases['civicrm_activity']}.source_contact_id IN ({$selectedContacts}) OR \n target_contact_id IN ({$selectedContacts}) OR \n assignee_contact_id IN ({$selectedContacts}) OR \n civicrm_case_contact.contact_id IN ({$selectedContacts}) ) AND \n civicrm_option_group.name = 'activity_type' AND \n {$this->_aliases['civicrm_activity']}.is_test = 0 AND \n ({$componentClause})\n\n GROUP BY {$this->_aliases['civicrm_activity']}.id \n\n ORDER BY {$this->_aliases['civicrm_activity']}.activity_date_time desc "; $dao = CRM_Core_DAO::executeQuery($sql); while ($dao->fetch()) { foreach ($this->_columnHeadersComponent[$val] as $key => $value) { if ($key == 'civicrm_activity_source_contact_id') { $row[$key] = $dao->added_by; continue; } $row[$key] = $dao->{$key}; } if (isset($dao->civicrm_activity_source_contact_id)) { $rows[$dao->civicrm_activity_source_contact_id][$val][] = $row; } if (isset($dao->target_contact_id)) { $rows[$dao->target_contact_id][$val][] = $row; } if (isset($dao->assignee_contact_id)) { $rows[$dao->assignee_contact_id][$val][] = $row; } } //unset the component header if data is not present foreach ($this->_component as $val) { if (!in_array($val, $eligibleResult)) { unset($this->_columnHeadersComponent[$val]); } } } return $rows; }
/** * Function to 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 $associated array of fields * @param array $moreReturnProperties additional return fields * @param int $exportMode export mode * @param string $componentClause component clause * * @static * @access public */ static function exportComponents($selectAll, $ids, $params, $order = null, $fields = null, $moreReturnProperties = null, $exportMode = CRM_Export_Form_Select::CONTACT_EXPORT, $componentClause = null) { $headerRows = array(); $primary = false; $returnProperties = array(); $origFields = $fields; $queryMode = null; $paymentFields = false; $phoneTypes = CRM_Core_PseudoConstant::phoneType(); $imProviders = CRM_Core_PseudoConstant::IMProvider(); $contactRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(null, null, null, null, true, 'label', false); $queryMode = CRM_Contact_BAO_Query::MODE_CONTACTS; switch ($exportMode) { case CRM_Export_Form_Select::CONTRIBUTE_EXPORT: $queryMode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE; break; case CRM_Export_Form_Select::EVENT_EXPORT: $queryMode = CRM_Contact_BAO_Query::MODE_EVENT; break; case CRM_Export_Form_Select::MEMBER_EXPORT: $queryMode = CRM_Contact_BAO_Query::MODE_MEMBER; break; case CRM_Export_Form_Select::PLEDGE_EXPORT: $queryMode = CRM_Contact_BAO_Query::MODE_PLEDGE; break; case CRM_Export_Form_Select::CASE_EXPORT: $queryMode = CRM_Contact_BAO_Query::MODE_CASE; break; } require_once 'CRM/Core/BAO/CustomField.php'; if ($fields) { //construct return properties $locationTypes =& CRM_Core_PseudoConstant::locationType(); $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 = null; $imProviderId = null; $relationshipTypes = $fieldName = CRM_Utils_Array::value(1, $value); if (!$fieldName) { continue; } // get phoneType id and IM service provider id seperately if ($fieldName == 'phone') { $phoneTypeId = CRM_Utils_Array::value(3, $value); } else { if ($fieldName == 'im') { $imProviderId = CRM_Utils_Array::value(3, $value); } } if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) { if (CRM_Utils_Array::value(2, $value)) { $relationField = CRM_Utils_Array::value(2, $value); if (trim(CRM_Utils_Array::value(3, $value))) { $relLocTypeId = CRM_Utils_Array::value(3, $value); } else { $relLocTypeId = 1; } if ($relationField == 'phone') { $relPhoneTypeId = CRM_Utils_Array::value(4, $value); } else { if ($relationField == 'im') { $relIMProviderId = CRM_Utils_Array::value(4, $value); } } } else { if (CRM_Utils_Array::value(4, $value)) { $relationField = CRM_Utils_Array::value(4, $value); $relLocTypeId = CRM_Utils_Array::value(5, $value); if ($relationField == 'phone') { $relPhoneTypeId = CRM_Utils_Array::value(6, $value); } else { if ($relationField == 'im') { $relIMProviderId = CRM_Utils_Array::value(6, $value); } } } } } $contactType = CRM_Utils_Array::value(0, $value); $locTypeId = CRM_Utils_Array::value(2, $value); $phoneTypeId = CRM_Utils_Array::value(3, $value); if ($relationField) { if (in_array($relationField, $locationTypeFields)) { if ($relPhoneTypeId) { $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1; } else { if ($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; } } else { if (is_numeric($locTypeId)) { if ($phoneTypeId) { $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1; } else { if (isset($imProviderId)) { //build returnProperties for IM service provider $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1; } else { $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1; } } } else { //hack to fix component fields if ($fieldName == 'event_id') { $returnProperties['event_title'] = 1; } else { $returnProperties[$fieldName] = 1; } } } } // hack to add default returnproperty based on export mode if ($exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT) { $returnProperties['contribution_id'] = 1; } else { if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) { $returnProperties['participant_id'] = 1; } else { if ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) { $returnProperties['membership_id'] = 1; } else { if ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) { $returnProperties['pledge_id'] = 1; } else { if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) { $returnProperties['case_id'] = 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: require_once 'CRM/Pledge/BAO/Query.php'; $extraReturnProperties = CRM_Pledge_BAO_Query::extraReturnProperties($queryMode); $paymentFields = true; $paymentTableId = "pledge_payment_id"; break; case CRM_Contact_BAO_Query::MODE_CASE: require_once 'CRM/Case/BAO/Query.php'; $extraReturnProperties = CRM_Case_BAO_Query::extraReturnProperties($queryMode); break; } if ($queryMode != CRM_Contact_BAO_Query::MODE_CONTACTS) { $componentReturnProperties =& CRM_Contact_BAO_Query::defaultReturnProperties($queryMode); $returnProperties = array_merge($returnProperties, $componentReturnProperties); if (!empty($extraReturnProperties)) { $returnProperties = array_merge($returnProperties, $extraReturnProperties); } // unset groups, tags, notes for components foreach (array('groups', 'tags', 'notes') as $value) { unset($returnProperties[$value]); } } } if ($moreReturnProperties) { $returnProperties = array_merge($returnProperties, $moreReturnProperties); } $query =& new CRM_Contact_BAO_Query(0, $returnProperties, null, false, false, $queryMode); list($select, $from, $where) = $query->query(); // 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 (CRM_Utils_Array::value('groups', $returnProperties)) { $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 ($componentClause) { if (empty($where)) { $where = "WHERE {$componentClause}"; } else { $where .= " AND {$componentClause}"; } } $queryString = "{$select} {$from} {$where}"; if (CRM_Utils_Array::value('tags', $returnProperties) || CRM_Utils_Array::value('groups', $returnProperties) || CRM_Utils_Array::value('notes', $returnProperties) || $query->_useGroupBy) { $queryString .= " GROUP BY contact_a.id"; } if ($order) { list($field, $dir) = explode(' ', $order, 2); $field = trim($field); if (CRM_Utils_Array::value($field, $returnProperties)) { $queryString .= " ORDER BY {$order}"; } } //hack for student data require_once 'CRM/Core/OptionGroup.php'; $multipleSelectFields = array('preferred_communication_method' => 1); if (CRM_Core_Permission::access('Quest')) { require_once 'CRM/Quest/BAO/Student.php'; $studentFields = array(); $studentFields = CRM_Quest_BAO_Student::$multipleSelectFields; $multipleSelectFields = array_merge($multipleSelectFields, $studentFields); } $dao =& CRM_Core_DAO::executeQuery($queryString, CRM_Core_DAO::$_nullArray); $header = false; $addPaymentHeader = false; if ($paymentFields) { $addPaymentHeader = true; //special return properties for event and members $paymentHeaders = array(ts('Total Amount'), ts('Contribution Status'), ts('Received Date'), ts('Payment Instrument'), ts('Transaction ID')); // get payment related in for event and members require_once 'CRM/Contribute/BAO/Contribution.php'; $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids); } $componentDetails = $headerRows = array(); $setHeader = true; while ($dao->fetch()) { $row = array(); //first loop through returnproperties so that we return what is required, and in same order. $relationshipField = 0; foreach ($returnProperties as $field => $value) { //we should set header only once if ($setHeader) { if (isset($query->_fields[$field]['title'])) { $headerRows[] = $query->_fields[$field]['title']; } else { if ($field == 'phone_type_id') { $headerRows[] = 'Phone Type'; } else { if ($field == 'provider_id') { $headerRows[] = 'Im Service Provider'; } else { if (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 (CRM_Utils_Array::value(1, $type)) { if (CRM_Utils_Array::value(0, $type) == 'phone') { $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes); } else { if (CRM_Utils_Array::value(0, $type) == 'im') { $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders); } } } $headerRows[] = $hdr; } } } else { if (substr($field, 0, 5) == 'case_') { if ($query->_fields['case'][$field]['title']) { $headerRows[] = $query->_fields['case'][$field]['title']; } else { if ($query->_fields['activity'][$field]['title']) { $headerRows[] = $query->_fields['activity'][$field]['title']; } } } else { if (array_key_exists($field, $contactRelationshipTypes)) { foreach ($value as $relationField => $relationValue) { if (is_array($relationValue)) { foreach ($relationValue as $locType => $locValue) { if ($relationField == 'location') { foreach ($locValue as $locKey => $dont) { list($serviceProvider, $serviceProviderID) = explode('-', $locKey); if ($serviceProvider == 'phone') { $headerRows[] = $contactRelationshipTypes[$field] . ' : ' . $locType . ' - ' . $serviceProvider . ' - ' . CRM_Utils_Array::value($serviceProviderID, $phoneTypes, 'Primary'); } else { if ($serviceProvider == 'im') { $headerRows[] = $contactRelationshipTypes[$field] . ' : ' . $locType . ' - ' . $serviceProvider . ' - ' . CRM_Utils_Array::value($serviceProviderID, $imProviders, 'Primary'); } else { $headerRows[] = $contactRelationshipTypes[$field] . ' : ' . $locType . ' - ' . $query->_fields[$locKey]['title']; } } } } } } else { if ($query->_fields[$relationField]['title']) { $headerRows[] = $contactRelationshipTypes[$field] . ' : ' . $query->_fields[$relationField]['title']; } else { $headerRows[] = $contactRelationshipTypes[$field] . ' : ' . $relationField; } } } } else { $headerRows[] = $field; } } } } } } } //build row values (data) if (property_exists($dao, $field)) { $fieldValue = $dao->{$field}; // to get phone type from phone type id if ($field == 'phone_type_id') { $fieldValue = $phoneTypes[$fieldValue]; } else { if ($field == 'provider_id') { $fieldValue = CRM_Utils_Array::value($fieldValue, $imProviders); } } } else { $fieldValue = ''; } if ($field == 'id') { $row[$field] = $dao->contact_id; } else { if ($field == 'pledge_balance_amount') { //special case for calculated field $row[$field] = $dao->pledge_amount - $dao->pledge_total_paid; } else { if ($field == 'pledge_next_pay_amount') { //special case for calculated field $row[$field] = $dao->pledge_next_pay_amount + $dao->pledge_outstanding_amount; } else { if (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]; if (CRM_Utils_Array::value(1, $type)) { $fldValue .= "-" . $type[1]; } $row[$fldValue] = $dao->{$fldValue}; } } } else { if (array_key_exists($field, $contactRelationshipTypes)) { list($id, $direction) = explode('_', $field, 2); require_once 'api/v2/Relationship.php'; require_once 'CRM/Contact/BAO/Contact.php'; require_once 'CRM/Core/BAO/CustomValueTable.php'; require_once 'CRM/Core/BAO/CustomQuery.php'; $params['relationship_type_id'] = $contactRelationshipTypes[$field]; $contact_id['contact_id'] = $dao->contact_id; //Get relationships $val = civicrm_contact_relationship_get($contact_id, null, $params); if (is_array($val['result'])) { asort($val['result']); } $is_valid = null; $data = null; if ($val['result']) { foreach ($val['result'] as $k => $v) { //consider only active relationships if ($v['is_active'] && $v['rtype'] == $direction) { $cID['contact_id'] = $v['cid']; if ($cID) { //Get Contact Details $data = CRM_Contact_BAO_Contact::retrieve($cID, $defaults); } $is_valid = true; break; } } } $relCustomIDs = array(); foreach ($value as $relationkey => $relationvalue) { if ($val['result'] && ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationkey))) { foreach ($val['result'] as $k1 => $v1) { $contID = $v1['cid']; $param1 = array('entityID' => $contID, $relationkey => 1); $getcustomValue = CRM_Core_BAO_CustomValueTable::getValues($param1); $custom_ID = CRM_Core_BAO_CustomField::getKeyID($relationkey); if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationkey)) { if (empty($query->_options)) { $relCustomIDs[$cfID] = array(); $relQuery = new CRM_Core_BAO_CustomQuery($relCustomIDs); $relQuery->query(); $relOptions = $relQuery->_options; } else { $relOptions = $query->_options; } $custom_data = CRM_Core_BAO_CustomField::getDisplayValue($getcustomValue[$relationkey], $cfID, $relOptions); } else { $custom_data = ''; } } } //Get all relationships type custom fields list($id, $atype, $btype) = explode('_', $field); $relCustomData = CRM_Core_BAO_CustomField::getFields('Relationship', null, null, $id, null, null); $tmpArray = array_keys($relCustomData); $customIDs = array(); foreach ($tmpArray as $customID) { $customIDs[$customID] = array(); } require_once 'CRM/Core/BAO/CustomQuery.php'; $customQuery = new CRM_Core_BAO_CustomQuery($customIDs); $customQuery->query(); $options = $customQuery->_options; foreach ($relCustomData as $id => $customdatavalue) { if (in_array($relationkey, $customdatavalue)) { $customkey = "custom_{$id}"; if ($val['result']) { foreach ($val['result'] as $k => $v) { $cid = $v['id']; $param = array('entityID' => $cid, $customkey => 1); //Get custom data values $getCustomValueRel = CRM_Core_BAO_CustomValueTable::getValues($param); if (!array_key_exists('error_message', $getCustomValueRel)) { $customData = CRM_Core_BAO_CustomField::getDisplayValue($getCustomValueRel[$customkey], $id, $options); } else { $customData = ''; } if ($customData) { break; } } } } } if (is_array($relationvalue)) { if (array_key_exists('location', $value)) { foreach ($value['location'] as $columnkey => $columnvalue) { foreach ($columnvalue as $colkey => $colvalue) { list($serviceProvider, $serviceProviderID) = explode('-', $colkey); if (in_array($serviceProvider, array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'postal_code', 'postal_code_suffix', 'state_province', 'country'))) { $serviceProvider = 'address'; } $output = null; foreach ((array) $data->{$serviceProvider} as $datakey => $datavalue) { if ($columnkey == 'Primary') { $columnkey = $locationTypes[$datavalue['location_type_id']]; } if ($locationTypes[$datavalue['location_type_id']] == $columnkey) { if (array_key_exists($colkey, $datavalue)) { $output = $datavalue[$colkey]; } else { if ($colkey == 'country') { $countryId = $datavalue['country_id']; if ($countryId) { require_once 'CRM/Core/PseudoConstant.php'; $country =& CRM_Core_PseudoConstant::country($countryId); } else { $country = ''; } $output = $country; } else { if ($colkey == 'state_province') { $stateProvinceId = $datavalue['state_province_id']; if ($stateProvinceId) { $stateProvince =& CRM_Core_PseudoConstant::stateProvince($stateProvinceId); } else { $stateProvince = ''; } $output = $stateProvince; } else { if (is_numeric($serviceProviderID)) { if ($serviceProvider == 'phone') { if (isset($datavalue['phone'])) { $output = $datavalue['phone']; } else { $output = ''; } } else { if ($serviceProvider == 'im') { if (isset($datavalue['name'])) { $output = $datavalue['name']; } else { $output = ''; } } } } else { if ($datavalue['location_type_id']) { if ($colkey == 'im') { $output = $datavalue['name']; } else { $output = $datavalue[$colkey]; } } else { $output = ''; } } } } } } } if ($is_valid) { $row[] = $output; } else { $row[] = ''; } } } } } else { if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationkey) && $is_valid) { $row[] = $custom_data; } else { if ($query->_fields[$relationkey]['name'] && $is_valid) { if ($query->_fields[$relationkey]['name'] == 'gender') { $getGenders =& CRM_Core_PseudoConstant::gender(); $gender = array_search($data->gender_id, array_flip($getGenders)); $row[] = $gender; } else { if ($query->_fields[$relationkey]['name'] == 'greeting_type') { $getgreeting =& CRM_Core_PseudoConstant::greeting(); $greeting = array_search($data->greeting_type_id, array_flip($getgreeting)); $row[] = $greeting; } else { $colValue = $query->_fields[$relationkey]['name']; $row[] = $data->{$colValue}; } } } else { if ($customData && $is_valid) { $row[] = $customData; } else { $row[] = ''; } } } } } } else { if (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); } else { if (array_key_exists($field, $multipleSelectFields)) { //option group fixes $paramsNew = array($field => $fieldValue); if ($field == 'test_tutoring') { $name = array($field => array('newName' => $field, 'groupName' => 'test')); } else { if (substr($field, 0, 4) == 'cmr_') { //for readers group $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]; } else { if (in_array($field, array('email_greeting', 'postal_greeting', 'addressee'))) { //special case for greeting replacement $fldValue = "{$field}_display"; $row[$field] = $dao->{$fldValue}; } else { //normal fields $row[$field] = $fieldValue; } } } } else { // if field is empty or null $row[$field] = ''; } } } } } } } //build header only once $setHeader = false; // add payment headers if required if ($addPaymentHeader && $paymentFields) { $headerRows = array_merge($headerRows, $paymentHeaders); $addPaymentHeader = false; } // add payment related information if ($paymentFields && isset($paymentDetails[$row[$paymentTableId]])) { $row = array_merge($row, $paymentDetails[$row[$paymentTableId]]); } //remove organization name for individuals if it is set for current employer if (CRM_Utils_Array::value('contact_type', $row) && $row['contact_type'] == 'Individual') { $row['organization_name'] = ''; } // add component info $componentDetails[] = $row; } require_once 'CRM/Core/Report/Excel.php'; CRM_Core_Report_Excel::writeCSVFile(self::getExportFileName('csv', $exportMode), $headerRows, $componentDetails); exit; }
/** * Build the form object. */ public function buildQuickForm() { if ($this->_action & CRM_Core_Action::DELETE) { $this->addButtons(array(array('type' => 'next', 'name' => ts('Delete'), 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Cancel')))); return; } // Select list $relationshipList = CRM_Contact_BAO_Relationship::getContactRelationshipType($this->_contactId, $this->_rtype, $this->_relationshipId); // Metadata needed on clientside $contactTypes = CRM_Contact_BAO_ContactType::contactTypeInfo(TRUE); $jsData = array(); // Get just what we need to keep the dom small $whatWeWant = array_flip(array('contact_type_a', 'contact_type_b', 'contact_sub_type_a', 'contact_sub_type_b')); foreach ($this->_allRelationshipNames as $id => $vals) { if ($vals['name_a_b'] === 'Employee of') { $this->assign('employmentRelationship', $id); } if (isset($relationshipList["{$id}_a_b"]) || isset($relationshipList["{$id}_b_a"])) { $jsData[$id] = array_filter(array_intersect_key($this->_allRelationshipNames[$id], $whatWeWant)); // Add user-friendly placeholder foreach (array('a', 'b') as $x) { $type = !empty($jsData[$id]["contact_sub_type_{$x}"]) ? $jsData[$id]["contact_sub_type_{$x}"] : CRM_Utils_Array::value("contact_type_{$x}", $jsData[$id]); $jsData[$id]["placeholder_{$x}"] = $type ? ts('- select %1 -', array(strtolower($contactTypes[$type]['label']))) : ts('- select contact -'); } } } $this->assign('relationshipData', $jsData); $this->addField('relationship_type_id', array('options' => array('' => ts('- select -')) + $relationshipList, 'class' => 'huge', 'placeholder' => '- select -'), TRUE); $label = $this->_action & CRM_Core_Action::ADD ? ts('Contact(s)') : ts('Contact'); $contactField = $this->addField('related_contact_id', array('label' => $label, 'name' => 'contact_id_b', 'multiple' => TRUE, 'create' => TRUE), TRUE); // This field cannot be updated if ($this->_action & CRM_Core_Action::UPDATE) { $contactField->freeze(); } $this->add('advcheckbox', 'is_current_employer', $this->_contactType == 'Organization' ? ts('Current Employee') : ts('Current Employer')); $this->addField('start_date', array('label' => ts('Start Date'), 'formatType' => 'searchDate')); $this->addField('end_date', array('label' => ts('End Date'), 'formatType' => 'searchDate')); $this->addField('is_active', array('label' => ts('Enabled?'))); $this->addField('is_permission_a_b'); $this->addField('is_permission_b_a'); $this->addField('description', array('label' => ts('Description'))); CRM_Contact_Form_Edit_Notes::buildQuickForm($this); if ($this->_action & CRM_Core_Action::VIEW) { $this->addButtons(array(array('type' => 'cancel', 'name' => ts('Done')))); } else { // make this form an upload since we don't know if the custom data injected dynamically is of type file etc. $this->addButtons(array(array('type' => 'upload', 'name' => ts('Save Relationship'), 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Cancel')))); } }
/** * where / qill clause for relationship * * @return void * @access public */ function relationship(&$values) { list($name, $op, $value, $grouping, $wildcard) = $values; // also get values array for relation_target_name // for relatinship search we always do wildcard $targetName = $this->getWhereValues('relation_target_name', $grouping); $relStatus = $this->getWhereValues('relation_status', $grouping); $nameClause = null; if ($targetName) { $name = trim($targetName[2]); if (substr($name, 0, 1) == '"' && substr($name, -1, 1) == '"') { $name = substr($name, 1, -1); $name = strtolower(CRM_Core_DAO::escapeString($name)); $nameClause = "= '{$name}'"; } else { $name = strtolower(CRM_Core_DAO::escapeString($name)); $nameClause = "LIKE '%{$name}%'"; } } $rel = explode('_', $value); self::$_relType = $rel[1]; if ($nameClause) { require_once 'CRM/Contact/BAO/RelationshipType.php'; $params = array('id' => $rel[0]); $rTypeValues = array(); require_once "CRM/Contact/BAO/RelationshipType.php"; $rType =& CRM_Contact_BAO_RelationshipType::retrieve($params, $rTypeValues); if (!$rType) { return; } // for relatinship search we always do wildcard if ($rTypeValues['name_a_b'] == $rTypeValues['name_b_a']) { self::$_relType = 'reciprocal'; } $this->_where[$grouping][] = "( contact_b.sort_name {$nameClause} AND contact_b.id != contact_a.id )"; } require_once 'CRM/Contact/BAO/Relationship.php'; $relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(null, 'null', null, 'Individual'); $relTypeOrg = CRM_Contact_BAO_Relationship::getContactRelationshipType(null, 'null', null, 'Organization'); $relTypeHou = CRM_Contact_BAO_Relationship::getContactRelationshipType(null, 'null', null, 'Household'); $allRelationshipType = array(); $allRelationshipType = array_merge($relTypeInd, $relTypeOrg); $allRelationshipType = array_merge($allRelationshipType, $relTypeHou); $this->_qill[$grouping][] = "{$allRelationshipType[$value]} {$name}"; //check for active, inactive and all relation status $today = date('Ymd'); if ($relStatus[2] == 0) { $this->_where[$grouping][] = "civicrm_relationship.is_active = 1 AND ( civicrm_relationship.end_date is NULL OR civicrm_relationship.end_date >= {$today} )"; $this->_qill[$grouping][] = ts('Relationship - Active'); } else { if ($relStatus[2] == 1) { $this->_where[$grouping][] = "(civicrm_relationship.is_active = 0 OR civicrm_relationship.end_date < {$today})"; $this->_qill[$grouping][] = ts('Relationship - Inactive'); } } $this->_where[$grouping][] = 'civicrm_relationship.relationship_type_id = ' . $rel[0]; $this->_tables['civicrm_relationship'] = $this->_whereTables['civicrm_relationship'] = 1; $this->_useDistinct = true; }
/** * Build the form object. */ public function buildQuickForm() { //this call is for show related cases. if ($this->_showRelatedCases) { return; } $allowedRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType($this->_contactID); CRM_Core_Resources::singleton()->addScriptFile('civicrm', 'js/crm.livePage.js', 1, 'html-header')->addScriptFile('civicrm', 'templates/CRM/Case/Form/CaseView.js', 2, 'html-header')->addVars('relationshipTypes', CRM_Contact_Form_Relationship::getRelationshipTypeMetadata($allowedRelationshipTypes)); $xmlProcessor = new CRM_Case_XMLProcessor_Process(); $caseRoles = $xmlProcessor->get($this->_caseType, 'CaseRoles'); $reports = $xmlProcessor->get($this->_caseType, 'ActivitySets'); //adding case manager.CRM-4510. $managerRoleId = $xmlProcessor->getCaseManagerRoleId($this->_caseType); if (!empty($managerRoleId)) { $caseRoles[$managerRoleId] = $caseRoles[$managerRoleId] . '<br />' . '(' . ts('Case Manager') . ')'; } $aTypes = $xmlProcessor->get($this->_caseType, 'ActivityTypes', TRUE); $allActTypes = CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'name'); $emailActivityType = array_search('Email', $allActTypes); $pdfActivityType = array_search('Print PDF Letter', $allActTypes); if ($pdfActivityType) { $this->assign('exportDoc', CRM_Utils_System::url('civicrm/activity/pdf/add', "action=add&context=standalone&reset=1&cid={$this->_contactID}&caseid={$this->_caseID}&atype={$pdfActivityType}")); } // remove Open Case activity type since we're inside an existing case if ($openActTypeId = array_search('Open Case', $allActTypes)) { unset($aTypes[$openActTypeId]); } //check for link cases. $unclosedCases = CRM_Case_BAO_Case::getUnclosedCases(NULL, array($this->_caseID)); if (empty($unclosedCases) && ($linkActTypeId = array_search('Link Cases', $allActTypes))) { unset($aTypes[$linkActTypeId]); } if (!$xmlProcessor->getNaturalActivityTypeSort()) { asort($aTypes); } $activityLinks = array('' => ts('Add Activity')); foreach ($aTypes as $type => $label) { if ($type == $emailActivityType) { $url = CRM_Utils_System::url('civicrm/activity/email/add', "action=add&context=standalone&reset=1&caseid={$this->_caseID}&atype={$type}", FALSE, NULL, FALSE); } elseif ($type == $pdfActivityType) { $url = CRM_Utils_System::url('civicrm/activity/pdf/add', "action=add&context=standalone&reset=1&cid={$this->_contactID}&caseid={$this->_caseID}&atype={$type}", FALSE, NULL, FALSE); } else { $url = CRM_Utils_System::url('civicrm/case/activity', "action=add&reset=1&cid={$this->_contactID}&caseid={$this->_caseID}&atype={$type}", FALSE, NULL, FALSE); } $activityLinks[$url] = $label; } $this->add('select', 'add_activity_type_id', '', $activityLinks, FALSE, array('class' => 'crm-select2 crm-action-menu fa-calendar-check-o twenty')); if ($this->_hasAccessToAllCases) { $this->add('select', 'report_id', '', array('' => ts('Activity Audit')) + $reports, FALSE, array('class' => 'crm-select2 crm-action-menu fa-list-alt')); $this->add('select', 'timeline_id', '', array('' => ts('Add Timeline')) + $reports, FALSE, array('class' => 'crm-select2 crm-action-menu fa-list-ol')); } $this->addElement('submit', $this->getButtonName('next'), ' ', array('class' => 'hiddenElement')); if ($this->_mergeCases) { $allCases = CRM_Case_BAO_Case::getContactCases($this->_contactID); $otherCases = array(); foreach ($allCases as $caseId => $details) { //filter current and own cases. if ($caseId == $this->_caseID || !$this->_hasAccessToAllCases && !array_key_exists($caseId, $this->_userCases)) { continue; } $otherCases[$caseId] = 'Case ID: ' . $caseId . ' Type: ' . $details['case_type'] . ' Start: ' . $details['case_start_date']; } if (empty($otherCases)) { $this->_mergeCases = FALSE; $this->assign('mergeCases', $this->_mergeCases); } else { $this->add('select', 'merge_case_id', ts('Select Case for Merge'), array('' => ts('- select case -')) + $otherCases, FALSE, array('class' => 'crm-select2 huge')); $this->addElement('submit', $this->getButtonName('next', 'merge_case'), ts('Merge'), array('class' => 'hiddenElement')); } } //call activity form self::activityForm($this, $aTypes); //get case related relationships (Case Role) $caseRelationships = CRM_Case_BAO_Case::getCaseRoles($this->_contactID, $this->_caseID); //save special label because we unset it in the loop $managerLabel = empty($managerRoleId) ? '' : $caseRoles[$managerRoleId]; foreach ($caseRelationships as $key => &$value) { if (!empty($managerRoleId)) { if ($managerRoleId == $value['relation_type']) { $value['relation'] = $managerLabel; } } //calculate roles that don't have relationships if (!empty($caseRoles[$value['relation_type']])) { unset($caseRoles[$value['relation_type']]); } } $this->assign('caseRelationships', $caseRelationships); //also add client as role. CRM-4438 $caseRoles['client'] = CRM_Case_BAO_Case::getContactNames($this->_caseID); $this->assign('caseRoles', $caseRoles); // Retrieve ALL client relationships $relClient = CRM_Contact_BAO_Relationship::getRelationship($this->_contactID, CRM_Contact_BAO_Relationship::CURRENT, 0, 0, 0, NULL, NULL, FALSE); // Now build 'Other Relationships' array by removing relationships that are already listed under Case Roles // so they don't show up twice. $clientRelationships = array(); foreach ($relClient as $r) { if (!array_key_exists($r['id'], $caseRelationships)) { $clientRelationships[] = $r; } } $this->assign('clientRelationships', $clientRelationships); // Now global contact list that appears on all cases. $globalGroupInfo = array(); CRM_Case_BAO_Case::getGlobalContacts($globalGroupInfo); $this->assign('globalGroupInfo', $globalGroupInfo); // List relationship types for adding an arbitrary new role to the case $this->add('select', 'role_type', ts('Relationship Type'), array('' => ts('- select type -')) + $allowedRelationshipTypes, FALSE, array('class' => 'crm-select2 twenty', 'data-select-params' => '{"allowClear": false}')); $hookCaseSummary = CRM_Utils_Hook::caseSummary($this->_caseID); if (is_array($hookCaseSummary)) { $this->assign('hookCaseSummary', $hookCaseSummary); } CRM_Core_BAO_Tag::getTags('civicrm_case', $allTags, NULL, ' ', TRUE); if (!empty($allTags)) { $this->add('select', 'case_tag', ts('Tags'), $allTags, FALSE, array('id' => 'tags', 'multiple' => 'multiple', 'class' => 'crm-select2')); $tags = CRM_Core_BAO_EntityTag::getTag($this->_caseID, 'civicrm_case'); $this->setDefaults(array('case_tag' => $tags)); foreach ($tags as $tid) { if (isset($allTags[$tid])) { $tags[$tid] = $allTags[$tid]; } else { unset($tags[$tid]); } } $this->assign('tags', implode(', ', array_filter($tags))); $this->assign('showTags', TRUE); } else { $this->assign('showTags', FALSE); } // build tagset widget // see if we have any tagsets which can be assigned to cases $parentNames = CRM_Core_BAO_Tag::getTagSet('civicrm_case'); if ($parentNames) { $this->assign('showTagsets', TRUE); } else { $this->assign('showTagsets', FALSE); } CRM_Core_Form_Tag::buildQuickForm($this, $parentNames, 'civicrm_case', $this->_caseID, FALSE, TRUE); $this->addButtons(array(array('type' => 'cancel', 'name' => ts('Done'), 'spacing' => ' ', 'isDefault' => TRUE))); }
static function relationship(&$form) { $form->add('hidden', 'hidden_relationship', 1); $allRelationshipType = array(); $allRelationshipType = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE); $form->addElement('select', 'relation_type_id', ts('Relationship Type'), array('' => ts('- select -')) + $allRelationshipType); $form->addElement('text', 'relation_target_name', ts('Target Contact'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name')); $relStatusOption = array(ts('Active '), ts('Inactive '), ts('All')); $form->addRadio('relation_status', ts('Relationship Status'), $relStatusOption); $form->setDefaults(array('relation_status' => 0)); //add the target group if ($form->_group) { $form->add('select', 'relation_target_group', ts('Target Contact(s) in Group'), $form->_group, FALSE, array('id' => 'relation_target_group', 'multiple' => 'multiple', 'title' => ts('- select -'))); } // add all the custom searchable fields $relationship = array('Relationship'); $groupDetails = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, TRUE, $relationship); if ($groupDetails) { $form->assign('relationshipGroupTree', $groupDetails); foreach ($groupDetails as $group) { foreach ($group['fields'] as $field) { $fieldId = $field['id']; $elementName = 'custom_' . $fieldId; CRM_Core_BAO_CustomField::addQuickFormElement($form, $elementName, $fieldId, FALSE, FALSE, TRUE); } } } }
/** * The initializer code, called before processing. */ public function init() { $contactFields = CRM_Contact_BAO_Contact::importableFields($this->_contactType); // exclude the address options disabled in the Address Settings $fields = CRM_Core_BAO_Address::validateAddressOptions($contactFields); //CRM-5125 //supporting import for contact subtypes $csType = NULL; if (!empty($this->_contactSubType)) { //custom fields for sub type $subTypeFields = CRM_Core_BAO_CustomField::getFieldsForImport($this->_contactSubType); if (!empty($subTypeFields)) { foreach ($subTypeFields as $customSubTypeField => $details) { $fields[$customSubTypeField] = $details; } } } //Relationship importables $this->_relationships = $relations = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $this->_contactType, FALSE, 'label', TRUE, $this->_contactSubType); asort($relations); foreach ($relations as $key => $var) { list($type) = explode('_', $key); $relationshipType[$key]['title'] = $var; $relationshipType[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/'; $relationshipType[$key]['import'] = TRUE; $relationshipType[$key]['relationship_type_id'] = $type; $relationshipType[$key]['related'] = TRUE; } if (!empty($relationshipType)) { $fields = array_merge($fields, array('related' => array('title' => ts('- related contact info -'))), $relationshipType); } foreach ($fields as $name => $field) { $this->addField($name, $field['title'], CRM_Utils_Array::value('type', $field), CRM_Utils_Array::value('headerPattern', $field), CRM_Utils_Array::value('dataPattern', $field), CRM_Utils_Array::value('hasLocationType', $field)); } $this->_newContacts = array(); $this->setActiveFields($this->_mapperKeys); $this->setActiveFieldLocationTypes($this->_mapperLocType); $this->setActiveFieldPhoneTypes($this->_mapperPhoneType); $this->setActiveFieldWebsiteTypes($this->_mapperWebsiteType); //set active fields of IM provider of contact $this->setActiveFieldImProviders($this->_mapperImProvider); //related info $this->setActiveFieldRelated($this->_mapperRelated); $this->setActiveFieldRelatedContactType($this->_mapperRelatedContactType); $this->setActiveFieldRelatedContactDetails($this->_mapperRelatedContactDetails); $this->setActiveFieldRelatedContactLocType($this->_mapperRelatedContactLocType); $this->setActiveFieldRelatedContactPhoneType($this->_mapperRelatedContactPhoneType); $this->setActiveFieldRelatedContactWebsiteType($this->_mapperRelatedContactWebsiteType); //set active fields of IM provider of related contact $this->setActiveFieldRelatedContactImProvider($this->_mapperRelatedContactImProvider); $this->_phoneIndex = -1; $this->_emailIndex = -1; $this->_firstNameIndex = -1; $this->_lastNameIndex = -1; $this->_spouseFirstNameIndex = -1; $this->_spouseLastNameIndex = -1; $this->_householdNameIndex = -1; $this->_organizationNameIndex = -1; $this->_externalIdentifierIndex = -1; $index = 0; foreach ($this->_mapperKeys as $key) { if (substr($key, 0, 5) == 'email' && substr($key, 0, 14) != 'email_greeting') { $this->_emailIndex = $index; $this->_allEmails = array(); } if (substr($key, 0, 5) == 'phone') { $this->_phoneIndex = $index; } if ($key == 'first_name') { $this->_firstNameIndex = $index; } if ($key == 'last_name') { $this->_lastNameIndex = $index; } if ($key == 'spouse_first_name') { $this->_spouseFirstNameIndex = $index; } if ($key == 'spouse_last_name') { $this->_spouseLastNameIndex = $index; } if ($key == 'household_name') { $this->_householdNameIndex = $index; } if ($key == 'organization_name') { $this->_organizationNameIndex = $index; } if ($key == 'external_identifier') { $this->_externalIdentifierIndex = $index; $this->_allExternalIdentifiers = array(); } $index++; } $this->_updateWithId = FALSE; if (in_array('id', $this->_mapperKeys) || $this->_externalIdentifierIndex >= 0 && in_array($this->_onDuplicate, array(CRM_Import_Parser::DUPLICATE_UPDATE, CRM_Import_Parser::DUPLICATE_FILL))) { $this->_updateWithId = TRUE; } $this->_parseStreetAddress = CRM_Utils_Array::value('street_address_parsing', CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'address_options'), FALSE); }
/** * Build the form object. * * @return void */ public function buildQuickForm() { parent::buildQuickForm(); if ($this->_action & CRM_Core_Action::DELETE) { return; } $this->applyFilter('__ALL__', 'trim'); $this->add('text', 'name', ts('Name'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'name'), TRUE); $this->addRule('name', ts('A membership type with this name already exists. Please select another name.'), 'objectExists', array('CRM_Member_DAO_MembershipType', $this->_id)); $this->add('text', 'description', ts('Description'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'description')); $this->add('text', 'minimum_fee', ts('Minimum Fee'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'minimum_fee')); $this->addRule('minimum_fee', ts('Please enter a monetary value for the Minimum Fee.'), 'money'); $this->addSelect('duration_unit', array(), TRUE); //period type $this->addSelect('period_type', array(), TRUE); $this->add('text', 'duration_interval', ts('Duration Interval'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'duration_interval')); $props = array('api' => array('params' => array('contact_type' => 'Organization'))); $this->addEntityRef('member_of_contact_id', ts('Membership Organization'), $props, TRUE); //start day $this->add('date', 'fixed_period_start_day', ts('Fixed Period Start Day'), CRM_Core_SelectValues::date(NULL, 'M d'), FALSE); //Auto-renew Option $paymentProcessor = CRM_Core_PseudoConstant::paymentProcessor(FALSE, FALSE, 'is_recur = 1'); $isAuthorize = FALSE; $options = array(); if (is_array($paymentProcessor) && !empty($paymentProcessor)) { $isAuthorize = TRUE; $options = CRM_Core_SelectValues::memberAutoRenew(); } $this->addRadio('auto_renew', ts('Auto-renew Option'), $options); $this->assign('authorize', $isAuthorize); //rollover day $this->add('date', 'fixed_period_rollover_day', ts('Fixed Period Rollover Day'), CRM_Core_SelectValues::date(NULL, 'M d'), FALSE); $this->add('date', 'month_fixed_period_rollover_day', ts('Fixed Period Rollover Day'), CRM_Core_SelectValues::date(NULL, 'd'), FALSE); $this->add('select', 'financial_type_id', ts('Financial Type'), array('' => ts('- select -')) + CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes, $this->_action), TRUE, array('class' => 'crm-select2')); $relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE); if (is_array($relTypeInd)) { asort($relTypeInd); } $memberRel = $this->add('select', 'relationship_type_id', ts('Relationship Type'), $relTypeInd, FALSE, array('class' => 'crm-select2 huge', 'multiple' => 1)); $this->addSelect('visibility', array('placeholder' => NULL, 'option_url' => NULL)); $this->add('text', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'weight')); $this->add('checkbox', 'is_active', ts('Enabled?')); $membershipRecords = FALSE; if ($this->_action & CRM_Core_Action::UPDATE) { $membershipType = new CRM_Member_BAO_Membership(); $membershipType->membership_type_id = $this->_id; if ($membershipType->find(TRUE)) { $membershipRecords = TRUE; $memberRel->freeze(); } } $this->assign('membershipRecordsExists', $membershipRecords); $this->add('text', 'max_related', ts('Max related'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'max_related')); $this->addFormRule(array('CRM_Member_Form_MembershipType', 'formRule')); $this->assign('membershipTypeId', $this->_id); }
/** * @param $form */ public static function relationship(&$form) { $form->add('hidden', 'hidden_relationship', 1); $allRelationshipType = array(); $allRelationshipType = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE); $form->add('select', 'relation_type_id', ts('Relationship Type'), array('' => ts('- select -')) + $allRelationshipType, FALSE, array('class' => 'crm-select2')); $form->addElement('text', 'relation_target_name', ts('Target Contact'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Contact', 'sort_name')); // relation status $relStatusOption = array(ts('Active'), ts('Inactive'), ts('All')); $form->addRadio('relation_status', ts('Relationship Status'), $relStatusOption); $form->setDefaults(array('relation_status' => 0)); // relation permission $relPermissionOption = array(ts('Any'), ts('Yes'), ts('No')); $form->addRadio('relation_permission', ts('Permissioned Relationship?'), $relPermissionOption); $form->setDefaults(array('relation_permission' => 0)); //add the target group if ($form->_group) { $form->add('select', 'relation_target_group', ts('Target Contact(s) in Group'), $form->_group, FALSE, array('id' => 'relation_target_group', 'multiple' => 'multiple', 'class' => 'crm-select2')); } CRM_Core_Form_Date::buildDateRange($form, 'relation_start_date', 1, '_low', '_high', ts('From:'), FALSE, FALSE); CRM_Core_Form_Date::buildDateRange($form, 'relation_end_date', 1, '_low', '_high', ts('From:'), FALSE, FALSE); // Add reltionship dates CRM_Core_Form_Date::buildDateRange($form, 'relation_date', 1, '_low', '_high', ts('From:'), FALSE, FALSE); // add all the custom searchable fields $relationship = array('Relationship'); $groupDetails = CRM_Core_BAO_CustomGroup::getGroupDetail(NULL, TRUE, $relationship); if ($groupDetails) { $form->assign('relationshipGroupTree', $groupDetails); foreach ($groupDetails as $group) { foreach ($group['fields'] as $field) { $fieldId = $field['id']; $elementName = 'custom_' . $fieldId; CRM_Core_BAO_CustomField::addQuickFormElement($form, $elementName, $fieldId, FALSE, FALSE, TRUE); } } } }
/** * Function to build the form * * @return None * @access public */ public function buildQuickForm() { if ($this->_cdType) { return CRM_Custom_Form_CustomData::buildQuickForm($this); } $relTypeID = explode('_', $this->_rtypeId, 3); if ($this->_action & CRM_Core_Action::DELETE) { $this->addButtons(array(array('type' => 'next', 'name' => ts('Delete'), 'isDefault' => true), array('type' => 'cancel', 'name' => ts('Cancel')))); return; } $callAjax = $this->get('callAjax'); $searchRows = null; if (!$callAjax) { $searchRows = $this->get('searchRows'); } else { $this->addElement('hidden', 'store_contacts', '', array('id' => 'store_contacts')); $sourceUrl = 'snippet=4&relType=' . $this->get('relType'); $sourceUrl .= '&relContact=' . $this->get('relContact'); $sourceUrl .= '&cid=' . $this->_contactId; $this->assign('searchCount', true); // To handle employee of and employer of if (!empty($this->_relationshipTypeId) && !empty($this->_rtype)) { $sourceUrl .= '&typeName=' . $this->_allRelationshipNames[$this->_relationshipTypeId]["name_{$this->_rtype}"]; } $this->assign('sourceUrl', CRM_Utils_System::url('civicrm/ajax/relationshipcontacts', $sourceUrl, false, null, false)); } $this->assign('callAjax', $callAjax); $this->_callAjax = $callAjax; $this->addElement('select', 'relationship_type_id', ts('Relationship Type'), array('' => ts('- select -')) + CRM_Contact_BAO_Relationship::getContactRelationshipType($this->_contactId, $this->_rtype, $this->_relationshipId, null, false, 'label')); // add a ajax facility for searching contacts $dataUrl = CRM_Utils_System::url("civicrm/ajax/search", "reset=1", true, null, false); $this->assign('dataUrl', $dataUrl); $this->add('text', 'rel_contact', ts('Find Target Contact')); $this->add('hidden', "rel_contact_id"); $this->addDate('start_date', ts('Start Date'), false, array('formatType' => 'searchDate')); $this->addDate('end_date', ts('End Date'), false, array('formatType' => 'searchDate')); $this->addElement('advcheckbox', 'is_active', ts('Enabled?'), null, 'setChecked()'); $this->addElement('checkbox', 'is_permission_a_b', ts('Permission for contact a to view and update information for contact b'), null); $this->addElement('checkbox', 'is_permission_b_a', ts('permission for contact b to view and update information for contact a'), null); $this->add('text', 'description', ts('Description'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Relationship', 'description')); CRM_Contact_Form_Edit_Notes::buildQuickForm($this); $searchCount = $this->get('searchCount'); $duplicateRelationship = $this->get('duplicateRelationship'); $searchDone = $this->get('searchDone'); $isEmployeeOf = $isEmployerOf = false; if (!empty($this->_relationshipTypeId) && !empty($this->_rtype)) { if ($this->_allRelationshipNames[$this->_relationshipTypeId]["name_{$this->_rtype}"] == 'Employee of') { $isEmployeeOf = true; } else { if ($this->_allRelationshipNames[$this->_relationshipTypeId]["name_{$this->_rtype}"] == 'Employer of') { $isEmployerOf = true; } } } $employers = $checkBoxes = $employees = array(); if ($searchRows) { foreach ($searchRows as $id => $row) { $checkBoxes[$id] = $this->createElement('checkbox', $id, null, ''); if ($isEmployeeOf) { $employers[$id] = $this->createElement('radio', null, $id, null, $id); } else { if ($isEmployerOf) { $employees[$id] = $this->createElement('checkbox', $id, null, ''); } } } $this->addGroup($checkBoxes, 'contact_check'); $this->assign('searchRows', $searchRows); } if ($isEmployeeOf) { $this->assign('isEmployeeOf', $isEmployeeOf); if (!$callAjax) { $this->addGroup($employers, 'employee_of'); } } else { if ($isEmployerOf) { $this->assign('isEmployerOf', $isEmployerOf); if (!$callAjax) { $this->addGroup($employees, 'employer_of'); } } } if ($callAjax && ($isEmployeeOf || $isEmployerOf)) { $this->addElement('hidden', 'store_employers', '', array('id' => 'store_employers')); } if ($this->_action & CRM_Core_Action::UPDATE) { $this->addElement('checkbox', 'is_current_employer'); } $this->assign('duplicateRelationship', $duplicateRelationship); $this->assign('searchCount', $searchCount); $this->assign('searchDone', $searchDone); if ($this->get('contact_type')) { require_once 'CRM/Contact/BAO/ContactType.php'; $typeLabel = CRM_Contact_BAO_ContactType::getLabel($this->get('contact_type')); $this->assign('contact_type', $this->get('contact_type')); $this->assign('contact_type_display', $typeLabel); } if ($searchDone) { $searchBtn = ts('Search Again'); } else { $searchBtn = ts('Search'); } $this->addElement('submit', $this->getButtonName('refresh'), $searchBtn, array('class' => 'form-submit', 'id' => 'search-button')); $this->addElement('submit', $this->getButtonName('refresh', 'save'), 'Quick Save', array('class' => 'form-submit', 'id' => 'quick-save')); $this->addElement('submit', $this->getButtonName('cancel'), ts('Cancel'), array('class' => 'form-submit')); $this->addElement('submit', $this->getButtonName('refresh', 'savedetails'), 'Save Relationship', array('class' => 'form-submit hiddenElement', 'id' => 'details-save')); $this->addElement('checkbox', 'add_current_employer', ts('Current Employer'), null); $this->addElement('checkbox', 'add_current_employee', ts('Current Employee'), null); //need to assign custom data type and subtype to the template $this->assign('customDataType', 'Relationship'); $this->assign('customDataSubType', $this->_relationshipTypeId); $this->assign('entityID', $this->_relationshipId); // make this form an upload since we dont know if the custom data injected dynamically // is of type file etc $uploadNames = $this->get( // 'uploadNames' ); $buttonParams = array('type' => 'upload', 'name' => ts('Save Relationship'), 'isDefault' => true); if ($callAjax) { $buttonParams['js'] = array('onclick' => ' submitAjaxData();'); } $this->addButtons(array($buttonParams, array('type' => 'cancel', 'name' => ts('Cancel')))); }
/** * Build the mapping form. * * @param CRM_Core_Form $form * @param string $mappingType * (Export/Import/Search Builder). * @param int $mappingId * @param int $columnNo * @param int $blockCount * (no of blocks shown). * @param NULL $exportMode * * @return void */ public static function buildMappingForm(&$form, $mappingType = 'Export', $mappingId = NULL, $columnNo, $blockCount = 3, $exportMode = NULL) { if ($mappingType == 'Export') { $name = "Map"; $columnCount = array('1' => $columnNo); } elseif ($mappingType == 'Search Builder') { $name = "Builder"; $columnCount = $columnNo; } //get the saved mapping details if ($mappingType == 'Export') { $form->applyFilter('saveMappingName', 'trim'); //to save the current mappings if (!isset($mappingId)) { $saveDetailsName = ts('Save this field mapping'); $form->add('text', 'saveMappingName', ts('Name')); $form->add('text', 'saveMappingDesc', ts('Description')); } else { $form->assign('loadedMapping', $mappingId); $params = array('id' => $mappingId); $temp = array(); $mappingDetails = CRM_Core_BAO_Mapping::retrieve($params, $temp); $form->assign('savedName', $mappingDetails->name); $form->add('hidden', 'mappingId', $mappingId); $form->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL); $saveDetailsName = ts('Save as a new field mapping'); $form->add('text', 'saveMappingName', ts('Name')); $form->add('text', 'saveMappingDesc', ts('Description')); } $form->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, array('onclick' => "showSaveDetails(this)")); $form->addFormRule(array('CRM_Export_Form_Map', 'formRule'), $form->get('mappingTypeId')); } elseif ($mappingType == 'Search Builder') { $form->addElement('submit', 'addBlock', ts('Also include contacts where'), array('class' => 'submit-link')); } $defaults = array(); $hasLocationTypes = array(); $hasRelationTypes = array(); $fields = array(); if ($mappingType == 'Export') { $required = TRUE; } elseif ($mappingType == 'Search Builder') { $required = FALSE; } $contactType = array('Individual', 'Household', 'Organization'); foreach ($contactType as $value) { $contactFields = CRM_Contact_BAO_Contact::exportableFields($value, FALSE, $required); $contactFields = array_merge($contactFields, CRM_Contact_BAO_Query_Hook::singleton()->getFields()); // exclude the address options disabled in the Address Settings $fields[$value] = CRM_Core_BAO_Address::validateAddressOptions($contactFields); ksort($fields[$value]); if ($mappingType == 'Export') { $relationships = array(); $relationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $value); asort($relationshipTypes); foreach ($relationshipTypes as $key => $var) { list($type) = explode('_', $key); $relationships[$key]['title'] = $var; $relationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/'; $relationships[$key]['export'] = TRUE; $relationships[$key]['relationship_type_id'] = $type; $relationships[$key]['related'] = TRUE; $relationships[$key]['hasRelationType'] = 1; } if (!empty($relationships)) { $fields[$value] = array_merge($fields[$value], array('related' => array('title' => ts('- related contact info -'))), $relationships); } } } //get the current employer for mapping. if ($required) { $fields['Individual']['current_employer']['title'] = ts('Current Employer'); } // add component fields $compArray = array(); //we need to unset groups, tags, notes for component export if ($exportMode != CRM_Export_Form_Select::CONTACT_EXPORT) { foreach (array('groups', 'tags', 'notes') as $value) { unset($fields['Individual'][$value]); unset($fields['Household'][$value]); unset($fields['Organization'][$value]); } } if ($mappingType == 'Search Builder') { //build the common contact fields array. $fields['Contact'] = array(); foreach ($fields['Individual'] as $key => $value) { if (!empty($fields['Household'][$key]) && !empty($fields['Organization'][$key])) { $fields['Contact'][$key] = $value; unset($fields['Organization'][$key], $fields['Household'][$key], $fields['Individual'][$key]); } } if (array_key_exists('note', $fields['Contact'])) { $noteTitle = $fields['Contact']['note']['title']; $fields['Contact']['note']['title'] = $noteTitle . ': ' . ts('Body and Subject'); $fields['Contact']['note_body'] = array('title' => $noteTitle . ': ' . ts('Body Only'), 'name' => 'note_body'); $fields['Contact']['note_subject'] = array('title' => $noteTitle . ': ' . ts('Subject Only'), 'name' => 'note_subject'); } } if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT) { if (CRM_Core_Permission::access('CiviContribute')) { $fields['Contribution'] = CRM_Contribute_BAO_Contribution::exportableFields(); foreach (array('contribution_contact_id', 'contribution_soft_credit_name', 'contribution_soft_credit_amount', 'contribution_soft_credit_type', 'contribution_soft_credit_contribution_id') as $element) { unset($fields['Contribution'][$element]); } $compArray['Contribution'] = ts('Contribution'); } } if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::EVENT_EXPORT) { if (CRM_Core_Permission::access('CiviEvent')) { $fields['Participant'] = CRM_Event_BAO_Participant::exportableFields(); //get the component payment fields if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) { $componentPaymentFields = array(); foreach (CRM_Export_BAO_Export::componentPaymentFields() as $payField => $payTitle) { $componentPaymentFields[$payField] = array('title' => $payTitle); } $fields['Participant'] = array_merge($fields['Participant'], $componentPaymentFields); } $compArray['Participant'] = ts('Participant'); } } if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) { if (CRM_Core_Permission::access('CiviMember')) { $fields['Membership'] = CRM_Member_BAO_Membership::getMembershipFields($exportMode); unset($fields['Membership']['membership_contact_id']); $compArray['Membership'] = ts('Membership'); } } if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) { if (CRM_Core_Permission::access('CiviPledge')) { $fields['Pledge'] = CRM_Pledge_BAO_Pledge::exportableFields(); unset($fields['Pledge']['pledge_contact_id']); $compArray['Pledge'] = ts('Pledge'); } } if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::CASE_EXPORT) { if (CRM_Core_Permission::access('CiviCase')) { $fields['Case'] = CRM_Case_BAO_Case::exportableFields(); $compArray['Case'] = ts('Case'); $fields['Activity'] = CRM_Activity_BAO_Activity::exportableFields('Case'); $compArray['Activity'] = ts('Case Activity'); unset($fields['Case']['case_contact_id']); } } if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::GRANT_EXPORT) { if (CRM_Core_Permission::access('CiviGrant')) { $fields['Grant'] = CRM_Grant_BAO_Grant::exportableFields(); unset($fields['Grant']['grant_contact_id']); if ($mappingType == 'Search Builder') { unset($fields['Grant']['grant_type_id']); } $compArray['Grant'] = ts('Grant'); } } if ($mappingType == 'Search Builder' || $exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) { $fields['Activity'] = CRM_Activity_BAO_Activity::exportableFields('Activity'); $compArray['Activity'] = ts('Activity'); } //Contact Sub Type For export $contactSubTypes = array(); $subTypes = CRM_Contact_BAO_ContactType::subTypeInfo(); foreach ($subTypes as $subType => $val) { //adding subtype specific relationships CRM-5256 $csRelationships = array(); if ($mappingType == 'Export') { $subTypeRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $val['parent'], FALSE, 'label', TRUE, $subType); foreach ($subTypeRelationshipTypes as $key => $var) { if (!array_key_exists($key, $fields[$val['parent']])) { list($type) = explode('_', $key); $csRelationships[$key]['title'] = $var; $csRelationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/'; $csRelationships[$key]['export'] = TRUE; $csRelationships[$key]['relationship_type_id'] = $type; $csRelationships[$key]['related'] = TRUE; $csRelationships[$key]['hasRelationType'] = 1; } } } $fields[$subType] = $fields[$val['parent']] + $csRelationships; //custom fields for sub type $subTypeFields = CRM_Core_BAO_CustomField::getFieldsForImport($subType); $fields[$subType] += $subTypeFields; if (!empty($subTypeFields) || !empty($csRelationships)) { $contactSubTypes[$subType] = $val['label']; } } unset($subTypes); foreach ($fields as $key => $value) { foreach ($value as $key1 => $value1) { //CRM-2676, replacing the conflict for same custom field name from different custom group. $customGroupName = self::getCustomGroupName($key1); if ($customGroupName) { $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $customGroupName . ': ' . $value1['title']; } else { $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $value1['title']; } if (isset($value1['hasLocationType'])) { $hasLocationTypes[$key][$key1] = $value1['hasLocationType']; } if (isset($value1['hasRelationType'])) { $hasRelationTypes[$key][$key1] = $value1['hasRelationType']; unset($relatedMapperFields[$key][$key1]); } } if (array_key_exists('related', $relatedMapperFields[$key])) { unset($relatedMapperFields[$key]['related']); } } $mapperKeys = array_keys($mapperFields); $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); $defaultLocationType = CRM_Core_BAO_LocationType::getDefault(); // FIXME: dirty hack to make the default option show up first. This // avoids a mozilla browser bug with defaults on dynamically constructed // selector widgets. if ($defaultLocationType) { $defaultLocation = $locationTypes[$defaultLocationType->id]; unset($locationTypes[$defaultLocationType->id]); $locationTypes = array($defaultLocationType->id => $defaultLocation) + $locationTypes; } $locationTypes = array(' ' => ts('Primary')) + $locationTypes; // since we need a hierarchical list to display contact types & subtypes, // this is what we going to display in first selector $contactTypes = CRM_Contact_BAO_ContactType::getSelectElements(FALSE, FALSE); if ($mappingType == 'Search Builder') { $contactTypes = array('Contact' => ts('Contacts')) + $contactTypes; } $sel1 = array('' => ts('- select record type -')) + $contactTypes + $compArray; foreach ($sel1 as $key => $sel) { if ($key) { // sort everything BUT the contactType which is sorted seperately by // an initial commit of CRM-13278 (check ksort above) if (!in_array($key, $contactType)) { asort($mapperFields[$key]); } $sel2[$key] = array('' => ts('- select field -')) + $mapperFields[$key]; } } $sel3[''] = NULL; $sel5[''] = NULL; $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'); $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'); asort($phoneTypes); foreach ($sel1 as $k => $sel) { if ($k) { foreach ($locationTypes as $key => $value) { if (trim($key) != '') { $sel4[$k]['phone'][$key] =& $phoneTypes; $sel4[$k]['im'][$key] =& $imProviders; } } } } foreach ($sel1 as $k => $sel) { if ($k) { foreach ($mapperFields[$k] as $key => $value) { if (isset($hasLocationTypes[$k][$key])) { $sel3[$k][$key] = $locationTypes; } else { $sel3[$key] = NULL; } } } } // Array for core fields and relationship custom data $relationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE); if ($mappingType == 'Export') { foreach ($sel1 as $k => $sel) { if ($k) { foreach ($mapperFields[$k] as $field => $dontCare) { if (isset($hasRelationTypes[$k][$field])) { list($id, $first, $second) = explode('_', $field); // FIX ME: For now let's not expose custom data related to relationship $relationshipCustomFields = array(); //$relationshipCustomFields = self::getRelationTypeCustomGroupData( $id ); //asort($relationshipCustomFields); $relationshipType = new CRM_Contact_BAO_RelationshipType(); $relationshipType->id = $id; if ($relationshipType->find(TRUE)) { $direction = "contact_sub_type_{$second}"; if (isset($relationshipType->{$direction})) { $relatedFields = array_merge((array) $relatedMapperFields[$relationshipType->{$direction}], (array) $relationshipCustomFields); } else { $target_type = 'contact_type_' . $second; $relatedFields = array_merge((array) $relatedMapperFields[$relationshipType->{$target_type}], (array) $relationshipCustomFields); } } $relationshipType->free(); asort($relatedFields); $sel5[$k][$field] = $relatedFields; } } } } //Location Type for relationship fields foreach ($sel5 as $k => $v) { if ($v) { foreach ($v as $rel => $fields) { foreach ($fields as $field => $fieldLabel) { if (isset($hasLocationTypes[$k][$field])) { $sel6[$k][$rel][$field] = $locationTypes; } } } } } //PhoneTypes for relationship fields $sel7[''] = NULL; foreach ($sel6 as $k => $rel) { if ($k) { foreach ($rel as $phonekey => $phonevalue) { foreach ($locationTypes as $locType => $loc) { if (trim($locType) != '') { $sel7[$k][$phonekey]['phone'][$locType] =& $phoneTypes; $sel7[$k][$phonekey]['im'][$locType] =& $imProviders; } } } } } } //special fields that have location, hack for primary location $specialFields = 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'); if (isset($mappingId)) { $colCnt = 0; list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingImProvider, $mappingRelation, $mappingOperator, $mappingValue) = CRM_Core_BAO_Mapping::getMappingFields($mappingId); $blkCnt = count($mappingName); if ($blkCnt >= $blockCount) { $blockCount = $blkCnt + 1; } for ($x = 1; $x < $blockCount; $x++) { if (isset($mappingName[$x])) { $colCnt = count($mappingName[$x]); if ($colCnt >= $columnCount[$x]) { $columnCount[$x] = $colCnt; } } } } $form->_blockCount = $blockCount; $form->_columnCount = $columnCount; $form->set('blockCount', $form->_blockCount); $form->set('columnCount', $form->_columnCount); $defaults = $noneArray = $nullArray = array(); //used to warn for mismatch column count or mismatch mapping $warning = 0; for ($x = 1; $x < $blockCount; $x++) { for ($i = 0; $i < $columnCount[$x]; $i++) { $sel =& $form->addElement('hierselect', "mapper[{$x}][{$i}]", ts('Mapper for Field %1', array(1 => $i)), NULL); $jsSet = FALSE; if (isset($mappingId)) { $locationId = isset($mappingLocation[$x][$i]) ? $mappingLocation[$x][$i] : 0; if (isset($mappingName[$x][$i])) { if (is_array($mapperFields[$mappingContactType[$x][$i]])) { if (isset($mappingRelation[$x][$i])) { $contactDetails = strtolower(str_replace(" ", "_", $mappingName[$x][$i])); $relLocationId = isset($mappingLocation[$x][$i]) ? $mappingLocation[$x][$i] : 0; if (!$relLocationId && in_array($mappingName[$x][$i], $specialFields)) { $relLocationId = " "; } $relPhoneType = isset($mappingPhoneType[$x][$i]) ? $mappingPhoneType[$x][$i] : NULL; $defaults["mapper[{$x}][{$i}]"] = array($mappingContactType[$x][$i], $mappingRelation[$x][$i], $locationId, $phoneType, $mappingName[$x][$i], $relLocationId, $relPhoneType); if (!$locationId) { $noneArray[] = array($x, $i, 2); } if (!$phoneType && !$imProvider) { $noneArray[] = array($x, $i, 3); } if (!$mappingName[$x][$i]) { $noneArray[] = array($x, $i, 4); } if (!$relLocationId) { $noneArray[] = array($x, $i, 5); } if (!$relPhoneType) { $noneArray[] = array($x, $i, 6); } $noneArray[] = array($x, $i, 2); } else { $phoneType = isset($mappingPhoneType[$x][$i]) ? $mappingPhoneType[$x][$i] : NULL; $imProvider = isset($mappingImProvider[$x][$i]) ? $mappingImProvider[$x][$i] : NULL; if (!$locationId && in_array($mappingName[$x][$i], $specialFields)) { $locationId = " "; } $defaults["mapper[{$x}][{$i}]"] = array($mappingContactType[$x][$i], $mappingName[$x][$i], $locationId, $phoneType); if (!$mappingName[$x][$i]) { $noneArray[] = array($x, $i, 1); } if (!$locationId) { $noneArray[] = array($x, $i, 2); } if (!$phoneType && !$imProvider) { $noneArray[] = array($x, $i, 3); } $noneArray[] = array($x, $i, 4); $noneArray[] = array($x, $i, 5); $noneArray[] = array($x, $i, 6); } $jsSet = TRUE; if (CRM_Utils_Array::value($i, CRM_Utils_Array::value($x, $mappingOperator))) { $defaults["operator[{$x}][{$i}]"] = CRM_Utils_Array::value($i, $mappingOperator[$x]); } if (CRM_Utils_Array::value($i, CRM_Utils_Array::value($x, $mappingValue))) { $defaults["value[{$x}][{$i}]"] = CRM_Utils_Array::value($i, $mappingValue[$x]); } } } } //Fix for Search Builder if ($mappingType == 'Export') { $j = 7; } else { $j = 4; } $formValues = $form->exportValues(); if (!$jsSet) { if (empty($formValues)) { // Incremented length for third select box(relationship type) for ($k = 1; $k < $j; $k++) { $noneArray[] = array($x, $i, $k); } } else { if (!empty($formValues['mapper'][$x])) { foreach ($formValues['mapper'][$x] as $value) { for ($k = 1; $k < $j; $k++) { if (!isset($formValues['mapper'][$x][$i][$k]) || !$formValues['mapper'][$x][$i][$k]) { $noneArray[] = array($x, $i, $k); } else { $nullArray[] = array($x, $i, $k); } } } } else { for ($k = 1; $k < $j; $k++) { $noneArray[] = array($x, $i, $k); } } } } //Fix for Search Builder if ($mappingType == 'Export') { if (!isset($mappingId) || $i >= count(reset($mappingName))) { if (isset($formValues['mapper']) && isset($formValues['mapper'][$x][$i][1]) && array_key_exists($formValues['mapper'][$x][$i][1], $relationshipTypes)) { $sel->setOptions(array($sel1, $sel2, $sel5, $sel6, $sel7, $sel3, $sel4)); } else { $sel->setOptions(array($sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7)); } } else { $sel->setOptions(array($sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7)); } } else { $sel->setOptions(array($sel1, $sel2, $sel3, $sel4)); } if ($mappingType == 'Search Builder') { //CRM -2292, restricted array set $operatorArray = array('' => ts('-operator-')) + CRM_Core_SelectValues::getSearchBuilderOperators(); $form->add('select', "operator[{$x}][{$i}]", '', $operatorArray); $form->add('text', "value[{$x}][{$i}]", ''); } } //end of columnCnt for if ($mappingType == 'Search Builder') { $title = ts('Another search field'); } else { $title = ts('Select more fields'); } $form->addElement('submit', "addMore[{$x}]", $title, array('class' => 'submit-link')); } //end of block for $js = "<script type='text/javascript'>\n"; $formName = "document.{$name}"; if (!empty($nullArray)) { $js .= "var nullArray = ["; $elements = array(); $seen = array(); foreach ($nullArray as $element) { $key = "{$element[0]}, {$element[1]}, {$element[2]}"; if (!isset($seen[$key])) { $elements[] = "[{$key}]"; $seen[$key] = 1; } } $js .= implode(', ', $elements); $js .= "]"; $js .= "\n for (var i=0;i<nullArray.length;i++) {\n if ( {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'] ) {\n {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'].style.display = '';\n }\n }\n"; } if (!empty($noneArray)) { $js .= "var noneArray = ["; $elements = array(); $seen = array(); foreach ($noneArray as $element) { $key = "{$element[0]}, {$element[1]}, {$element[2]}"; if (!isset($seen[$key])) { $elements[] = "[{$key}]"; $seen[$key] = 1; } } $js .= implode(', ', $elements); $js .= "]"; $js .= "\n for (var i=0;i<noneArray.length;i++) {\n if ( {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'] ) {\n {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'].style.display = 'none';\n }\n }\n"; } $js .= "</script>\n"; $form->assign('initHideBoxes', $js); $form->assign('columnCount', $columnCount); $form->assign('blockCount', $blockCount); $form->setDefaults($defaults); $form->setDefaultAction('refresh'); }
/** * Build the form object. */ public function buildQuickForm() { //to save the current mappings if (!$this->get('savedMapping')) { $saveDetailsName = ts('Save this field mapping'); $this->applyFilter('saveMappingName', 'trim'); $this->add('text', 'saveMappingName', ts('Name')); $this->add('text', 'saveMappingDesc', ts('Description')); } else { $savedMapping = $this->get('savedMapping'); list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingImProvider, $mappingRelation, $mappingOperator, $mappingValue, $mappingWebsiteType) = CRM_Core_BAO_Mapping::getMappingFields($savedMapping); //get loaded Mapping Fields $mappingName = CRM_Utils_Array::value(1, $mappingName); $mappingContactType = CRM_Utils_Array::value(1, $mappingContactType); $mappingLocation = CRM_Utils_Array::value(1, $mappingLocation); $mappingPhoneType = CRM_Utils_Array::value(1, $mappingPhoneType); $mappingImProvider = CRM_Utils_Array::value(1, $mappingImProvider); $mappingRelation = CRM_Utils_Array::value(1, $mappingRelation); $mappingWebsiteType = CRM_Utils_Array::value(1, $mappingWebsiteType); $this->assign('loadedMapping', $savedMapping); $this->set('loadedMapping', $savedMapping); $params = array('id' => $savedMapping); $temp = array(); $mappingDetails = CRM_Core_BAO_Mapping::retrieve($params, $temp); $this->assign('savedName', $mappingDetails->name); $this->add('hidden', 'mappingId', $savedMapping); $this->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL); $saveDetailsName = ts('Save as a new field mapping'); $this->add('text', 'saveMappingName', ts('Name')); $this->add('text', 'saveMappingDesc', ts('Description')); } $this->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, array('onclick' => "showSaveDetails(this)")); $this->addFormRule(array('CRM_Contact_Import_Form_MapField', 'formRule')); //-------- end of saved mapping stuff --------- $defaults = array(); $mapperKeys = array_keys($this->_mapperFields); $hasColumnNames = !empty($this->_columnNames); $columnPatterns = $this->get('columnPatterns'); $dataPatterns = $this->get('dataPatterns'); $hasLocationTypes = $this->get('fieldTypes'); $this->_location_types = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'); $defaultLocationType = CRM_Core_BAO_LocationType::getDefault(); // Pass default location to js if ($defaultLocationType) { $this->assign('defaultLocationType', $defaultLocationType->id); $this->assign('defaultLocationTypeLabel', $this->_location_types[$defaultLocationType->id]); } /* Initialize all field usages to false */ foreach ($mapperKeys as $key) { $this->_fieldUsed[$key] = FALSE; } $sel1 = $this->_mapperFields; $sel2[''] = NULL; $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'); $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'); $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id'); foreach ($this->_location_types as $key => $value) { $sel3['phone'][$key] =& $phoneTypes; //build array for IM service provider type for contact $sel3['im'][$key] =& $imProviders; } $sel4 = NULL; // store and cache all relationship types $contactRelation = new CRM_Contact_DAO_RelationshipType(); $contactRelation->find(); while ($contactRelation->fetch()) { $contactRelationCache[$contactRelation->id] = array(); $contactRelationCache[$contactRelation->id]['contact_type_a'] = $contactRelation->contact_type_a; $contactRelationCache[$contactRelation->id]['contact_sub_type_a'] = $contactRelation->contact_sub_type_a; $contactRelationCache[$contactRelation->id]['contact_type_b'] = $contactRelation->contact_type_b; $contactRelationCache[$contactRelation->id]['contact_sub_type_b'] = $contactRelation->contact_sub_type_b; } $highlightedFields = $highlightedRelFields = array(); $highlightedFields['email'] = 'All'; $highlightedFields['external_identifier'] = 'All'; $highlightedFields['first_name'] = 'Individual'; $highlightedFields['last_name'] = 'Individual'; $highlightedFields['household_name'] = 'Household'; $highlightedFields['organization_name'] = 'Organization'; foreach ($mapperKeys as $key) { // check if there is a _a_b or _b_a in the key if (strpos($key, '_a_b') || strpos($key, '_b_a')) { list($id, $first, $second) = explode('_', $key); } else { $id = $first = $second = NULL; } if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') { $cType = $contactRelationCache[$id]["contact_type_{$second}"]; //CRM-5125 for contact subtype specific relationshiptypes $cSubType = NULL; if (!empty($contactRelationCache[$id]["contact_sub_type_{$second}"])) { $cSubType = $contactRelationCache[$id]["contact_sub_type_{$second}"]; } if (!$cType) { $cType = 'All'; } $relatedFields = array(); $relatedFields = CRM_Contact_BAO_Contact::importableFields($cType); unset($relatedFields['']); $values = array(); foreach ($relatedFields as $name => $field) { $values[$name] = $field['title']; if (isset($hasLocationTypes[$name])) { $sel3[$key][$name] = $this->_location_types; } elseif ($name == 'url') { $sel3[$key][$name] = $websiteTypes; } else { $sel3[$name] = NULL; } } //fix to append custom group name to field name, CRM-2676 if (empty($this->_formattedFieldNames[$cType]) || $cType == $this->_contactType) { $this->_formattedFieldNames[$cType] = $this->formatCustomFieldName($values); } $this->_formattedFieldNames[$cType] = array_merge($values, $this->_formattedFieldNames[$cType]); //Modified the Relationship fields if the fields are //present in dedupe rule if ($this->_onDuplicate != CRM_Import_Parser::DUPLICATE_NOCHECK && !empty($this->_dedupeFields[$cType]) && is_array($this->_dedupeFields[$cType])) { static $cTypeArray = array(); if ($cType != $this->_contactType && !in_array($cType, $cTypeArray)) { foreach ($this->_dedupeFields[$cType] as $val) { if ($valTitle = CRM_Utils_Array::value($val, $this->_formattedFieldNames[$cType])) { $this->_formattedFieldNames[$cType][$val] = $valTitle . ' (match to contact)'; } } $cTypeArray[] = $cType; } } foreach ($highlightedFields as $k => $v) { if ($v == $cType || $v == 'All') { $highlightedRelFields[$key][] = $k; } } $this->assign('highlightedRelFields', $highlightedRelFields); $sel2[$key] = $this->_formattedFieldNames[$cType]; if (!empty($cSubType)) { //custom fields for sub type $subTypeFields = CRM_Core_BAO_CustomField::getFieldsForImport($cSubType); if (!empty($subTypeFields)) { $subType = NULL; foreach ($subTypeFields as $customSubTypeField => $details) { $subType[$customSubTypeField] = $details['title']; $sel2[$key] = array_merge($sel2[$key], $this->formatCustomFieldName($subType)); } } } foreach ($this->_location_types as $k => $value) { $sel4[$key]['phone'][$k] =& $phoneTypes; //build array of IM service provider for related contact $sel4[$key]['im'][$k] =& $imProviders; } } else { $options = NULL; if (!empty($hasLocationTypes[$key])) { $options = $this->_location_types; } elseif ($key == 'url') { $options = $websiteTypes; } $sel2[$key] = $options; } } $js = "<script type='text/javascript'>\n"; $formName = 'document.forms.' . $this->_name; //used to warn for mismatch column count or mismatch mapping $warning = 0; for ($i = 0; $i < $this->_columnCount; $i++) { $sel =& $this->addElement('hierselect', "mapper[{$i}]", ts('Mapper for Field %1', array(1 => $i)), NULL); $jsSet = FALSE; if ($this->get('savedMapping')) { if (isset($mappingName[$i])) { if ($mappingName[$i] != ts('- do not import -')) { if (isset($mappingRelation[$i])) { // relationship mapping switch ($this->get('contactType')) { case CRM_Import_Parser::CONTACT_INDIVIDUAL: $contactType = 'Individual'; break; case CRM_Import_Parser::CONTACT_HOUSEHOLD: $contactType = 'Household'; break; case CRM_Import_Parser::CONTACT_ORGANIZATION: $contactType = 'Organization'; } //CRM-5125 $contactSubType = NULL; if ($this->get('contactSubType')) { $contactSubType = $this->get('contactSubType'); } $relations = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $contactType, FALSE, 'label', TRUE, $contactSubType); foreach ($relations as $key => $var) { if ($key == $mappingRelation[$i]) { $relation = $key; break; } } $contactDetails = strtolower(str_replace(" ", "_", $mappingName[$i])); $websiteTypeId = isset($mappingWebsiteType[$i]) ? $mappingWebsiteType[$i] : NULL; $locationId = isset($mappingLocation[$i]) ? $mappingLocation[$i] : 0; $phoneType = isset($mappingPhoneType[$i]) ? $mappingPhoneType[$i] : NULL; //get provider id from saved mappings $imProvider = isset($mappingImProvider[$i]) ? $mappingImProvider[$i] : NULL; if ($websiteTypeId) { $defaults["mapper[{$i}]"] = array($relation, $contactDetails, $websiteTypeId); if (!$websiteTypeId) { $js .= "{$formName}['mapper[{$i}][2]'].style.display = 'none';\n"; } } else { // default for IM/phone when mapping with relation is true $typeId = NULL; if (isset($phoneType)) { $typeId = $phoneType; } elseif (isset($imProvider)) { $typeId = $imProvider; } $defaults["mapper[{$i}]"] = array($relation, $contactDetails, $locationId, $typeId); if (!$locationId) { $js .= "{$formName}['mapper[{$i}][2]'].style.display = 'none';\n"; } } // fix for edge cases, CRM-4954 if ($contactDetails == 'image_url') { $contactDetails = str_replace('url', 'URL', $contactDetails); } if (!$contactDetails) { $js .= "{$formName}['mapper[{$i}][1]'].style.display = 'none';\n"; } if (!$phoneType && !$imProvider) { $js .= "{$formName}['mapper[{$i}][3]'].style.display = 'none';\n"; } //$js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n"; $jsSet = TRUE; } else { $mappingHeader = array_keys($this->_mapperFields, $mappingName[$i]); $websiteTypeId = isset($mappingWebsiteType[$i]) ? $mappingWebsiteType[$i] : NULL; $locationId = isset($mappingLocation[$i]) ? $mappingLocation[$i] : 0; $phoneType = isset($mappingPhoneType[$i]) ? $mappingPhoneType[$i] : NULL; // get IM service provider id $imProvider = isset($mappingImProvider[$i]) ? $mappingImProvider[$i] : NULL; if ($websiteTypeId) { if (!$websiteTypeId) { $js .= "{$formName}['mapper[{$i}][1]'].style.display = 'none';\n"; } $defaults["mapper[{$i}]"] = array($mappingHeader[0], $websiteTypeId); } else { if (!$locationId) { $js .= "{$formName}['mapper[{$i}][1]'].style.display = 'none';\n"; } //default for IM/phone without related contact $typeId = NULL; if (isset($phoneType)) { $typeId = $phoneType; } elseif (isset($imProvider)) { $typeId = $imProvider; } $defaults["mapper[{$i}]"] = array($mappingHeader[0], $locationId, $typeId); } if (!$phoneType && !$imProvider) { $js .= "{$formName}['mapper[{$i}][2]'].style.display = 'none';\n"; } $js .= "{$formName}['mapper[{$i}][3]'].style.display = 'none';\n"; $jsSet = TRUE; } } else { $defaults["mapper[{$i}]"] = array(); } if (!$jsSet) { for ($k = 1; $k < 4; $k++) { $js .= "{$formName}['mapper[{$i}][{$k}]'].style.display = 'none';\n"; } } } else { // this load section to help mapping if we ran out of saved columns when doing Load Mapping $js .= "swapOptions({$formName}, 'mapper[{$i}]', 0, 3, 'hs_mapper_0_');\n"; if ($hasColumnNames) { $defaults["mapper[{$i}]"] = array($this->defaultFromColumnName($this->_columnNames[$i], $columnPatterns)); } else { $defaults["mapper[{$i}]"] = array($this->defaultFromData($dataPatterns, $i)); } } //end of load mapping } else { $js .= "swapOptions({$formName}, 'mapper[{$i}]', 0, 3, 'hs_mapper_0_');\n"; if ($hasColumnNames) { // do array search first to see if has mapped key $columnKey = ''; $columnKey = array_search($this->_columnNames[$i], $this->_mapperFields); if (isset($this->_fieldUsed[$columnKey])) { $defaults["mapper[{$i}]"] = $columnKey; $this->_fieldUsed[$key] = TRUE; } else { // Infer the default from the column names if we have them $defaults["mapper[{$i}]"] = array($this->defaultFromColumnName($this->_columnNames[$i], $columnPatterns), 0); } } else { // Otherwise guess the default from the form of the data $defaults["mapper[{$i}]"] = array($this->defaultFromData($dataPatterns, $i), 0); } } $sel->setOptions(array($sel1, $sel2, $sel3, $sel4)); } $js .= "</script>\n"; $this->assign('initHideBoxes', $js); //set warning if mismatch in more than if (isset($mappingName) && $this->_columnCount != count($mappingName)) { $warning++; } if ($warning != 0 && $this->get('savedMapping')) { $session = CRM_Core_Session::singleton(); $session->setStatus(ts('The data columns in this import file appear to be different from the saved mapping. Please verify that you have selected the correct saved mapping before continuing.')); } else { $session = CRM_Core_Session::singleton(); $session->setStatus(NULL); } $this->setDefaults($defaults); $this->addButtons(array(array('type' => 'back', 'name' => ts('Previous')), array('type' => 'next', 'name' => ts('Continue'), 'spacing' => ' ', 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Cancel')))); }
/** * Build the form object. * * * @return void */ public function buildQuickForm() { $this->applyFilter('__ALL__', 'trim'); $attributes = CRM_Core_DAO::getAttribute('CRM_Core_DAO_CustomGroup'); //title $this->add('text', 'title', ts('Set Name'), $attributes['title'], TRUE); //Fix for code alignment, CRM-3058 $contactTypes = array('Contact', 'Individual', 'Household', 'Organization'); $this->assign('contactTypes', json_encode($contactTypes)); $sel1 = array("" => ts("- select -")) + CRM_Core_SelectValues::customGroupExtends(); $sel2 = array(); $activityType = CRM_Core_PseudoConstant::activityType(FALSE, TRUE, FALSE, 'label', TRUE); $eventType = CRM_Core_OptionGroup::values('event_type'); $grantType = CRM_Core_OptionGroup::values('grant_type'); $campaignTypes = CRM_Campaign_PseudoConstant::campaignType(); $membershipType = CRM_Member_BAO_MembershipType::getMembershipTypes(FALSE); $participantRole = CRM_Core_OptionGroup::values('participant_role'); $relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Individual'); $relTypeOrg = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Organization'); $relTypeHou = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Household'); ksort($sel1); asort($activityType); asort($eventType); asort($grantType); asort($membershipType); asort($participantRole); $allRelationshipType = array(); $allRelationshipType = array_merge($relTypeInd, $relTypeOrg); $allRelationshipType = array_merge($allRelationshipType, $relTypeHou); //adding subtype specific relationships CRM-5256 $subTypes = CRM_Contact_BAO_ContactType::subTypeInfo(); foreach ($subTypes as $subType => $val) { $subTypeRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $val['parent'], FALSE, 'label', TRUE, $subType); $allRelationshipType = array_merge($allRelationshipType, $subTypeRelationshipTypes); } $sel2['Event'] = $eventType; $sel2['Grant'] = $grantType; $sel2['Activity'] = $activityType; $sel2['Campaign'] = $campaignTypes; $sel2['Membership'] = $membershipType; $sel2['ParticipantRole'] = $participantRole; $sel2['ParticipantEventName'] = CRM_Event_PseudoConstant::event(NULL, FALSE, "( is_template IS NULL OR is_template != 1 )"); $sel2['ParticipantEventType'] = $eventType; $sel2['Contribution'] = CRM_Contribute_PseudoConstant::financialType(); $sel2['Relationship'] = $allRelationshipType; $sel2['Individual'] = CRM_Contact_BAO_ContactType::subTypePairs('Individual', FALSE, NULL); $sel2['Household'] = CRM_Contact_BAO_ContactType::subTypePairs('Household', FALSE, NULL); $sel2['Organization'] = CRM_Contact_BAO_ContactType::subTypePairs('Organization', FALSE, NULL); CRM_Core_BAO_CustomGroup::getExtendedObjectTypes($sel2); foreach ($sel2 as $main => $sub) { if (!empty($sel2[$main])) { if ($main == 'Relationship') { $relName = self::getFormattedList($sel2[$main]); $sel2[$main] = array('' => ts("- Any -")) + $relName; } else { $sel2[$main] = array('' => ts("- Any -")) + $sel2[$main]; } } } $cSubTypes = CRM_Core_Component::contactSubTypes(); if (!empty($cSubTypes)) { $contactSubTypes = array(); foreach ($cSubTypes as $key => $value) { $contactSubTypes[$key] = $key; } $sel2['Contact'] = array("" => "- Any -") + $contactSubTypes; } else { if (!isset($this->_id)) { $formName = 'document.forms.' . $this->_name; $js = "<script type='text/javascript'>\n"; $js .= "{$formName}['extends_1'].style.display = 'none';\n"; $js .= "</script>"; $this->assign('initHideBlocks', $js); } } $sel =& $this->add('hierselect', 'extends', ts('Used For'), array('name' => 'extends[0]', 'style' => 'vertical-align: top;'), TRUE); $sel->setOptions(array($sel1, $sel2)); if (is_a($sel->_elements[1], 'HTML_QuickForm_select')) { // make second selector a multi-select - $sel->_elements[1]->setMultiple(TRUE); $sel->_elements[1]->setSize(5); } if ($this->_action == CRM_Core_Action::UPDATE) { $subName = CRM_Utils_Array::value('extends_entity_column_id', $this->_defaults); if ($this->_defaults['extends'] == 'Participant') { if ($subName == 1) { $this->_defaults['extends'] = 'ParticipantRole'; } elseif ($subName == 2) { $this->_defaults['extends'] = 'ParticipantEventName'; } elseif ($subName == 3) { $this->_defaults['extends'] = 'ParticipantEventType'; } } //allow to edit settings if custom set is empty CRM-5258 $this->_isGroupEmpty = CRM_Core_BAO_CustomGroup::isGroupEmpty($this->_id); if (!$this->_isGroupEmpty) { if (!empty($this->_subtypes)) { // we want to allow adding / updating subtypes for this case, // and therefore freeze the first selector only. $sel->_elements[0]->freeze(); } else { // freeze both the selectors $sel->freeze(); } } $this->assign('isCustomGroupEmpty', $this->_isGroupEmpty); $this->assign('gid', $this->_id); } $this->assign('defaultSubtypes', json_encode($this->_subtypes)); // help text $this->add('wysiwyg', 'help_pre', ts('Pre-form Help'), $attributes['help_pre']); $this->add('wysiwyg', 'help_post', ts('Post-form Help'), $attributes['help_post']); // weight $this->add('text', 'weight', ts('Order'), $attributes['weight'], TRUE); $this->addRule('weight', ts('is a numeric field'), 'numeric'); // display style $this->add('select', 'style', ts('Display Style'), CRM_Core_SelectValues::customGroupStyle()); // is this set collapsed or expanded ? $this->addElement('checkbox', 'collapse_display', ts('Collapse this set on initial display')); // is this set collapsed or expanded ? in advanced search $this->addElement('checkbox', 'collapse_adv_display', ts('Collapse this set in Advanced Search')); // is this set active ? $this->addElement('checkbox', 'is_active', ts('Is this Custom Data Set active?')); // does this set have multiple record? $multiple = $this->addElement('checkbox', 'is_multiple', ts('Does this Custom Field Set allow multiple records?'), NULL); // $min_multiple = $this->add('text', 'min_multiple', ts('Minimum number of multiple records'), $attributes['min_multiple'] ); // $this->addRule('min_multiple', ts('is a numeric field') , 'numeric'); $max_multiple = $this->add('text', 'max_multiple', ts('Maximum number of multiple records'), $attributes['max_multiple']); $this->addRule('max_multiple', ts('is a numeric field'), 'numeric'); //allow to edit settings if custom set is empty CRM-5258 $this->assign('isGroupEmpty', $this->_isGroupEmpty); if (!$this->_isGroupEmpty) { $multiple->freeze(); //$min_multiple->freeze(); $max_multiple->freeze(); } $this->assign('showStyle', FALSE); $this->assign('showMultiple', FALSE); $buttons = array(array('type' => 'next', 'name' => ts('Save'), 'spacing' => ' ', 'isDefault' => TRUE), array('type' => 'cancel', 'name' => ts('Cancel'))); if (!$this->_isGroupEmpty && !empty($this->_subtypes)) { $buttons[0]['class'] = 'crm-warnDataLoss'; } $this->addButtons($buttons); // TODO: Is this condition ever true? Can this code be removed? if ($this->_action & CRM_Core_Action::VIEW) { $this->freeze(); $this->addElement('button', 'done', ts('Done'), array('onclick' => "location.href='civicrm/admin/custom/group?reset=1&action=browse'")); } }
/** * Function to build the form * * @return None * @access public */ function buildQuickForm() { if ($this->_action & CRM_CORE_ACTION_DELETE) { $this->addButtons(array(array('type' => 'next', 'name' => ts('Delete'), 'isDefault' => true), array('type' => 'cancel', 'name' => ts('Cancel')))); return; } $this->addElement('select', 'relationship_type_id', ts('Relationship Type'), array('' => ts('- select -')) + CRM_Contact_BAO_Relationship::getContactRelationshipType($this->_contactId, $this->_rtype, $this->_relationshipId)); $this->addElement('text', 'name', ts('Find Target Contact')); $this->addElement('date', 'start_date', ts('Start Date'), CRM_Core_SelectValues::date('relative')); $this->addElement('date', 'end_date', ts('End Date'), CRM_Core_SelectValues::date('relative')); $searchRows = $this->get('searchRows'); $searchCount = $this->get('searchCount'); $duplicateRelationship = $this->get('duplicateRelationship'); if ($searchRows) { $checkBoxes = array(); foreach ($searchRows as $id => $row) { $checkBoxes[$id] = $this->createElement('checkbox', $id, null, ''); } $this->addGroup($checkBoxes, 'contact_check'); $this->assign('searchRows', $searchRows); } $this->assign('duplicateRelationship', $duplicateRelationship); $this->assign('searchCount', $searchCount); $this->assign('searchDone', $this->get('searchDone')); if ($this->get('contact_type')) { $this->assign('contact_type', $this->get('contact_type')); $this->assign('contact_type_display', CRM_Contact_DAO_Contact::tsEnum('contact_type', $this->get('contact_type'))); } $this->addElement('submit', $this->getButtonName('refresh'), ts('Search'), array('class' => 'form-submit')); $this->addElement('submit', $this->getButtonName('cancel'), ts('Cancel'), array('class' => 'form-submit')); $this->addButtons(array(array('type' => 'next', 'name' => ts('Save Relationship'), 'isDefault' => true), array('type' => 'cancel', 'name' => ts('Cancel')))); }
/** * Get columns for relationship fields. * * @param array $options * * @return array */ function getRelationshipColumns($options = array()) { $defaultOptions = array( 'prefix' => '', 'prefix_label' => '', 'group_by' => FALSE, 'order_by' => TRUE, 'filters' => TRUE, 'defaults' => array(), ); $options = array_merge($defaultOptions, $options); $prefix = $options['prefix']; $specs = array( $prefix . 'id' => array( 'name' => 'id', 'title' => ts('Relationship ID'), ), $prefix . 'relationship_start_date' => array( 'title' => ts('Relationship Start Date'), 'name' => 'start_date', 'type' => CRM_Utils_Type::T_DATE, 'is_fields' => TRUE, 'is_filters' => TRUE, 'is_join_filters' => TRUE, ), $prefix . 'relationship_end_date' => array( 'title' => ts('Relationship End Date'), 'name' => 'end_date', 'is_fields' => TRUE, 'type' => CRM_Utils_Type::T_DATE, 'is_fields' => TRUE, 'is_filters' => TRUE, 'is_join_filters' => TRUE, ), $prefix . 'relationship_description' => array( 'title' => ts('Description'), 'name' => 'description', 'type' => CRM_Utils_Type::T_STRING, 'is_fields' => TRUE, 'is_filters' => TRUE, ), $prefix . 'relationship_is_active' => array( 'title' => ts('Relationship Status'), 'name' => 'is_active', 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => array( '' => '- Any -', 1 => 'Active', 0 => 'Inactive', 'is_filters' => TRUE, ), 'type' => CRM_Utils_Type::T_INT, 'is_join_filters' => TRUE, ), $prefix . 'relationship_type_id' => array( 'name' => 'relationship_type_id', 'title' => ts('Relationship Type'), 'operatorType' => CRM_Report_Form::OP_MULTISELECT, 'options' => array( '' => '- any relationship type -' ) + CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, NULL, TRUE), 'type' => CRM_Utils_Type::T_INT, 'is_filters' => TRUE, 'is_join_filters' => FALSE, ), // For the join filters we will use a one-way option list to make our life easier. $prefix . 'join_relationship_type_id' => array( 'name' => 'relationship_type_id', 'title' => ts('Relationship Type'), 'operatorType' => CRM_Report_Form::OP_SELECT, 'options' => array( '' => '- any relationship type -' ) + $this->getRelationshipABOptions(), 'type' => CRM_Utils_Type::T_INT, 'is_join_filters' => TRUE, ), ); return $this->buildColumns($specs, 'civicrm_relationship', 'CRM_Contact_BAO_Relationship'); }
/** * Browse all custom data groups. * * @param string $action the action to be invoked * * @return void * @access public */ function browse($action = NULL) { // get all custom groups sorted by weight $customGroup = array(); $dao = new CRM_Core_DAO_CustomGroup(); $dao->orderBy('weight, title'); $dao->find(); while ($dao->fetch()) { $customGroup[$dao->id] = array(); CRM_Core_DAO::storeValues($dao, $customGroup[$dao->id]); // form all action links $action = array_sum(array_keys($this->actionLinks())); // update enable/disable links depending on custom_group properties. if ($dao->is_active) { $action -= CRM_Core_Action::ENABLE; } else { $action -= CRM_Core_Action::DISABLE; } $customGroup[$dao->id]['order'] = $customGroup[$dao->id]['weight']; $customGroup[$dao->id]['action'] = CRM_Core_Action::formLink(self::actionLinks(), $action, array('id' => $dao->id)); } $customGroupExtends = CRM_Core_SelectValues::customGroupExtends(); foreach ($customGroup as $key => $array) { CRM_Core_DAO_CustomGroup::addDisplayEnums($customGroup[$key]); $customGroup[$key]['extends_display'] = $customGroupExtends[$customGroup[$key]['extends']]; } //fix for Displaying subTypes $subTypes = array(); $subTypes['Activity'] = CRM_Core_PseudoConstant::activityType(FALSE, TRUE, FALSE, 'label', TRUE); $subTypes['Contribution'] = CRM_Contribute_PseudoConstant::contributionType(); $subTypes['Membership'] = CRM_Member_BAO_MembershipType::getMembershipTypes(FALSE); $subTypes['Event'] = CRM_Core_OptionGroup::values('event_type'); $subTypes['Grant'] = CRM_Core_OptionGroup::values('grant_type'); $subTypes['Campaign'] = CRM_Campaign_PseudoConstant::campaignType(); $subTypes['Participant'] = array(); $subTypes['ParticipantRole'] = CRM_Core_OptionGroup::values('participant_role'); $subTypes['ParticipantEventName'] = CRM_Event_PseudoConstant::event(); $subTypes['ParticipantEventType'] = CRM_Core_OptionGroup::values('event_type'); $subTypes['Individual'] = CRM_Contact_BAO_ContactType::subTypePairs('Individual', FALSE, NULL); $subTypes['Household'] = CRM_Contact_BAO_ContactType::subTypePairs('Household', FALSE, NULL); $subTypes['Organization'] = CRM_Contact_BAO_ContactType::subTypePairs('Organization', FALSE, NULL); $relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Individual'); $relTypeOrg = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Organization'); $relTypeHou = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, 'null', NULL, 'Household'); $allRelationshipType = array(); $allRelationshipType = array_merge($relTypeInd, $relTypeOrg); $allRelationshipType = array_merge($allRelationshipType, $relTypeHou); //adding subtype specific relationships CRM-5256 $relSubType = CRM_Contact_BAO_ContactType::subTypeInfo(); foreach ($relSubType as $subType => $val) { $subTypeRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $val['parent'], FALSE, 'label', TRUE, $subType); $allRelationshipType = array_merge($allRelationshipType, $subTypeRelationshipTypes); } $subTypes['Relationship'] = $allRelationshipType; $cSubTypes = CRM_Core_Component::contactSubTypes(); $contactSubTypes = array(); foreach ($cSubTypes as $key => $value) { $contactSubTypes[$key] = $key; } $subTypes['Contact'] = $contactSubTypes; CRM_Core_BAO_CustomGroup::getExtendedObjectTypes($subTypes); foreach ($customGroup as $key => $values) { $subValue = CRM_Utils_Array::value('extends_entity_column_value', $customGroup[$key]); $subName = CRM_Utils_Array::value('extends_entity_column_id', $customGroup[$key]); $type = CRM_Utils_Array::value('extends', $customGroup[$key]); if ($subValue) { $subValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, substr($subValue, 1, -1)); $colValue = NULL; foreach ($subValue as $sub) { if ($sub) { if ($type == 'Participant') { if ($subName == 1) { $colValue = $colValue ? $colValue . ', ' . $subTypes['ParticipantRole'][$sub] : $subTypes['ParticipantRole'][$sub]; } elseif ($subName == 2) { $colValue = $colValue ? $colValue . ', ' . $subTypes['ParticipantEventName'][$sub] : $subTypes['ParticipantEventName'][$sub]; } elseif ($subName == 3) { $colValue = $colValue ? $colValue . ', ' . $subTypes['ParticipantEventType'][$sub] : $subTypes['ParticipantEventType'][$sub]; } } elseif ($type == 'Relationship') { $colValue = $colValue ? $colValue . ', ' . $subTypes[$type][$sub . '_a_b'] : $subTypes[$type][$sub . '_a_b']; if (isset($subTypes[$type][$sub . '_b_a'])) { $colValue = $colValue ? $colValue . ', ' . $subTypes[$type][$sub . '_b_a'] : $subTypes[$type][$sub . '_b_a']; } } else { $colValue = $colValue ? $colValue . (isset($subTypes[$type][$sub]) ? ', ' . $subTypes[$type][$sub] : '') : (isset($subTypes[$type][$sub]) ? $subTypes[$type][$sub] : ''); } } } $customGroup[$key]["extends_entity_column_value"] = $colValue; } else { if (is_array(CRM_Utils_Array::value($type, $subTypes))) { $customGroup[$key]["extends_entity_column_value"] = ts("Any"); } } } $returnURL = CRM_Utils_System::url('civicrm/admin/custom/group', "reset=1&action=browse"); CRM_Utils_Weight::addOrder($customGroup, 'CRM_Core_DAO_CustomGroup', 'id', $returnURL); $this->assign('rows', $customGroup); }
/** * Function to build the form * * @return None * @access public */ public function buildQuickForm() { parent::buildQuickForm(); if ($this->_action & CRM_Core_Action::DELETE) { return; } $this->applyFilter('__ALL__', 'trim'); $this->add('text', 'name', ts('Name'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'name'), true); $this->addRule('name', ts('A membership type with this name already exists. Please select another name.'), 'objectExists', array('CRM_Member_DAO_MembershipType', $this->_id)); $this->add('text', 'description', ts('Description'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'description')); $this->add('text', 'minimum_fee', ts('Minimum Fee'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'minimum_fee')); $this->addRule('minimum_fee', ts('Please enter a monetary value for the Minimum Fee.'), 'money'); $this->addElement('select', 'duration_unit', ts('Duration') . ' ', CRM_Core_SelectValues::unitList('duration'), array('onchange' => 'showHidePeriodSettings()')); //period type $this->addElement('select', 'period_type', ts('Period Type'), CRM_Core_SelectValues::periodType(), array('onchange' => 'showHidePeriodSettings()')); $this->add('text', 'duration_interval', ts('Duration Interval'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'duration_interval')); $memberOrg =& $this->add('text', 'member_org', ts('Membership Organization'), 'size=30 maxlength=120'); //start day $this->add('date', 'fixed_period_start_day', ts('Fixed Period Start Day'), CRM_Core_SelectValues::date('custom', 3, 1, "Md"), false); //rollover day $this->add('date', 'fixed_period_rollover_day', ts('Fixed Period Rollover Day'), CRM_Core_SelectValues::date('custom', 3, 1, "Md"), false); $this->add('hidden', 'action', $this->_action); //required in form rule require_once 'CRM/Contribute/PseudoConstant.php'; $this->add('select', 'contribution_type_id', ts('Contribution Type'), array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::contributionType()); require_once 'CRM/Contact/BAO/Relationship.php'; $relTypeInd = CRM_Contact_BAO_Relationship::getContactRelationshipType(null, null, null, null, true); if (is_array($relTypeInd)) { asort($relTypeInd); } $memberRel =& $this->add('select', 'relationship_type_id', ts('Relationship Type'), array('' => ts('- select -')) + $relTypeInd); $this->add('select', 'visibility', ts('Visibility'), CRM_Core_SelectValues::memberVisibility()); $this->add('text', 'weight', ts('Order'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'weight')); $this->add('checkbox', 'is_active', ts('Enabled?')); require_once "CRM/Core/BAO/MessageTemplates.php"; $msgTemplates = CRM_Core_BAO_MessageTemplates::getMessageTemplates(); if (!empty($msgTemplates)) { $reminderMsg = $this->add('select', 'renewal_msg_id', ts('Renewal Reminder Message'), array('' => ts('- select -')) + $msgTemplates); } else { $this->assign('noMsgTemplates', true); } $reminderDay =& $this->add('text', 'renewal_reminder_day', ts('Renewal Reminder Day'), CRM_Core_DAO::getAttribute('CRM_Member_DAO_MembershipType', 'renewal_reminder_day')); $searchRows = $this->get('searchRows'); $searchCount = $this->get('searchCount'); $searchDone = $this->get('searchDone'); if ($searchRows) { $checkBoxes = array(); $chekFlag = 0; foreach ($searchRows as $id => $row) { $checked = ''; if (!$chekFlag) { $checked = array('checked' => null); $chekFlag++; } $checkBoxes[$id] = $this->createElement('radio', null, null, null, $id, $checked); } $this->addGroup($checkBoxes, 'contact_check'); $this->assign('searchRows', $searchRows); } $this->assign('searchCount', $searchCount); $this->assign('searchDone', $searchDone); if ($searchDone) { $searchBtn = ts('Search Again'); } elseif ($this->_action & CRM_Core_Action::UPDATE) { $searchBtn = ts('Change'); } else { $searchBtn = ts('Search'); } $membershipRecords = false; if ($this->_action & CRM_Core_Action::UPDATE) { require_once 'CRM/Member/BAO/Membership.php'; $membershipType = new CRM_Member_BAO_Membership(); $membershipType->membership_type_id = $this->_id; if ($membershipType->find(true)) { $membershipRecords = true; $memberRel->freeze(); } $memberOrg->freeze(); if ($searchDone) { $memberOrg->unfreeze(); } } if ($this->_action & CRM_Core_Action::UPDATE && $reminderDay) { $renewMessage = array(); $returnProperties = array('renewal_msg_id', 'renewal_reminder_day'); CRM_Core_DAO::commonRetrieveAll('CRM_Member_DAO_MembershipType', 'id', $this->_id, $renewMessage, $returnProperties); if (CRM_Utils_Array::value('renewal_msg_id', $renewMessage[$this->_id]) && CRM_Utils_Array::value('renewal_reminder_day', $renewMessage[$this->_id]) && $membershipRecords) { $reminderMsg = $this->add('select', 'renewal_msg_id', ts('Renewal Reminder Message'), array('' => ts('- select -')) + $msgTemplates); $reminderDay->freeze(); $reminderMsg->freeze(); } } $this->addElement('submit', $this->getButtonName('refresh'), $searchBtn, array('class' => 'form-submit')); $this->addFormRule(array('CRM_Member_Form_MembershipType', 'formRule')); $this->assign('membershipTypeId', $this->_id); }
/** * 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')); } }
/** * Replace ids of household members in $this->_contactIds with the id of their household. * * CRM-8338 */ public function mergeContactIdsByHousehold() { if (empty($this->_contactIds)) { return; } $contactRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE, 'name', FALSE); // Get Head of Household & Household Member relationships $relationKeyMOH = CRM_Utils_Array::key('Household Member of', $contactRelationshipTypes); $relationKeyHOH = CRM_Utils_Array::key('Head of Household for', $contactRelationshipTypes); $householdRelationshipTypes = array($relationKeyMOH => $contactRelationshipTypes[$relationKeyMOH], $relationKeyHOH => $contactRelationshipTypes[$relationKeyHOH]); $relID = implode(',', $this->_contactIds); foreach ($householdRelationshipTypes as $rel => $dnt) { 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'; } // Find related households. $relationSelect = "SELECT contact_household.id as household_id, {$contactA} as refContact "; $relationFrom = " FROM civicrm_contact contact_household\n INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_household.id AND crel.relationship_type_id = {$id} "; // 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_household.is_deleted = 0 AND crel.{$contactA} IN ( {$relID} ) {$relationActive}"; $relationGroupBy = " GROUP BY crel.{$contactA}"; $relationQueryString = "{$relationSelect} {$relationFrom} {$relationWhere} {$relationGroupBy}"; $householdsDAO = CRM_Core_DAO::executeQuery($relationQueryString); while ($householdsDAO->fetch()) { // Remove contact's id from $this->_contactIds and replace with their household's id. foreach (array_keys($this->_contactIds, $householdsDAO->refContact) as $idKey) { unset($this->_contactIds[$idKey]); } if (!in_array($householdsDAO->household_id, $this->_contactIds)) { $this->_contactIds[] = $householdsDAO->household_id; } } $householdsDAO->free(); } }