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