Mapping.php 39.2 KB
Newer Older
totten's avatar
totten committed
1 2 3
<?php
/*
 +--------------------------------------------------------------------+
4
 | Copyright CiviCRM LLC. All rights reserved.                        |
totten's avatar
totten committed
5
 |                                                                    |
6 7 8
 | This work is published under the GNU AGPLv3 license with some      |
 | permitted exceptions and without any warranty. For full license    |
 | and copyright information, see https://civicrm.org/licensing       |
totten's avatar
totten committed
9
 +--------------------------------------------------------------------+
10
 */
totten's avatar
totten committed
11 12 13 14

/**
 *
 * @package CRM
15
 * @copyright CiviCRM LLC https://civicrm.org/licensing
totten's avatar
totten committed
16 17 18 19
 */
class CRM_Core_BAO_Mapping extends CRM_Core_DAO_Mapping {

  /**
20
   * Class constructor.
totten's avatar
totten committed
21
   */
22
  public function __construct() {
totten's avatar
totten committed
23 24 25 26
    parent::__construct();
  }

  /**
27
   * Fetch object based on array of properties.
totten's avatar
totten committed
28
   *
29 30 31 32
   * @param array $params
   *   (reference ) an assoc array of name/value pairs.
   * @param array $defaults
   *   (reference ) an assoc array to hold the flattened values.
totten's avatar
totten committed
33
   *
34 35
   * @return object
   *   CRM_Core_DAO_Mapping object on success, otherwise NULL
totten's avatar
totten committed
36
   */
37
  public static function retrieve(&$params, &$defaults) {
totten's avatar
totten committed
38 39 40 41 42 43 44 45 46 47
    $mapping = new CRM_Core_DAO_Mapping();
    $mapping->copyValues($params);
    if ($mapping->find(TRUE)) {
      CRM_Core_DAO::storeValues($mapping, $defaults);
      return $mapping;
    }
    return NULL;
  }

  /**
48
   * Delete the mapping.
totten's avatar
totten committed
49
   *
50 51
   * @param int $id
   *   Mapping id.
totten's avatar
totten committed
52
   *
Web Access's avatar
Web Access committed
53
   * @return bool
totten's avatar
totten committed
54
   */
55
  public static function del($id) {
totten's avatar
totten committed
56 57 58
    // delete from mapping_field table
    $mappingField = new CRM_Core_DAO_MappingField();
    $mappingField->mapping_id = $id;
59
    $mappingField->delete();
totten's avatar
totten committed
60 61 62 63

    // delete from mapping table
    $mapping = new CRM_Core_DAO_Mapping();
    $mapping->id = $id;
Sudha Bisht's avatar
Sudha Bisht committed
64 65 66 67 68
    if ($mapping->find(TRUE)) {
      $result = $mapping->delete();
      return $result;
    }
    return FALSE;
totten's avatar
totten committed
69 70 71
  }

  /**
72
   * Takes an associative array and creates a contact object.
totten's avatar
totten committed
73 74 75 76 77
   *
   * The function extract all the params it needs to initialize the create a
   * contact object. the params array could contain additional unused name/value
   * pairs
   *
78 79
   * @param array $params
   *   An array of name/value pairs.
totten's avatar
totten committed
80
   *
81 82
   * @return object
   *   CRM_Core_DAO_Mapper object on success, otherwise NULL
totten's avatar
totten committed
83
   */
84
  public static function add($params) {
totten's avatar
totten committed
85 86 87 88 89 90 91 92
    $mapping = new CRM_Core_DAO_Mapping();
    $mapping->copyValues($params);
    $mapping->save();

    return $mapping;
  }

  /**
93
   * Get the list of mappings for a select or select2 element.
totten's avatar
totten committed
94
   *
95 96
   * @param string $mappingType
   *   Mapping type name.
97 98
   * @param bool $select2
   *   Format for select2
99
   *
100
   * @return array
101
   *   Array of mapping names, keyed by id.
totten's avatar
totten committed
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 109
        'sort' => 'name',
        'limit' => 0,
110 111 112
      ],
    ]);
    $mapping = [];
totten's avatar
totten committed
113

114 115 116 117 118 119 120 121 122 123 124
    foreach ($result['values'] as $id => $value) {
      if ($select2) {
        $item = ['id' => $id, 'text' => $value['name']];
        if (!empty($value['description'])) {
          $item['description'] = $value['description'];
        }
        $mapping[] = $item;
      }
      else {
        $mapping[$id] = $value['name'];
      }
totten's avatar
totten committed
125 126 127 128
    }
    return $mapping;
  }

129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
  /**
   * Get the mappings array, creating if it does not exist.
   *
   * @param string $mappingType
   *   Mapping type name.
   *
   * @return array
   *   Array of mapping names, keyed by id.
   *
   * @throws \CiviCRM_API3_Exception
   */
  public static function getCreateMappingValues($mappingType) {
    try {
      return CRM_Core_BAO_Mapping::getMappings($mappingType);
    }
    catch (CiviCRM_API3_Exception $e) {
      // Having a valid mapping_type_id is now enforced. However, rather than error let's
      // add it. This is required for Multi value which could be done by upgrade script, but
      // it feels like there could be other instances so this is safer.
      $errorParams = $e->getExtraParams();
      if ($errorParams['error_field'] === 'mapping_type_id') {
150 151
        $mappingValues = civicrm_api3('Mapping', 'getoptions', ['field' => 'mapping_type_id']);
        civicrm_api3('OptionValue', 'create', [
152 153
          'option_group_id' => 'mapping_type',
          'label' => $mappingType,
JonGold's avatar
JonGold committed
154
          'name' => $mappingType,
155 156
          'value' => max(array_keys($mappingValues['values'])) + 1,
          'is_reserved' => 1,
157
        ]);
158 159 160 161 162 163
        return CRM_Core_BAO_Mapping::getMappings($mappingType);
      }
      throw $e;
    }
  }

totten's avatar
totten committed
164
  /**
165
   * Get the mapping fields.
totten's avatar
totten committed
166
   *
167 168
   * @param int $mappingId
   *   Mapping id.
169
   *
170 171 172 173
   * @param bool $addPrimary
   *   Add the key 'Primary' when the field is a location field AND there is
   *   no location type (meaning Primary)?
   *
174 175
   * @return array
   *   array of mapping fields
totten's avatar
totten committed
176
   */
177
  public static function getMappingFields($mappingId, $addPrimary = FALSE) {
totten's avatar
totten committed
178 179 180 181 182 183
    //mapping is to be loaded from database
    $mapping = new CRM_Core_DAO_MappingField();
    $mapping->mapping_id = $mappingId;
    $mapping->orderBy('column_number');
    $mapping->find();

184 185
    $mappingName = $mappingLocation = $mappingContactType = $mappingPhoneType = [];
    $mappingImProvider = $mappingRelation = $mappingOperator = $mappingValue = $mappingWebsiteType = [];
totten's avatar
totten committed
186 187 188 189 190 191 192
    while ($mapping->fetch()) {
      $mappingName[$mapping->grouping][$mapping->column_number] = $mapping->name;
      $mappingContactType[$mapping->grouping][$mapping->column_number] = $mapping->contact_type;

      if (!empty($mapping->location_type_id)) {
        $mappingLocation[$mapping->grouping][$mapping->column_number] = $mapping->location_type_id;
      }
193 194 195 196 197 198 199 200
      elseif ($addPrimary) {
        if (CRM_Contact_BAO_Contact::isFieldHasLocationType($mapping->name)) {
          $mappingLocation[$mapping->grouping][$mapping->column_number] = ts('Primary');
        }
        else {
          $mappingLocation[$mapping->grouping][$mapping->column_number] = NULL;
        }
      }
totten's avatar
totten committed
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227

      if (!empty($mapping->phone_type_id)) {
        $mappingPhoneType[$mapping->grouping][$mapping->column_number] = $mapping->phone_type_id;
      }

      // get IM service provider type id from mapping fields
      if (!empty($mapping->im_provider_id)) {
        $mappingImProvider[$mapping->grouping][$mapping->column_number] = $mapping->im_provider_id;
      }

      if (!empty($mapping->website_type_id)) {
        $mappingWebsiteType[$mapping->grouping][$mapping->column_number] = $mapping->website_type_id;
      }

      if (!empty($mapping->relationship_type_id)) {
        $mappingRelation[$mapping->grouping][$mapping->column_number] = "{$mapping->relationship_type_id}_{$mapping->relationship_direction}";
      }

      if (!empty($mapping->operator)) {
        $mappingOperator[$mapping->grouping][$mapping->column_number] = $mapping->operator;
      }

      if (!empty($mapping->value)) {
        $mappingValue[$mapping->grouping][$mapping->column_number] = $mapping->value;
      }
    }

228
    return [
totten's avatar
totten committed
229 230 231 232 233 234 235 236 237
      $mappingName,
      $mappingContactType,
      $mappingLocation,
      $mappingPhoneType,
      $mappingImProvider,
      $mappingRelation,
      $mappingOperator,
      $mappingValue,
      $mappingWebsiteType,
238
    ];
totten's avatar
totten committed
239 240
  }

241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
  /**
   * Get un-indexed array of the field values for the given mapping id.
   *
   * For example if passing a mapping ID & name the returned array would look like
   *   ['First field name', 'second field name']
   *
   * @param int $mappingID
   * @param string $fieldName
   *
   * @return array
   * @throws \CiviCRM_API3_Exception
   */
  public static function getMappingFieldValues($mappingID, $fieldName) {
    return array_merge(CRM_Utils_Array::collect($fieldName, civicrm_api3('MappingField', 'get', ['mapping_id' => $mappingID, 'return' => $fieldName])['values']));
  }

totten's avatar
totten committed
257
  /**
258
   * Check Duplicate Mapping Name.
totten's avatar
totten committed
259
   *
colemanw's avatar
colemanw committed
260 261 262 263
   * @param string $nameField
   *   mapping Name.
   * @param string $mapTypeId
   *   mapping Type.
totten's avatar
totten committed
264
   *
Web Access's avatar
Web Access committed
265
   * @return bool
totten's avatar
totten committed
266
   */
267
  public static function checkMapping($nameField, $mapTypeId) {
totten's avatar
totten committed
268 269 270
    $mapping = new CRM_Core_DAO_Mapping();
    $mapping->name = $nameField;
    $mapping->mapping_type_id = $mapTypeId;
271
    return (bool) $mapping->find(TRUE);
totten's avatar
totten committed
272 273 274
  }

  /**
eileenmcnaugton's avatar
eileenmcnaugton committed
275
   * Function returns associated array of elements, that will be passed for search.
totten's avatar
totten committed
276
   *
277 278
   * @param int $smartGroupId
   *   Smart group id.
totten's avatar
totten committed
279
   *
280 281
   * @return array
   *   associated array of elements
totten's avatar
totten committed
282
   */
283
  public static function getFormattedFields($smartGroupId) {
284
    $returnFields = [];
totten's avatar
totten committed
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305

    //get the fields from mapping table
    $dao = new CRM_Core_DAO_MappingField();
    $dao->mapping_id = $smartGroupId;
    $dao->find();
    while ($dao->fetch()) {
      $fldName = $dao->name;
      if ($dao->location_type_id) {
        $fldName .= "-{$dao->location_type_id}";
      }
      if ($dao->phone_type) {
        $fldName .= "-{$dao->phone_type}";
      }
      $returnFields[$fldName]['value'] = $dao->value;
      $returnFields[$fldName]['op'] = $dao->operator;
      $returnFields[$fldName]['grouping'] = $dao->grouping;
    }
    return $returnFields;
  }

  /**
306
   * Build the mapping form for Search Builder.
totten's avatar
totten committed
307
   *
308 309 310
   * @param CRM_Core_Form $form
   * @param int $mappingId
   * @param int $columnNo
311 312
   * @param int $blockCount
   *   (no of blocks shown).
eileen's avatar
eileen committed
313
   * @param int $exportMode
totten's avatar
totten committed
314
   */
315
  public static function buildMappingForm(&$form, $mappingId, $columnNo, $blockCount, $exportMode = NULL) {
316

317 318
    $hasLocationTypes = [];
    $hasRelationTypes = [];
totten's avatar
totten committed
319

320
    $columnCount = $columnNo;
321 322 323 324
    $form->addElement('xbutton', 'addBlock', ts('Also include contacts where'),
      [
        'type' => 'submit',
        'class' => 'submit-link',
325
        'value' => 1,
326
      ]
327
    );
totten's avatar
totten committed
328

329
    $contactTypes = CRM_Contact_BAO_ContactType::basicTypes();
330
    $fields = self::getBasicFields('Search Builder');
totten's avatar
totten committed
331

332
    // Unset groups, tags, notes for component export
totten's avatar
totten committed
333
    if ($exportMode != CRM_Export_Form_Select::CONTACT_EXPORT) {
334 335
      foreach (array_keys($fields) as $type) {
        CRM_Utils_Array::remove($fields[$type], 'groups', 'tags', 'notes');
totten's avatar
totten committed
336 337 338
      }
    }

339 340 341 342 343 344 345 346
    // Build the common contact fields array.
    $fields['Contact'] = [];
    foreach ($fields[$contactTypes[0]] as $key => $value) {
      // If a field exists across all contact types, move it to the "Contact" selector
      $ubiquitious = TRUE;
      foreach ($contactTypes as $type) {
        if (!isset($fields[$type][$key])) {
          $ubiquitious = FALSE;
totten's avatar
totten committed
347 348
        }
      }
349 350 351 352 353
      if ($ubiquitious) {
        $fields['Contact'][$key] = $value;
        foreach ($contactTypes as $type) {
          unset($fields[$type][$key]);
        }
totten's avatar
totten committed
354 355
      }
    }
356 357 358 359 360 361 362 363 364
    if (array_key_exists('note', $fields['Contact'])) {
      $noteTitle = $fields['Contact']['note']['title'];
      $fields['Contact']['note']['title'] = $noteTitle . ': ' . ts('Body and Subject');
      $fields['Contact']['note_body'] = ['title' => $noteTitle . ': ' . ts('Body Only'), 'name' => 'note_body'];
      $fields['Contact']['note_subject'] = [
        'title' => $noteTitle . ': ' . ts('Subject Only'),
        'name' => 'note_subject',
      ];
    }
totten's avatar
totten committed
365

366
    // add component fields
367
    $compArray = self::addComponentFields($fields, 'Search Builder', $exportMode);
totten's avatar
totten committed
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390

    foreach ($fields as $key => $value) {

      foreach ($value as $key1 => $value1) {
        //CRM-2676, replacing the conflict for same custom field name from different custom group.
        $customGroupName = self::getCustomGroupName($key1);

        if ($customGroupName) {
          $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $customGroupName . ': ' . $value1['title'];
        }
        else {
          $relatedMapperFields[$key][$key1] = $mapperFields[$key][$key1] = $value1['title'];
        }
        if (isset($value1['hasLocationType'])) {
          $hasLocationTypes[$key][$key1] = $value1['hasLocationType'];
        }

        if (isset($value1['hasRelationType'])) {
          $hasRelationTypes[$key][$key1] = $value1['hasRelationType'];
          unset($relatedMapperFields[$key][$key1]);
        }
      }

391
      if (isset($relatedMapperFields[$key]['related'])) {
totten's avatar
totten committed
392 393 394 395
        unset($relatedMapperFields[$key]['related']);
      }
    }

396
    $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
totten's avatar
totten committed
397 398 399

    $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();

400 401 402
    // FIXME: dirty hack to make the default option show up first.  This
    // avoids a mozilla browser bug with defaults on dynamically constructed
    // selector widgets.
totten's avatar
totten committed
403 404 405
    if ($defaultLocationType) {
      $defaultLocation = $locationTypes[$defaultLocationType->id];
      unset($locationTypes[$defaultLocationType->id]);
406
      $locationTypes = [$defaultLocationType->id => $defaultLocation] + $locationTypes;
totten's avatar
totten committed
407 408
    }

409
    $locationTypes = [' ' => ts('Primary')] + $locationTypes;
totten's avatar
totten committed
410 411 412

    // since we need a hierarchical list to display contact types & subtypes,
    // 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;
totten's avatar
totten committed
415

416
    $sel1 = ['' => ts('- select record type -')] + $contactTypeSelect + $compArray;
totten's avatar
totten committed
417 418 419

    foreach ($sel1 as $key => $sel) {
      if ($key) {
Dmitry Smirnov's avatar
Dmitry Smirnov committed
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 424
          asort($mapperFields[$key]);
        }
425
        $sel2[$key] = ['' => ts('- select field -')] + $mapperFields[$key];
totten's avatar
totten committed
426 427 428
      }
    }

totten's avatar
totten committed
429 430 431
    $sel3[''] = NULL;
    $sel5[''] = NULL;
    $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
432
    $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
totten's avatar
totten committed
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
    asort($phoneTypes);

    foreach ($sel1 as $k => $sel) {
      if ($k) {
        foreach ($locationTypes as $key => $value) {
          if (trim($key) != '') {
            $sel4[$k]['phone'][$key] = &$phoneTypes;
            $sel4[$k]['im'][$key] = &$imProviders;
          }
        }
      }
    }

    foreach ($sel1 as $k => $sel) {
      if ($k) {
        foreach ($mapperFields[$k] as $key => $value) {
          if (isset($hasLocationTypes[$k][$key])) {
            $sel3[$k][$key] = $locationTypes;
          }
          else {
            $sel3[$key] = NULL;
          }
        }
      }
    }

459
    // Array for core fields and relationship custom data
totten's avatar
totten committed
460 461 462
    $relationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, NULL, TRUE);

    //special fields that have location, hack for primary location
463
    $specialFields = [
totten's avatar
totten committed
464 465 466
      'street_address',
      'supplemental_address_1',
      'supplemental_address_2',
467
      'supplemental_address_3',
totten's avatar
totten committed
468 469 470 471 472 473 474 475 476 477
      'city',
      'postal_code',
      'postal_code_suffix',
      'geo_code_1',
      'geo_code_2',
      'state_province',
      'country',
      'phone',
      'email',
      'im',
478
    ];
totten's avatar
totten committed
479 480 481 482

    if (isset($mappingId)) {
      list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingImProvider,
        $mappingRelation, $mappingOperator, $mappingValue
totten's avatar
totten committed
483
        ) = CRM_Core_BAO_Mapping::getMappingFields($mappingId);
totten's avatar
totten committed
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504

      $blkCnt = count($mappingName);
      if ($blkCnt >= $blockCount) {
        $blockCount = $blkCnt + 1;
      }
      for ($x = 1; $x < $blockCount; $x++) {
        if (isset($mappingName[$x])) {
          $colCnt = count($mappingName[$x]);
          if ($colCnt >= $columnCount[$x]) {
            $columnCount[$x] = $colCnt;
          }
        }
      }
    }

    $form->_blockCount = $blockCount;
    $form->_columnCount = $columnCount;

    $form->set('blockCount', $form->_blockCount);
    $form->set('columnCount', $form->_columnCount);

505
    $defaults = $noneArray = $nullArray = [];
totten's avatar
totten committed
506 507 508 509 510

    for ($x = 1; $x < $blockCount; $x++) {

      for ($i = 0; $i < $columnCount[$x]; $i++) {

511
        $sel = &$form->addElement('hierselect', "mapper[$x][$i]", ts('Mapper for Field %1', [1 => $i]), NULL);
totten's avatar
totten committed
512 513 514
        $jsSet = FALSE;

        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);
totten's avatar
totten committed
516 517
        }
        //Fix for Search Builder
518
        $j = 4;
totten's avatar
totten committed
519 520 521 522 523 524

        $formValues = $form->exportValues();
        if (!$jsSet) {
          if (empty($formValues)) {
            // Incremented length for third select box(relationship type)
            for ($k = 1; $k < $j; $k++) {
525
              $noneArray[] = [$x, $i, $k];
totten's avatar
totten committed
526 527 528 529 530 531 532 533 534
            }
          }
          else {
            if (!empty($formValues['mapper'][$x])) {
              foreach ($formValues['mapper'][$x] as $value) {
                for ($k = 1; $k < $j; $k++) {
                  if (!isset($formValues['mapper'][$x][$i][$k]) ||
                    (!$formValues['mapper'][$x][$i][$k])
                  ) {
535
                    $noneArray[] = [$x, $i, $k];
totten's avatar
totten committed
536 537
                  }
                  else {
538
                    $nullArray[] = [$x, $i, $k];
totten's avatar
totten committed
539 540 541 542 543 544
                  }
                }
              }
            }
            else {
              for ($k = 1; $k < $j; $k++) {
545
                $noneArray[] = [$x, $i, $k];
totten's avatar
totten committed
546 547 548 549 550
              }
            }
          }
        }
        //Fix for Search Builder
551
        $sel->setOptions([$sel1, $sel2, $sel3, $sel4]);
totten's avatar
totten committed
552

553 554
        //CRM -2292, restricted array set
        $operatorArray = ['' => ts('-operator-')] + CRM_Core_SelectValues::getSearchBuilderOperators();
totten's avatar
totten committed
555

556 557
        $form->add('select', "operator[$x][$i]", '', $operatorArray);
        $form->add('text', "value[$x][$i]", '');
totten's avatar
totten committed
558 559
      }

560 561 562
      $form->addElement('xbutton', "addMore[$x]", ts('Another search field'), [
        'type' => 'submit',
        'class' => 'submit-link',
563
        'value' => 1,
564
      ]);
totten's avatar
totten committed
565 566 567 568
    }
    //end of block for

    $js = "<script type='text/javascript'>\n";
569
    $formName = "document.Builder";
totten's avatar
totten committed
570
    if (!empty($nullArray)) {
totten's avatar
totten committed
571
      $js .= "var nullArray = [";
572 573
      $elements = [];
      $seen = [];
totten's avatar
totten committed
574 575 576 577 578 579 580 581 582 583
      foreach ($nullArray as $element) {
        $key = "{$element[0]}, {$element[1]}, {$element[2]}";
        if (!isset($seen[$key])) {
          $elements[] = "[$key]";
          $seen[$key] = 1;
        }
      }
      $js .= implode(', ', $elements);
      $js .= "]";
      $js .= "
584
                for (var i=0;i<nullArray.length;i++) {
totten's avatar
totten committed
585 586 587 588 589 590 591
                    if ( {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'] ) {
                        {$formName}['mapper['+nullArray[i][0]+']['+nullArray[i][1]+']['+nullArray[i][2]+']'].style.display = '';
                    }
                }
";
    }
    if (!empty($noneArray)) {
totten's avatar
totten committed
592
      $js .= "var noneArray = [";
593 594
      $elements = [];
      $seen = [];
totten's avatar
totten committed
595 596 597 598 599 600 601 602 603 604
      foreach ($noneArray as $element) {
        $key = "{$element[0]}, {$element[1]}, {$element[2]}";
        if (!isset($seen[$key])) {
          $elements[] = "[$key]";
          $seen[$key] = 1;
        }
      }
      $js .= implode(', ', $elements);
      $js .= "]";
      $js .= "
605
                for (var i=0;i<noneArray.length;i++) {
totten's avatar
totten committed
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
                    if ( {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'] ) {
  {$formName}['mapper['+noneArray[i][0]+']['+noneArray[i][1]+']['+noneArray[i][2]+']'].style.display = 'none';
                    }
                }
";
    }
    $js .= "</script>\n";

    $form->assign('initHideBoxes', $js);
    $form->assign('columnCount', $columnCount);
    $form->assign('blockCount', $blockCount);
    $form->setDefaults($defaults);

    $form->setDefaultAction('refresh');
  }

622 623 624 625 626
  /**
   * @param string $mappingType
   * @return array
   */
  public static function getBasicFields($mappingType) {
627
    $contactTypes = CRM_Contact_BAO_ContactType::basicTypes();
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
    $fields = [];
    foreach ($contactTypes as $contactType) {
      if ($mappingType == 'Search Builder') {
        // Get multiple custom group fields in this context
        $contactFields = CRM_Contact_BAO_Contact::exportableFields($contactType, FALSE, FALSE, FALSE, TRUE);
      }
      else {
        $contactFields = CRM_Contact_BAO_Contact::exportableFields($contactType, FALSE, TRUE);
      }
      $contactFields = array_merge($contactFields, CRM_Contact_BAO_Query_Hook::singleton()->getFields());

      // Exclude the address options disabled in the Address Settings
      $fields[$contactType] = CRM_Core_BAO_Address::validateAddressOptions($contactFields);
      ksort($fields[$contactType]);
      if ($mappingType == 'Export') {
        $relationships = [];
644
        $relationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $contactType);
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
        asort($relationshipTypes);

        foreach ($relationshipTypes as $key => $var) {
          list($type) = explode('_', $key);

          $relationships[$key]['title'] = $var;
          $relationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
          $relationships[$key]['export'] = TRUE;
          $relationships[$key]['relationship_type_id'] = $type;
          $relationships[$key]['related'] = TRUE;
          $relationships[$key]['hasRelationType'] = 1;
        }

        if (!empty($relationships)) {
          $fields[$contactType] = array_merge($fields[$contactType],
            ['related' => ['title' => ts('- related contact info -')]],
            $relationships
          );
        }
      }
    }

    // Get the current employer for mapping.
    if ($mappingType == 'Export') {
      $fields['Individual']['current_employer_id']['title'] = ts('Current Employer ID');
    }

672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
    // Contact Sub Type For export
    $subTypes = CRM_Contact_BAO_ContactType::subTypeInfo();
    foreach ($subTypes as $subType => $info) {
      //adding subtype specific relationships CRM-5256
      $csRelationships = [];

      if ($mappingType == 'Export') {
        $subTypeRelationshipTypes
          = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $info['parent'],
          FALSE, 'label', TRUE, $subType);

        foreach ($subTypeRelationshipTypes as $key => $var) {
          if (!array_key_exists($key, $fields[$info['parent']])) {
            list($type) = explode('_', $key);

            $csRelationships[$key]['title'] = $var;
            $csRelationships[$key]['headerPattern'] = '/' . preg_quote($var, '/') . '/';
            $csRelationships[$key]['export'] = TRUE;
            $csRelationships[$key]['relationship_type_id'] = $type;
            $csRelationships[$key]['related'] = TRUE;
            $csRelationships[$key]['hasRelationType'] = 1;
          }
        }
      }

      $fields[$subType] = $fields[$info['parent']] + $csRelationships;

      //custom fields for sub type
      $subTypeFields = CRM_Core_BAO_CustomField::getFieldsForImport($subType);
      $fields[$subType] += $subTypeFields;
    }

704 705 706
    return $fields;
  }

707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
  /**
   * Adds component fields to the export fields array; returns list of components.
   *
   * @param array $fields
   * @param string $mappingType
   * @param int $exportMode
   * @return array
   */
  public static function addComponentFields(&$fields, $mappingType, $exportMode) {
    $compArray = [];

    if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT)) {
      if (CRM_Core_Permission::access('CiviContribute')) {
        $fields['Contribution'] = CRM_Core_DAO::getExportableFieldsWithPseudoConstants('CRM_Contribute_BAO_Contribution');
        unset($fields['Contribution']['contribution_contact_id']);
        $compArray['Contribution'] = ts('Contribution');
      }
    }

    if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT)) {
      if (CRM_Core_Permission::access('CiviEvent')) {
        $fields['Participant'] = CRM_Event_BAO_Participant::exportableFields();
        //get the component payment fields
        // @todo - review this - inconsistent with other entities & hacky.
        if ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
          $componentPaymentFields = [];
733 734 735 736 737 738 739
          foreach ([
            'componentPaymentField_total_amount' => ts('Total Amount'),
            'componentPaymentField_contribution_status' => ts('Contribution Status'),
            'componentPaymentField_received_date' => ts('Date Received'),
            'componentPaymentField_payment_instrument' => ts('Payment Method'),
            'componentPaymentField_transaction_id' => ts('Transaction ID'),
          ] as $payField => $payTitle) {
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
            $componentPaymentFields[$payField] = ['title' => $payTitle];
          }
          $fields['Participant'] = array_merge($fields['Participant'], $componentPaymentFields);
        }

        $compArray['Participant'] = ts('Participant');
      }
    }

    if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT)) {
      if (CRM_Core_Permission::access('CiviMember')) {
        $fields['Membership'] = CRM_Member_BAO_Membership::getMembershipFields($exportMode);
        unset($fields['Membership']['membership_contact_id']);
        $compArray['Membership'] = ts('Membership');
      }
    }

    if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT)) {
      if (CRM_Core_Permission::access('CiviPledge')) {
        $fields['Pledge'] = CRM_Pledge_BAO_Pledge::exportableFields();
        unset($fields['Pledge']['pledge_contact_id']);
        $compArray['Pledge'] = ts('Pledge');
      }
    }

    if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::CASE_EXPORT)) {
      if (CRM_Core_Permission::access('CiviCase')) {
        $fields['Case'] = CRM_Case_BAO_Case::exportableFields();
        $compArray['Case'] = ts('Case');

        $fields['Activity'] = CRM_Activity_BAO_Activity::exportableFields('Case');
        $compArray['Activity'] = ts('Case Activity');

        unset($fields['Case']['case_contact_id']);
      }
    }
    if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::GRANT_EXPORT)) {
      if (CRM_Core_Permission::access('CiviGrant')) {
        $fields['Grant'] = CRM_Grant_BAO_Grant::exportableFields();
        unset($fields['Grant']['grant_contact_id']);
        if ($mappingType == 'Search Builder') {
          unset($fields['Grant']['grant_type_id']);
        }
        $compArray['Grant'] = ts('Grant');
      }
    }

    if (($mappingType == 'Search Builder') || ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT)) {
      $fields['Activity'] = CRM_Activity_BAO_Activity::exportableFields('Activity');
      $compArray['Activity'] = ts('Activity');
    }

    return $compArray;
  }

795 796 797
  /**
   * Get the parameters for a mapping field in a saveable format from the quickform mapping format.
   *
798
   * @param array $defaults
799 800 801 802
   * @param array $v
   *
   * @return array
   */
803
  public static function getMappingParams($defaults, $v) {
804
    $locationTypeId = NULL;
805
    $saveMappingFields = $defaults;
806

807 808 809
    $saveMappingFields['name'] = $v['1'] ?? NULL;
    $saveMappingFields['contact_type'] = $v['0'] ?? NULL;
    $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 820 821 822 823 824
    }

    // Handle mapping for 'related contact' fields
    if (count(explode('_', CRM_Utils_Array::value('1', $v))) > 2) {
      list($id, $first, $second) = explode('_', CRM_Utils_Array::value('1', $v));
      if (($first == 'a' && $second == 'b') || ($first == 'b' && $second == 'a')) {

        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 840 841 842
          if ($saveMappingFields['name'] === 'im') {
            $saveMappingFields['im_provider_id'] = $v[4];
          }
          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 851 852
        $saveMappingFields['location_type_id'] = is_numeric($locationTypeId) ? $locationTypeId : NULL;
        $saveMappingFields['relationship_type_id'] = $id;
        $saveMappingFields['relationship_direction'] = "{$first}_{$second}";
853 854 855
      }
    }

856
    return $saveMappingFields;
857 858
  }

859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
  /**
   * Load saved mapping.
   *
   * @param $mappingLocation
   * @param int $x
   * @param int $i
   * @param $mappingName
   * @param $mapperFields
   * @param $mappingContactType
   * @param $mappingRelation
   * @param array $specialFields
   * @param $mappingPhoneType
   * @param $phoneType
   * @param array $defaults
   * @param array $noneArray
   * @param $imProvider
   * @param $mappingImProvider
   * @param $mappingOperator
   * @param $mappingValue
   *
   * @return array
   */
  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 885 886 887
    if (isset($mappingName[$x][$i])) {
      if (is_array($mapperFields[$mappingContactType[$x][$i]])) {

        if (isset($mappingRelation[$x][$i])) {
888
          $relLocationId = $mappingLocation[$x][$i] ?? 0;
889 890 891 892
          if (!$relLocationId && in_array($mappingName[$x][$i], $specialFields)) {
            $relLocationId = " ";
          }

893
          $relPhoneType = $mappingPhoneType[$x][$i] ?? NULL;
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922

          $defaults["mapper[$x][$i]"] = [
            $mappingContactType[$x][$i],
            $mappingRelation[$x][$i],
            $locationId,
            $phoneType,
            $mappingName[$x][$i],
            $relLocationId,
            $relPhoneType,
          ];

          if (!$locationId) {
            $noneArray[] = [$x, $i, 2];
          }
          if (!$phoneType && !$imProvider) {
            $noneArray[] = [$x, $i, 3];
          }
          if (!$mappingName[$x][$i]) {
            $noneArray[] = [$x, $i, 4];
          }
          if (!$relLocationId) {
            $noneArray[] = [$x, $i, 5];
          }
          if (!$relPhoneType) {
            $noneArray[] = [$x, $i, 6];
          }
          $noneArray[] = [$x, $i, 2];
        }
        else {
923 924
          $phoneType = $mappingPhoneType[$x][$i] ?? NULL;
          $imProvider = $mappingImProvider[$x][$i] ?? NULL;
925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
          if (!$locationId && in_array($mappingName[$x][$i], $specialFields)) {
            $locationId = " ";
          }

          $defaults["mapper[$x][$i]"] = [
            $mappingContactType[$x][$i],
            $mappingName[$x][$i],
            $locationId,
            $phoneType,
          ];
          if (!$mappingName[$x][$i]) {
            $noneArray[] = [$x, $i, 1];
          }
          if (!$locationId) {
            $noneArray[] = [$x, $i, 2];
          }
          if (!$phoneType && !$imProvider) {
            $noneArray[] = [$x, $i, 3];
          }

          $noneArray[] = [$x, $i, 4];
          $noneArray[] = [$x, $i, 5];
          $noneArray[] = [$x, $i, 6];
        }

        $jsSet = TRUE;

        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 962 963
        }
      }
    }
    return [$mappingName, $defaults, $noneArray, $jsSet];
  }

964
  /**
965 966
   * Function returns all custom fields with group title and
   * field label
967
   *
968 969
   * @param int $relationshipTypeId
   *   Related relationship type id.
970
   *
971 972
   * @return array
   *   all custom field titles
973
   */
974
  public function getRelationTypeCustomGroupData($relationshipTypeId) {
totten's avatar
totten committed
975 976

    $customFields = CRM_Core_BAO_CustomField::getFields('Relationship', NULL, NULL, $relationshipTypeId, NULL, NULL);
977
    $groupTitle = [];
totten's avatar
totten committed
978 979 980 981 982 983 984
    foreach ($customFields as $krelation => $vrelation) {
      $groupTitle[$vrelation['label']] = $vrelation['groupTitle'] . '...' . $vrelation['label'];
    }
    return $groupTitle;
  }

  /**
985
   * Function returns all  Custom group Names.
totten's avatar
totten committed
986
   *
987 988
   * @param int $customfieldId
   *   Related file id.
989
   *
990 991
   * @return null|string
   *   $customGroupName all custom group names
totten's avatar
totten committed
992
   */
993
  public static function getCustomGroupName($customfieldId) {
totten's avatar
totten committed
994 995 996 997
    if ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($customfieldId)) {
      $customGroupId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $customFieldId, 'custom_group_id');
      $customGroupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $customGroupId, 'title');

998
      $customGroupName = CRM_Utils_String::ellipsify($customGroupName, 13);
totten's avatar
totten committed
999 1000 1001 1002 1003 1004 1005 1006

      return $customGroupName;
    }
  }

  /**
   * Function returns associated array of elements, that will be passed for search
   *
1007 1008 1009 1010
   * @param array $params
   *   Associated array of submitted values.
   * @param bool $row
   *   Row no of the fields.
totten's avatar
totten committed
1011 1012
   *
   *
1013 1014
   * @return array
   *   formatted associated array of elements
1015
   * @throws CRM_Core_Exception
totten's avatar
totten committed
1016
   */
1017
  public static function formattedFields(&$params, $row = FALSE) {
1018
    $fields = [];
totten's avatar
totten committed
1019 1020 1021 1022 1023

    if (empty($params) || !isset($params['mapper'])) {
      return $fields;
    }

1024
    $types = ['Individual', 'Organization', 'Household'];
totten's avatar
totten committed
1025 1026 1027 1028 1029
    foreach ($params['mapper'] as $key => $value) {
      $contactType = NULL;
      foreach ($value as $k => $v) {
        if (in_array($v[0], $types)) {
          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]]
totten's avatar
totten committed
1032
            ));
totten's avatar
totten committed
1033 1034 1035
          }
          $contactType = $v[0];
        }
1036
        if (!empty($v['1'])) {
totten's avatar
totten committed
1037
          $fldName = $v[1];
1038
          $v2 = $v['2'] ?? NULL;
totten's avatar
totten committed
1039 1040 1041 1042
          if ($v2 && trim($v2)) {
            $fldName .= "-{$v[2]}";
          }

1043
          $v3 = $v['3'] ?? NULL;
totten's avatar
totten committed
1044 1045 1046 1047 1048 1049
          if ($v3 && trim($v3)) {
            $fldName .= "-{$v[3]}";
          }

          $value = $params['value'][$key][$k];

eileen's avatar
eileen committed
1050
          if ($v[0] == 'Contribution' && substr($fldName, 0, 7) != 'custom_'
totten's avatar
totten committed
1051
            && substr($fldName, 0, 10) != 'financial_'
monishdeb's avatar
monishdeb committed
1052
            && substr($fldName, 0, 8) != 'payment_') {
totten's avatar
totten committed
1053 1054 1055 1056 1057
            if (substr($fldName, 0, 13) != 'contribution_') {
              $fldName = 'contribution_' . $fldName;
            }
          }

1058
          // CRM-14983: verify if values are comma separated convert to array
1059 1060
          if (!is_array($value) && strstr($params['operator'][$key][$k], 'IN')) {
            $value = explode(',', $value);
1061
            $value = [$params['operator'][$key][$k] => $value];
1062
          }
1063 1064 1065 1066 1067 1068
          // CRM-19081 Fix legacy StateProvince Field Values.
          // These derive from smart groups created using search builder under older
          // CiviCRM versions.
          if (!is_numeric($value) && $fldName == 'state_province') {
            $value = CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Address', 'state_province_id', $value);
          }
1069

totten's avatar
totten committed
1070
          if ($row) {
1071
            $fields[] = [
totten's avatar
totten committed
1072 1073 1074 1075 1076
              $fldName,
              $params['operator'][$key][$k],
              $value,
              $key,
              $k,
1077
            ];
totten's avatar
totten committed
1078 1079
          }
          else {
1080
            $fields[] = [
totten's avatar
totten committed
1081 1082 1083 1084 1085
              $fldName,
              $params['operator'][$key][$k],
              $value,
              $key,
              0,
1086
            ];
totten's avatar
totten committed
1087 1088 1089 1090
          }
        }
      }
      if ($contactType) {
1091
        $fields[] = [
totten's avatar
totten committed
1092 1093 1094 1095 1096
          'contact_type',
          '=',
          $contactType,
          $key,
          0,
1097
        ];
totten's avatar
totten committed
1098 1099 1100 1101 1102
      }
    }

    //add sortByCharacter values
    if (isset($params['sortByCharacter'])) {
1103
      $fields[] = [
totten's avatar
totten committed
1104 1105 1106 1107 1108
        'sortByCharacter',
        '=',
        $params['sortByCharacter'],
        0,
        0,
1109
      ];
totten's avatar
totten committed
1110 1111 1112 1113
    }
    return $fields;
  }

1114
  /**
1115
   * @param array $params
1116 1117 1118
   *
   * @return array
   */
1119
  public static function &returnProperties(&$params) {
1120
    $fields = [
totten's avatar
totten committed
1121 1122 1123
      'contact_type' => 1,
      'contact_sub_type' => 1,
      'sort_name' => 1,
1124
    ];
totten's avatar
totten committed
1125 1126 1127 1128 1129

    if (empty($params) || empty($params['mapper'])) {
      return $fields;
    }

1130
    $locationTypes = CRM_Core_DAO_Address::buildOptions('location_type_id', 'validate');
totten's avatar
totten committed
1131 1132 1133 1134 1135 1136 1137 1138 1139
    foreach ($params['mapper'] as $key => $value) {
      foreach ($value as $k => $v) {
        if (isset($v[1])) {
          if ($v[1] == 'groups' || $v[1] == 'tags') {
            continue;
          }

          if (isset($v[2]) && is_numeric($v[2])) {
            if (!array_key_exists('location', $fields)) {
1140
              $fields['location'] = [];
totten's avatar
totten committed
1141 1142 1143 1144 1145
            }

            // make sure that we have a location fields and a location type for this
            $locationName = $locationTypes[$v[2]];
            if (!array_key_exists($locationName, $fields['location'])) {
1146
              $fields['location'][$locationName] = [];
totten's avatar
totten committed
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
              $fields['location'][$locationName]['location_type'] = $v[2];
            }

            if ($v[1] == 'phone' || $v[1] == 'email' || $v[1] == 'im') {
              // phone type handling
              if (isset($v[3])) {
                $fields['location'][$locationName][$v[1] . "-" . $v[3]] = 1;
              }
              else {
                $fields['location'][$locationName][$v[1]] = 1;
              }
            }
            else {
              $fields['location'][$locationName][$v[1]] = 1;
            }
          }
          else {
            $fields[$v[1]] = 1;
          }
        }
      }
    }

    return $fields;
  }

  /**
colemanw's avatar
colemanw committed
1174
   * Save the mapping field info for search builder / export given the formvalues
totten's avatar
totten committed
1175
   *
1176 1177 1178 1179
   * @param array $params
   *   Asscociated array of formvalues.
   * @param int $mappingId
   *   Mapping id.
totten's avatar
totten committed
1180
   *
totten's avatar
totten committed
1181
   * @return NULL
totten's avatar
totten committed