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