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