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 $contactTypes = CRM_Contact_BAO_ContactType
::basicTypes();
377 $fields = self
::getBasicFields($mappingType);
379 // Unset groups, tags, notes for component export
380 if ($exportMode != CRM_Export_Form_Select
::CONTACT_EXPORT
) {
381 foreach (array_keys($fields) as $type) {
382 CRM_Utils_Array
::remove($fields[$type], 'groups', 'tags', 'notes');
386 if ($mappingType == 'Search Builder') {
387 // Build the common contact fields array.
388 $fields['Contact'] = [];
389 foreach ($fields[$contactTypes[0]] as $key => $value) {
390 // If a field exists across all contact types, move it to the "Contact" selector
392 foreach ($contactTypes as $type) {
393 if (!isset($fields[$type][$key])) {
394 $ubiquitious = FALSE;
398 $fields['Contact'][$key] = $value;
399 foreach ($contactTypes as $type) {
400 unset($fields[$type][$key]);
404 if (array_key_exists('note', $fields['Contact'])) {
405 $noteTitle = $fields['Contact']['note']['title'];
406 $fields['Contact']['note']['title'] = $noteTitle . ': ' . ts('Body and Subject');
407 $fields['Contact']['note_body'] = ['title' => $noteTitle . ': ' . ts('Body Only'), 'name' => 'note_body'];
408 $fields['Contact']['note_subject'] = [
409 'title' => $noteTitle . ': ' . ts('Subject Only'),
410 'name' => 'note_subject',
415 // add component fields
416 $compArray = self
::addComponentFields($fields, $mappingType, $exportMode);
418 foreach ($fields as $key => $value) {
420 foreach ($value as $key1 => $value1) {
421 //CRM-2676, replacing the conflict for same custom field name from different custom group.
422 $customGroupName = self
::getCustomGroupName($key1);
424 if ($customGroupName) {
425 $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $customGroupName . ': ' . $value1['title'];
428 $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $value1['title'];
430 if (isset($value1['hasLocationType'])) {
431 $hasLocationTypes[$key][$key1] = $value1['hasLocationType'];
434 if (isset($value1['hasRelationType'])) {
435 $hasRelationTypes[$key][$key1] = $value1['hasRelationType'];
436 unset($relatedMapperFields[$key][$key1]);
440 if (isset($relatedMapperFields[$key]['related'])) {
441 unset($relatedMapperFields[$key]['related']);
445 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
447 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
449 // FIXME: dirty hack to make the default option show up first. This
450 // avoids a mozilla browser bug with defaults on dynamically constructed
452 if ($defaultLocationType) {
453 $defaultLocation = $locationTypes[$defaultLocationType->id
];
454 unset($locationTypes[$defaultLocationType->id
]);
455 $locationTypes = [$defaultLocationType->id
=> $defaultLocation] +
$locationTypes;
458 $locationTypes = [' ' => ts('Primary')] +
$locationTypes;
460 // since we need a hierarchical list to display contact types & subtypes,
461 // this is what we going to display in first selector
462 $contactTypeSelect = CRM_Contact_BAO_ContactType
::getSelectElements(FALSE, FALSE);
463 if ($mappingType == 'Search Builder') {
464 $contactTypeSelect = ['Contact' => ts('Contacts')] +
$contactTypeSelect;
467 $sel1 = ['' => ts('- select record type -')] +
$contactTypeSelect +
$compArray;
469 foreach ($sel1 as $key => $sel) {
471 // sort everything BUT the contactType which is sorted separately by
472 // an initial commit of CRM-13278 (check ksort above)
473 if (!in_array($key, $contactTypes)) {
474 asort($mapperFields[$key]);
476 $sel2[$key] = ['' => ts('- select field -')] +
$mapperFields[$key];
482 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
483 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
486 foreach ($sel1 as $k => $sel) {
488 foreach ($locationTypes as $key => $value) {
489 if (trim($key) != '') {
490 $sel4[$k]['phone'][$key] = &$phoneTypes;
491 $sel4[$k]['im'][$key] = &$imProviders;
497 foreach ($sel1 as $k => $sel) {
499 foreach ($mapperFields[$k] as $key => $value) {
500 if (isset($hasLocationTypes[$k][$key])) {
501 $sel3[$k][$key] = $locationTypes;
510 // Array for core fields and relationship custom data
511 $relationshipTypes = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE);
513 if ($mappingType == 'Export') {
514 foreach ($sel1 as $k => $sel) {
516 foreach ($mapperFields[$k] as $field => $dontCare) {
517 if (isset($hasRelationTypes[$k][$field])) {
518 list($id, $first, $second) = explode('_', $field);
519 // FIX ME: For now let's not expose custom data related to relationship
520 $relationshipCustomFields = [];
521 //$relationshipCustomFields = self::getRelationTypeCustomGroupData( $id );
522 //asort($relationshipCustomFields);
525 $relationshipType = new CRM_Contact_BAO_RelationshipType();
526 $relationshipType->id
= $id;
527 if ($relationshipType->find(TRUE)) {
528 $direction = "contact_sub_type_$second";
529 $target_type = 'contact_type_' . $second;
530 if (isset($relationshipType->$direction)) {
531 $relatedFields = array_merge((array) $relatedMapperFields[$relationshipType->$direction], (array) $relationshipCustomFields);
533 elseif (isset($relationshipType->$target_type)) {
534 $relatedFields = array_merge((array) $relatedMapperFields[$relationshipType->$target_type], (array) $relationshipCustomFields);
536 //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
538 $types = CRM_Contact_BAO_ContactType
::basicTypes(FALSE);
539 foreach ($types as $contactType => $label) {
540 $relatedFields = array_merge($relatedFields, (array) $relatedMapperFields[$label]);
542 $relatedFields = array_merge($relatedFields, (array) $relationshipCustomFields);
545 asort($relatedFields);
546 $sel5[$k][$field] = $relatedFields;
552 //Location Type for relationship fields
553 foreach ($sel5 as $k => $v) {
555 foreach ($v as $rel => $fields) {
556 foreach ($fields as $field => $fieldLabel) {
557 if (isset($hasLocationTypes[$k][$field])) {
558 $sel6[$k][$rel][$field] = $locationTypes;
565 //PhoneTypes for relationship fields
567 foreach ($sel6 as $k => $rel) {
569 foreach ($rel as $phonekey => $phonevalue) {
570 foreach ($locationTypes as $locType => $loc) {
571 if (trim($locType) != '') {
572 $sel7[$k][$phonekey]['phone'][$locType] = &$phoneTypes;
573 $sel7[$k][$phonekey]['im'][$locType] = &$imProviders;
581 //special fields that have location, hack for primary location
584 'supplemental_address_1',
585 'supplemental_address_2',
586 'supplemental_address_3',
589 'postal_code_suffix',
599 if (isset($mappingId)) {
600 list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingImProvider,
601 $mappingRelation, $mappingOperator, $mappingValue
602 ) = CRM_Core_BAO_Mapping
::getMappingFields($mappingId);
604 $blkCnt = count($mappingName);
605 if ($blkCnt >= $blockCount) {
606 $blockCount = $blkCnt +
1;
608 for ($x = 1; $x < $blockCount; $x++
) {
609 if (isset($mappingName[$x])) {
610 $colCnt = count($mappingName[$x]);
611 if ($colCnt >= $columnCount[$x]) {
612 $columnCount[$x] = $colCnt;
618 $form->_blockCount
= $blockCount;
619 $form->_columnCount
= $columnCount;
621 $form->set('blockCount', $form->_blockCount
);
622 $form->set('columnCount', $form->_columnCount
);
624 $defaults = $noneArray = $nullArray = [];
626 for ($x = 1; $x < $blockCount; $x++
) {
628 for ($i = 0; $i < $columnCount[$x]; $i++
) {
630 $sel = &$form->addElement('hierselect', "mapper[$x][$i]", ts('Mapper for Field %1', [1 => $i]), NULL);
633 if (isset($mappingId)) {
634 list($mappingName, $defaults, $noneArray, $jsSet) = self
::loadSavedMapping($mappingLocation, $x, $i, $mappingName, $mapperFields, $mappingContactType, $mappingRelation, $specialFields, $mappingPhoneType, $defaults, $noneArray, $mappingImProvider, $mappingOperator, $mappingValue);
636 //Fix for Search Builder
637 if ($mappingType == 'Export') {
644 $formValues = $form->exportValues();
646 if (empty($formValues)) {
647 // Incremented length for third select box(relationship type)
648 for ($k = 1; $k < $j; $k++
) {
649 $noneArray[] = [$x, $i, $k];
653 if (!empty($formValues['mapper'][$x])) {
654 foreach ($formValues['mapper'][$x] as $value) {
655 for ($k = 1; $k < $j; $k++
) {
656 if (!isset($formValues['mapper'][$x][$i][$k]) ||
657 (!$formValues['mapper'][$x][$i][$k])
659 $noneArray[] = [$x, $i, $k];
662 $nullArray[] = [$x, $i, $k];
668 for ($k = 1; $k < $j; $k++
) {
669 $noneArray[] = [$x, $i, $k];
674 //Fix for Search Builder
675 if ($mappingType == 'Export') {
676 if (!isset($mappingId) ||
$i >= count(reset($mappingName))) {
677 if (isset($formValues['mapper']) &&
678 isset($formValues['mapper'][$x][$i][1]) &&
679 array_key_exists($formValues['mapper'][$x][$i][1], $relationshipTypes)
681 $sel->setOptions([$sel1, $sel2, $sel5, $sel6, $sel7, $sel3, $sel4]);
684 $sel->setOptions([$sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7]);
688 $sel->setOptions([$sel1, $sel2, $sel3, $sel4, $sel5, $sel6, $sel7]);
692 $sel->setOptions([$sel1, $sel2, $sel3, $sel4]);
695 if ($mappingType == 'Search Builder') {
696 //CRM -2292, restricted array set
697 $operatorArray = ['' => ts('-operator-')] + CRM_Core_SelectValues
::getSearchBuilderOperators();
699 $form->add('select', "operator[$x][$i]", '', $operatorArray);
700 $form->add('text', "value[$x][$i]", '');
703 //end of columnCnt for
704 if ($mappingType == 'Search Builder') {
705 $title = ts('Another search field');
708 $title = ts('Select more fields');
711 $form->addElement('submit', "addMore[$x]", $title, ['class' => 'submit-link']);
715 $js = "<script type='text/javascript'>\n";
716 $formName = "document." . (($mappingType == 'Export') ?
'Map' : 'Builder');
717 if (!empty($nullArray)) {
718 $js .= "var nullArray = [";
721 foreach ($nullArray as $element) {
722 $key = "{$element[0]}, {$element[1]}, {$element[2]}";
723 if (!isset($seen[$key])) {
724 $elements[] = "[$key]";
728 $js .= implode(', ', $elements);
731 for (var i=0;i<nullArray.length;i++) {
732 if ( {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'] ) {
733 {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'].style.display = '';
738 if (!empty($noneArray)) {
739 $js .= "var noneArray = [";
742 foreach ($noneArray as $element) {
743 $key = "{$element[0]}, {$element[1]}, {$element[2]}";
744 if (!isset($seen[$key])) {
745 $elements[] = "[$key]";
749 $js .= implode(', ', $elements);
752 for (var i=0;i<noneArray.length;i++) {
753 if ( {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'] ) {
754 {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'].style.display = 'none';
759 $js .= "</script>\n";
761 $form->assign('initHideBoxes', $js);
762 $form->assign('columnCount', $columnCount);
763 $form->assign('blockCount', $blockCount);
764 $form->setDefaults($defaults);
766 $form->setDefaultAction('refresh');
770 * @param string $mappingType
773 public static function getBasicFields($mappingType) {
774 $contactTypes = CRM_Contact_BAO_ContactType
::basicTypes();
776 foreach ($contactTypes as $contactType) {
777 if ($mappingType == 'Search Builder') {
778 // Get multiple custom group fields in this context
779 $contactFields = CRM_Contact_BAO_Contact
::exportableFields($contactType, FALSE, FALSE, FALSE, TRUE);
782 $contactFields = CRM_Contact_BAO_Contact
::exportableFields($contactType, FALSE, TRUE);
784 $contactFields = array_merge($contactFields, CRM_Contact_BAO_Query_Hook
::singleton()->getFields());
786 // Exclude the address options disabled in the Address Settings
787 $fields[$contactType] = CRM_Core_BAO_Address
::validateAddressOptions($contactFields);
788 ksort($fields[$contactType]);
789 if ($mappingType == 'Export') {
791 $relationshipTypes = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, NULL, NULL, $contactType);
792 asort($relationshipTypes);
794 foreach ($relationshipTypes as $key => $var) {
795 list($type) = explode('_', $key);
797 $relationships[$key]['title'] = $var;
798 $relationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
799 $relationships[$key]['export'] = TRUE;
800 $relationships[$key]['relationship_type_id'] = $type;
801 $relationships[$key]['related'] = TRUE;
802 $relationships[$key]['hasRelationType'] = 1;
805 if (!empty($relationships)) {
806 $fields[$contactType] = array_merge($fields[$contactType],
807 ['related' => ['title' => ts('- related contact info -')]],
814 // Get the current employer for mapping.
815 if ($mappingType == 'Export') {
816 $fields['Individual']['current_employer_id']['title'] = ts('Current Employer ID');
819 // Contact Sub Type For export
820 $subTypes = CRM_Contact_BAO_ContactType
::subTypeInfo();
821 foreach ($subTypes as $subType => $info) {
822 //adding subtype specific relationships CRM-5256
823 $csRelationships = [];
825 if ($mappingType == 'Export') {
826 $subTypeRelationshipTypes
827 = CRM_Contact_BAO_Relationship
::getContactRelationshipType(NULL, NULL, NULL, $info['parent'],
828 FALSE, 'label', TRUE, $subType);
830 foreach ($subTypeRelationshipTypes as $key => $var) {
831 if (!array_key_exists($key, $fields[$info['parent']])) {
832 list($type) = explode('_', $key);
834 $csRelationships[$key]['title'] = $var;
835 $csRelationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
836 $csRelationships[$key]['export'] = TRUE;
837 $csRelationships[$key]['relationship_type_id'] = $type;
838 $csRelationships[$key]['related'] = TRUE;
839 $csRelationships[$key]['hasRelationType'] = 1;
844 $fields[$subType] = $fields[$info['parent']] +
$csRelationships;
846 //custom fields for sub type
847 $subTypeFields = CRM_Core_BAO_CustomField
::getFieldsForImport($subType);
848 $fields[$subType] +
= $subTypeFields;
855 * Adds component fields to the export fields array; returns list of components.
857 * @param array $fields
858 * @param string $mappingType
859 * @param int $exportMode
862 public static function addComponentFields(&$fields, $mappingType, $exportMode) {
865 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
)) {
866 if (CRM_Core_Permission
::access('CiviContribute')) {
867 $fields['Contribution'] = CRM_Core_DAO
::getExportableFieldsWithPseudoConstants('CRM_Contribute_BAO_Contribution');
868 unset($fields['Contribution']['contribution_contact_id']);
869 $compArray['Contribution'] = ts('Contribution');
873 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
)) {
874 if (CRM_Core_Permission
::access('CiviEvent')) {
875 $fields['Participant'] = CRM_Event_BAO_Participant
::exportableFields();
876 //get the component payment fields
877 // @todo - review this - inconsistent with other entities & hacky.
878 if ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
879 $componentPaymentFields = [];
881 'componentPaymentField_total_amount' => ts('Total Amount'),
882 'componentPaymentField_contribution_status' => ts('Contribution Status'),
883 'componentPaymentField_received_date' => ts('Date Received'),
884 'componentPaymentField_payment_instrument' => ts('Payment Method'),
885 'componentPaymentField_transaction_id' => ts('Transaction ID'),
886 ] as $payField => $payTitle) {
887 $componentPaymentFields[$payField] = ['title' => $payTitle];
889 $fields['Participant'] = array_merge($fields['Participant'], $componentPaymentFields);
892 $compArray['Participant'] = ts('Participant');
896 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
)) {
897 if (CRM_Core_Permission
::access('CiviMember')) {
898 $fields['Membership'] = CRM_Member_BAO_Membership
::getMembershipFields($exportMode);
899 unset($fields['Membership']['membership_contact_id']);
900 $compArray['Membership'] = ts('Membership');
904 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
)) {
905 if (CRM_Core_Permission
::access('CiviPledge')) {
906 $fields['Pledge'] = CRM_Pledge_BAO_Pledge
::exportableFields();
907 unset($fields['Pledge']['pledge_contact_id']);
908 $compArray['Pledge'] = ts('Pledge');
912 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
)) {
913 if (CRM_Core_Permission
::access('CiviCase')) {
914 $fields['Case'] = CRM_Case_BAO_Case
::exportableFields();
915 $compArray['Case'] = ts('Case');
917 $fields['Activity'] = CRM_Activity_BAO_Activity
::exportableFields('Case');
918 $compArray['Activity'] = ts('Case Activity');
920 unset($fields['Case']['case_contact_id']);
923 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::GRANT_EXPORT
)) {
924 if (CRM_Core_Permission
::access('CiviGrant')) {
925 $fields['Grant'] = CRM_Grant_BAO_Grant
::exportableFields();
926 unset($fields['Grant']['grant_contact_id']);
927 if ($mappingType == 'Search Builder') {
928 unset($fields['Grant']['grant_type_id']);
930 $compArray['Grant'] = ts('Grant');
934 if (($mappingType == 'Search Builder') ||
($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
)) {
935 $fields['Activity'] = CRM_Activity_BAO_Activity
::exportableFields('Activity');
936 $compArray['Activity'] = ts('Activity');
943 * Get the parameters for a mapping field in a saveable format from the quickform mapping format.
945 * @param array $defaults
950 public static function getMappingParams($defaults, $v) {
951 $locationTypeId = NULL;
952 $saveMappingFields = $defaults;
954 $saveMappingFields['name'] = CRM_Utils_Array
::value('1', $v);
955 $saveMappingFields['contact_type'] = CRM_Utils_Array
::value('0', $v);
956 $locationId = CRM_Utils_Array
::value('2', $v);
957 $saveMappingFields['location_type_id'] = is_numeric($locationId) ?
$locationId : NULL;
959 if ($v[1] == 'phone') {
960 $saveMappingFields['phone_type_id'] = CRM_Utils_Array
::value('3', $v);
962 elseif ($v[1] == 'im') {
963 $saveMappingFields['im_provider_id'] = CRM_Utils_Array
::value('3', $v);
966 // Handle mapping for 'related contact' fields
967 if (count(explode('_', CRM_Utils_Array
::value('1', $v))) > 2) {
968 list($id, $first, $second) = explode('_', CRM_Utils_Array
::value('1', $v));
969 if (($first == 'a' && $second == 'b') ||
($first == 'b' && $second == 'a')) {
971 if (!empty($v['2'])) {
972 $saveMappingFields['name'] = CRM_Utils_Array
::value('2', $v);
974 elseif (!empty($v['4'])) {
975 $saveMappingFields['name'] = CRM_Utils_Array
::value('4', $v);
978 if (is_numeric(CRM_Utils_Array
::value('3', $v))) {
979 $locationTypeId = CRM_Utils_Array
::value('3', $v);
981 elseif (is_numeric(CRM_Utils_Array
::value('5', $v))) {
982 $locationTypeId = CRM_Utils_Array
::value('5', $v);
985 if (is_numeric(CRM_Utils_Array
::value('4', $v))) {
986 if ($saveMappingFields['name'] === 'im') {
987 $saveMappingFields['im_provider_id'] = $v[4];
990 $saveMappingFields['phone_type_id'] = CRM_Utils_Array
::value('4', $v);
993 elseif (is_numeric(CRM_Utils_Array
::value('6', $v))) {
994 $saveMappingFields['phone_type_id'] = CRM_Utils_Array
::value('6', $v);
997 $saveMappingFields['location_type_id'] = is_numeric($locationTypeId) ?
$locationTypeId : NULL;
998 $saveMappingFields['relationship_type_id'] = $id;
999 $saveMappingFields['relationship_direction'] = "{$first}_{$second}";
1003 return $saveMappingFields;
1007 * Load saved mapping.
1009 * @param $mappingLocation
1012 * @param $mappingName
1013 * @param $mapperFields
1014 * @param $mappingContactType
1015 * @param $mappingRelation
1016 * @param array $specialFields
1017 * @param $mappingPhoneType
1019 * @param array $defaults
1020 * @param array $noneArray
1021 * @param $imProvider
1022 * @param $mappingImProvider
1023 * @param $mappingOperator
1024 * @param $mappingValue
1028 protected static function loadSavedMapping($mappingLocation, int $x, int $i, $mappingName, $mapperFields, $mappingContactType, $mappingRelation, array $specialFields, $mappingPhoneType, array $defaults, array $noneArray, $mappingImProvider, $mappingOperator, $mappingValue) {
1029 $locationId = isset($mappingLocation[$x][$i]) ?
$mappingLocation[$x][$i] : 0;
1030 if (isset($mappingName[$x][$i])) {
1031 if (is_array($mapperFields[$mappingContactType[$x][$i]])) {
1033 if (isset($mappingRelation[$x][$i])) {
1034 $relLocationId = isset($mappingLocation[$x][$i]) ?
$mappingLocation[$x][$i] : 0;
1035 if (!$relLocationId && in_array($mappingName[$x][$i], $specialFields)) {
1036 $relLocationId = " ";
1039 $relPhoneType = isset($mappingPhoneType[$x][$i]) ?
$mappingPhoneType[$x][$i] : NULL;
1041 $defaults["mapper[$x][$i]"] = [
1042 $mappingContactType[$x][$i],
1043 $mappingRelation[$x][$i],
1046 $mappingName[$x][$i],
1052 $noneArray[] = [$x, $i, 2];
1054 if (!$phoneType && !$imProvider) {
1055 $noneArray[] = [$x, $i, 3];
1057 if (!$mappingName[$x][$i]) {
1058 $noneArray[] = [$x, $i, 4];
1060 if (!$relLocationId) {
1061 $noneArray[] = [$x, $i, 5];
1063 if (!$relPhoneType) {
1064 $noneArray[] = [$x, $i, 6];
1066 $noneArray[] = [$x, $i, 2];
1069 $phoneType = isset($mappingPhoneType[$x][$i]) ?
$mappingPhoneType[$x][$i] : NULL;
1070 $imProvider = isset($mappingImProvider[$x][$i]) ?
$mappingImProvider[$x][$i] : NULL;
1071 if (!$locationId && in_array($mappingName[$x][$i], $specialFields)) {
1075 $defaults["mapper[$x][$i]"] = [
1076 $mappingContactType[$x][$i],
1077 $mappingName[$x][$i],
1081 if (!$mappingName[$x][$i]) {
1082 $noneArray[] = [$x, $i, 1];
1085 $noneArray[] = [$x, $i, 2];
1087 if (!$phoneType && !$imProvider) {
1088 $noneArray[] = [$x, $i, 3];
1091 $noneArray[] = [$x, $i, 4];
1092 $noneArray[] = [$x, $i, 5];
1093 $noneArray[] = [$x, $i, 6];
1098 if (CRM_Utils_Array
::value($i, CRM_Utils_Array
::value($x, $mappingOperator))) {
1099 $defaults["operator[$x][$i]"] = CRM_Utils_Array
::value($i, $mappingOperator[$x]);
1102 if (CRM_Utils_Array
::value($i, CRM_Utils_Array
::value($x, $mappingValue))) {
1103 $defaults["value[$x][$i]"] = CRM_Utils_Array
::value($i, $mappingValue[$x]);
1107 return [$mappingName, $defaults, $noneArray, $jsSet];
1111 * Function returns all custom fields with group title and
1114 * @param int $relationshipTypeId
1115 * Related relationship type id.
1118 * all custom field titles
1120 public function getRelationTypeCustomGroupData($relationshipTypeId) {
1122 $customFields = CRM_Core_BAO_CustomField
::getFields('Relationship', NULL, NULL, $relationshipTypeId, NULL, NULL);
1124 foreach ($customFields as $krelation => $vrelation) {
1125 $groupTitle[$vrelation['label']] = $vrelation['groupTitle'] . '...' . $vrelation['label'];
1131 * Function returns all Custom group Names.
1133 * @param int $customfieldId
1136 * @return null|string
1137 * $customGroupName all custom group names
1139 public static function getCustomGroupName($customfieldId) {
1140 if ($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($customfieldId)) {
1141 $customGroupId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField', $customFieldId, 'custom_group_id');
1142 $customGroupName = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'title');
1144 $customGroupName = CRM_Utils_String
::ellipsify($customGroupName, 13);
1146 return $customGroupName;
1151 * Function returns associated array of elements, that will be passed for search
1153 * @param array $params
1154 * Associated array of submitted values.
1156 * Row no of the fields.
1160 * formatted associated array of elements
1162 public static function formattedFields(&$params, $row = FALSE) {
1165 if (empty($params) ||
!isset($params['mapper'])) {
1169 $types = ['Individual', 'Organization', 'Household'];
1170 foreach ($params['mapper'] as $key => $value) {
1171 $contactType = NULL;
1172 foreach ($value as $k => $v) {
1173 if (in_array($v[0], $types)) {
1174 if ($contactType && $contactType != $v[0]) {
1175 CRM_Core_Error
::fatal(ts("Cannot have two clauses with different types: %1, %2",
1176 [1 => $contactType, 2 => $v[0]]
1179 $contactType = $v[0];
1181 if (!empty($v['1'])) {
1183 $v2 = CRM_Utils_Array
::value('2', $v);
1184 if ($v2 && trim($v2)) {
1185 $fldName .= "-{$v[2]}";
1188 $v3 = CRM_Utils_Array
::value('3', $v);
1189 if ($v3 && trim($v3)) {
1190 $fldName .= "-{$v[3]}";
1193 $value = $params['value'][$key][$k];
1195 if ($v[0] == 'Contribution' && substr($fldName, 0, 7) != 'custom_'
1196 && substr($fldName, 0, 10) != 'financial_'
1197 && substr($fldName, 0, 8) != 'payment_') {
1198 if (substr($fldName, 0, 13) != 'contribution_') {
1199 $fldName = 'contribution_' . $fldName;
1203 // CRM-14983: verify if values are comma separated convert to array
1204 if (!is_array($value) && strstr($params['operator'][$key][$k], 'IN')) {
1205 $value = explode(',', $value);
1206 $value = [$params['operator'][$key][$k] => $value];
1208 // CRM-19081 Fix legacy StateProvince Field Values.
1209 // These derive from smart groups created using search builder under older
1210 // CiviCRM versions.
1211 if (!is_numeric($value) && $fldName == 'state_province') {
1212 $value = CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Address', 'state_province_id', $value);
1218 $params['operator'][$key][$k],
1227 $params['operator'][$key][$k],
1246 //add sortByCharacter values
1247 if (isset($params['sortByCharacter'])) {
1251 $params['sortByCharacter'],
1260 * @param array $params
1264 public static function &returnProperties(&$params) {
1266 'contact_type' => 1,
1267 'contact_sub_type' => 1,
1271 if (empty($params) ||
empty($params['mapper'])) {
1275 $locationTypes = CRM_Core_DAO_Address
::buildOptions('location_type_id', 'validate');
1276 foreach ($params['mapper'] as $key => $value) {
1277 foreach ($value as $k => $v) {
1279 if ($v[1] == 'groups' ||
$v[1] == 'tags') {
1283 if (isset($v[2]) && is_numeric($v[2])) {
1284 if (!array_key_exists('location', $fields)) {
1285 $fields['location'] = [];
1288 // make sure that we have a location fields and a location type for this
1289 $locationName = $locationTypes[$v[2]];
1290 if (!array_key_exists($locationName, $fields['location'])) {
1291 $fields['location'][$locationName] = [];
1292 $fields['location'][$locationName]['location_type'] = $v[2];
1295 if ($v[1] == 'phone' ||
$v[1] == 'email' ||
$v[1] == 'im') {
1296 // phone type handling
1298 $fields['location'][$locationName][$v[1] . "-" . $v[3]] = 1;
1301 $fields['location'][$locationName][$v[1]] = 1;
1305 $fields['location'][$locationName][$v[1]] = 1;
1319 * Save the mapping field info for search builder / export given the formvalues
1321 * @param array $params
1322 * Asscociated array of formvalues.
1323 * @param int $mappingId
1328 public static function saveMappingFields($params, $mappingId) {
1329 //delete mapping fields records for existing mapping
1330 $mappingFields = new CRM_Core_DAO_MappingField();
1331 $mappingFields->mapping_id
= $mappingId;
1332 $mappingFields->delete();
1334 if (empty($params['mapper'])) {
1338 //save record in mapping field table
1339 foreach ($params['mapper'] as $key => $value) {
1341 foreach ($value as $k => $v) {
1343 if (!empty($v['1'])) {
1344 $saveMappingParams = self
::getMappingParams(
1346 'mapping_id' => $mappingId,
1348 'operator' => $params['operator'][$key][$k] ??
NULL,
1349 'value' => $params['value'][$key][$k] ??
NULL,
1350 'column_number' => $colCnt,
1352 $saveMappingField = new CRM_Core_DAO_MappingField();
1353 $saveMappingField->copyValues($saveMappingParams, TRUE);
1354 $saveMappingField->save();