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