3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
33 class CRM_Core_BAO_Mapping
extends CRM_Core_DAO_Mapping
{
38 public function __construct() {
39 parent
::__construct();
43 * Fetch object based on array of properties.
45 * @param array $params
46 * (reference ) an assoc array of name/value pairs.
47 * @param array $defaults
48 * (reference ) an assoc array to hold the flattened values.
51 * CRM_Core_DAO_Mapping object on success, otherwise NULL
53 public static function retrieve(&$params, &$defaults) {
54 $mapping = new CRM_Core_DAO_Mapping();
55 $mapping->copyValues($params);
56 if ($mapping->find(TRUE)) {
57 CRM_Core_DAO
::storeValues($mapping, $defaults);
71 public static function del($id) {
72 // delete from mapping_field table
73 $mappingField = new CRM_Core_DAO_MappingField();
74 $mappingField->mapping_id
= $id;
75 $mappingField->delete();
77 // delete from mapping table
78 $mapping = new CRM_Core_DAO_Mapping();
80 if ($mapping->find(TRUE)) {
81 $result = $mapping->delete();
88 * Takes an associative array and creates a contact object.
90 * The function extract all the params it needs to initialize the create a
91 * contact object. the params array could contain additional unused name/value
94 * @param array $params
95 * An array of name/value pairs.
98 * CRM_Core_DAO_Mapper object on success, otherwise NULL
100 public static function add($params) {
101 $mapping = new CRM_Core_DAO_Mapping();
102 $mapping->copyValues($params);
109 * Get the list of mappings for a select or select2 element.
111 * @param string $mappingType
113 * @param bool $select2
117 * Array of mapping names, keyed by id.
119 public static function getMappings($mappingType, $select2 = FALSE) {
120 $result = civicrm_api3('Mapping', 'get', [
121 'mapping_type_id' => $mappingType,
122 'return' => ['name', 'description'],
130 foreach ($result['values'] as $id => $value) {
132 $item = ['id' => $id, 'text' => $value['name']];
133 if (!empty($value['description'])) {
134 $item['description'] = $value['description'];
139 $mapping[$id] = $value['name'];
146 * Get the mappings array, creating if it does not exist.
148 * @param string $mappingType
152 * Array of mapping names, keyed by id.
154 * @throws \CiviCRM_API3_Exception
156 public static function getCreateMappingValues($mappingType) {
158 return CRM_Core_BAO_Mapping
::getMappings($mappingType);
160 catch (CiviCRM_API3_Exception
$e) {
161 // Having a valid mapping_type_id is now enforced. However, rather than error let's
162 // add it. This is required for Multi value which could be done by upgrade script, but
163 // it feels like there could be other instances so this is safer.
164 $errorParams = $e->getExtraParams();
165 if ($errorParams['error_field'] === 'mapping_type_id') {
166 $mappingValues = civicrm_api3('Mapping', 'getoptions', ['field' => 'mapping_type_id']);
167 civicrm_api3('OptionValue', 'create', [
168 'option_group_id' => 'mapping_type',
169 'label' => $mappingType,
170 'value' => max(array_keys($mappingValues['values'])) +
1,
173 return CRM_Core_BAO_Mapping
::getMappings($mappingType);
180 * Get the mapping fields.
182 * @param int $mappingId
185 * @param bool $addPrimary
186 * Add the key 'Primary' when the field is a location field AND there is
187 * no location type (meaning Primary)?
190 * array of mapping fields
192 public static function getMappingFields($mappingId, $addPrimary = FALSE) {
193 //mapping is to be loaded from database
194 $mapping = new CRM_Core_DAO_MappingField();
195 $mapping->mapping_id
= $mappingId;
196 $mapping->orderBy('column_number');
199 $mappingName = $mappingLocation = $mappingContactType = $mappingPhoneType = [];
200 $mappingImProvider = $mappingRelation = $mappingOperator = $mappingValue = $mappingWebsiteType = [];
201 while ($mapping->fetch()) {
202 $mappingName[$mapping->grouping
][$mapping->column_number
] = $mapping->name
;
203 $mappingContactType[$mapping->grouping
][$mapping->column_number
] = $mapping->contact_type
;
205 if (!empty($mapping->location_type_id
)) {
206 $mappingLocation[$mapping->grouping
][$mapping->column_number
] = $mapping->location_type_id
;
208 elseif ($addPrimary) {
209 if (CRM_Contact_BAO_Contact
::isFieldHasLocationType($mapping->name
)) {
210 $mappingLocation[$mapping->grouping
][$mapping->column_number
] = ts('Primary');
213 $mappingLocation[$mapping->grouping
][$mapping->column_number
] = NULL;
217 if (!empty($mapping->phone_type_id
)) {
218 $mappingPhoneType[$mapping->grouping
][$mapping->column_number
] = $mapping->phone_type_id
;
221 // get IM service provider type id from mapping fields
222 if (!empty($mapping->im_provider_id
)) {
223 $mappingImProvider[$mapping->grouping
][$mapping->column_number
] = $mapping->im_provider_id
;
226 if (!empty($mapping->website_type_id
)) {
227 $mappingWebsiteType[$mapping->grouping
][$mapping->column_number
] = $mapping->website_type_id
;
230 if (!empty($mapping->relationship_type_id
)) {
231 $mappingRelation[$mapping->grouping
][$mapping->column_number
] = "{$mapping->relationship_type_id}_{$mapping->relationship_direction}";
234 if (!empty($mapping->operator
)) {
235 $mappingOperator[$mapping->grouping
][$mapping->column_number
] = $mapping->operator
;
238 if (!empty($mapping->value
)) {
239 $mappingValue[$mapping->grouping
][$mapping->column_number
] = $mapping->value
;
257 * Get un-indexed array of the field values for the given mapping id.
259 * For example if passing a mapping ID & name the returned array would look like
260 * ['First field name', 'second field name']
262 * @param int $mappingID
263 * @param string $fieldName
266 * @throws \CiviCRM_API3_Exception
268 public static function getMappingFieldValues($mappingID, $fieldName) {
269 return array_merge(CRM_Utils_Array
::collect($fieldName, civicrm_api3('MappingField', 'get', ['mapping_id' => $mappingID, 'return' => $fieldName])['values']));
273 * Check Duplicate Mapping Name.
275 * @param string $nameField
277 * @param string $mapTypeId
282 public static function checkMapping($nameField, $mapTypeId) {
283 $mapping = new CRM_Core_DAO_Mapping();
284 $mapping->name
= $nameField;
285 $mapping->mapping_type_id
= $mapTypeId;
286 return (bool) $mapping->find(TRUE);
290 * Function returns associated array of elements, that will be passed for search.
292 * @param int $smartGroupId
296 * associated array of elements
298 public static function getFormattedFields($smartGroupId) {
301 //get the fields from mapping table
302 $dao = new CRM_Core_DAO_MappingField();
303 $dao->mapping_id
= $smartGroupId;
305 while ($dao->fetch()) {
306 $fldName = $dao->name
;
307 if ($dao->location_type_id
) {
308 $fldName .= "-{$dao->location_type_id}";
310 if ($dao->phone_type
) {
311 $fldName .= "-{$dao->phone_type}";
313 $returnFields[$fldName]['value'] = $dao->value
;
314 $returnFields[$fldName]['op'] = $dao->operator
;
315 $returnFields[$fldName]['grouping'] = $dao->grouping
;
317 return $returnFields;
321 * Build the mapping form.
323 * @param CRM_Core_Form $form
324 * @param string $mappingType
325 * (Export/Search Builder). (Import apparently used to use this but does no longer).
326 * @param int $mappingId
327 * @param int $columnNo
328 * @param int $blockCount
329 * (no of blocks shown).
330 * @param int $exportMode
332 public static function buildMappingForm(&$form, $mappingType, $mappingId, $columnNo, $blockCount, $exportMode = NULL) {
334 $hasLocationTypes = [];
335 $hasRelationTypes = [];
337 //get the saved mapping details
339 if ($mappingType == 'Export') {
340 $columnCount = ['1' => $columnNo];
341 $form->applyFilter('saveMappingName', 'trim');
343 //to save the current mappings
344 if (!isset($mappingId)) {
345 $saveDetailsName = ts('Save this field mapping');
346 $form->add('text', 'saveMappingName', ts('Name'));
347 $form->add('text', 'saveMappingDesc', ts('Description'));
350 $form->assign('loadedMapping', $mappingId);
352 $params = ['id' => $mappingId];
354 $mappingDetails = CRM_Core_BAO_Mapping
::retrieve($params, $temp);
356 $form->assign('savedName', $mappingDetails->name
);
358 $form->add('hidden', 'mappingId', $mappingId);
360 $form->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL);
361 $saveDetailsName = ts('Save as a new field mapping');
362 $form->add('text', 'saveMappingName', ts('Name'));
363 $form->add('text', 'saveMappingDesc', ts('Description'));
366 $form->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, ['onclick' => "showSaveDetails(this)"]);
367 $form->addFormRule(['CRM_Export_Form_Map', 'formRule'], $form->get('mappingTypeId'));
369 elseif ($mappingType == 'Search Builder') {
370 $columnCount = $columnNo;
371 $form->addElement('submit', 'addBlock', ts('Also include contacts where'),
372 ['class' => 'submit-link']
376 $fields = self
::getBasicFields($mappingType);
378 // Unset groups, tags, notes for component export
379 if ($exportMode != CRM_Export_Form_Select
::CONTACT_EXPORT
) {
380 foreach (array_keys($fields) as $type) {
381 CRM_Utils_Array
::remove($fields[$type], 'groups', 'tags', 'notes');
385 if ($mappingType == 'Search Builder') {
386 //build the common contact fields array.
387 $fields['Contact'] = [];
388 foreach ($fields['Individual'] as $key => $value) {
389 if (!empty($fields['Household'][$key]) && !empty($fields['Organization'][$key])) {
390 $fields['Contact'][$key] = $value;
391 unset($fields['Organization'][$key],
392 $fields['Household'][$key],
393 $fields['Individual'][$key]);
396 if (array_key_exists('note', $fields['Contact'])) {
397 $noteTitle = $fields['Contact']['note']['title'];
398 $fields['Contact']['note']['title'] = $noteTitle . ': ' . ts('Body and Subject');
399 $fields['Contact']['note_body'] = ['title' => $noteTitle . ': ' . ts('Body Only'), 'name' => 'note_body'];
400 $fields['Contact']['note_subject'] = [
401 'title' => $noteTitle . ': ' . ts('Subject Only'),
402 'name' => 'note_subject',
407 // add component fields
408 $compArray = self
::addComponentFields($fields, $mappingType, $exportMode);
410 foreach ($fields as $key => $value) {
412 foreach ($value as $key1 => $value1) {
413 //CRM-2676, replacing the conflict for same custom field name from different custom group.
414 $customGroupName = self
::getCustomGroupName($key1);
416 if ($customGroupName) {
417 $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $customGroupName . ': ' . $value1['title'];
420 $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $value1['title'];
422 if (isset($value1['hasLocationType'])) {
423 $hasLocationTypes[$key][$key1] = $value1['hasLocationType'];
426 if (isset($value1['hasRelationType'])) {
427 $hasRelationTypes[$key][$key1] = $value1['hasRelationType'];
428 unset($relatedMapperFields[$key][$key1]);
432 if (array_key_exists('related', $relatedMapperFields[$key])) {
433 unset($relatedMapperFields[$key]['related']);
437 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
439 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
441 // FIXME: dirty hack to make the default option show up first. This
442 // avoids a mozilla browser bug with defaults on dynamically constructed
444 if ($defaultLocationType) {
445 $defaultLocation = $locationTypes[$defaultLocationType->id
];
446 unset($locationTypes[$defaultLocationType->id
]);
447 $locationTypes = [$defaultLocationType->id
=> $defaultLocation] +
$locationTypes;
450 $locationTypes = [' ' => ts('Primary')] +
$locationTypes;
452 // since we need a hierarchical list to display contact types & subtypes,
453 // this is what we going to display in first selector
454 $contactTypes = CRM_Contact_BAO_ContactType
::getSelectElements(FALSE, FALSE);
455 if ($mappingType == 'Search Builder') {
456 $contactTypes = ['Contact' => ts('Contacts')] +
$contactTypes;
459 $sel1 = ['' => ts('- select record type -')] +
$contactTypes +
$compArray;
461 foreach ($sel1 as $key => $sel) {
463 // sort everything BUT the contactType which is sorted separately by
464 // an initial commit of CRM-13278 (check ksort above)
465 if (!in_array($key, ['Individual', 'Household', 'Organization'])) {
466 asort($mapperFields[$key]);
468 $sel2[$key] = ['' => ts('- select field -')] +
$mapperFields[$key];
474 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
475 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
478 foreach ($sel1 as $k => $sel) {
480 foreach ($locationTypes as $key => $value) {
481 if (trim($key) != '') {
482 $sel4[$k]['phone'][$key] = &$phoneTypes;
483 $sel4[$k]['im'][$key] = &$imProviders;
489 foreach ($sel1 as $k => $sel) {
491 foreach ($mapperFields[$k] as $key => $value) {
492 if (isset($hasLocationTypes[$k][$key])) {
493 $sel3[$k][$key] = $locationTypes;
502 // Array for core fields and relationship custom data
503 $relationshipTypes = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE);
505 if ($mappingType == 'Export') {
506 foreach ($sel1 as $k => $sel) {
508 foreach ($mapperFields[$k] as $field => $dontCare) {
509 if (isset($hasRelationTypes[$k][$field])) {
510 list($id, $first, $second) = explode('_', $field);
511 // FIX ME: For now let's not expose custom data related to relationship
512 $relationshipCustomFields = [];
513 //$relationshipCustomFields = self::getRelationTypeCustomGroupData( $id );
514 //asort($relationshipCustomFields);
517 $relationshipType = new CRM_Contact_BAO_RelationshipType();
518 $relationshipType->id
= $id;
519 if ($relationshipType->find(TRUE)) {
520 $direction = "contact_sub_type_$second";
521 $target_type = 'contact_type_' . $second;
522 if (isset($relationshipType->$direction)) {
523 $relatedFields = array_merge((array) $relatedMapperFields[$relationshipType->$direction], (array) $relationshipCustomFields);
525 elseif (isset($relationshipType->$target_type)) {
526 $relatedFields = array_merge((array) $relatedMapperFields[$relationshipType->$target_type], (array) $relationshipCustomFields);
528 //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
530 $types = CRM_Contact_BAO_ContactType
::basicTypes(FALSE);
531 foreach ($types as $contactType => $label) {
532 $relatedFields = array_merge($relatedFields, (array) $relatedMapperFields[$label]);
534 $relatedFields = array_merge($relatedFields, (array) $relationshipCustomFields);
537 asort($relatedFields);
538 $sel5[$k][$field] = $relatedFields;
544 //Location Type for relationship fields
545 foreach ($sel5 as $k => $v) {
547 foreach ($v as $rel => $fields) {
548 foreach ($fields as $field => $fieldLabel) {
549 if (isset($hasLocationTypes[$k][$field])) {
550 $sel6[$k][$rel][$field] = $locationTypes;
557 //PhoneTypes for relationship fields
559 foreach ($sel6 as $k => $rel) {
561 foreach ($rel as $phonekey => $phonevalue) {
562 foreach ($locationTypes as $locType => $loc) {
563 if (trim($locType) != '') {
564 $sel7[$k][$phonekey]['phone'][$locType] = &$phoneTypes;
565 $sel7[$k][$phonekey]['im'][$locType] = &$imProviders;
573 //special fields that have location, hack for primary location
576 'supplemental_address_1',
577 'supplemental_address_2',
578 'supplemental_address_3',
581 'postal_code_suffix',
591 if (isset($mappingId)) {
592 list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingImProvider,
593 $mappingRelation, $mappingOperator, $mappingValue
594 ) = CRM_Core_BAO_Mapping
::getMappingFields($mappingId);
596 $blkCnt = count($mappingName);
597 if ($blkCnt >= $blockCount) {
598 $blockCount = $blkCnt +
1;
600 for ($x = 1; $x < $blockCount; $x++
) {
601 if (isset($mappingName[$x])) {
602 $colCnt = count($mappingName[$x]);
603 if ($colCnt >= $columnCount[$x]) {
604 $columnCount[$x] = $colCnt;
610 $form->_blockCount
= $blockCount;
611 $form->_columnCount
= $columnCount;
613 $form->set('blockCount', $form->_blockCount
);
614 $form->set('columnCount', $form->_columnCount
);
616 $defaults = $noneArray = $nullArray = [];
618 for ($x = 1; $x < $blockCount; $x++
) {
620 for ($i = 0; $i < $columnCount[$x]; $i++
) {
622 $sel = &$form->addElement('hierselect', "mapper[$x][$i]", ts('Mapper for Field %1', [1 => $i]), NULL);
625 if (isset($mappingId)) {
626 list($mappingName, $defaults, $noneArray, $jsSet) = self
::loadSavedMapping($mappingLocation, $x, $i, $mappingName, $mapperFields, $mappingContactType, $mappingRelation, $specialFields, $mappingPhoneType, $defaults, $noneArray, $mappingImProvider, $mappingOperator, $mappingValue);
628 //Fix for Search Builder
629 if ($mappingType == 'Export') {
636 $formValues = $form->exportValues();
638 if (empty($formValues)) {
639 // Incremented length for third select box(relationship type)
640 for ($k = 1; $k < $j; $k++
) {
641 $noneArray[] = [$x, $i, $k];
645 if (!empty($formValues['mapper'][$x])) {
646 foreach ($formValues['mapper'][$x] as $value) {
647 for ($k = 1; $k < $j; $k++
) {
648 if (!isset($formValues['mapper'][$x][$i][$k]) ||
649 (!$formValues['mapper'][$x][$i][$k])
651 $noneArray[] = [$x, $i, $k];
654 $nullArray[] = [$x, $i, $k];
660 for ($k = 1; $k < $j; $k++
) {
661 $noneArray[] = [$x, $i, $k];
666 //Fix for Search Builder
667 if ($mappingType == 'Export') {
668 if (!isset($mappingId) ||
$i >= count(reset($mappingName))) {
669 if (isset($formValues['mapper']) &&
670 isset($formValues['mapper'][$x][$i][1]) &&
671 array_key_exists($formValues['mapper'][$x][$i][1], $relationshipTypes)
673 $sel->setOptions([$sel1, $sel2, $sel5, $sel6, $sel7, $sel3, $sel4]);
676 $sel->setOptions([$sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7]);
680 $sel->setOptions([$sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7]);
684 $sel->setOptions([$sel1, $sel2, $sel3, $sel4]);
687 if ($mappingType == 'Search Builder') {
688 //CRM -2292, restricted array set
689 $operatorArray = ['' => ts('-operator-')] + CRM_Core_SelectValues
::getSearchBuilderOperators();
691 $form->add('select', "operator[$x][$i]", '', $operatorArray);
692 $form->add('text', "value[$x][$i]", '');
695 //end of columnCnt for
696 if ($mappingType == 'Search Builder') {
697 $title = ts('Another search field');
700 $title = ts('Select more fields');
703 $form->addElement('submit', "addMore[$x]", $title, ['class' => 'submit-link']);
707 $js = "<script type='text/javascript'>\n";
708 $formName = "document." . (($mappingType == 'Export') ?
'Map' : 'Builder');
709 if (!empty($nullArray)) {
710 $js .= "var nullArray = [";
713 foreach ($nullArray as $element) {
714 $key = "{$element[0]}, {$element[1]}, {$element[2]}";
715 if (!isset($seen[$key])) {
716 $elements[] = "[$key]";
720 $js .= implode(', ', $elements);
723 for (var i=0;i<nullArray.length;i++) {
724 if ( {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'] ) {
725 {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'].style.display = '';
730 if (!empty($noneArray)) {
731 $js .= "var noneArray = [";
734 foreach ($noneArray as $element) {
735 $key = "{$element[0]}, {$element[1]}, {$element[2]}";
736 if (!isset($seen[$key])) {
737 $elements[] = "[$key]";
741 $js .= implode(', ', $elements);
744 for (var i=0;i<noneArray.length;i++) {
745 if ( {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'] ) {
746 {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'].style.display = 'none';
751 $js .= "</script>\n";
753 $form->assign('initHideBoxes', $js);
754 $form->assign('columnCount', $columnCount);
755 $form->assign('blockCount', $blockCount);
756 $form->setDefaults($defaults);
758 $form->setDefaultAction('refresh');
762 * @param string $mappingType
765 public static function getBasicFields($mappingType) {
766 $contactTypes = CRM_Contact_BAO_ContactType
::basicTypes();
768 foreach ($contactTypes as $contactType) {
769 if ($mappingType == 'Search Builder') {
770 // Get multiple custom group fields in this context
771 $contactFields = CRM_Contact_BAO_Contact
::exportableFields($contactType, FALSE, FALSE, FALSE, TRUE);
774 $contactFields = CRM_Contact_BAO_Contact
::exportableFields($contactType, FALSE, TRUE);
776 $contactFields = array_merge($contactFields, CRM_Contact_BAO_Query_Hook
::singleton()->getFields());
778 // Exclude the address options disabled in the Address Settings
779 $fields[$contactType] = CRM_Core_BAO_Address
::validateAddressOptions($contactFields);
780 ksort($fields[$contactType]);
781 if ($mappingType == 'Export') {
783 $relationshipTypes = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, NULL, NULL, $contactType);
784 asort($relationshipTypes);
786 foreach ($relationshipTypes as $key => $var) {
787 list($type) = explode('_', $key);
789 $relationships[$key]['title'] = $var;
790 $relationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
791 $relationships[$key]['export'] = TRUE;
792 $relationships[$key]['relationship_type_id'] = $type;
793 $relationships[$key]['related'] = TRUE;
794 $relationships[$key]['hasRelationType'] = 1;
797 if (!empty($relationships)) {
798 $fields[$contactType] = array_merge($fields[$contactType],
799 ['related' => ['title' => ts('- related contact info -')]],
806 // Get the current employer for mapping.
807 if ($mappingType == 'Export') {
808 $fields['Individual']['current_employer_id']['title'] = ts('Current Employer ID');
811 // Contact Sub Type For export
812 $subTypes = CRM_Contact_BAO_ContactType
::subTypeInfo();
813 foreach ($subTypes as $subType => $info) {
814 //adding subtype specific relationships CRM-5256
815 $csRelationships = [];
817 if ($mappingType == 'Export') {
818 $subTypeRelationshipTypes
819 = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, NULL, NULL, $info['parent'],
820 FALSE, 'label', TRUE, $subType);
822 foreach ($subTypeRelationshipTypes as $key => $var) {
823 if (!array_key_exists($key, $fields[$info['parent']])) {
824 list($type) = explode('_', $key);
826 $csRelationships[$key]['title'] = $var;
827 $csRelationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
828 $csRelationships[$key]['export'] = TRUE;
829 $csRelationships[$key]['relationship_type_id'] = $type;
830 $csRelationships[$key]['related'] = TRUE;
831 $csRelationships[$key]['hasRelationType'] = 1;
836 $fields[$subType] = $fields[$info['parent']] +
$csRelationships;
838 //custom fields for sub type
839 $subTypeFields = CRM_Core_BAO_CustomField
::getFieldsForImport($subType);
840 $fields[$subType] +
= $subTypeFields;
847 * Adds component fields to the export fields array; returns list of components.
849 * @param array $fields
850 * @param string $mappingType
851 * @param int $exportMode
854 public static function addComponentFields(&$fields, $mappingType, $exportMode) {
857 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
)) {
858 if (CRM_Core_Permission
::access('CiviContribute')) {
859 $fields['Contribution'] = CRM_Core_DAO
::getExportableFieldsWithPseudoConstants('CRM_Contribute_BAO_Contribution');
860 unset($fields['Contribution']['contribution_contact_id']);
861 $compArray['Contribution'] = ts('Contribution');
865 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
)) {
866 if (CRM_Core_Permission
::access('CiviEvent')) {
867 $fields['Participant'] = CRM_Event_BAO_Participant
::exportableFields();
868 //get the component payment fields
869 // @todo - review this - inconsistent with other entities & hacky.
870 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
871 $componentPaymentFields = [];
873 'componentPaymentField_total_amount' => ts('Total Amount'),
874 'componentPaymentField_contribution_status' => ts('Contribution Status'),
875 'componentPaymentField_received_date' => ts('Date Received'),
876 'componentPaymentField_payment_instrument' => ts('Payment Method'),
877 'componentPaymentField_transaction_id' => ts('Transaction ID'),
878 ] as $payField => $payTitle) {
879 $componentPaymentFields[$payField] = ['title' => $payTitle];
881 $fields['Participant'] = array_merge($fields['Participant'], $componentPaymentFields);
884 $compArray['Participant'] = ts('Participant');
888 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
)) {
889 if (CRM_Core_Permission
::access('CiviMember')) {
890 $fields['Membership'] = CRM_Member_BAO_Membership
::getMembershipFields($exportMode);
891 unset($fields['Membership']['membership_contact_id']);
892 $compArray['Membership'] = ts('Membership');
896 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
)) {
897 if (CRM_Core_Permission
::access('CiviPledge')) {
898 $fields['Pledge'] = CRM_Pledge_BAO_Pledge
::exportableFields();
899 unset($fields['Pledge']['pledge_contact_id']);
900 $compArray['Pledge'] = ts('Pledge');
904 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
)) {
905 if (CRM_Core_Permission
::access('CiviCase')) {
906 $fields['Case'] = CRM_Case_BAO_Case
::exportableFields();
907 $compArray['Case'] = ts('Case');
909 $fields['Activity'] = CRM_Activity_BAO_Activity
::exportableFields('Case');
910 $compArray['Activity'] = ts('Case Activity');
912 unset($fields['Case']['case_contact_id']);
915 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::GRANT_EXPORT
)) {
916 if (CRM_Core_Permission
::access('CiviGrant')) {
917 $fields['Grant'] = CRM_Grant_BAO_Grant
::exportableFields();
918 unset($fields['Grant']['grant_contact_id']);
919 if ($mappingType == 'Search Builder') {
920 unset($fields['Grant']['grant_type_id']);
922 $compArray['Grant'] = ts('Grant');
926 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
)) {
927 $fields['Activity'] = CRM_Activity_BAO_Activity
::exportableFields('Activity');
928 $compArray['Activity'] = ts('Activity');
935 * Get the parameters for a mapping field in a saveable format from the quickform mapping format.
937 * @param array $defaults
942 public static function getMappingParams($defaults, $v) {
943 $locationTypeId = NULL;
944 $saveMappingFields = $defaults;
946 $saveMappingFields['name'] = CRM_Utils_Array
::value('1', $v);
947 $saveMappingFields['contact_type'] = CRM_Utils_Array
::value('0', $v);
948 $locationId = CRM_Utils_Array
::value('2', $v);
949 $saveMappingFields['location_type_id'] = is_numeric($locationId) ?
$locationId : NULL;
951 if ($v[1] == 'phone') {
952 $saveMappingFields['phone_type_id'] = CRM_Utils_Array
::value('3', $v);
954 elseif ($v[1] == 'im') {
955 $saveMappingFields['im_provider_id'] = CRM_Utils_Array
::value('3', $v);
958 // Handle mapping for 'related contact' fields
959 if (count(explode('_', CRM_Utils_Array
::value('1', $v))) > 2) {
960 list($id, $first, $second) = explode('_', CRM_Utils_Array
::value('1', $v));
961 if (($first == 'a' && $second == 'b') ||
($first == 'b' && $second == 'a')) {
963 if (!empty($v['2'])) {
964 $saveMappingFields['name'] = CRM_Utils_Array
::value('2', $v);
966 elseif (!empty($v['4'])) {
967 $saveMappingFields['name'] = CRM_Utils_Array
::value('4', $v);
970 if (is_numeric(CRM_Utils_Array
::value('3', $v))) {
971 $locationTypeId = CRM_Utils_Array
::value('3', $v);
973 elseif (is_numeric(CRM_Utils_Array
::value('5', $v))) {
974 $locationTypeId = CRM_Utils_Array
::value('5', $v);
977 if (is_numeric(CRM_Utils_Array
::value('4', $v))) {
978 if ($saveMappingFields['name'] === 'im') {
979 $saveMappingFields['im_provider_id'] = $v[4];
982 $saveMappingFields['phone_type_id'] = CRM_Utils_Array
::value('4', $v);
985 elseif (is_numeric(CRM_Utils_Array
::value('6', $v))) {
986 $saveMappingFields['phone_type_id'] = CRM_Utils_Array
::value('6', $v);
989 $saveMappingFields['location_type_id'] = is_numeric($locationTypeId) ?
$locationTypeId : NULL;
990 $saveMappingFields['relationship_type_id'] = $id;
991 $saveMappingFields['relationship_direction'] = "{$first}_{$second}";
995 return $saveMappingFields;
999 * Load saved mapping.
1001 * @param $mappingLocation
1004 * @param $mappingName
1005 * @param $mapperFields
1006 * @param $mappingContactType
1007 * @param $mappingRelation
1008 * @param array $specialFields
1009 * @param $mappingPhoneType
1011 * @param array $defaults
1012 * @param array $noneArray
1013 * @param $imProvider
1014 * @param $mappingImProvider
1015 * @param $mappingOperator
1016 * @param $mappingValue
1020 protected static function loadSavedMapping($mappingLocation, int $x, int $i, $mappingName, $mapperFields, $mappingContactType, $mappingRelation, array $specialFields, $mappingPhoneType, array $defaults, array $noneArray, $mappingImProvider, $mappingOperator, $mappingValue) {
1021 $locationId = isset($mappingLocation[$x][$i]) ?
$mappingLocation[$x][$i] : 0;
1022 if (isset($mappingName[$x][$i])) {
1023 if (is_array($mapperFields[$mappingContactType[$x][$i]])) {
1025 if (isset($mappingRelation[$x][$i])) {
1026 $relLocationId = isset($mappingLocation[$x][$i]) ?
$mappingLocation[$x][$i] : 0;
1027 if (!$relLocationId && in_array($mappingName[$x][$i], $specialFields)) {
1028 $relLocationId = " ";
1031 $relPhoneType = isset($mappingPhoneType[$x][$i]) ?
$mappingPhoneType[$x][$i] : NULL;
1033 $defaults["mapper[$x][$i]"] = [
1034 $mappingContactType[$x][$i],
1035 $mappingRelation[$x][$i],
1038 $mappingName[$x][$i],
1044 $noneArray[] = [$x, $i, 2];
1046 if (!$phoneType && !$imProvider) {
1047 $noneArray[] = [$x, $i, 3];
1049 if (!$mappingName[$x][$i]) {
1050 $noneArray[] = [$x, $i, 4];
1052 if (!$relLocationId) {
1053 $noneArray[] = [$x, $i, 5];
1055 if (!$relPhoneType) {
1056 $noneArray[] = [$x, $i, 6];
1058 $noneArray[] = [$x, $i, 2];
1061 $phoneType = isset($mappingPhoneType[$x][$i]) ?
$mappingPhoneType[$x][$i] : NULL;
1062 $imProvider = isset($mappingImProvider[$x][$i]) ?
$mappingImProvider[$x][$i] : NULL;
1063 if (!$locationId && in_array($mappingName[$x][$i], $specialFields)) {
1067 $defaults["mapper[$x][$i]"] = [
1068 $mappingContactType[$x][$i],
1069 $mappingName[$x][$i],
1073 if (!$mappingName[$x][$i]) {
1074 $noneArray[] = [$x, $i, 1];
1077 $noneArray[] = [$x, $i, 2];
1079 if (!$phoneType && !$imProvider) {
1080 $noneArray[] = [$x, $i, 3];
1083 $noneArray[] = [$x, $i, 4];
1084 $noneArray[] = [$x, $i, 5];
1085 $noneArray[] = [$x, $i, 6];
1090 if (CRM_Utils_Array
::value($i, CRM_Utils_Array
::value($x, $mappingOperator))) {
1091 $defaults["operator[$x][$i]"] = CRM_Utils_Array
::value($i, $mappingOperator[$x]);
1094 if (CRM_Utils_Array
::value($i, CRM_Utils_Array
::value($x, $mappingValue))) {
1095 $defaults["value[$x][$i]"] = CRM_Utils_Array
::value($i, $mappingValue[$x]);
1099 return [$mappingName, $defaults, $noneArray, $jsSet];
1103 * Function returns all custom fields with group title and
1106 * @param int $relationshipTypeId
1107 * Related relationship type id.
1110 * all custom field titles
1112 public function getRelationTypeCustomGroupData($relationshipTypeId) {
1114 $customFields = CRM_Core_BAO_CustomField
::getFields('Relationship', NULL, NULL, $relationshipTypeId, NULL, NULL);
1116 foreach ($customFields as $krelation => $vrelation) {
1117 $groupTitle[$vrelation['label']] = $vrelation['groupTitle'] . '...' . $vrelation['label'];
1123 * Function returns all Custom group Names.
1125 * @param int $customfieldId
1128 * @return null|string
1129 * $customGroupName all custom group names
1131 public static function getCustomGroupName($customfieldId) {
1132 if ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($customfieldId)) {
1133 $customGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $customFieldId, 'custom_group_id');
1134 $customGroupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'title');
1136 $customGroupName = CRM_Utils_String
::ellipsify($customGroupName, 13);
1138 return $customGroupName;
1143 * Function returns associated array of elements, that will be passed for search
1145 * @param array $params
1146 * Associated array of submitted values.
1148 * Row no of the fields.
1152 * formatted associated array of elements
1154 public static function formattedFields(&$params, $row = FALSE) {
1157 if (empty($params) ||
!isset($params['mapper'])) {
1161 $types = ['Individual', 'Organization', 'Household'];
1162 foreach ($params['mapper'] as $key => $value) {
1163 $contactType = NULL;
1164 foreach ($value as $k => $v) {
1165 if (in_array($v[0], $types)) {
1166 if ($contactType && $contactType != $v[0]) {
1167 CRM_Core_Error
::fatal(ts("Cannot have two clauses with different types: %1, %2",
1168 [1 => $contactType, 2 => $v[0]]
1171 $contactType = $v[0];
1173 if (!empty($v['1'])) {
1175 $v2 = CRM_Utils_Array
::value('2', $v);
1176 if ($v2 && trim($v2)) {
1177 $fldName .= "-{$v[2]}";
1180 $v3 = CRM_Utils_Array
::value('3', $v);
1181 if ($v3 && trim($v3)) {
1182 $fldName .= "-{$v[3]}";
1185 $value = $params['value'][$key][$k];
1187 if ($v[0] == 'Contribution' && substr($fldName, 0, 7) != 'custom_'
1188 && substr($fldName, 0, 10) != 'financial_'
1189 && substr($fldName, 0, 8) != 'payment_') {
1190 if (substr($fldName, 0, 13) != 'contribution_') {
1191 $fldName = 'contribution_' . $fldName;
1195 // CRM-14983: verify if values are comma separated convert to array
1196 if (!is_array($value) && strstr($params['operator'][$key][$k], 'IN')) {
1197 $value = explode(',', $value);
1198 $value = [$params['operator'][$key][$k] => $value];
1200 // CRM-19081 Fix legacy StateProvince Field Values.
1201 // These derive from smart groups created using search builder under older
1202 // CiviCRM versions.
1203 if (!is_numeric($value) && $fldName == 'state_province') {
1204 $value = CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Address', 'state_province_id', $value);
1210 $params['operator'][$key][$k],
1219 $params['operator'][$key][$k],
1238 //add sortByCharacter values
1239 if (isset($params['sortByCharacter'])) {
1243 $params['sortByCharacter'],
1252 * @param array $params
1256 public static function &returnProperties(&$params) {
1258 'contact_type' => 1,
1259 'contact_sub_type' => 1,
1263 if (empty($params) ||
empty($params['mapper'])) {
1267 $locationTypes = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
1268 foreach ($params['mapper'] as $key => $value) {
1269 foreach ($value as $k => $v) {
1271 if ($v[1] == 'groups' ||
$v[1] == 'tags') {
1275 if (isset($v[2]) && is_numeric($v[2])) {
1276 if (!array_key_exists('location', $fields)) {
1277 $fields['location'] = [];
1280 // make sure that we have a location fields and a location type for this
1281 $locationName = $locationTypes[$v[2]];
1282 if (!array_key_exists($locationName, $fields['location'])) {
1283 $fields['location'][$locationName] = [];
1284 $fields['location'][$locationName]['location_type'] = $v[2];
1287 if ($v[1] == 'phone' ||
$v[1] == 'email' ||
$v[1] == 'im') {
1288 // phone type handling
1290 $fields['location'][$locationName][$v[1] . "-" . $v[3]] = 1;
1293 $fields['location'][$locationName][$v[1]] = 1;
1297 $fields['location'][$locationName][$v[1]] = 1;
1311 * Save the mapping field info for search builder / export given the formvalues
1313 * @param array $params
1314 * Asscociated array of formvalues.
1315 * @param int $mappingId
1320 public static function saveMappingFields($params, $mappingId) {
1321 //delete mapping fields records for existing mapping
1322 $mappingFields = new CRM_Core_DAO_MappingField();
1323 $mappingFields->mapping_id
= $mappingId;
1324 $mappingFields->delete();
1326 if (empty($params['mapper'])) {
1330 //save record in mapping field table
1331 foreach ($params['mapper'] as $key => $value) {
1333 foreach ($value as $k => $v) {
1335 if (!empty($v['1'])) {
1336 $saveMappingParams = self
::getMappingParams(
1338 'mapping_id' => $mappingId,
1340 'operator' => $params['operator'][$key][$k] ??
NULL,
1341 'value' => $params['value'][$key][$k] ??
NULL,
1342 'column_number' => $colCnt,
1344 $saveMappingField = new CRM_Core_DAO_MappingField();
1345 $saveMappingField->copyValues($saveMappingParams, TRUE);
1346 $saveMappingField->save();