58b573c3f807a27af89ee4362b58d2577277c7d1
[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('xbutton', 'addBlock', ts('Also include contacts where'),
322 [
323 'type' => 'submit',
324 'class' => 'submit-link',
325 ]
326 );
327
328 $contactTypes = CRM_Contact_BAO_ContactType::basicTypes();
329 $fields = self::getBasicFields('Search Builder');
330
331 // Unset groups, tags, notes for component export
332 if ($exportMode != CRM_Export_Form_Select::CONTACT_EXPORT) {
333 foreach (array_keys($fields) as $type) {
334 CRM_Utils_Array::remove($fields[$type], 'groups', 'tags', 'notes');
335 }
336 }
337
338 // Build the common contact fields array.
339 $fields['Contact'] = [];
340 foreach ($fields[$contactTypes[0]] as $key => $value) {
341 // If a field exists across all contact types, move it to the "Contact" selector
342 $ubiquitious = TRUE;
343 foreach ($contactTypes as $type) {
344 if (!isset($fields[$type][$key])) {
345 $ubiquitious = FALSE;
346 }
347 }
348 if ($ubiquitious) {
349 $fields['Contact'][$key] = $value;
350 foreach ($contactTypes as $type) {
351 unset($fields[$type][$key]);
352 }
353 }
354 }
355 if (array_key_exists('note', $fields['Contact'])) {
356 $noteTitle = $fields['Contact']['note']['title'];
357 $fields['Contact']['note']['title'] = $noteTitle . ': ' . ts('Body and Subject');
358 $fields['Contact']['note_body'] = ['title' => $noteTitle . ': ' . ts('Body Only'), 'name' => 'note_body'];
359 $fields['Contact']['note_subject'] = [
360 'title' => $noteTitle . ': ' . ts('Subject Only'),
361 'name' => 'note_subject',
362 ];
363 }
364
365 // add component fields
366 $compArray = self::addComponentFields($fields, 'Search Builder', $exportMode);
367
368 foreach ($fields as $key => $value) {
369
370 foreach ($value as $key1 => $value1) {
371 //CRM-2676, replacing the conflict for same custom field name from different custom group.
372 $customGroupName = self::getCustomGroupName($key1);
373
374 if ($customGroupName) {
375 $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $customGroupName . ': ' . $value1['title'];
376 }
377 else {
378 $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $value1['title'];
379 }
380 if (isset($value1['hasLocationType'])) {
381 $hasLocationTypes[$key][$key1] = $value1['hasLocationType'];
382 }
383
384 if (isset($value1['hasRelationType'])) {
385 $hasRelationTypes[$key][$key1] = $value1['hasRelationType'];
386 unset($relatedMapperFields[$key][$key1]);
387 }
388 }
389
390 if (isset($relatedMapperFields[$key]['related'])) {
391 unset($relatedMapperFields[$key]['related']);
392 }
393 }
394
395 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
396
397 $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
398
399 // FIXME: dirty hack to make the default option show up first. This
400 // avoids a mozilla browser bug with defaults on dynamically constructed
401 // selector widgets.
402 if ($defaultLocationType) {
403 $defaultLocation = $locationTypes[$defaultLocationType->id];
404 unset($locationTypes[$defaultLocationType->id]);
405 $locationTypes = [$defaultLocationType->id => $defaultLocation] + $locationTypes;
406 }
407
408 $locationTypes = [' ' => ts('Primary')] + $locationTypes;
409
410 // since we need a hierarchical list to display contact types & subtypes,
411 // this is what we going to display in first selector
412 $contactTypeSelect = CRM_Contact_BAO_ContactType::getSelectElements(FALSE, FALSE);
413 $contactTypeSelect = ['Contact' => ts('Contacts')] + $contactTypeSelect;
414
415 $sel1 = ['' => ts('- select record type -')] + $contactTypeSelect + $compArray;
416
417 foreach ($sel1 as $key => $sel) {
418 if ($key) {
419 // sort everything BUT the contactType which is sorted separately by
420 // an initial commit of CRM-13278 (check ksort above)
421 if (!in_array($key, $contactTypes)) {
422 asort($mapperFields[$key]);
423 }
424 $sel2[$key] = ['' => ts('- select field -')] + $mapperFields[$key];
425 }
426 }
427
428 $sel3[''] = NULL;
429 $sel5[''] = NULL;
430 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
431 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
432 asort($phoneTypes);
433
434 foreach ($sel1 as $k => $sel) {
435 if ($k) {
436 foreach ($locationTypes as $key => $value) {
437 if (trim($key) != '') {
438 $sel4[$k]['phone'][$key] = &$phoneTypes;
439 $sel4[$k]['im'][$key] = &$imProviders;
440 }
441 }
442 }
443 }
444
445 foreach ($sel1 as $k => $sel) {
446 if ($k) {
447 foreach ($mapperFields[$k] as $key => $value) {
448 if (isset($hasLocationTypes[$k][$key])) {
449 $sel3[$k][$key] = $locationTypes;
450 }
451 else {
452 $sel3[$key] = NULL;
453 }
454 }
455 }
456 }
457
458 // Array for core fields and relationship custom data
459 $relationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE);
460
461 //special fields that have location, hack for primary location
462 $specialFields = [
463 'street_address',
464 'supplemental_address_1',
465 'supplemental_address_2',
466 'supplemental_address_3',
467 'city',
468 'postal_code',
469 'postal_code_suffix',
470 'geo_code_1',
471 'geo_code_2',
472 'state_province',
473 'country',
474 'phone',
475 'email',
476 'im',
477 ];
478
479 if (isset($mappingId)) {
480 list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingImProvider,
481 $mappingRelation, $mappingOperator, $mappingValue
482 ) = CRM_Core_BAO_Mapping::getMappingFields($mappingId);
483
484 $blkCnt = count($mappingName);
485 if ($blkCnt >= $blockCount) {
486 $blockCount = $blkCnt + 1;
487 }
488 for ($x = 1; $x < $blockCount; $x++) {
489 if (isset($mappingName[$x])) {
490 $colCnt = count($mappingName[$x]);
491 if ($colCnt >= $columnCount[$x]) {
492 $columnCount[$x] = $colCnt;
493 }
494 }
495 }
496 }
497
498 $form->_blockCount = $blockCount;
499 $form->_columnCount = $columnCount;
500
501 $form->set('blockCount', $form->_blockCount);
502 $form->set('columnCount', $form->_columnCount);
503
504 $defaults = $noneArray = $nullArray = [];
505
506 for ($x = 1; $x < $blockCount; $x++) {
507
508 for ($i = 0; $i < $columnCount[$x]; $i++) {
509
510 $sel = &$form->addElement('hierselect', "mapper[$x][$i]", ts('Mapper for Field %1', [1 => $i]), NULL);
511 $jsSet = FALSE;
512
513 if (isset($mappingId)) {
514 list($mappingName, $defaults, $noneArray, $jsSet) = self::loadSavedMapping($mappingLocation, $x, $i, $mappingName, $mapperFields, $mappingContactType, $mappingRelation, $specialFields, $mappingPhoneType, $defaults, $noneArray, $mappingImProvider, $mappingOperator, $mappingValue);
515 }
516 //Fix for Search Builder
517 $j = 4;
518
519 $formValues = $form->exportValues();
520 if (!$jsSet) {
521 if (empty($formValues)) {
522 // Incremented length for third select box(relationship type)
523 for ($k = 1; $k < $j; $k++) {
524 $noneArray[] = [$x, $i, $k];
525 }
526 }
527 else {
528 if (!empty($formValues['mapper'][$x])) {
529 foreach ($formValues['mapper'][$x] as $value) {
530 for ($k = 1; $k < $j; $k++) {
531 if (!isset($formValues['mapper'][$x][$i][$k]) ||
532 (!$formValues['mapper'][$x][$i][$k])
533 ) {
534 $noneArray[] = [$x, $i, $k];
535 }
536 else {
537 $nullArray[] = [$x, $i, $k];
538 }
539 }
540 }
541 }
542 else {
543 for ($k = 1; $k < $j; $k++) {
544 $noneArray[] = [$x, $i, $k];
545 }
546 }
547 }
548 }
549 //Fix for Search Builder
550 $sel->setOptions([$sel1, $sel2, $sel3, $sel4]);
551
552 //CRM -2292, restricted array set
553 $operatorArray = ['' => ts('-operator-')] + CRM_Core_SelectValues::getSearchBuilderOperators();
554
555 $form->add('select', "operator[$x][$i]", '', $operatorArray);
556 $form->add('text', "value[$x][$i]", '');
557 }
558
559 $form->addElement('xbutton', "addMore[$x]", ts('Another search field'), [
560 'type' => 'submit',
561 'class' => 'submit-link',
562 ]);
563 }
564 //end of block for
565
566 $js = "<script type='text/javascript'>\n";
567 $formName = "document.Builder";
568 if (!empty($nullArray)) {
569 $js .= "var nullArray = [";
570 $elements = [];
571 $seen = [];
572 foreach ($nullArray 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<nullArray.length;i++) {
583 if ( {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'] ) {
584 {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'].style.display = '';
585 }
586 }
587 ";
588 }
589 if (!empty($noneArray)) {
590 $js .= "var noneArray = [";
591 $elements = [];
592 $seen = [];
593 foreach ($noneArray as $element) {
594 $key = "{$element[0]}, {$element[1]}, {$element[2]}";
595 if (!isset($seen[$key])) {
596 $elements[] = "[$key]";
597 $seen[$key] = 1;
598 }
599 }
600 $js .= implode(', ', $elements);
601 $js .= "]";
602 $js .= "
603 for (var i=0;i<noneArray.length;i++) {
604 if ( {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'] ) {
605 {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'].style.display = 'none';
606 }
607 }
608 ";
609 }
610 $js .= "</script>\n";
611
612 $form->assign('initHideBoxes', $js);
613 $form->assign('columnCount', $columnCount);
614 $form->assign('blockCount', $blockCount);
615 $form->setDefaults($defaults);
616
617 $form->setDefaultAction('refresh');
618 }
619
620 /**
621 * @param string $mappingType
622 * @return array
623 */
624 public static function getBasicFields($mappingType) {
625 $contactTypes = CRM_Contact_BAO_ContactType::basicTypes();
626 $fields = [];
627 foreach ($contactTypes as $contactType) {
628 if ($mappingType == 'Search Builder') {
629 // Get multiple custom group fields in this context
630 $contactFields = CRM_Contact_BAO_Contact::exportableFields($contactType, FALSE, FALSE, FALSE, TRUE);
631 }
632 else {
633 $contactFields = CRM_Contact_BAO_Contact::exportableFields($contactType, FALSE, TRUE);
634 }
635 $contactFields = array_merge($contactFields, CRM_Contact_BAO_Query_Hook::singleton()->getFields());
636
637 // Exclude the address options disabled in the Address Settings
638 $fields[$contactType] = CRM_Core_BAO_Address::validateAddressOptions($contactFields);
639 ksort($fields[$contactType]);
640 if ($mappingType == 'Export') {
641 $relationships = [];
642 $relationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $contactType);
643 asort($relationshipTypes);
644
645 foreach ($relationshipTypes as $key => $var) {
646 list($type) = explode('_', $key);
647
648 $relationships[$key]['title'] = $var;
649 $relationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
650 $relationships[$key]['export'] = TRUE;
651 $relationships[$key]['relationship_type_id'] = $type;
652 $relationships[$key]['related'] = TRUE;
653 $relationships[$key]['hasRelationType'] = 1;
654 }
655
656 if (!empty($relationships)) {
657 $fields[$contactType] = array_merge($fields[$contactType],
658 ['related' => ['title' => ts('- related contact info -')]],
659 $relationships
660 );
661 }
662 }
663 }
664
665 // Get the current employer for mapping.
666 if ($mappingType == 'Export') {
667 $fields['Individual']['current_employer_id']['title'] = ts('Current Employer ID');
668 }
669
670 // Contact Sub Type For export
671 $subTypes = CRM_Contact_BAO_ContactType::subTypeInfo();
672 foreach ($subTypes as $subType => $info) {
673 //adding subtype specific relationships CRM-5256
674 $csRelationships = [];
675
676 if ($mappingType == 'Export') {
677 $subTypeRelationshipTypes
678 = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $info['parent'],
679 FALSE, 'label', TRUE, $subType);
680
681 foreach ($subTypeRelationshipTypes as $key => $var) {
682 if (!array_key_exists($key, $fields[$info['parent']])) {
683 list($type) = explode('_', $key);
684
685 $csRelationships[$key]['title'] = $var;
686 $csRelationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
687 $csRelationships[$key]['export'] = TRUE;
688 $csRelationships[$key]['relationship_type_id'] = $type;
689 $csRelationships[$key]['related'] = TRUE;
690 $csRelationships[$key]['hasRelationType'] = 1;
691 }
692 }
693 }
694
695 $fields[$subType] = $fields[$info['parent']] + $csRelationships;
696
697 //custom fields for sub type
698 $subTypeFields = CRM_Core_BAO_CustomField::getFieldsForImport($subType);
699 $fields[$subType] += $subTypeFields;
700 }
701
702 return $fields;
703 }
704
705 /**
706 * Adds component fields to the export fields array; returns list of components.
707 *
708 * @param array $fields
709 * @param string $mappingType
710 * @param int $exportMode
711 * @return array
712 */
713 public static function addComponentFields(&$fields, $mappingType, $exportMode) {
714 $compArray = [];
715
716 if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT)) {
717 if (CRM_Core_Permission::access('CiviContribute')) {
718 $fields['Contribution'] = CRM_Core_DAO::getExportableFieldsWithPseudoConstants('CRM_Contribute_BAO_Contribution');
719 unset($fields['Contribution']['contribution_contact_id']);
720 $compArray['Contribution'] = ts('Contribution');
721 }
722 }
723
724 if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT)) {
725 if (CRM_Core_Permission::access('CiviEvent')) {
726 $fields['Participant'] = CRM_Event_BAO_Participant::exportableFields();
727 //get the component payment fields
728 // @todo - review this - inconsistent with other entities & hacky.
729 if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
730 $componentPaymentFields = [];
731 foreach ([
732 'componentPaymentField_total_amount' => ts('Total Amount'),
733 'componentPaymentField_contribution_status' => ts('Contribution Status'),
734 'componentPaymentField_received_date' => ts('Date Received'),
735 'componentPaymentField_payment_instrument' => ts('Payment Method'),
736 'componentPaymentField_transaction_id' => ts('Transaction ID'),
737 ] as $payField => $payTitle) {
738 $componentPaymentFields[$payField] = ['title' => $payTitle];
739 }
740 $fields['Participant'] = array_merge($fields['Participant'], $componentPaymentFields);
741 }
742
743 $compArray['Participant'] = ts('Participant');
744 }
745 }
746
747 if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT)) {
748 if (CRM_Core_Permission::access('CiviMember')) {
749 $fields['Membership'] = CRM_Member_BAO_Membership::getMembershipFields($exportMode);
750 unset($fields['Membership']['membership_contact_id']);
751 $compArray['Membership'] = ts('Membership');
752 }
753 }
754
755 if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT)) {
756 if (CRM_Core_Permission::access('CiviPledge')) {
757 $fields['Pledge'] = CRM_Pledge_BAO_Pledge::exportableFields();
758 unset($fields['Pledge']['pledge_contact_id']);
759 $compArray['Pledge'] = ts('Pledge');
760 }
761 }
762
763 if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::CASE_EXPORT)) {
764 if (CRM_Core_Permission::access('CiviCase')) {
765 $fields['Case'] = CRM_Case_BAO_Case::exportableFields();
766 $compArray['Case'] = ts('Case');
767
768 $fields['Activity'] = CRM_Activity_BAO_Activity::exportableFields('Case');
769 $compArray['Activity'] = ts('Case Activity');
770
771 unset($fields['Case']['case_contact_id']);
772 }
773 }
774 if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::GRANT_EXPORT)) {
775 if (CRM_Core_Permission::access('CiviGrant')) {
776 $fields['Grant'] = CRM_Grant_BAO_Grant::exportableFields();
777 unset($fields['Grant']['grant_contact_id']);
778 if ($mappingType == 'Search Builder') {
779 unset($fields['Grant']['grant_type_id']);
780 }
781 $compArray['Grant'] = ts('Grant');
782 }
783 }
784
785 if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT)) {
786 $fields['Activity'] = CRM_Activity_BAO_Activity::exportableFields('Activity');
787 $compArray['Activity'] = ts('Activity');
788 }
789
790 return $compArray;
791 }
792
793 /**
794 * Get the parameters for a mapping field in a saveable format from the quickform mapping format.
795 *
796 * @param array $defaults
797 * @param array $v
798 *
799 * @return array
800 */
801 public static function getMappingParams($defaults, $v) {
802 $locationTypeId = NULL;
803 $saveMappingFields = $defaults;
804
805 $saveMappingFields['name'] = $v['1'] ?? NULL;
806 $saveMappingFields['contact_type'] = $v['0'] ?? NULL;
807 $locationId = $v['2'] ?? NULL;
808 $saveMappingFields['location_type_id'] = is_numeric($locationId) ? $locationId : NULL;
809
810 if ($v[1] == 'phone') {
811 $saveMappingFields['phone_type_id'] = $v['3'] ?? NULL;
812 }
813 elseif ($v[1] == 'im') {
814 $saveMappingFields['im_provider_id'] = $v['3'] ?? NULL;
815 }
816
817 // Handle mapping for 'related contact' fields
818 if (count(explode('_', CRM_Utils_Array::value('1', $v))) > 2) {
819 list($id, $first, $second) = explode('_', CRM_Utils_Array::value('1', $v));
820 if (($first == 'a' && $second == 'b') || ($first == 'b' && $second == 'a')) {
821
822 if (!empty($v['2'])) {
823 $saveMappingFields['name'] = $v['2'] ?? NULL;
824 }
825 elseif (!empty($v['4'])) {
826 $saveMappingFields['name'] = $v['4'] ?? NULL;
827 }
828
829 if (is_numeric(CRM_Utils_Array::value('3', $v))) {
830 $locationTypeId = $v['3'] ?? NULL;
831 }
832 elseif (is_numeric(CRM_Utils_Array::value('5', $v))) {
833 $locationTypeId = $v['5'] ?? NULL;
834 }
835
836 if (is_numeric(CRM_Utils_Array::value('4', $v))) {
837 if ($saveMappingFields['name'] === 'im') {
838 $saveMappingFields['im_provider_id'] = $v[4];
839 }
840 else {
841 $saveMappingFields['phone_type_id'] = $v['4'] ?? NULL;
842 }
843 }
844 elseif (is_numeric(CRM_Utils_Array::value('6', $v))) {
845 $saveMappingFields['phone_type_id'] = $v['6'] ?? NULL;
846 }
847
848 $saveMappingFields['location_type_id'] = is_numeric($locationTypeId) ? $locationTypeId : NULL;
849 $saveMappingFields['relationship_type_id'] = $id;
850 $saveMappingFields['relationship_direction'] = "{$first}_{$second}";
851 }
852 }
853
854 return $saveMappingFields;
855 }
856
857 /**
858 * Load saved mapping.
859 *
860 * @param $mappingLocation
861 * @param int $x
862 * @param int $i
863 * @param $mappingName
864 * @param $mapperFields
865 * @param $mappingContactType
866 * @param $mappingRelation
867 * @param array $specialFields
868 * @param $mappingPhoneType
869 * @param $phoneType
870 * @param array $defaults
871 * @param array $noneArray
872 * @param $imProvider
873 * @param $mappingImProvider
874 * @param $mappingOperator
875 * @param $mappingValue
876 *
877 * @return array
878 */
879 protected static function loadSavedMapping($mappingLocation, int $x, int $i, $mappingName, $mapperFields, $mappingContactType, $mappingRelation, array $specialFields, $mappingPhoneType, array $defaults, array $noneArray, $mappingImProvider, $mappingOperator, $mappingValue) {
880 $jsSet = FALSE;
881 $locationId = $mappingLocation[$x][$i] ?? 0;
882 if (isset($mappingName[$x][$i])) {
883 if (is_array($mapperFields[$mappingContactType[$x][$i]])) {
884
885 if (isset($mappingRelation[$x][$i])) {
886 $relLocationId = $mappingLocation[$x][$i] ?? 0;
887 if (!$relLocationId && in_array($mappingName[$x][$i], $specialFields)) {
888 $relLocationId = " ";
889 }
890
891 $relPhoneType = $mappingPhoneType[$x][$i] ?? NULL;
892
893 $defaults["mapper[$x][$i]"] = [
894 $mappingContactType[$x][$i],
895 $mappingRelation[$x][$i],
896 $locationId,
897 $phoneType,
898 $mappingName[$x][$i],
899 $relLocationId,
900 $relPhoneType,
901 ];
902
903 if (!$locationId) {
904 $noneArray[] = [$x, $i, 2];
905 }
906 if (!$phoneType && !$imProvider) {
907 $noneArray[] = [$x, $i, 3];
908 }
909 if (!$mappingName[$x][$i]) {
910 $noneArray[] = [$x, $i, 4];
911 }
912 if (!$relLocationId) {
913 $noneArray[] = [$x, $i, 5];
914 }
915 if (!$relPhoneType) {
916 $noneArray[] = [$x, $i, 6];
917 }
918 $noneArray[] = [$x, $i, 2];
919 }
920 else {
921 $phoneType = $mappingPhoneType[$x][$i] ?? NULL;
922 $imProvider = $mappingImProvider[$x][$i] ?? NULL;
923 if (!$locationId && in_array($mappingName[$x][$i], $specialFields)) {
924 $locationId = " ";
925 }
926
927 $defaults["mapper[$x][$i]"] = [
928 $mappingContactType[$x][$i],
929 $mappingName[$x][$i],
930 $locationId,
931 $phoneType,
932 ];
933 if (!$mappingName[$x][$i]) {
934 $noneArray[] = [$x, $i, 1];
935 }
936 if (!$locationId) {
937 $noneArray[] = [$x, $i, 2];
938 }
939 if (!$phoneType && !$imProvider) {
940 $noneArray[] = [$x, $i, 3];
941 }
942
943 $noneArray[] = [$x, $i, 4];
944 $noneArray[] = [$x, $i, 5];
945 $noneArray[] = [$x, $i, 6];
946 }
947
948 $jsSet = TRUE;
949
950 if (CRM_Utils_Array::value($i, CRM_Utils_Array::value($x, $mappingOperator))) {
951 $defaults["operator[$x][$i]"] = $mappingOperator[$x][$i] ?? NULL;
952 }
953
954 if (CRM_Utils_Array::value($i, CRM_Utils_Array::value($x, $mappingValue))) {
955 $defaults["value[$x][$i]"] = $mappingValue[$x][$i] ?? NULL;
956 }
957 }
958 }
959 return [$mappingName, $defaults, $noneArray, $jsSet];
960 }
961
962 /**
963 * Function returns all custom fields with group title and
964 * field label
965 *
966 * @param int $relationshipTypeId
967 * Related relationship type id.
968 *
969 * @return array
970 * all custom field titles
971 */
972 public function getRelationTypeCustomGroupData($relationshipTypeId) {
973
974 $customFields = CRM_Core_BAO_CustomField::getFields('Relationship', NULL, NULL, $relationshipTypeId, NULL, NULL);
975 $groupTitle = [];
976 foreach ($customFields as $krelation => $vrelation) {
977 $groupTitle[$vrelation['label']] = $vrelation['groupTitle'] . '...' . $vrelation['label'];
978 }
979 return $groupTitle;
980 }
981
982 /**
983 * Function returns all Custom group Names.
984 *
985 * @param int $customfieldId
986 * Related file id.
987 *
988 * @return null|string
989 * $customGroupName all custom group names
990 */
991 public static function getCustomGroupName($customfieldId) {
992 if ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($customfieldId)) {
993 $customGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $customFieldId, 'custom_group_id');
994 $customGroupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'title');
995
996 $customGroupName = CRM_Utils_String::ellipsify($customGroupName, 13);
997
998 return $customGroupName;
999 }
1000 }
1001
1002 /**
1003 * Function returns associated array of elements, that will be passed for search
1004 *
1005 * @param array $params
1006 * Associated array of submitted values.
1007 * @param bool $row
1008 * Row no of the fields.
1009 *
1010 *
1011 * @return array
1012 * formatted associated array of elements
1013 * @throws CRM_Core_Exception
1014 */
1015 public static function formattedFields(&$params, $row = FALSE) {
1016 $fields = [];
1017
1018 if (empty($params) || !isset($params['mapper'])) {
1019 return $fields;
1020 }
1021
1022 $types = ['Individual', 'Organization', 'Household'];
1023 foreach ($params['mapper'] as $key => $value) {
1024 $contactType = NULL;
1025 foreach ($value as $k => $v) {
1026 if (in_array($v[0], $types)) {
1027 if ($contactType && $contactType != $v[0]) {
1028 throw new CRM_Core_Exception(ts("Cannot have two clauses with different types: %1, %2",
1029 [1 => $contactType, 2 => $v[0]]
1030 ));
1031 }
1032 $contactType = $v[0];
1033 }
1034 if (!empty($v['1'])) {
1035 $fldName = $v[1];
1036 $v2 = $v['2'] ?? NULL;
1037 if ($v2 && trim($v2)) {
1038 $fldName .= "-{$v[2]}";
1039 }
1040
1041 $v3 = $v['3'] ?? NULL;
1042 if ($v3 && trim($v3)) {
1043 $fldName .= "-{$v[3]}";
1044 }
1045
1046 $value = $params['value'][$key][$k];
1047
1048 if ($v[0] == 'Contribution' && substr($fldName, 0, 7) != 'custom_'
1049 && substr($fldName, 0, 10) != 'financial_'
1050 && substr($fldName, 0, 8) != 'payment_') {
1051 if (substr($fldName, 0, 13) != 'contribution_') {
1052 $fldName = 'contribution_' . $fldName;
1053 }
1054 }
1055
1056 // CRM-14983: verify if values are comma separated convert to array
1057 if (!is_array($value) && strstr($params['operator'][$key][$k], 'IN')) {
1058 $value = explode(',', $value);
1059 $value = [$params['operator'][$key][$k] => $value];
1060 }
1061 // CRM-19081 Fix legacy StateProvince Field Values.
1062 // These derive from smart groups created using search builder under older
1063 // CiviCRM versions.
1064 if (!is_numeric($value) && $fldName == 'state_province') {
1065 $value = CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Address', 'state_province_id', $value);
1066 }
1067
1068 if ($row) {
1069 $fields[] = [
1070 $fldName,
1071 $params['operator'][$key][$k],
1072 $value,
1073 $key,
1074 $k,
1075 ];
1076 }
1077 else {
1078 $fields[] = [
1079 $fldName,
1080 $params['operator'][$key][$k],
1081 $value,
1082 $key,
1083 0,
1084 ];
1085 }
1086 }
1087 }
1088 if ($contactType) {
1089 $fields[] = [
1090 'contact_type',
1091 '=',
1092 $contactType,
1093 $key,
1094 0,
1095 ];
1096 }
1097 }
1098
1099 //add sortByCharacter values
1100 if (isset($params['sortByCharacter'])) {
1101 $fields[] = [
1102 'sortByCharacter',
1103 '=',
1104 $params['sortByCharacter'],
1105 0,
1106 0,
1107 ];
1108 }
1109 return $fields;
1110 }
1111
1112 /**
1113 * @param array $params
1114 *
1115 * @return array
1116 */
1117 public static function &returnProperties(&$params) {
1118 $fields = [
1119 'contact_type' => 1,
1120 'contact_sub_type' => 1,
1121 'sort_name' => 1,
1122 ];
1123
1124 if (empty($params) || empty($params['mapper'])) {
1125 return $fields;
1126 }
1127
1128 $locationTypes = CRM_Core_DAO_Address::buildOptions('location_type_id', 'validate');
1129 foreach ($params['mapper'] as $key => $value) {
1130 foreach ($value as $k => $v) {
1131 if (isset($v[1])) {
1132 if ($v[1] == 'groups' || $v[1] == 'tags') {
1133 continue;
1134 }
1135
1136 if (isset($v[2]) && is_numeric($v[2])) {
1137 if (!array_key_exists('location', $fields)) {
1138 $fields['location'] = [];
1139 }
1140
1141 // make sure that we have a location fields and a location type for this
1142 $locationName = $locationTypes[$v[2]];
1143 if (!array_key_exists($locationName, $fields['location'])) {
1144 $fields['location'][$locationName] = [];
1145 $fields['location'][$locationName]['location_type'] = $v[2];
1146 }
1147
1148 if ($v[1] == 'phone' || $v[1] == 'email' || $v[1] == 'im') {
1149 // phone type handling
1150 if (isset($v[3])) {
1151 $fields['location'][$locationName][$v[1] . "-" . $v[3]] = 1;
1152 }
1153 else {
1154 $fields['location'][$locationName][$v[1]] = 1;
1155 }
1156 }
1157 else {
1158 $fields['location'][$locationName][$v[1]] = 1;
1159 }
1160 }
1161 else {
1162 $fields[$v[1]] = 1;
1163 }
1164 }
1165 }
1166 }
1167
1168 return $fields;
1169 }
1170
1171 /**
1172 * Save the mapping field info for search builder / export given the formvalues
1173 *
1174 * @param array $params
1175 * Asscociated array of formvalues.
1176 * @param int $mappingId
1177 * Mapping id.
1178 *
1179 * @return NULL
1180 */
1181 public static function saveMappingFields($params, $mappingId) {
1182 //delete mapping fields records for existing mapping
1183 $mappingFields = new CRM_Core_DAO_MappingField();
1184 $mappingFields->mapping_id = $mappingId;
1185 $mappingFields->delete();
1186
1187 if (empty($params['mapper'])) {
1188 return NULL;
1189 }
1190
1191 //save record in mapping field table
1192 foreach ($params['mapper'] as $key => $value) {
1193 $colCnt = 0;
1194 foreach ($value as $k => $v) {
1195
1196 if (!empty($v['1'])) {
1197 $saveMappingParams = self::getMappingParams(
1198 [
1199 'mapping_id' => $mappingId,
1200 'grouping' => $key,
1201 'operator' => $params['operator'][$key][$k] ?? NULL,
1202 'value' => $params['value'][$key][$k] ?? NULL,
1203 'column_number' => $colCnt,
1204 ], $v);
1205 $saveMappingField = new CRM_Core_DAO_MappingField();
1206 $saveMappingField->copyValues($saveMappingParams);
1207 $saveMappingField->save();
1208 $colCnt++;
1209 }
1210 }
1211 }
1212 }
1213
1214 }