Merge pull request #23939 from civicrm/5.51
[civicrm-core.git] / CRM / Core / BAO / Mapping.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17 class CRM_Core_BAO_Mapping extends CRM_Core_DAO_Mapping implements \Civi\Core\HookInterface {
18
19 /**
20 * Retrieve DB object and copy to defaults array.
21 *
22 * @param array $params
23 * Array of criteria values.
24 * @param array $defaults
25 * Array to be populated with found values.
26 *
27 * @return self|null
28 * The DAO object, if found.
29 *
30 * @deprecated
31 */
32 public static function retrieve($params, &$defaults) {
33 return self::commonRetrieve(self::class, $params, $defaults);
34 }
35
36 /**
37 * Delete the mapping.
38 *
39 * @param int $id
40 *
41 * @deprecated
42 * @return bool
43 */
44 public static function del($id) {
45 return (bool) static::deleteRecord(['id' => $id]);
46 }
47
48 /**
49 * Takes an associative array and creates a contact object.
50 *
51 * The function extract all the params it needs to initialize the create a
52 * contact object. the params array could contain additional unused name/value
53 * pairs
54 *
55 * @param array $params
56 * An array of name/value pairs.
57 *
58 * @return object
59 * CRM_Core_DAO_Mapper object on success, otherwise NULL
60 */
61 public static function add($params) {
62 $mapping = new CRM_Core_DAO_Mapping();
63 $mapping->copyValues($params);
64 $mapping->save();
65
66 return $mapping;
67 }
68
69 /**
70 * Get the list of mappings for a select or select2 element.
71 *
72 * @param string $mappingType
73 * Mapping type name.
74 * @param bool $select2
75 * Format for select2
76 *
77 * @return array
78 * Array of mapping names, keyed by id.
79 */
80 public static function getMappings($mappingType, $select2 = FALSE) {
81 $result = civicrm_api3('Mapping', 'get', [
82 'mapping_type_id' => $mappingType,
83 'return' => ['name', 'description'],
84 'options' => [
85 'sort' => 'name',
86 'limit' => 0,
87 ],
88 ]);
89 $mapping = [];
90
91 foreach ($result['values'] as $id => $value) {
92 if ($select2) {
93 $item = ['id' => $id, 'text' => $value['name']];
94 if (!empty($value['description'])) {
95 $item['description'] = $value['description'];
96 }
97 $mapping[] = $item;
98 }
99 else {
100 $mapping[$id] = $value['name'];
101 }
102 }
103 return $mapping;
104 }
105
106 /**
107 * Get the mappings array, creating if it does not exist.
108 *
109 * @param string $mappingType
110 * Mapping type name.
111 *
112 * @return array
113 * Array of mapping names, keyed by id.
114 *
115 * @throws \CiviCRM_API3_Exception
116 */
117 public static function getCreateMappingValues($mappingType) {
118 try {
119 return CRM_Core_BAO_Mapping::getMappings($mappingType);
120 }
121 catch (CiviCRM_API3_Exception $e) {
122 // Having a valid mapping_type_id is now enforced. However, rather than error let's
123 // add it. This is required for Multi value which could be done by upgrade script, but
124 // it feels like there could be other instances so this is safer.
125 $errorParams = $e->getExtraParams();
126 if ($errorParams['error_field'] === 'mapping_type_id') {
127 $mappingValues = civicrm_api3('Mapping', 'getoptions', ['field' => 'mapping_type_id']);
128 civicrm_api3('OptionValue', 'create', [
129 'option_group_id' => 'mapping_type',
130 'label' => $mappingType,
131 'name' => $mappingType,
132 'value' => max(array_keys($mappingValues['values'])) + 1,
133 'is_reserved' => 1,
134 ]);
135 return CRM_Core_BAO_Mapping::getMappings($mappingType);
136 }
137 throw $e;
138 }
139 }
140
141 /**
142 * Get the mapping fields.
143 *
144 * @param int $mappingId
145 * Mapping id.
146 *
147 * @param bool $addPrimary
148 * Add the key 'Primary' when the field is a location field AND there is
149 * no location type (meaning Primary)?
150 *
151 * @return array
152 * array of mapping fields
153 */
154 public static function getMappingFields($mappingId, $addPrimary = FALSE) {
155 //mapping is to be loaded from database
156 $mapping = new CRM_Core_DAO_MappingField();
157 $mapping->mapping_id = $mappingId;
158 $mapping->orderBy('column_number');
159 $mapping->find();
160
161 $mappingName = $mappingLocation = $mappingContactType = $mappingPhoneType = [];
162 $mappingImProvider = $mappingRelation = $mappingOperator = $mappingValue = $mappingWebsiteType = [];
163 while ($mapping->fetch()) {
164 $mappingName[$mapping->grouping][$mapping->column_number] = $mapping->name;
165 $mappingContactType[$mapping->grouping][$mapping->column_number] = $mapping->contact_type;
166
167 if (!empty($mapping->location_type_id)) {
168 $mappingLocation[$mapping->grouping][$mapping->column_number] = $mapping->location_type_id;
169 }
170 elseif ($addPrimary) {
171 if (CRM_Contact_BAO_Contact::isFieldHasLocationType($mapping->name)) {
172 $mappingLocation[$mapping->grouping][$mapping->column_number] = ts('Primary');
173 }
174 else {
175 $mappingLocation[$mapping->grouping][$mapping->column_number] = NULL;
176 }
177 }
178
179 if (!empty($mapping->phone_type_id)) {
180 $mappingPhoneType[$mapping->grouping][$mapping->column_number] = $mapping->phone_type_id;
181 }
182
183 // get IM service provider type id from mapping fields
184 if (!empty($mapping->im_provider_id)) {
185 $mappingImProvider[$mapping->grouping][$mapping->column_number] = $mapping->im_provider_id;
186 }
187
188 if (!empty($mapping->website_type_id)) {
189 $mappingWebsiteType[$mapping->grouping][$mapping->column_number] = $mapping->website_type_id;
190 }
191
192 if (!empty($mapping->relationship_type_id)) {
193 $mappingRelation[$mapping->grouping][$mapping->column_number] = "{$mapping->relationship_type_id}_{$mapping->relationship_direction}";
194 }
195
196 if (!empty($mapping->operator)) {
197 $mappingOperator[$mapping->grouping][$mapping->column_number] = $mapping->operator;
198 }
199
200 if (isset($mapping->value)) {
201 $mappingValue[$mapping->grouping][$mapping->column_number] = $mapping->value;
202 }
203 }
204
205 return [
206 $mappingName,
207 $mappingContactType,
208 $mappingLocation,
209 $mappingPhoneType,
210 $mappingImProvider,
211 $mappingRelation,
212 $mappingOperator,
213 $mappingValue,
214 $mappingWebsiteType,
215 ];
216 }
217
218 /**
219 * Get un-indexed array of the field values for the given mapping id.
220 *
221 * For example if passing a mapping ID & name the returned array would look like
222 * ['First field name', 'second field name']
223 *
224 * @param int $mappingID
225 * @param string $fieldName
226 *
227 * @return array
228 * @throws \CiviCRM_API3_Exception
229 */
230 public static function getMappingFieldValues($mappingID, $fieldName) {
231 return array_merge(CRM_Utils_Array::collect($fieldName, civicrm_api3('MappingField', 'get', ['mapping_id' => $mappingID, 'return' => $fieldName])['values']));
232 }
233
234 /**
235 * Check Duplicate Mapping Name.
236 *
237 * @param string $nameField
238 * mapping Name.
239 * @param string $mapTypeId
240 * mapping Type.
241 *
242 * @return bool
243 */
244 public static function checkMapping($nameField, $mapTypeId) {
245 $mapping = new CRM_Core_DAO_Mapping();
246 $mapping->name = $nameField;
247 $mapping->mapping_type_id = $mapTypeId;
248 return (bool) $mapping->find(TRUE);
249 }
250
251 /**
252 * Function returns associated array of elements, that will be passed for search.
253 *
254 * @param int $smartGroupId
255 * Smart group id.
256 *
257 * @return array
258 * associated array of elements
259 */
260 public static function getFormattedFields($smartGroupId) {
261 $returnFields = [];
262
263 //get the fields from mapping table
264 $dao = new CRM_Core_DAO_MappingField();
265 $dao->mapping_id = $smartGroupId;
266 $dao->find();
267 while ($dao->fetch()) {
268 $fldName = $dao->name;
269 if ($dao->location_type_id) {
270 $fldName .= "-{$dao->location_type_id}";
271 }
272 if ($dao->phone_type) {
273 $fldName .= "-{$dao->phone_type}";
274 }
275 $returnFields[$fldName]['value'] = $dao->value;
276 $returnFields[$fldName]['op'] = $dao->operator;
277 $returnFields[$fldName]['grouping'] = $dao->grouping;
278 }
279 return $returnFields;
280 }
281
282 /**
283 * Build the mapping form for Search Builder.
284 *
285 * @param CRM_Core_Form $form
286 * @param int $mappingId
287 * @param int $columnNo
288 * @param int $blockCount
289 * (no of blocks shown).
290 * @param int $exportMode
291 */
292 public static function buildMappingForm(&$form, $mappingId, $columnNo, $blockCount, $exportMode = NULL) {
293
294 $hasLocationTypes = [];
295 $hasRelationTypes = [];
296
297 $columnCount = $columnNo;
298 $form->addElement('xbutton', 'addBlock', ts('Also include contacts where'),
299 [
300 'type' => 'submit',
301 'class' => 'submit-link',
302 'value' => 1,
303 ]
304 );
305
306 $contactTypes = CRM_Contact_BAO_ContactType::basicTypes();
307 $fields = self::getBasicFields('Search Builder');
308
309 // Unset groups, tags, notes for component export
310 if ($exportMode != CRM_Export_Form_Select::CONTACT_EXPORT) {
311 foreach (array_keys($fields) as $type) {
312 CRM_Utils_Array::remove($fields[$type], 'groups', 'tags', 'notes');
313 }
314 }
315
316 // Build the common contact fields array.
317 $fields['Contact'] = [];
318 foreach ($fields[$contactTypes[0]] as $key => $value) {
319 // If a field exists across all contact types, move it to the "Contact" selector
320 $ubiquitious = TRUE;
321 foreach ($contactTypes as $type) {
322 if (!isset($fields[$type][$key])) {
323 $ubiquitious = FALSE;
324 }
325 }
326 if ($ubiquitious) {
327 $fields['Contact'][$key] = $value;
328 foreach ($contactTypes as $type) {
329 unset($fields[$type][$key]);
330 }
331 }
332 }
333 if (array_key_exists('note', $fields['Contact'])) {
334 $noteTitle = $fields['Contact']['note']['title'];
335 $fields['Contact']['note']['title'] = $noteTitle . ': ' . ts('Body and Subject');
336 $fields['Contact']['note_body'] = ['title' => $noteTitle . ': ' . ts('Body Only'), 'name' => 'note_body'];
337 $fields['Contact']['note_subject'] = [
338 'title' => $noteTitle . ': ' . ts('Subject Only'),
339 'name' => 'note_subject',
340 ];
341 }
342
343 // add component fields
344 $compArray = self::addComponentFields($fields, 'Search Builder', $exportMode);
345
346 foreach ($fields as $key => $value) {
347
348 foreach ($value as $key1 => $value1) {
349 //CRM-2676, replacing the conflict for same custom field name from different custom group.
350 $customGroupName = self::getCustomGroupName($key1);
351
352 if ($customGroupName) {
353 $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $customGroupName . ': ' . $value1['title'];
354 }
355 else {
356 $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $value1['title'];
357 }
358 if (isset($value1['hasLocationType'])) {
359 $hasLocationTypes[$key][$key1] = $value1['hasLocationType'];
360 }
361
362 if (isset($value1['hasRelationType'])) {
363 $hasRelationTypes[$key][$key1] = $value1['hasRelationType'];
364 unset($relatedMapperFields[$key][$key1]);
365 }
366 }
367
368 if (isset($relatedMapperFields[$key]['related'])) {
369 unset($relatedMapperFields[$key]['related']);
370 }
371 }
372
373 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
374
375 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
376
377 // FIXME: dirty hack to make the default option show up first. This
378 // avoids a mozilla browser bug with defaults on dynamically constructed
379 // selector widgets.
380 if ($defaultLocationType) {
381 $defaultLocation = $locationTypes[$defaultLocationType->id];
382 unset($locationTypes[$defaultLocationType->id]);
383 $locationTypes = [$defaultLocationType->id => $defaultLocation] + $locationTypes;
384 }
385
386 $locationTypes = [' ' => ts('Primary')] + $locationTypes;
387
388 // since we need a hierarchical list to display contact types & subtypes,
389 // this is what we going to display in first selector
390 $contactTypeSelect = CRM_Contact_BAO_ContactType::getSelectElements(FALSE, FALSE);
391 $contactTypeSelect = ['Contact' => ts('Contacts')] + $contactTypeSelect;
392
393 $sel1 = ['' => ts('- select record type -')] + $contactTypeSelect + $compArray;
394
395 foreach ($sel1 as $key => $sel) {
396 if ($key) {
397 // sort everything BUT the contactType which is sorted separately by
398 // an initial commit of CRM-13278 (check ksort above)
399 if (!in_array($key, $contactTypes)) {
400 asort($mapperFields[$key]);
401 }
402 $sel2[$key] = ['' => ts('- select field -')] + $mapperFields[$key];
403 }
404 }
405
406 $sel3[''] = NULL;
407 $sel5[''] = NULL;
408 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
409 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
410 asort($phoneTypes);
411
412 foreach ($sel1 as $k => $sel) {
413 if ($k) {
414 foreach ($locationTypes as $key => $value) {
415 if (trim($key) != '') {
416 $sel4[$k]['phone'][$key] = &$phoneTypes;
417 $sel4[$k]['im'][$key] = &$imProviders;
418 }
419 }
420 }
421 }
422
423 foreach ($sel1 as $k => $sel) {
424 if ($k) {
425 foreach ($mapperFields[$k] as $key => $value) {
426 if (isset($hasLocationTypes[$k][$key])) {
427 $sel3[$k][$key] = $locationTypes;
428 }
429 else {
430 $sel3[$key] = NULL;
431 }
432 }
433 }
434 }
435
436 // Array for core fields and relationship custom data
437 $relationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE);
438
439 //special fields that have location, hack for primary location
440 $specialFields = [
441 'street_address',
442 'supplemental_address_1',
443 'supplemental_address_2',
444 'supplemental_address_3',
445 'city',
446 'postal_code',
447 'postal_code_suffix',
448 'geo_code_1',
449 'geo_code_2',
450 'state_province',
451 'country',
452 'phone',
453 'email',
454 'im',
455 ];
456
457 if (isset($mappingId)) {
458 list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingImProvider,
459 $mappingRelation, $mappingOperator, $mappingValue
460 ) = CRM_Core_BAO_Mapping::getMappingFields($mappingId);
461
462 $blkCnt = count($mappingName);
463 if ($blkCnt >= $blockCount) {
464 $blockCount = $blkCnt + 1;
465 }
466 for ($x = 1; $x < $blockCount; $x++) {
467 if (isset($mappingName[$x])) {
468 $colCnt = count($mappingName[$x]);
469 if ($colCnt >= $columnCount[$x]) {
470 $columnCount[$x] = $colCnt;
471 }
472 }
473 }
474 }
475
476 $form->_blockCount = $blockCount;
477 $form->_columnCount = $columnCount;
478
479 $form->set('blockCount', $form->_blockCount);
480 $form->set('columnCount', $form->_columnCount);
481
482 $defaults = $noneArray = $nullArray = [];
483
484 for ($x = 1; $x < $blockCount; $x++) {
485
486 for ($i = 0; $i < $columnCount[$x]; $i++) {
487
488 $sel = &$form->addElement('hierselect', "mapper[$x][$i]", ts('Mapper for Field %1', [1 => $i]), NULL);
489 $jsSet = FALSE;
490
491 if (isset($mappingId)) {
492 list($mappingName, $defaults, $noneArray, $jsSet) = self::loadSavedMapping($mappingLocation, $x, $i, $mappingName, $mapperFields, $mappingContactType, $mappingRelation, $specialFields, $mappingPhoneType, $defaults, $noneArray, $mappingImProvider, $mappingOperator, $mappingValue);
493 }
494 //Fix for Search Builder
495 $j = 4;
496
497 $formValues = $form->exportValues();
498 if (!$jsSet) {
499 if (empty($formValues)) {
500 // Incremented length for third select box(relationship type)
501 for ($k = 1; $k < $j; $k++) {
502 $noneArray[] = [$x, $i, $k];
503 }
504 }
505 else {
506 if (!empty($formValues['mapper'][$x])) {
507 foreach ($formValues['mapper'][$x] as $value) {
508 for ($k = 1; $k < $j; $k++) {
509 if (!isset($formValues['mapper'][$x][$i][$k]) ||
510 (!$formValues['mapper'][$x][$i][$k])
511 ) {
512 $noneArray[] = [$x, $i, $k];
513 }
514 else {
515 $nullArray[] = [$x, $i, $k];
516 }
517 }
518 }
519 }
520 else {
521 for ($k = 1; $k < $j; $k++) {
522 $noneArray[] = [$x, $i, $k];
523 }
524 }
525 }
526 }
527 //Fix for Search Builder
528 $sel->setOptions([$sel1, $sel2, $sel3, $sel4]);
529
530 //CRM -2292, restricted array set
531 $operatorArray = ['' => ts('-operator-')] + CRM_Core_SelectValues::getSearchBuilderOperators();
532
533 $form->add('select', "operator[$x][$i]", '', $operatorArray);
534 $form->add('text', "value[$x][$i]", '');
535 }
536
537 $form->addElement('xbutton', "addMore[$x]", ts('Another search field'), [
538 'type' => 'submit',
539 'class' => 'submit-link',
540 'value' => 1,
541 ]);
542 }
543 //end of block for
544
545 $js = "<script type='text/javascript'>\n";
546 $formName = "document.Builder";
547 if (!empty($nullArray)) {
548 $js .= "var nullArray = [";
549 $elements = [];
550 $seen = [];
551 foreach ($nullArray as $element) {
552 $key = "{$element[0]}, {$element[1]}, {$element[2]}";
553 if (!isset($seen[$key])) {
554 $elements[] = "[$key]";
555 $seen[$key] = 1;
556 }
557 }
558 $js .= implode(', ', $elements);
559 $js .= "]";
560 $js .= "
561 for (var i=0;i<nullArray.length;i++) {
562 if ( {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'] ) {
563 {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'].style.display = '';
564 }
565 }
566 ";
567 }
568 if (!empty($noneArray)) {
569 $js .= "var noneArray = [";
570 $elements = [];
571 $seen = [];
572 foreach ($noneArray as $element) {
573 $key = "{$element[0]}, {$element[1]}, {$element[2]}";
574 if (!isset($seen[$key])) {
575 $elements[] = "[$key]";
576 $seen[$key] = 1;
577 }
578 }
579 $js .= implode(', ', $elements);
580 $js .= "]";
581 $js .= "
582 for (var i=0;i<noneArray.length;i++) {
583 if ( {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'] ) {
584 {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'].style.display = 'none';
585 }
586 }
587 ";
588 }
589 $js .= "</script>\n";
590
591 $form->assign('initHideBoxes', $js);
592 $form->assign('columnCount', $columnCount);
593 $form->assign('blockCount', $blockCount);
594 $form->setDefaults($defaults);
595
596 $form->setDefaultAction('refresh');
597 }
598
599 /**
600 * @param string $mappingType
601 * @return array
602 */
603 public static function getBasicFields($mappingType) {
604 $contactTypes = CRM_Contact_BAO_ContactType::basicTypes();
605 $fields = [];
606 foreach ($contactTypes as $contactType) {
607 if ($mappingType == 'Search Builder') {
608 // Get multiple custom group fields in this context
609 $contactFields = CRM_Contact_BAO_Contact::exportableFields($contactType, FALSE, FALSE, FALSE, TRUE);
610 }
611 else {
612 $contactFields = CRM_Contact_BAO_Contact::exportableFields($contactType, FALSE, TRUE);
613 }
614 // It's unclear when we would want this but.... see
615 // https://lab.civicrm.org/dev/core/-/issues/3069 for when we don't....
616 $contactFields = array_merge($contactFields, CRM_Contact_BAO_Query_Hook::singleton()
617 ->getContactFields());
618
619 // Exclude the address options disabled in the Address Settings
620 $fields[$contactType] = CRM_Core_BAO_Address::validateAddressOptions($contactFields);
621 ksort($fields[$contactType]);
622 if ($mappingType == 'Export') {
623 $relationships = [];
624 $relationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $contactType);
625 asort($relationshipTypes);
626
627 foreach ($relationshipTypes as $key => $var) {
628 list($type) = explode('_', $key);
629
630 $relationships[$key]['title'] = $var;
631 $relationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
632 $relationships[$key]['export'] = TRUE;
633 $relationships[$key]['relationship_type_id'] = $type;
634 $relationships[$key]['related'] = TRUE;
635 $relationships[$key]['hasRelationType'] = 1;
636 }
637
638 if (!empty($relationships)) {
639 $fields[$contactType] = array_merge($fields[$contactType],
640 ['related' => ['title' => ts('- related contact info -')]],
641 $relationships
642 );
643 }
644 if (!empty($fields[$contactType]['state_province']) && empty($fields[$contactType]['state_province_name'])) {
645 $fields[$contactType]['state_province_name'] = $fields[$contactType]['state_province'];
646 $fields[$contactType]['state_province_name']['title'] = ts('State/Province Name');
647 $fields[$contactType]['state_province']['title'] = ts('State/Province Abbreviation');
648 }
649 }
650 }
651
652 // Get the current employer for mapping.
653 if ($mappingType == 'Export') {
654 $fields['Individual']['current_employer_id']['title'] = ts('Current Employer ID');
655 }
656
657 // Contact Sub Type For export
658 $subTypes = CRM_Contact_BAO_ContactType::subTypeInfo();
659 foreach ($subTypes as $subType => $info) {
660 //adding subtype specific relationships CRM-5256
661 $csRelationships = [];
662
663 if ($mappingType == 'Export') {
664 $subTypeRelationshipTypes
665 = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $info['parent'],
666 FALSE, 'label', TRUE, $subType);
667
668 foreach ($subTypeRelationshipTypes as $key => $var) {
669 if (!array_key_exists($key, $fields[$info['parent']])) {
670 list($type) = explode('_', $key);
671
672 $csRelationships[$key]['title'] = $var;
673 $csRelationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
674 $csRelationships[$key]['export'] = TRUE;
675 $csRelationships[$key]['relationship_type_id'] = $type;
676 $csRelationships[$key]['related'] = TRUE;
677 $csRelationships[$key]['hasRelationType'] = 1;
678 }
679 }
680 }
681
682 $fields[$subType] = $fields[$info['parent']] + $csRelationships;
683
684 //custom fields for sub type
685 $subTypeFields = CRM_Core_BAO_CustomField::getFieldsForImport($subType);
686 $fields[$subType] += $subTypeFields;
687 }
688
689 return $fields;
690 }
691
692 /**
693 * Adds component fields to the export fields array; returns list of components.
694 *
695 * @param array $fields
696 * @param string $mappingType
697 * @param int $exportMode
698 * @return array
699 */
700 public static function addComponentFields(&$fields, $mappingType, $exportMode) {
701 $compArray = [];
702
703 if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT)) {
704 if (CRM_Core_Permission::access('CiviContribute')) {
705 $fields['Contribution'] = CRM_Core_DAO::getExportableFieldsWithPseudoConstants('CRM_Contribute_BAO_Contribution');
706 unset($fields['Contribution']['contribution_contact_id']);
707 $compArray['Contribution'] = ts('Contribution');
708 }
709 }
710
711 if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT)) {
712 if (CRM_Core_Permission::access('CiviEvent')) {
713 $fields['Participant'] = CRM_Event_BAO_Participant::exportableFields();
714 //get the component payment fields
715 // @todo - review this - inconsistent with other entities & hacky.
716 if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
717 $componentPaymentFields = [];
718 foreach ([
719 'componentPaymentField_total_amount' => ts('Total Amount'),
720 'componentPaymentField_contribution_status' => ts('Contribution Status'),
721 'componentPaymentField_received_date' => ts('Date Received'),
722 'componentPaymentField_payment_instrument' => ts('Payment Method'),
723 'componentPaymentField_transaction_id' => ts('Transaction ID'),
724 ] as $payField => $payTitle) {
725 $componentPaymentFields[$payField] = ['title' => $payTitle];
726 }
727 $fields['Participant'] = array_merge($fields['Participant'], $componentPaymentFields);
728 }
729
730 $compArray['Participant'] = ts('Participant');
731 }
732 }
733
734 if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT)) {
735 if (CRM_Core_Permission::access('CiviMember')) {
736 $fields['Membership'] = CRM_Member_BAO_Membership::getMembershipFields($exportMode);
737 unset($fields['Membership']['membership_contact_id']);
738 $compArray['Membership'] = ts('Membership');
739 }
740 }
741
742 if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT)) {
743 if (CRM_Core_Permission::access('CiviPledge')) {
744 $fields['Pledge'] = CRM_Pledge_BAO_Pledge::exportableFields();
745 unset($fields['Pledge']['pledge_contact_id']);
746 $compArray['Pledge'] = ts('Pledge');
747 }
748 }
749
750 if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::CASE_EXPORT)) {
751 if (CRM_Core_Permission::access('CiviCase')) {
752 $fields['Case'] = CRM_Case_BAO_Case::exportableFields();
753 $compArray['Case'] = ts('Case');
754
755 $fields['Activity'] = CRM_Activity_BAO_Activity::exportableFields('Case');
756 $compArray['Activity'] = ts('Case Activity');
757
758 unset($fields['Case']['case_contact_id']);
759 }
760 }
761 if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::GRANT_EXPORT)) {
762 if (method_exists('CRM_Grant_BAO_Grant', 'exportableFields') && CRM_Core_Permission::check('access CiviGrant')) {
763 $fields['Grant'] = CRM_Grant_BAO_Grant::exportableFields();
764 unset($fields['Grant']['grant_contact_id']);
765 if ($mappingType == 'Search Builder') {
766 unset($fields['Grant']['grant_type_id']);
767 }
768 $compArray['Grant'] = ts('Grant');
769 }
770 }
771
772 if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT)) {
773 $fields['Activity'] = CRM_Activity_BAO_Activity::exportableFields('Activity');
774 $compArray['Activity'] = ts('Activity');
775 }
776
777 return $compArray;
778 }
779
780 /**
781 * Get the parameters for a mapping field in a saveable format from the quickform mapping format.
782 *
783 * @param array $defaults
784 * @param array $v
785 *
786 * @return array
787 */
788 public static function getMappingParams($defaults, $v) {
789 $locationTypeId = NULL;
790 $saveMappingFields = $defaults;
791
792 $saveMappingFields['name'] = $v['1'] ?? NULL;
793 $saveMappingFields['contact_type'] = $v['0'] ?? NULL;
794 $locationId = $v['2'] ?? NULL;
795 $saveMappingFields['location_type_id'] = is_numeric($locationId) ? $locationId : NULL;
796
797 if ($v[1] == 'phone') {
798 $saveMappingFields['phone_type_id'] = $v['3'] ?? NULL;
799 }
800 elseif ($v[1] == 'im') {
801 $saveMappingFields['im_provider_id'] = $v['3'] ?? NULL;
802 }
803
804 // Handle mapping for 'related contact' fields
805 if (count(explode('_', CRM_Utils_Array::value('1', $v))) > 2) {
806 list($id, $first, $second) = explode('_', CRM_Utils_Array::value('1', $v));
807 if (($first == 'a' && $second == 'b') || ($first == 'b' && $second == 'a')) {
808
809 if (!empty($v['2'])) {
810 $saveMappingFields['name'] = $v['2'] ?? NULL;
811 }
812 elseif (!empty($v['4'])) {
813 $saveMappingFields['name'] = $v['4'] ?? NULL;
814 }
815
816 if (is_numeric(CRM_Utils_Array::value('3', $v))) {
817 $locationTypeId = $v['3'] ?? NULL;
818 }
819 elseif (is_numeric(CRM_Utils_Array::value('5', $v))) {
820 $locationTypeId = $v['5'] ?? NULL;
821 }
822
823 if (is_numeric(CRM_Utils_Array::value('4', $v))) {
824 if ($saveMappingFields['name'] === 'im') {
825 $saveMappingFields['im_provider_id'] = $v[4];
826 }
827 else {
828 $saveMappingFields['phone_type_id'] = $v['4'] ?? NULL;
829 }
830 }
831 elseif (is_numeric(CRM_Utils_Array::value('6', $v))) {
832 $saveMappingFields['phone_type_id'] = $v['6'] ?? NULL;
833 }
834
835 $saveMappingFields['location_type_id'] = is_numeric($locationTypeId) ? $locationTypeId : NULL;
836 $saveMappingFields['relationship_type_id'] = $id;
837 $saveMappingFields['relationship_direction'] = "{$first}_{$second}";
838 }
839 }
840
841 return $saveMappingFields;
842 }
843
844 /**
845 * Load saved mapping.
846 *
847 * @param $mappingLocation
848 * @param int $x
849 * @param int $i
850 * @param $mappingName
851 * @param $mapperFields
852 * @param $mappingContactType
853 * @param $mappingRelation
854 * @param array $specialFields
855 * @param $mappingPhoneType
856 * @param $phoneType
857 * @param array $defaults
858 * @param array $noneArray
859 * @param $imProvider
860 * @param $mappingImProvider
861 * @param $mappingOperator
862 * @param $mappingValue
863 *
864 * @return array
865 */
866 protected static function loadSavedMapping($mappingLocation, int $x, int $i, $mappingName, $mapperFields, $mappingContactType, $mappingRelation, array $specialFields, $mappingPhoneType, array $defaults, array $noneArray, $mappingImProvider, $mappingOperator, $mappingValue) {
867 $jsSet = FALSE;
868 $locationId = $mappingLocation[$x][$i] ?? 0;
869 if (isset($mappingName[$x][$i])) {
870 if (is_array($mapperFields[$mappingContactType[$x][$i]])) {
871
872 if (isset($mappingRelation[$x][$i])) {
873 $relLocationId = $mappingLocation[$x][$i] ?? 0;
874 if (!$relLocationId && in_array($mappingName[$x][$i], $specialFields)) {
875 $relLocationId = " ";
876 }
877
878 $relPhoneType = $mappingPhoneType[$x][$i] ?? NULL;
879
880 $defaults["mapper[$x][$i]"] = [
881 $mappingContactType[$x][$i],
882 $mappingRelation[$x][$i],
883 $locationId,
884 $phoneType,
885 $mappingName[$x][$i],
886 $relLocationId,
887 $relPhoneType,
888 ];
889
890 if (!$locationId) {
891 $noneArray[] = [$x, $i, 2];
892 }
893 if (!$phoneType && !$imProvider) {
894 $noneArray[] = [$x, $i, 3];
895 }
896 if (!$mappingName[$x][$i]) {
897 $noneArray[] = [$x, $i, 4];
898 }
899 if (!$relLocationId) {
900 $noneArray[] = [$x, $i, 5];
901 }
902 if (!$relPhoneType) {
903 $noneArray[] = [$x, $i, 6];
904 }
905 $noneArray[] = [$x, $i, 2];
906 }
907 else {
908 $phoneType = $mappingPhoneType[$x][$i] ?? NULL;
909 $imProvider = $mappingImProvider[$x][$i] ?? NULL;
910 if (!$locationId && in_array($mappingName[$x][$i], $specialFields)) {
911 $locationId = " ";
912 }
913
914 $defaults["mapper[$x][$i]"] = [
915 $mappingContactType[$x][$i],
916 $mappingName[$x][$i],
917 $locationId,
918 $phoneType,
919 ];
920 if (!$mappingName[$x][$i]) {
921 $noneArray[] = [$x, $i, 1];
922 }
923 if (!$locationId) {
924 $noneArray[] = [$x, $i, 2];
925 }
926 if (!$phoneType && !$imProvider) {
927 $noneArray[] = [$x, $i, 3];
928 }
929
930 $noneArray[] = [$x, $i, 4];
931 $noneArray[] = [$x, $i, 5];
932 $noneArray[] = [$x, $i, 6];
933 }
934
935 $jsSet = TRUE;
936
937 if (CRM_Utils_Array::value($i, CRM_Utils_Array::value($x, $mappingOperator))) {
938 $defaults["operator[$x][$i]"] = $mappingOperator[$x][$i] ?? NULL;
939 }
940
941 if (isset($mappingValue[$x][$i])) {
942 $defaults["value[$x][$i]"] = $mappingValue[$x][$i] ?? NULL;
943 }
944 }
945 }
946 return [$mappingName, $defaults, $noneArray, $jsSet];
947 }
948
949 /**
950 * Function returns all custom fields with group title and
951 * field label
952 *
953 * @param int $relationshipTypeId
954 * Related relationship type id.
955 *
956 * @return array
957 * all custom field titles
958 */
959 public function getRelationTypeCustomGroupData($relationshipTypeId) {
960
961 $customFields = CRM_Core_BAO_CustomField::getFields('Relationship', NULL, NULL, $relationshipTypeId, NULL, NULL);
962 $groupTitle = [];
963 foreach ($customFields as $krelation => $vrelation) {
964 $groupTitle[$vrelation['label']] = $vrelation['groupTitle'] . '...' . $vrelation['label'];
965 }
966 return $groupTitle;
967 }
968
969 /**
970 * Function returns all Custom group Names.
971 *
972 * @param int $customfieldId
973 * Related file id.
974 *
975 * @return null|string
976 * $customGroupName all custom group names
977 */
978 public static function getCustomGroupName($customfieldId) {
979 if ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($customfieldId)) {
980 $customGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $customFieldId, 'custom_group_id');
981 $customGroupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'title');
982
983 $customGroupName = CRM_Utils_String::ellipsify($customGroupName, 13);
984
985 return $customGroupName;
986 }
987 }
988
989 /**
990 * Function returns associated array of elements, that will be passed for search
991 *
992 * @param array $params
993 * Associated array of submitted values.
994 * @param bool $row
995 * Row no of the fields.
996 *
997 *
998 * @return array
999 * formatted associated array of elements
1000 * @throws CRM_Core_Exception
1001 */
1002 public static function formattedFields(&$params, $row = FALSE) {
1003 $fields = [];
1004
1005 if (empty($params) || !isset($params['mapper'])) {
1006 return $fields;
1007 }
1008
1009 $types = CRM_Contact_BAO_ContactType::basicTypes(TRUE);
1010 foreach ($params['mapper'] as $key => $value) {
1011 $contactType = NULL;
1012 foreach ($value as $k => $v) {
1013 if (in_array($v[0], $types, TRUE)) {
1014 if ($contactType && $contactType != $v[0]) {
1015 throw new CRM_Core_Exception(ts("Cannot have two clauses with different types: %1, %2",
1016 [1 => $contactType, 2 => $v[0]]
1017 ));
1018 }
1019 $contactType = $v[0];
1020 }
1021 if (!empty($v['1'])) {
1022 $fldName = $v[1];
1023 $v2 = $v['2'] ?? NULL;
1024 if ($v2 && trim($v2)) {
1025 $fldName .= "-{$v[2]}";
1026 }
1027
1028 $v3 = $v['3'] ?? NULL;
1029 if ($v3 && trim($v3)) {
1030 $fldName .= "-{$v[3]}";
1031 }
1032
1033 $value = $params['value'][$key][$k];
1034
1035 if ($v[0] == 'Contribution' && substr($fldName, 0, 7) != 'custom_'
1036 && substr($fldName, 0, 10) != 'financial_'
1037 && substr($fldName, 0, 8) != 'payment_') {
1038 if (substr($fldName, 0, 13) != 'contribution_') {
1039 $fldName = 'contribution_' . $fldName;
1040 }
1041 }
1042
1043 // CRM-14983: verify if values are comma separated convert to array
1044 if (!is_array($value) && strstr($params['operator'][$key][$k], 'IN')) {
1045 $value = explode(',', $value);
1046 $value = [$params['operator'][$key][$k] => $value];
1047 }
1048 // CRM-19081 Fix legacy StateProvince Field Values.
1049 // These derive from smart groups created using search builder under older
1050 // CiviCRM versions.
1051 if ($fldName == 'state_province' && !is_numeric($value) && !is_array($value)) {
1052 $value = CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Address', 'state_province_id', $value);
1053 }
1054
1055 if ($row) {
1056 $fields[] = [
1057 $fldName,
1058 $params['operator'][$key][$k],
1059 $value,
1060 $key,
1061 $k,
1062 ];
1063 }
1064 else {
1065 $fields[] = [
1066 $fldName,
1067 $params['operator'][$key][$k],
1068 $value,
1069 $key,
1070 0,
1071 ];
1072 }
1073 }
1074 }
1075 if ($contactType) {
1076 $fields[] = [
1077 'contact_type',
1078 '=',
1079 $contactType,
1080 $key,
1081 0,
1082 ];
1083 }
1084 }
1085
1086 //add sortByCharacter values
1087 if (isset($params['sortByCharacter'])) {
1088 $fields[] = [
1089 'sortByCharacter',
1090 '=',
1091 $params['sortByCharacter'],
1092 0,
1093 0,
1094 ];
1095 }
1096 return $fields;
1097 }
1098
1099 /**
1100 * @param array $params
1101 *
1102 * @return array
1103 */
1104 public static function &returnProperties(&$params) {
1105 $fields = [
1106 'contact_type' => 1,
1107 'contact_sub_type' => 1,
1108 'sort_name' => 1,
1109 ];
1110
1111 if (empty($params) || empty($params['mapper'])) {
1112 return $fields;
1113 }
1114
1115 $locationTypes = CRM_Core_DAO_Address::buildOptions('location_type_id', 'validate');
1116 foreach ($params['mapper'] as $key => $value) {
1117 foreach ($value as $k => $v) {
1118 if (isset($v[1])) {
1119 if ($v[1] == 'groups' || $v[1] == 'tags') {
1120 continue;
1121 }
1122
1123 if (isset($v[2]) && is_numeric($v[2])) {
1124 if (!array_key_exists('location', $fields)) {
1125 $fields['location'] = [];
1126 }
1127
1128 // make sure that we have a location fields and a location type for this
1129 $locationName = $locationTypes[$v[2]];
1130 if (!array_key_exists($locationName, $fields['location'])) {
1131 $fields['location'][$locationName] = [];
1132 $fields['location'][$locationName]['location_type'] = $v[2];
1133 }
1134
1135 if ($v[1] == 'phone' || $v[1] == 'email' || $v[1] == 'im') {
1136 // phone type handling
1137 if (isset($v[3])) {
1138 $fields['location'][$locationName][$v[1] . "-" . $v[3]] = 1;
1139 }
1140 else {
1141 $fields['location'][$locationName][$v[1]] = 1;
1142 }
1143 }
1144 else {
1145 $fields['location'][$locationName][$v[1]] = 1;
1146 }
1147 }
1148 else {
1149 $fields[$v[1]] = 1;
1150 }
1151 }
1152 }
1153 }
1154
1155 return $fields;
1156 }
1157
1158 /**
1159 * Save the mapping field info for search builder / export given the formvalues
1160 *
1161 * @param array $params
1162 * Asscociated array of formvalues.
1163 * @param int $mappingId
1164 * Mapping id.
1165 *
1166 * @return NULL
1167 */
1168 public static function saveMappingFields($params, $mappingId) {
1169 //delete mapping fields records for existing mapping
1170 $mappingFields = new CRM_Core_DAO_MappingField();
1171 $mappingFields->mapping_id = $mappingId;
1172 $mappingFields->delete();
1173
1174 if (empty($params['mapper'])) {
1175 return NULL;
1176 }
1177
1178 //save record in mapping field table
1179 foreach ($params['mapper'] as $key => $value) {
1180 $colCnt = 0;
1181 foreach ($value as $k => $v) {
1182
1183 if (!empty($v['1'])) {
1184 $saveMappingParams = self::getMappingParams(
1185 [
1186 'mapping_id' => $mappingId,
1187 'grouping' => $key,
1188 'operator' => $params['operator'][$key][$k] ?? NULL,
1189 'value' => $params['value'][$key][$k] ?? NULL,
1190 'column_number' => $colCnt,
1191 ], $v);
1192 $saveMappingField = new CRM_Core_DAO_MappingField();
1193 $saveMappingField->copyValues($saveMappingParams);
1194 $saveMappingField->save();
1195 $colCnt++;
1196 }
1197 }
1198 }
1199 }
1200
1201 /**
1202 * Remove references to a specific field from save Mappings
1203 * @param string $fieldName
1204 */
1205 public static function removeFieldFromMapping($fieldName): void {
1206 $mappingField = new CRM_Core_DAO_MappingField();
1207 $mappingField->name = $fieldName;
1208 $mappingField->delete();
1209 }
1210
1211 /**
1212 * Callback for hook_civicrm_pre().
1213 * @param \Civi\Core\Event\PreEvent $event
1214 * @throws CRM_Core_Exception
1215 */
1216 public static function on_hook_civicrm_pre(\Civi\Core\Event\PreEvent $event) {
1217 if ($event->action === 'delete' && $event->entity === 'RelationshipType') {
1218 // CRM-3323 - Delete mappingField records when deleting relationship type
1219 \Civi\Api4\MappingField::delete(FALSE)
1220 ->addWhere('relationship_type_id', '=', $event->id)
1221 ->execute();
1222 }
1223 }
1224
1225 }