3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Core_BAO_Mapping
extends CRM_Core_DAO_Mapping
{
22 public function __construct() {
23 parent
::__construct();
27 * Fetch object based on array of properties.
29 * @param array $params
30 * (reference ) an assoc array of name/value pairs.
31 * @param array $defaults
32 * (reference ) an assoc array to hold the flattened values.
35 * CRM_Core_DAO_Mapping object on success, otherwise NULL
37 public static function retrieve(&$params, &$defaults) {
38 $mapping = new CRM_Core_DAO_Mapping();
39 $mapping->copyValues($params);
40 if ($mapping->find(TRUE)) {
41 CRM_Core_DAO
::storeValues($mapping, $defaults);
55 public static function del($id) {
56 // delete from mapping_field table
57 $mappingField = new CRM_Core_DAO_MappingField();
58 $mappingField->mapping_id
= $id;
59 $mappingField->delete();
61 // delete from mapping table
62 $mapping = new CRM_Core_DAO_Mapping();
64 if ($mapping->find(TRUE)) {
65 $result = $mapping->delete();
72 * Takes an associative array and creates a contact object.
74 * The function extract all the params it needs to initialize the create a
75 * contact object. the params array could contain additional unused name/value
78 * @param array $params
79 * An array of name/value pairs.
82 * CRM_Core_DAO_Mapper object on success, otherwise NULL
84 public static function add($params) {
85 $mapping = new CRM_Core_DAO_Mapping();
86 $mapping->copyValues($params);
93 * Get the list of mappings for a select or select2 element.
95 * @param string $mappingType
97 * @param bool $select2
101 * Array of mapping names, keyed by id.
103 public static function getMappings($mappingType, $select2 = FALSE) {
104 $result = civicrm_api3('Mapping', 'get', [
105 'mapping_type_id' => $mappingType,
106 'return' => ['name', 'description'],
114 foreach ($result['values'] as $id => $value) {
116 $item = ['id' => $id, 'text' => $value['name']];
117 if (!empty($value['description'])) {
118 $item['description'] = $value['description'];
123 $mapping[$id] = $value['name'];
130 * Get the mappings array, creating if it does not exist.
132 * @param string $mappingType
136 * Array of mapping names, keyed by id.
138 * @throws \CiviCRM_API3_Exception
140 public static function getCreateMappingValues($mappingType) {
142 return CRM_Core_BAO_Mapping
::getMappings($mappingType);
144 catch (CiviCRM_API3_Exception
$e) {
145 // Having a valid mapping_type_id is now enforced. However, rather than error let's
146 // add it. This is required for Multi value which could be done by upgrade script, but
147 // it feels like there could be other instances so this is safer.
148 $errorParams = $e->getExtraParams();
149 if ($errorParams['error_field'] === 'mapping_type_id') {
150 $mappingValues = civicrm_api3('Mapping', 'getoptions', ['field' => 'mapping_type_id']);
151 civicrm_api3('OptionValue', 'create', [
152 'option_group_id' => 'mapping_type',
153 'label' => $mappingType,
154 'value' => max(array_keys($mappingValues['values'])) +
1,
157 return CRM_Core_BAO_Mapping
::getMappings($mappingType);
164 * Get the mapping fields.
166 * @param int $mappingId
169 * @param bool $addPrimary
170 * Add the key 'Primary' when the field is a location field AND there is
171 * no location type (meaning Primary)?
174 * array of mapping fields
176 public static function getMappingFields($mappingId, $addPrimary = FALSE) {
177 //mapping is to be loaded from database
178 $mapping = new CRM_Core_DAO_MappingField();
179 $mapping->mapping_id
= $mappingId;
180 $mapping->orderBy('column_number');
183 $mappingName = $mappingLocation = $mappingContactType = $mappingPhoneType = [];
184 $mappingImProvider = $mappingRelation = $mappingOperator = $mappingValue = $mappingWebsiteType = [];
185 while ($mapping->fetch()) {
186 $mappingName[$mapping->grouping
][$mapping->column_number
] = $mapping->name
;
187 $mappingContactType[$mapping->grouping
][$mapping->column_number
] = $mapping->contact_type
;
189 if (!empty($mapping->location_type_id
)) {
190 $mappingLocation[$mapping->grouping
][$mapping->column_number
] = $mapping->location_type_id
;
192 elseif ($addPrimary) {
193 if (CRM_Contact_BAO_Contact
::isFieldHasLocationType($mapping->name
)) {
194 $mappingLocation[$mapping->grouping
][$mapping->column_number
] = ts('Primary');
197 $mappingLocation[$mapping->grouping
][$mapping->column_number
] = NULL;
201 if (!empty($mapping->phone_type_id
)) {
202 $mappingPhoneType[$mapping->grouping
][$mapping->column_number
] = $mapping->phone_type_id
;
205 // get IM service provider type id from mapping fields
206 if (!empty($mapping->im_provider_id
)) {
207 $mappingImProvider[$mapping->grouping
][$mapping->column_number
] = $mapping->im_provider_id
;
210 if (!empty($mapping->website_type_id
)) {
211 $mappingWebsiteType[$mapping->grouping
][$mapping->column_number
] = $mapping->website_type_id
;
214 if (!empty($mapping->relationship_type_id
)) {
215 $mappingRelation[$mapping->grouping
][$mapping->column_number
] = "{$mapping->relationship_type_id}_{$mapping->relationship_direction}";
218 if (!empty($mapping->operator
)) {
219 $mappingOperator[$mapping->grouping
][$mapping->column_number
] = $mapping->operator
;
222 if (!empty($mapping->value
)) {
223 $mappingValue[$mapping->grouping
][$mapping->column_number
] = $mapping->value
;
241 * Get un-indexed array of the field values for the given mapping id.
243 * For example if passing a mapping ID & name the returned array would look like
244 * ['First field name', 'second field name']
246 * @param int $mappingID
247 * @param string $fieldName
250 * @throws \CiviCRM_API3_Exception
252 public static function getMappingFieldValues($mappingID, $fieldName) {
253 return array_merge(CRM_Utils_Array
::collect($fieldName, civicrm_api3('MappingField', 'get', ['mapping_id' => $mappingID, 'return' => $fieldName])['values']));
257 * Check Duplicate Mapping Name.
259 * @param string $nameField
261 * @param string $mapTypeId
266 public static function checkMapping($nameField, $mapTypeId) {
267 $mapping = new CRM_Core_DAO_Mapping();
268 $mapping->name
= $nameField;
269 $mapping->mapping_type_id
= $mapTypeId;
270 return (bool) $mapping->find(TRUE);
274 * Function returns associated array of elements, that will be passed for search.
276 * @param int $smartGroupId
280 * associated array of elements
282 public static function getFormattedFields($smartGroupId) {
285 //get the fields from mapping table
286 $dao = new CRM_Core_DAO_MappingField();
287 $dao->mapping_id
= $smartGroupId;
289 while ($dao->fetch()) {
290 $fldName = $dao->name
;
291 if ($dao->location_type_id
) {
292 $fldName .= "-{$dao->location_type_id}";
294 if ($dao->phone_type
) {
295 $fldName .= "-{$dao->phone_type}";
297 $returnFields[$fldName]['value'] = $dao->value
;
298 $returnFields[$fldName]['op'] = $dao->operator
;
299 $returnFields[$fldName]['grouping'] = $dao->grouping
;
301 return $returnFields;
305 * Build the mapping form.
307 * @param CRM_Core_Form $form
308 * @param string $mappingType
309 * (Export/Search Builder). (Import apparently used to use this but does no longer).
310 * @param int $mappingId
311 * @param int $columnNo
312 * @param int $blockCount
313 * (no of blocks shown).
314 * @param int $exportMode
316 public static function buildMappingForm(&$form, $mappingType, $mappingId, $columnNo, $blockCount, $exportMode = NULL) {
318 $hasLocationTypes = [];
319 $hasRelationTypes = [];
321 //get the saved mapping details
323 if ($mappingType == 'Export') {
324 $columnCount = ['1' => $columnNo];
325 $form->applyFilter('saveMappingName', 'trim');
327 //to save the current mappings
328 if (!isset($mappingId)) {
329 $saveDetailsName = ts('Save this field mapping');
330 $form->add('text', 'saveMappingName', ts('Name'));
331 $form->add('text', 'saveMappingDesc', ts('Description'));
334 $form->assign('loadedMapping', $mappingId);
336 $params = ['id' => $mappingId];
338 $mappingDetails = CRM_Core_BAO_Mapping
::retrieve($params, $temp);
340 $form->assign('savedName', $mappingDetails->name
);
342 $form->add('hidden', 'mappingId', $mappingId);
344 $form->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL);
345 $saveDetailsName = ts('Save as a new field mapping');
346 $form->add('text', 'saveMappingName', ts('Name'));
347 $form->add('text', 'saveMappingDesc', ts('Description'));
350 $form->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, ['onclick' => "showSaveDetails(this)"]);
351 $form->addFormRule(['CRM_Export_Form_Map', 'formRule'], $form->get('mappingTypeId'));
353 elseif ($mappingType == 'Search Builder') {
354 $columnCount = $columnNo;
355 $form->addElement('submit', 'addBlock', ts('Also include contacts where'),
356 ['class' => 'submit-link']
360 $contactTypes = CRM_Contact_BAO_ContactType
::basicTypes();
361 $fields = self
::getBasicFields($mappingType);
363 // Unset groups, tags, notes for component export
364 if ($exportMode != CRM_Export_Form_Select
::CONTACT_EXPORT
) {
365 foreach (array_keys($fields) as $type) {
366 CRM_Utils_Array
::remove($fields[$type], 'groups', 'tags', 'notes');
370 if ($mappingType == 'Search Builder') {
371 // Build the common contact fields array.
372 $fields['Contact'] = [];
373 foreach ($fields[$contactTypes[0]] as $key => $value) {
374 // If a field exists across all contact types, move it to the "Contact" selector
376 foreach ($contactTypes as $type) {
377 if (!isset($fields[$type][$key])) {
378 $ubiquitious = FALSE;
382 $fields['Contact'][$key] = $value;
383 foreach ($contactTypes as $type) {
384 unset($fields[$type][$key]);
388 if (array_key_exists('note', $fields['Contact'])) {
389 $noteTitle = $fields['Contact']['note']['title'];
390 $fields['Contact']['note']['title'] = $noteTitle . ': ' . ts('Body and Subject');
391 $fields['Contact']['note_body'] = ['title' => $noteTitle . ': ' . ts('Body Only'), 'name' => 'note_body'];
392 $fields['Contact']['note_subject'] = [
393 'title' => $noteTitle . ': ' . ts('Subject Only'),
394 'name' => 'note_subject',
399 // add component fields
400 $compArray = self
::addComponentFields($fields, $mappingType, $exportMode);
402 foreach ($fields as $key => $value) {
404 foreach ($value as $key1 => $value1) {
405 //CRM-2676, replacing the conflict for same custom field name from different custom group.
406 $customGroupName = self
::getCustomGroupName($key1);
408 if ($customGroupName) {
409 $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $customGroupName . ': ' . $value1['title'];
412 $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $value1['title'];
414 if (isset($value1['hasLocationType'])) {
415 $hasLocationTypes[$key][$key1] = $value1['hasLocationType'];
418 if (isset($value1['hasRelationType'])) {
419 $hasRelationTypes[$key][$key1] = $value1['hasRelationType'];
420 unset($relatedMapperFields[$key][$key1]);
424 if (isset($relatedMapperFields[$key]['related'])) {
425 unset($relatedMapperFields[$key]['related']);
429 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
431 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
433 // FIXME: dirty hack to make the default option show up first. This
434 // avoids a mozilla browser bug with defaults on dynamically constructed
436 if ($defaultLocationType) {
437 $defaultLocation = $locationTypes[$defaultLocationType->id
];
438 unset($locationTypes[$defaultLocationType->id
]);
439 $locationTypes = [$defaultLocationType->id
=> $defaultLocation] +
$locationTypes;
442 $locationTypes = [' ' => ts('Primary')] +
$locationTypes;
444 // since we need a hierarchical list to display contact types & subtypes,
445 // this is what we going to display in first selector
446 $contactTypeSelect = CRM_Contact_BAO_ContactType
::getSelectElements(FALSE, FALSE);
447 if ($mappingType == 'Search Builder') {
448 $contactTypeSelect = ['Contact' => ts('Contacts')] +
$contactTypeSelect;
451 $sel1 = ['' => ts('- select record type -')] +
$contactTypeSelect +
$compArray;
453 foreach ($sel1 as $key => $sel) {
455 // sort everything BUT the contactType which is sorted separately by
456 // an initial commit of CRM-13278 (check ksort above)
457 if (!in_array($key, $contactTypes)) {
458 asort($mapperFields[$key]);
460 $sel2[$key] = ['' => ts('- select field -')] +
$mapperFields[$key];
466 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
467 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
470 foreach ($sel1 as $k => $sel) {
472 foreach ($locationTypes as $key => $value) {
473 if (trim($key) != '') {
474 $sel4[$k]['phone'][$key] = &$phoneTypes;
475 $sel4[$k]['im'][$key] = &$imProviders;
481 foreach ($sel1 as $k => $sel) {
483 foreach ($mapperFields[$k] as $key => $value) {
484 if (isset($hasLocationTypes[$k][$key])) {
485 $sel3[$k][$key] = $locationTypes;
494 // Array for core fields and relationship custom data
495 $relationshipTypes = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE);
497 if ($mappingType == 'Export') {
498 foreach ($sel1 as $k => $sel) {
500 foreach ($mapperFields[$k] as $field => $dontCare) {
501 if (isset($hasRelationTypes[$k][$field])) {
502 list($id, $first, $second) = explode('_', $field);
503 // FIX ME: For now let's not expose custom data related to relationship
504 $relationshipCustomFields = [];
505 //$relationshipCustomFields = self::getRelationTypeCustomGroupData( $id );
506 //asort($relationshipCustomFields);
509 $relationshipType = new CRM_Contact_BAO_RelationshipType();
510 $relationshipType->id
= $id;
511 if ($relationshipType->find(TRUE)) {
512 $direction = "contact_sub_type_$second";
513 $target_type = 'contact_type_' . $second;
514 if (isset($relationshipType->$direction)) {
515 $relatedFields = array_merge((array) $relatedMapperFields[$relationshipType->$direction], (array) $relationshipCustomFields);
517 elseif (isset($relationshipType->$target_type)) {
518 $relatedFields = array_merge((array) $relatedMapperFields[$relationshipType->$target_type], (array) $relationshipCustomFields);
520 //CRM-20672 If contact target type not set e.g. "All Contacts" relationship - present user with all field options and let them determine what they expect to work
522 $types = CRM_Contact_BAO_ContactType
::basicTypes(FALSE);
523 foreach ($types as $contactType => $label) {
524 $relatedFields = array_merge($relatedFields, (array) $relatedMapperFields[$label]);
526 $relatedFields = array_merge($relatedFields, (array) $relationshipCustomFields);
529 asort($relatedFields);
530 $sel5[$k][$field] = $relatedFields;
536 //Location Type for relationship fields
537 foreach ($sel5 as $k => $v) {
539 foreach ($v as $rel => $fields) {
540 foreach ($fields as $field => $fieldLabel) {
541 if (isset($hasLocationTypes[$k][$field])) {
542 $sel6[$k][$rel][$field] = $locationTypes;
549 //PhoneTypes for relationship fields
551 foreach ($sel6 as $k => $rel) {
553 foreach ($rel as $phonekey => $phonevalue) {
554 foreach ($locationTypes as $locType => $loc) {
555 if (trim($locType) != '') {
556 $sel7[$k][$phonekey]['phone'][$locType] = &$phoneTypes;
557 $sel7[$k][$phonekey]['im'][$locType] = &$imProviders;
565 //special fields that have location, hack for primary location
568 'supplemental_address_1',
569 'supplemental_address_2',
570 'supplemental_address_3',
573 'postal_code_suffix',
583 if (isset($mappingId)) {
584 list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingImProvider,
585 $mappingRelation, $mappingOperator, $mappingValue
586 ) = CRM_Core_BAO_Mapping
::getMappingFields($mappingId);
588 $blkCnt = count($mappingName);
589 if ($blkCnt >= $blockCount) {
590 $blockCount = $blkCnt +
1;
592 for ($x = 1; $x < $blockCount; $x++
) {
593 if (isset($mappingName[$x])) {
594 $colCnt = count($mappingName[$x]);
595 if ($colCnt >= $columnCount[$x]) {
596 $columnCount[$x] = $colCnt;
602 $form->_blockCount
= $blockCount;
603 $form->_columnCount
= $columnCount;
605 $form->set('blockCount', $form->_blockCount
);
606 $form->set('columnCount', $form->_columnCount
);
608 $defaults = $noneArray = $nullArray = [];
610 for ($x = 1; $x < $blockCount; $x++
) {
612 for ($i = 0; $i < $columnCount[$x]; $i++
) {
614 $sel = &$form->addElement('hierselect', "mapper[$x][$i]", ts('Mapper for Field %1', [1 => $i]), NULL);
617 if (isset($mappingId)) {
618 list($mappingName, $defaults, $noneArray, $jsSet) = self
::loadSavedMapping($mappingLocation, $x, $i, $mappingName, $mapperFields, $mappingContactType, $mappingRelation, $specialFields, $mappingPhoneType, $defaults, $noneArray, $mappingImProvider, $mappingOperator, $mappingValue);
620 //Fix for Search Builder
621 if ($mappingType == 'Export') {
628 $formValues = $form->exportValues();
630 if (empty($formValues)) {
631 // Incremented length for third select box(relationship type)
632 for ($k = 1; $k < $j; $k++
) {
633 $noneArray[] = [$x, $i, $k];
637 if (!empty($formValues['mapper'][$x])) {
638 foreach ($formValues['mapper'][$x] as $value) {
639 for ($k = 1; $k < $j; $k++
) {
640 if (!isset($formValues['mapper'][$x][$i][$k]) ||
641 (!$formValues['mapper'][$x][$i][$k])
643 $noneArray[] = [$x, $i, $k];
646 $nullArray[] = [$x, $i, $k];
652 for ($k = 1; $k < $j; $k++
) {
653 $noneArray[] = [$x, $i, $k];
658 //Fix for Search Builder
659 if ($mappingType == 'Export') {
660 if (!isset($mappingId) ||
$i >= count(reset($mappingName))) {
661 if (isset($formValues['mapper']) &&
662 isset($formValues['mapper'][$x][$i][1]) &&
663 array_key_exists($formValues['mapper'][$x][$i][1], $relationshipTypes)
665 $sel->setOptions([$sel1, $sel2, $sel5, $sel6, $sel7, $sel3, $sel4]);
668 $sel->setOptions([$sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7]);
672 $sel->setOptions([$sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7]);
676 $sel->setOptions([$sel1, $sel2, $sel3, $sel4]);
679 if ($mappingType == 'Search Builder') {
680 //CRM -2292, restricted array set
681 $operatorArray = ['' => ts('-operator-')] + CRM_Core_SelectValues
::getSearchBuilderOperators();
683 $form->add('select', "operator[$x][$i]", '', $operatorArray);
684 $form->add('text', "value[$x][$i]", '');
687 //end of columnCnt for
688 if ($mappingType == 'Search Builder') {
689 $title = ts('Another search field');
692 $title = ts('Select more fields');
695 $form->addElement('submit', "addMore[$x]", $title, ['class' => 'submit-link']);
699 $js = "<script type='text/javascript'>\n";
700 $formName = "document." . (($mappingType == 'Export') ?
'Map' : 'Builder');
701 if (!empty($nullArray)) {
702 $js .= "var nullArray = [";
705 foreach ($nullArray as $element) {
706 $key = "{$element[0]}, {$element[1]}, {$element[2]}";
707 if (!isset($seen[$key])) {
708 $elements[] = "[$key]";
712 $js .= implode(', ', $elements);
715 for (var i=0;i<nullArray.length;i++) {
716 if ( {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'] ) {
717 {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'].style.display = '';
722 if (!empty($noneArray)) {
723 $js .= "var noneArray = [";
726 foreach ($noneArray as $element) {
727 $key = "{$element[0]}, {$element[1]}, {$element[2]}";
728 if (!isset($seen[$key])) {
729 $elements[] = "[$key]";
733 $js .= implode(', ', $elements);
736 for (var i=0;i<noneArray.length;i++) {
737 if ( {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'] ) {
738 {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'].style.display = 'none';
743 $js .= "</script>\n";
745 $form->assign('initHideBoxes', $js);
746 $form->assign('columnCount', $columnCount);
747 $form->assign('blockCount', $blockCount);
748 $form->setDefaults($defaults);
750 $form->setDefaultAction('refresh');
754 * @param string $mappingType
757 public static function getBasicFields($mappingType) {
758 $contactTypes = CRM_Contact_BAO_ContactType
::basicTypes();
760 foreach ($contactTypes as $contactType) {
761 if ($mappingType == 'Search Builder') {
762 // Get multiple custom group fields in this context
763 $contactFields = CRM_Contact_BAO_Contact
::exportableFields($contactType, FALSE, FALSE, FALSE, TRUE);
766 $contactFields = CRM_Contact_BAO_Contact
::exportableFields($contactType, FALSE, TRUE);
768 $contactFields = array_merge($contactFields, CRM_Contact_BAO_Query_Hook
::singleton()->getFields());
770 // Exclude the address options disabled in the Address Settings
771 $fields[$contactType] = CRM_Core_BAO_Address
::validateAddressOptions($contactFields);
772 ksort($fields[$contactType]);
773 if ($mappingType == 'Export') {
775 $relationshipTypes = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, NULL, NULL, $contactType);
776 asort($relationshipTypes);
778 foreach ($relationshipTypes as $key => $var) {
779 list($type) = explode('_', $key);
781 $relationships[$key]['title'] = $var;
782 $relationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
783 $relationships[$key]['export'] = TRUE;
784 $relationships[$key]['relationship_type_id'] = $type;
785 $relationships[$key]['related'] = TRUE;
786 $relationships[$key]['hasRelationType'] = 1;
789 if (!empty($relationships)) {
790 $fields[$contactType] = array_merge($fields[$contactType],
791 ['related' => ['title' => ts('- related contact info -')]],
798 // Get the current employer for mapping.
799 if ($mappingType == 'Export') {
800 $fields['Individual']['current_employer_id']['title'] = ts('Current Employer ID');
803 // Contact Sub Type For export
804 $subTypes = CRM_Contact_BAO_ContactType
::subTypeInfo();
805 foreach ($subTypes as $subType => $info) {
806 //adding subtype specific relationships CRM-5256
807 $csRelationships = [];
809 if ($mappingType == 'Export') {
810 $subTypeRelationshipTypes
811 = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, NULL, NULL, $info['parent'],
812 FALSE, 'label', TRUE, $subType);
814 foreach ($subTypeRelationshipTypes as $key => $var) {
815 if (!array_key_exists($key, $fields[$info['parent']])) {
816 list($type) = explode('_', $key);
818 $csRelationships[$key]['title'] = $var;
819 $csRelationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
820 $csRelationships[$key]['export'] = TRUE;
821 $csRelationships[$key]['relationship_type_id'] = $type;
822 $csRelationships[$key]['related'] = TRUE;
823 $csRelationships[$key]['hasRelationType'] = 1;
828 $fields[$subType] = $fields[$info['parent']] +
$csRelationships;
830 //custom fields for sub type
831 $subTypeFields = CRM_Core_BAO_CustomField
::getFieldsForImport($subType);
832 $fields[$subType] +
= $subTypeFields;
839 * Adds component fields to the export fields array; returns list of components.
841 * @param array $fields
842 * @param string $mappingType
843 * @param int $exportMode
846 public static function addComponentFields(&$fields, $mappingType, $exportMode) {
849 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
)) {
850 if (CRM_Core_Permission
::access('CiviContribute')) {
851 $fields['Contribution'] = CRM_Core_DAO
::getExportableFieldsWithPseudoConstants('CRM_Contribute_BAO_Contribution');
852 unset($fields['Contribution']['contribution_contact_id']);
853 $compArray['Contribution'] = ts('Contribution');
857 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
)) {
858 if (CRM_Core_Permission
::access('CiviEvent')) {
859 $fields['Participant'] = CRM_Event_BAO_Participant
::exportableFields();
860 //get the component payment fields
861 // @todo - review this - inconsistent with other entities & hacky.
862 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
863 $componentPaymentFields = [];
865 'componentPaymentField_total_amount' => ts('Total Amount'),
866 'componentPaymentField_contribution_status' => ts('Contribution Status'),
867 'componentPaymentField_received_date' => ts('Date Received'),
868 'componentPaymentField_payment_instrument' => ts('Payment Method'),
869 'componentPaymentField_transaction_id' => ts('Transaction ID'),
870 ] as $payField => $payTitle) {
871 $componentPaymentFields[$payField] = ['title' => $payTitle];
873 $fields['Participant'] = array_merge($fields['Participant'], $componentPaymentFields);
876 $compArray['Participant'] = ts('Participant');
880 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
)) {
881 if (CRM_Core_Permission
::access('CiviMember')) {
882 $fields['Membership'] = CRM_Member_BAO_Membership
::getMembershipFields($exportMode);
883 unset($fields['Membership']['membership_contact_id']);
884 $compArray['Membership'] = ts('Membership');
888 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
)) {
889 if (CRM_Core_Permission
::access('CiviPledge')) {
890 $fields['Pledge'] = CRM_Pledge_BAO_Pledge
::exportableFields();
891 unset($fields['Pledge']['pledge_contact_id']);
892 $compArray['Pledge'] = ts('Pledge');
896 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
)) {
897 if (CRM_Core_Permission
::access('CiviCase')) {
898 $fields['Case'] = CRM_Case_BAO_Case
::exportableFields();
899 $compArray['Case'] = ts('Case');
901 $fields['Activity'] = CRM_Activity_BAO_Activity
::exportableFields('Case');
902 $compArray['Activity'] = ts('Case Activity');
904 unset($fields['Case']['case_contact_id']);
907 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::GRANT_EXPORT
)) {
908 if (CRM_Core_Permission
::access('CiviGrant')) {
909 $fields['Grant'] = CRM_Grant_BAO_Grant
::exportableFields();
910 unset($fields['Grant']['grant_contact_id']);
911 if ($mappingType == 'Search Builder') {
912 unset($fields['Grant']['grant_type_id']);
914 $compArray['Grant'] = ts('Grant');
918 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
)) {
919 $fields['Activity'] = CRM_Activity_BAO_Activity
::exportableFields('Activity');
920 $compArray['Activity'] = ts('Activity');
927 * Get the parameters for a mapping field in a saveable format from the quickform mapping format.
929 * @param array $defaults
934 public static function getMappingParams($defaults, $v) {
935 $locationTypeId = NULL;
936 $saveMappingFields = $defaults;
938 $saveMappingFields['name'] = CRM_Utils_Array
::value('1', $v);
939 $saveMappingFields['contact_type'] = CRM_Utils_Array
::value('0', $v);
940 $locationId = CRM_Utils_Array
::value('2', $v);
941 $saveMappingFields['location_type_id'] = is_numeric($locationId) ?
$locationId : NULL;
943 if ($v[1] == 'phone') {
944 $saveMappingFields['phone_type_id'] = CRM_Utils_Array
::value('3', $v);
946 elseif ($v[1] == 'im') {
947 $saveMappingFields['im_provider_id'] = CRM_Utils_Array
::value('3', $v);
950 // Handle mapping for 'related contact' fields
951 if (count(explode('_', CRM_Utils_Array
::value('1', $v))) > 2) {
952 list($id, $first, $second) = explode('_', CRM_Utils_Array
::value('1', $v));
953 if (($first == 'a' && $second == 'b') ||
($first == 'b' && $second == 'a')) {
955 if (!empty($v['2'])) {
956 $saveMappingFields['name'] = CRM_Utils_Array
::value('2', $v);
958 elseif (!empty($v['4'])) {
959 $saveMappingFields['name'] = CRM_Utils_Array
::value('4', $v);
962 if (is_numeric(CRM_Utils_Array
::value('3', $v))) {
963 $locationTypeId = CRM_Utils_Array
::value('3', $v);
965 elseif (is_numeric(CRM_Utils_Array
::value('5', $v))) {
966 $locationTypeId = CRM_Utils_Array
::value('5', $v);
969 if (is_numeric(CRM_Utils_Array
::value('4', $v))) {
970 if ($saveMappingFields['name'] === 'im') {
971 $saveMappingFields['im_provider_id'] = $v[4];
974 $saveMappingFields['phone_type_id'] = CRM_Utils_Array
::value('4', $v);
977 elseif (is_numeric(CRM_Utils_Array
::value('6', $v))) {
978 $saveMappingFields['phone_type_id'] = CRM_Utils_Array
::value('6', $v);
981 $saveMappingFields['location_type_id'] = is_numeric($locationTypeId) ?
$locationTypeId : NULL;
982 $saveMappingFields['relationship_type_id'] = $id;
983 $saveMappingFields['relationship_direction'] = "{$first}_{$second}";
987 return $saveMappingFields;
991 * Load saved mapping.
993 * @param $mappingLocation
996 * @param $mappingName
997 * @param $mapperFields
998 * @param $mappingContactType
999 * @param $mappingRelation
1000 * @param array $specialFields
1001 * @param $mappingPhoneType
1003 * @param array $defaults
1004 * @param array $noneArray
1005 * @param $imProvider
1006 * @param $mappingImProvider
1007 * @param $mappingOperator
1008 * @param $mappingValue
1012 protected static function loadSavedMapping($mappingLocation, int $x, int $i, $mappingName, $mapperFields, $mappingContactType, $mappingRelation, array $specialFields, $mappingPhoneType, array $defaults, array $noneArray, $mappingImProvider, $mappingOperator, $mappingValue) {
1013 $locationId = isset($mappingLocation[$x][$i]) ?
$mappingLocation[$x][$i] : 0;
1014 if (isset($mappingName[$x][$i])) {
1015 if (is_array($mapperFields[$mappingContactType[$x][$i]])) {
1017 if (isset($mappingRelation[$x][$i])) {
1018 $relLocationId = isset($mappingLocation[$x][$i]) ?
$mappingLocation[$x][$i] : 0;
1019 if (!$relLocationId && in_array($mappingName[$x][$i], $specialFields)) {
1020 $relLocationId = " ";
1023 $relPhoneType = isset($mappingPhoneType[$x][$i]) ?
$mappingPhoneType[$x][$i] : NULL;
1025 $defaults["mapper[$x][$i]"] = [
1026 $mappingContactType[$x][$i],
1027 $mappingRelation[$x][$i],
1030 $mappingName[$x][$i],
1036 $noneArray[] = [$x, $i, 2];
1038 if (!$phoneType && !$imProvider) {
1039 $noneArray[] = [$x, $i, 3];
1041 if (!$mappingName[$x][$i]) {
1042 $noneArray[] = [$x, $i, 4];
1044 if (!$relLocationId) {
1045 $noneArray[] = [$x, $i, 5];
1047 if (!$relPhoneType) {
1048 $noneArray[] = [$x, $i, 6];
1050 $noneArray[] = [$x, $i, 2];
1053 $phoneType = isset($mappingPhoneType[$x][$i]) ?
$mappingPhoneType[$x][$i] : NULL;
1054 $imProvider = isset($mappingImProvider[$x][$i]) ?
$mappingImProvider[$x][$i] : NULL;
1055 if (!$locationId && in_array($mappingName[$x][$i], $specialFields)) {
1059 $defaults["mapper[$x][$i]"] = [
1060 $mappingContactType[$x][$i],
1061 $mappingName[$x][$i],
1065 if (!$mappingName[$x][$i]) {
1066 $noneArray[] = [$x, $i, 1];
1069 $noneArray[] = [$x, $i, 2];
1071 if (!$phoneType && !$imProvider) {
1072 $noneArray[] = [$x, $i, 3];
1075 $noneArray[] = [$x, $i, 4];
1076 $noneArray[] = [$x, $i, 5];
1077 $noneArray[] = [$x, $i, 6];
1082 if (CRM_Utils_Array
::value($i, CRM_Utils_Array
::value($x, $mappingOperator))) {
1083 $defaults["operator[$x][$i]"] = CRM_Utils_Array
::value($i, $mappingOperator[$x]);
1086 if (CRM_Utils_Array
::value($i, CRM_Utils_Array
::value($x, $mappingValue))) {
1087 $defaults["value[$x][$i]"] = CRM_Utils_Array
::value($i, $mappingValue[$x]);
1091 return [$mappingName, $defaults, $noneArray, $jsSet];
1095 * Function returns all custom fields with group title and
1098 * @param int $relationshipTypeId
1099 * Related relationship type id.
1102 * all custom field titles
1104 public function getRelationTypeCustomGroupData($relationshipTypeId) {
1106 $customFields = CRM_Core_BAO_CustomField
::getFields('Relationship', NULL, NULL, $relationshipTypeId, NULL, NULL);
1108 foreach ($customFields as $krelation => $vrelation) {
1109 $groupTitle[$vrelation['label']] = $vrelation['groupTitle'] . '...' . $vrelation['label'];
1115 * Function returns all Custom group Names.
1117 * @param int $customfieldId
1120 * @return null|string
1121 * $customGroupName all custom group names
1123 public static function getCustomGroupName($customfieldId) {
1124 if ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($customfieldId)) {
1125 $customGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $customFieldId, 'custom_group_id');
1126 $customGroupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'title');
1128 $customGroupName = CRM_Utils_String
::ellipsify($customGroupName, 13);
1130 return $customGroupName;
1135 * Function returns associated array of elements, that will be passed for search
1137 * @param array $params
1138 * Associated array of submitted values.
1140 * Row no of the fields.
1144 * formatted associated array of elements
1146 public static function formattedFields(&$params, $row = FALSE) {
1149 if (empty($params) ||
!isset($params['mapper'])) {
1153 $types = ['Individual', 'Organization', 'Household'];
1154 foreach ($params['mapper'] as $key => $value) {
1155 $contactType = NULL;
1156 foreach ($value as $k => $v) {
1157 if (in_array($v[0], $types)) {
1158 if ($contactType && $contactType != $v[0]) {
1159 CRM_Core_Error
::fatal(ts("Cannot have two clauses with different types: %1, %2",
1160 [1 => $contactType, 2 => $v[0]]
1163 $contactType = $v[0];
1165 if (!empty($v['1'])) {
1167 $v2 = CRM_Utils_Array
::value('2', $v);
1168 if ($v2 && trim($v2)) {
1169 $fldName .= "-{$v[2]}";
1172 $v3 = CRM_Utils_Array
::value('3', $v);
1173 if ($v3 && trim($v3)) {
1174 $fldName .= "-{$v[3]}";
1177 $value = $params['value'][$key][$k];
1179 if ($v[0] == 'Contribution' && substr($fldName, 0, 7) != 'custom_'
1180 && substr($fldName, 0, 10) != 'financial_'
1181 && substr($fldName, 0, 8) != 'payment_') {
1182 if (substr($fldName, 0, 13) != 'contribution_') {
1183 $fldName = 'contribution_' . $fldName;
1187 // CRM-14983: verify if values are comma separated convert to array
1188 if (!is_array($value) && strstr($params['operator'][$key][$k], 'IN')) {
1189 $value = explode(',', $value);
1190 $value = [$params['operator'][$key][$k] => $value];
1192 // CRM-19081 Fix legacy StateProvince Field Values.
1193 // These derive from smart groups created using search builder under older
1194 // CiviCRM versions.
1195 if (!is_numeric($value) && $fldName == 'state_province') {
1196 $value = CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Address', 'state_province_id', $value);
1202 $params['operator'][$key][$k],
1211 $params['operator'][$key][$k],
1230 //add sortByCharacter values
1231 if (isset($params['sortByCharacter'])) {
1235 $params['sortByCharacter'],
1244 * @param array $params
1248 public static function &returnProperties(&$params) {
1250 'contact_type' => 1,
1251 'contact_sub_type' => 1,
1255 if (empty($params) ||
empty($params['mapper'])) {
1259 $locationTypes = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
1260 foreach ($params['mapper'] as $key => $value) {
1261 foreach ($value as $k => $v) {
1263 if ($v[1] == 'groups' ||
$v[1] == 'tags') {
1267 if (isset($v[2]) && is_numeric($v[2])) {
1268 if (!array_key_exists('location', $fields)) {
1269 $fields['location'] = [];
1272 // make sure that we have a location fields and a location type for this
1273 $locationName = $locationTypes[$v[2]];
1274 if (!array_key_exists($locationName, $fields['location'])) {
1275 $fields['location'][$locationName] = [];
1276 $fields['location'][$locationName]['location_type'] = $v[2];
1279 if ($v[1] == 'phone' ||
$v[1] == 'email' ||
$v[1] == 'im') {
1280 // phone type handling
1282 $fields['location'][$locationName][$v[1] . "-" . $v[3]] = 1;
1285 $fields['location'][$locationName][$v[1]] = 1;
1289 $fields['location'][$locationName][$v[1]] = 1;
1303 * Save the mapping field info for search builder / export given the formvalues
1305 * @param array $params
1306 * Asscociated array of formvalues.
1307 * @param int $mappingId
1312 public static function saveMappingFields($params, $mappingId) {
1313 //delete mapping fields records for existing mapping
1314 $mappingFields = new CRM_Core_DAO_MappingField();
1315 $mappingFields->mapping_id
= $mappingId;
1316 $mappingFields->delete();
1318 if (empty($params['mapper'])) {
1322 //save record in mapping field table
1323 foreach ($params['mapper'] as $key => $value) {
1325 foreach ($value as $k => $v) {
1327 if (!empty($v['1'])) {
1328 $saveMappingParams = self
::getMappingParams(
1330 'mapping_id' => $mappingId,
1332 'operator' => $params['operator'][$key][$k] ??
NULL,
1333 'value' => $params['value'][$key][$k] ??
NULL,
1334 'column_number' => $colCnt,
1336 $saveMappingField = new CRM_Core_DAO_MappingField();
1337 $saveMappingField->copyValues($saveMappingParams, TRUE);
1338 $saveMappingField->save();