Move default fetching to Processor class
[civicrm-core.git] / CRM / Contact / Import / Form / MapField.php
index e2710bee6f1dd1770209d82be69c7ff752815e3b..4b926c314fed2b5e0c94fba9859f06aaa652cb8d 100644 (file)
@@ -36,6 +36,7 @@
  */
 class CRM_Contact_Import_Form_MapField extends CRM_Import_Form_MapField {
 
+  use CRM_Contact_Import_MetadataTrait;
 
   /**
    * An array of all contact fields with
@@ -66,7 +67,7 @@ class CRM_Contact_Import_Form_MapField extends CRM_Import_Form_MapField {
    *
    * @return string
    */
-  public function defaultFromColumnName($columnName, &$patterns) {
+  public function defaultFromColumnName($columnName, $patterns) {
 
     if (!preg_match('/^[a-z0-9 ]$/i', $columnName)) {
       if ($columnKey = array_search($columnName, $this->_mapperFields)) {
@@ -98,7 +99,7 @@ class CRM_Contact_Import_Form_MapField extends CRM_Import_Form_MapField {
     $this->_mapperFields = $this->get('fields');
     $this->_importTableName = $this->get('importTableName');
     $this->_onDuplicate = $this->get('onDuplicate');
-    $highlightedFields = array();
+    $highlightedFields = [];
     $highlightedFields[] = 'email';
     $highlightedFields[] = 'external_identifier';
     //format custom field names, CRM-2676
@@ -129,15 +130,11 @@ class CRM_Contact_Import_Form_MapField extends CRM_Import_Form_MapField {
 
     if ($this->_onDuplicate != CRM_Import_Parser::DUPLICATE_NOCHECK) {
       //Mark Dedupe Rule Fields as required, since it's used in matching contact
-      foreach (array(
-        'Individual',
-        'Household',
-        'Organization',
-      ) as $cType) {
-        $ruleParams = array(
+      foreach (['Individual', 'Household', 'Organization'] as $cType) {
+        $ruleParams = [
           'contact_type' => $cType,
           'used' => 'Unsupervised',
-        );
+        ];
         $this->_dedupeFields[$cType] = CRM_Dedupe_BAO_Rule::dedupeRuleFields($ruleParams);
       }
 
@@ -161,7 +158,7 @@ class CRM_Contact_Import_Form_MapField extends CRM_Import_Form_MapField {
     $this->assign('highlightedFields', $highlightedFields);
     $this->_formattedFieldNames[$contactType] = $this->_mapperFields = array_merge($this->_mapperFields, $formattedFieldNames);
 
-    $columnNames = array();
+    $columnNames = [];
     //get original col headers from csv if present.
     if ($dataSource == 'CRM_Import_DataSource_CSV' && $skipColumnHeader) {
       $columnNames = $this->get('originalColHeader');
@@ -180,7 +177,7 @@ class CRM_Contact_Import_Form_MapField extends CRM_Import_Form_MapField {
     }
 
     $showColNames = TRUE;
-    if ($dataSource == 'CRM_Import_DataSource_CSV' && !$skipColumnHeader) {
+    if ($dataSource === 'CRM_Import_DataSource_CSV' && !$skipColumnHeader) {
       $showColNames = FALSE;
     }
     $this->assign('showColNames', $showColNames);
@@ -197,10 +194,13 @@ class CRM_Contact_Import_Form_MapField extends CRM_Import_Form_MapField {
 
   /**
    * Build the form object.
+   *
+   * @throws \CiviCRM_API3_Exception
    */
   public function buildQuickForm() {
+    $savedMappingID = (int) $this->get('savedMapping');
     //to save the current mappings
-    if (!$this->get('savedMapping')) {
+    if (!$savedMappingID) {
       $saveDetailsName = ts('Save this field mapping');
       $this->applyFilter('saveMappingName', 'trim');
       $this->add('text', 'saveMappingName', ts('Name'));
@@ -209,21 +209,16 @@ class CRM_Contact_Import_Form_MapField extends CRM_Import_Form_MapField {
     else {
       $savedMapping = $this->get('savedMapping');
 
-      list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingImProvider, $mappingRelation, $mappingOperator, $mappingValue, $mappingWebsiteType) = CRM_Core_BAO_Mapping::getMappingFields($savedMapping, TRUE);
+      list($mappingName) = CRM_Core_BAO_Mapping::getMappingFields($savedMapping, TRUE);
 
       //get loaded Mapping Fields
       $mappingName = CRM_Utils_Array::value(1, $mappingName);
-      $mappingLocation = CRM_Utils_Array::value(1, $mappingLocation);
-      $mappingPhoneType = CRM_Utils_Array::value(1, $mappingPhoneType);
-      $mappingImProvider = CRM_Utils_Array::value(1, $mappingImProvider);
-      $mappingRelation = CRM_Utils_Array::value(1, $mappingRelation);
-      $mappingWebsiteType = CRM_Utils_Array::value(1, $mappingWebsiteType);
 
       $this->assign('loadedMapping', $savedMapping);
       $this->set('loadedMapping', $savedMapping);
 
-      $params = array('id' => $savedMapping);
-      $temp = array();
+      $params = ['id' => $savedMapping];
+      $temp = [];
       $mappingDetails = CRM_Core_BAO_Mapping::retrieve($params, $temp);
 
       $this->assign('savedName', $mappingDetails->name);
@@ -236,20 +231,20 @@ class CRM_Contact_Import_Form_MapField extends CRM_Import_Form_MapField {
       $this->add('text', 'saveMappingDesc', ts('Description'));
     }
 
-    $this->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, array('onclick' => "showSaveDetails(this)"));
+    $this->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, ['onclick' => "showSaveDetails(this)"]);
 
-    $this->addFormRule(array('CRM_Contact_Import_Form_MapField', 'formRule'));
+    $this->addFormRule(['CRM_Contact_Import_Form_MapField', 'formRule']);
 
     //-------- end of saved mapping stuff ---------
 
-    $defaults = array();
+    $defaults = [];
     $mapperKeys = array_keys($this->_mapperFields);
     $hasColumnNames = !empty($this->_columnNames);
     $columnPatterns = $this->get('columnPatterns');
     $dataPatterns = $this->get('dataPatterns');
     $hasLocationTypes = $this->get('fieldTypes');
 
-    $this->_location_types = array('Primary' => ts('Primary')) + CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
+    $this->_location_types = ['Primary' => ts('Primary')] + CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
     $defaultLocationType = CRM_Core_BAO_LocationType::getDefault();
 
     // Pass default location to js
@@ -282,13 +277,13 @@ class CRM_Contact_Import_Form_MapField extends CRM_Import_Form_MapField {
     $contactRelation = new CRM_Contact_DAO_RelationshipType();
     $contactRelation->find();
     while ($contactRelation->fetch()) {
-      $contactRelationCache[$contactRelation->id] = array();
+      $contactRelationCache[$contactRelation->id] = [];
       $contactRelationCache[$contactRelation->id]['contact_type_a'] = $contactRelation->contact_type_a;
       $contactRelationCache[$contactRelation->id]['contact_sub_type_a'] = $contactRelation->contact_sub_type_a;
       $contactRelationCache[$contactRelation->id]['contact_type_b'] = $contactRelation->contact_type_b;
       $contactRelationCache[$contactRelation->id]['contact_sub_type_b'] = $contactRelation->contact_sub_type_b;
     }
-    $highlightedFields = $highlightedRelFields = array();
+    $highlightedFields = $highlightedRelFields = [];
 
     $highlightedFields['email'] = 'All';
     $highlightedFields['external_identifier'] = 'All';
@@ -305,7 +300,7 @@ class CRM_Contact_Import_Form_MapField extends CRM_Import_Form_MapField {
       else {
         $id = $first = $second = NULL;
       }
-      if (($first == 'a' && $second == 'b') || ($first == 'b' && $second == 'a')) {
+      if (($first === 'a' && $second === 'b') || ($first === 'b' && $second === 'a')) {
         $cType = $contactRelationCache[$id]["contact_type_{$second}"];
 
         //CRM-5125 for contact subtype specific relationshiptypes
@@ -320,13 +315,13 @@ class CRM_Contact_Import_Form_MapField extends CRM_Import_Form_MapField {
 
         $relatedFields = CRM_Contact_BAO_Contact::importableFields($cType);
         unset($relatedFields['']);
-        $values = array();
+        $values = [];
         foreach ($relatedFields as $name => $field) {
           $values[$name] = $field['title'];
           if (isset($hasLocationTypes[$name])) {
             $sel3[$key][$name] = $this->_location_types;
           }
-          elseif ($name == 'url') {
+          elseif ($name === 'url') {
             $sel3[$key][$name] = $websiteTypes;
           }
           else {
@@ -346,7 +341,7 @@ class CRM_Contact_Import_Form_MapField extends CRM_Import_Form_MapField {
         if ($this->_onDuplicate != CRM_Import_Parser::DUPLICATE_NOCHECK && !empty($this->_dedupeFields[$cType]) &&
           is_array($this->_dedupeFields[$cType])
         ) {
-          static $cTypeArray = array();
+          static $cTypeArray = [];
           if ($cType != $this->_contactType && !in_array($cType, $cTypeArray)) {
             foreach ($this->_dedupeFields[$cType] as $val) {
               if ($valTitle = CRM_Utils_Array::value($val, $this->_formattedFieldNames[$cType])) {
@@ -358,7 +353,7 @@ class CRM_Contact_Import_Form_MapField extends CRM_Import_Form_MapField {
         }
 
         foreach ($highlightedFields as $k => $v) {
-          if ($v == $cType || $v == 'All') {
+          if ($v == $cType || $v === 'All') {
             $highlightedRelFields[$key][] = $k;
           }
         }
@@ -389,7 +384,7 @@ class CRM_Contact_Import_Form_MapField extends CRM_Import_Form_MapField {
         if (!empty($hasLocationTypes[$key])) {
           $options = $this->_location_types;
         }
-        elseif ($key == 'url') {
+        elseif ($key === 'url') {
           $options = $websiteTypes;
         }
         $sel2[$key] = $options;
@@ -399,152 +394,23 @@ class CRM_Contact_Import_Form_MapField extends CRM_Import_Form_MapField {
     $js = "<script type='text/javascript'>\n";
     $formName = 'document.forms.' . $this->_name;
     //used to warn for mismatch column count or mismatch mapping
-    $warning = 0;
-    for ($i = 0; $i < $this->_columnCount; $i++) {
-      $sel = &$this->addElement('hierselect', "mapper[$i]", ts('Mapper for Field %1', array(1 => $i)), NULL);
-      $jsSet = FALSE;
-      if ($this->get('savedMapping')) {
-        if (isset($mappingName[$i])) {
-          if ($mappingName[$i] != ts('- do not import -')) {
-
-            if (isset($mappingRelation[$i])) {
-              // relationship mapping
-              switch ($this->get('contactType')) {
-                case CRM_Import_Parser::CONTACT_INDIVIDUAL:
-                  $contactType = 'Individual';
-                  break;
-
-                case CRM_Import_Parser::CONTACT_HOUSEHOLD:
-                  $contactType = 'Household';
-                  break;
-
-                case CRM_Import_Parser::CONTACT_ORGANIZATION:
-                  $contactType = 'Organization';
-              }
-              //CRM-5125
-              $contactSubType = NULL;
-              if ($this->get('contactSubType')) {
-                $contactSubType = $this->get('contactSubType');
-              }
+    CRM_Core_Session::singleton()->setStatus(NULL);
+    $processor = new CRM_Import_ImportProcessor();
+    $processor->setMappingID($savedMappingID);
+    $processor->setFormName($formName);
+    $processor->setMetadata($this->getContactImportMetadata());
+    $processor->setContactTypeByConstant($this->get('contactType'));
 
-              $relations = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $contactType,
-                FALSE, 'label', TRUE, $contactSubType
-              );
-
-              foreach ($relations as $key => $var) {
-                if ($key == $mappingRelation[$i]) {
-                  $relation = $key;
-                  break;
-                }
-              }
-
-              $contactDetails = strtolower(str_replace(" ", "_", $mappingName[$i]));
-              $websiteTypeId = isset($mappingWebsiteType[$i]) ? $mappingWebsiteType[$i] : NULL;
-              $locationId = isset($mappingLocation[$i]) ? $mappingLocation[$i] : 0;
-              $phoneType = isset($mappingPhoneType[$i]) ? $mappingPhoneType[$i] : NULL;
-              //get provider id from saved mappings
-              $imProvider = isset($mappingImProvider[$i]) ? $mappingImProvider[$i] : NULL;
-
-              if ($websiteTypeId) {
-                $defaults["mapper[$i]"] = array($relation, $contactDetails, $websiteTypeId);
-                if (!$websiteTypeId) {
-                  $js .= "{$formName}['mapper[$i][2]'].style.display = 'none';\n";
-                }
-              }
-              else {
-                // default for IM/phone when mapping with relation is true
-                $typeId = NULL;
-                if (isset($phoneType)) {
-                  $typeId = $phoneType;
-                }
-                elseif (isset($imProvider)) {
-                  $typeId = $imProvider;
-                }
-                $defaults["mapper[$i]"] = array($relation, $contactDetails, $locationId, $typeId);
-                if (!$locationId) {
-                  $js .= "{$formName}['mapper[$i][2]'].style.display = 'none';\n";
-                }
-              }
-              // fix for edge cases, CRM-4954
-              if ($contactDetails == 'image_url') {
-                $contactDetails = str_replace('url', 'URL', $contactDetails);
-              }
-
-              if (!$contactDetails) {
-                $js .= "{$formName}['mapper[$i][1]'].style.display = 'none';\n";
-              }
-
-              if ((!$phoneType) && (!$imProvider)) {
-                $js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
-              }
-              //$js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
-              $jsSet = TRUE;
-            }
-            else {
-              $mappingHeader = array_keys($this->_mapperFields, $mappingName[$i]);
-              $websiteTypeId = isset($mappingWebsiteType[$i]) ? $mappingWebsiteType[$i] : NULL;
-              $locationId = isset($mappingLocation[$i]) ? $mappingLocation[$i] : 0;
-              $phoneType = isset($mappingPhoneType[$i]) ? $mappingPhoneType[$i] : NULL;
-              // get IM service provider id
-              $imProvider = isset($mappingImProvider[$i]) ? $mappingImProvider[$i] : NULL;
-
-              if ($websiteTypeId) {
-                if (!$websiteTypeId) {
-                  $js .= "{$formName}['mapper[$i][1]'].style.display = 'none';\n";
-                }
-                $defaults["mapper[$i]"] = array($mappingHeader[0], $websiteTypeId);
-              }
-              else {
-                if (!$locationId) {
-                  $js .= "{$formName}['mapper[$i][1]'].style.display = 'none';\n";
-                }
-                //default for IM/phone without related contact
-                $typeId = NULL;
-                if (isset($phoneType)) {
-                  $typeId = $phoneType;
-                }
-                elseif (isset($imProvider)) {
-                  $typeId = $imProvider;
-                }
-                $defaults["mapper[$i]"] = array($mappingHeader[0], $locationId, $typeId);
-              }
-
-              if ((!$phoneType) && (!$imProvider)) {
-                $js .= "{$formName}['mapper[$i][2]'].style.display = 'none';\n";
-              }
-
-              $js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
-
-              $jsSet = TRUE;
-            }
-          }
-          else {
-            $defaults["mapper[$i]"] = array();
-          }
-          if (!$jsSet) {
-            for ($k = 1; $k < 4; $k++) {
-              $js .= "{$formName}['mapper[$i][$k]'].style.display = 'none';\n";
-            }
-          }
-        }
-        else {
-          // this load section to help mapping if we ran out of saved columns when doing Load Mapping
-          $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_0_');\n";
+    for ($i = 0; $i < $this->_columnCount; $i++) {
+      $sel = &$this->addElement('hierselect', "mapper[$i]", ts('Mapper for Field %1', [1 => $i]), NULL);
 
-          if ($hasColumnNames) {
-            $defaults["mapper[$i]"] = array($this->defaultFromColumnName($this->_columnNames[$i], $columnPatterns));
-          }
-          else {
-            $defaults["mapper[$i]"] = array($this->defaultFromData($dataPatterns, $i));
-          }
-        }
-        //end of load mapping
+      if ($this->get('savedMapping')) {
+        list($defaults, $js) = $this->loadSavedMapping($processor, $mappingName, $i, $defaults, $js, $hasColumnNames, $dataPatterns, $columnPatterns);
       }
       else {
         $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_0_');\n";
         if ($hasColumnNames) {
           // do array search first to see if has mapped key
-          $columnKey = '';
           $columnKey = array_search($this->_columnNames[$i], $this->_mapperFields);
           if (isset($this->_fieldUsed[$columnKey])) {
             $defaults["mapper[$i]"] = $columnKey;
@@ -552,24 +418,24 @@ class CRM_Contact_Import_Form_MapField extends CRM_Import_Form_MapField {
           }
           else {
             // Infer the default from the column names if we have them
-            $defaults["mapper[$i]"] = array(
+            $defaults["mapper[$i]"] = [
               $this->defaultFromColumnName($this->_columnNames[$i],
                 $columnPatterns
               ),
               0,
-            );
+            ];
           }
         }
         else {
           // Otherwise guess the default from the form of the data
-          $defaults["mapper[$i]"] = array(
+          $defaults["mapper[$i]"] = [
             $this->defaultFromData($dataPatterns, $i),
             //                     $defaultLocationType->id
             0,
-          );
+          ];
         }
       }
-      $sel->setOptions(array($sel1, $sel2, $sel3, $sel4));
+      $sel->setOptions([$sel1, $sel2, $sel3, $sel4]);
     }
 
     $js .= "</script>\n";
@@ -579,37 +445,27 @@ class CRM_Contact_Import_Form_MapField extends CRM_Import_Form_MapField {
     if (isset($mappingName) &&
       ($this->_columnCount != count($mappingName))
     ) {
-      $warning++;
-    }
-
-    if ($warning != 0 && $this->get('savedMapping')) {
-      $session = CRM_Core_Session::singleton();
-      $session->setStatus(ts('The data columns in this import file appear to be different from the saved mapping. Please verify that you have selected the correct saved mapping before continuing.'));
-    }
-    else {
-      $session = CRM_Core_Session::singleton();
-      $session->setStatus(NULL);
+      CRM_Core_Session::singleton()->setStatus(ts('The data columns in this import file appear to be different from the saved mapping. Please verify that you have selected the correct saved mapping before continuing.'));
     }
 
     $this->setDefaults($defaults);
 
-    $this->addButtons(array(
-        array(
-          'type' => 'back',
-          'name' => ts('Previous'),
-        ),
-        array(
-          'type' => 'next',
-          'name' => ts('Continue'),
-          'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
-          'isDefault' => TRUE,
-        ),
-        array(
-          'type' => 'cancel',
-          'name' => ts('Cancel'),
-        ),
-    )
-    );
+    $this->addButtons([
+      [
+        'type' => 'back',
+        'name' => ts('Previous'),
+      ],
+      [
+        'type' => 'next',
+        'name' => ts('Continue'),
+        'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
+        'isDefault' => TRUE,
+      ],
+      [
+        'type' => 'cancel',
+        'name' => ts('Cancel'),
+      ],
+    ]);
   }
 
   /**
@@ -622,7 +478,7 @@ class CRM_Contact_Import_Form_MapField extends CRM_Import_Form_MapField {
    *   list of errors to be posted back to the form
    */
   public static function formRule($fields) {
-    $errors = array();
+    $errors = [];
     if (!empty($fields['saveMapping'])) {
       $nameField = CRM_Utils_Array::value('saveMappingName', $fields);
       if (empty($nameField)) {
@@ -680,9 +536,9 @@ class CRM_Contact_Import_Form_MapField extends CRM_Import_Form_MapField {
    *
    * @return array
    */
-  public function formatCustomFieldName(&$fields) {
+  public function formatCustomFieldName($fields) {
     //CRM-2676, replacing the conflict for same custom field name from different custom group.
-    $fieldIds = $formattedFieldNames = array();
+    $fieldIds = $formattedFieldNames = [];
     foreach ($fields as $key => $value) {
       if ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($key)) {
         $fieldIds[] = $customFieldId;
@@ -716,7 +572,7 @@ class CRM_Contact_Import_Form_MapField extends CRM_Import_Form_MapField {
    * @throws \CiviCRM_API3_Exception
    */
   public function submit($params, $mapperKeys) {
-    $mapper = $mapperKeysMain = $locations = array();
+    $mapper = $mapperKeysMain = $locations = [];
     $parserParameters = CRM_Contact_Import_Parser_Contact::getParameterForParser($this->_columnCount);
 
     $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
@@ -736,17 +592,17 @@ class CRM_Contact_Import_Form_MapField extends CRM_Import_Form_MapField {
 
       //need to differentiate non location elements.
       if ($selOne && (is_numeric($selOne) || $selOne === 'Primary')) {
-        if ($fldName == 'url') {
+        if ($fldName === 'url') {
           $parserParameters['mapperWebsiteType'][$i] = $websiteTypes[$selOne];
         }
         else {
           $locations[$i] = $locationTypes[$selOne];
           $parserParameters['mapperLocType'][$i] = $selOne;
           if ($selTwo && is_numeric($selTwo)) {
-            if ($fldName == 'phone') {
+            if ($fldName === 'phone') {
               $parserParameters['mapperPhoneType'][$i] = $phoneTypes[$selTwo];
             }
-            elseif ($fldName == 'im') {
+            elseif ($fldName === 'im') {
               $parserParameters['mapperImProvider'][$i] = $imProviders[$selTwo];
             }
           }
@@ -755,21 +611,21 @@ class CRM_Contact_Import_Form_MapField extends CRM_Import_Form_MapField {
 
       //relationship contact mapper info.
       list($id, $first, $second) = CRM_Utils_System::explode('_', $fldName, 3);
-      if (($first == 'a' && $second == 'b') ||
-        ($first == 'b' && $second == 'a')
+      if (($first === 'a' && $second === 'b') ||
+        ($first === 'b' && $second === 'a')
       ) {
         $parserParameters['mapperRelated'][$i] = $this->_mapperFields[$fldName];
         if ($selOne) {
-          if ($selOne == 'url') {
+          if ($selOne === 'url') {
             $parserParameters['relatedContactWebsiteType'][$i] = $websiteTypes[$selTwo];
           }
           else {
             $parserParameters['relatedContactLocType'][$i] = CRM_Utils_Array::value($selTwo, $locationTypes);
             if ($selThree) {
-              if ($selOne == 'phone') {
+              if ($selOne === 'phone') {
                 $parserParameters['relatedContactPhoneType'][$i] = $phoneTypes[$selThree];
               }
-              elseif ($selOne == 'im') {
+              elseif ($selOne === 'im') {
                 $parserParameters['relatedContactImProvider'][$i] = $imProviders[$selThree];
               }
             }
@@ -809,7 +665,7 @@ class CRM_Contact_Import_Form_MapField extends CRM_Import_Form_MapField {
       $mappingFields->mapping_id = $params['mappingId'];
       $mappingFields->find();
 
-      $mappingFieldsId = array();
+      $mappingFieldsId = [];
       while ($mappingFields->fetch()) {
         if ($mappingFields->id) {
           $mappingFieldsId[$mappingFields->column_number] = $mappingFields->id;
@@ -872,11 +728,11 @@ class CRM_Contact_Import_Form_MapField extends CRM_Import_Form_MapField {
 
     //Saving Mapping Details and Records
     if (!empty($params['saveMapping'])) {
-      $mappingParams = array(
+      $mappingParams = [
         'name' => $params['saveMappingName'],
         'description' => $params['saveMappingDesc'],
         'mapping_type_id' => 'Import Contact',
-      );
+      ];
 
       $saveMapping = civicrm_api3('Mapping', 'create', $mappingParams);
 
@@ -987,4 +843,99 @@ class CRM_Contact_Import_Form_MapField extends CRM_Import_Form_MapField {
     return $saveMappingFields->mapping_id;
   }
 
+  /**
+   * @param \CRM_Import_ImportProcessor $processor
+   * @param $mappingName
+   * @param int $i
+   * @param array $defaults
+   * @param string $js
+   * @param bool $hasColumnNames
+   * @param array $dataPatterns
+   * @param array $columnPatterns
+   *
+   * @return array
+   * @throws \CiviCRM_API3_Exception
+   */
+  public function loadSavedMapping($processor, $mappingName, $i, $defaults, $js, $hasColumnNames, $dataPatterns, $columnPatterns) {
+    $jsSet = FALSE;
+    $formName = $processor->getFormName();
+    if (isset($mappingName[$i])) {
+      if ($mappingName[$i] != ts('- do not import -')) {
+
+        if ($processor->getRelationshipKey($i)) {
+          $contactType = $processor->getContactType();
+          //CRM-5125
+          $contactSubType = NULL;
+          if ($this->get('contactSubType')) {
+            $contactSubType = $this->get('contactSubType');
+          }
+
+          $relations = CRM_Contact_BAO_Relationship::getContactRelationshipType(NULL, NULL, NULL, $contactType,
+            FALSE, 'label', TRUE, $contactSubType
+          );
+
+          foreach ($relations as $key => $var) {
+            if ($processor->getValidRelationshipKey($i)) {
+              $relation = $processor->getValidRelationshipKey($i);
+              break;
+            }
+          }
+
+          $contactDetails = strtolower(str_replace(" ", "_", $mappingName[$i]));
+          $websiteTypeId = $processor->getWebsiteTypeID($i);
+          $locationId = $processor->getLocationTypeID($i);
+          $phoneType = $processor->getPhoneTypeID($i);
+          $imProvider = $processor->getIMProviderID($i);
+
+          $defaults["mapper[$i]"] = $processor->getSavedQuickformDefaultsForColumn($i);
+          if (!$websiteTypeId) {
+            if (!$locationId) {
+              $js .= "{$formName}['mapper[$i][2]'].style.display = 'none';\n";
+            }
+          }
+          // fix for edge cases, CRM-4954
+          if ($contactDetails == 'image_url') {
+            $contactDetails = str_replace('url', 'URL', $contactDetails);
+          }
+
+          if (!$contactDetails) {
+            $js .= "{$formName}['mapper[$i][1]'].style.display = 'none';\n";
+          }
+
+          if ((!$phoneType) && (!$imProvider)) {
+            $js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
+          }
+          //$js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
+          $jsSet = TRUE;
+        }
+        else {
+          $defaults["mapper[$i]"] = $processor->getSavedQuickformDefaultsForColumn($i);
+          $js .= $processor->getQuickFormJSForField($i);
+
+          $jsSet = TRUE;
+        }
+      }
+      else {
+        $defaults["mapper[$i]"] = [];
+      }
+      if (!$jsSet) {
+        for ($k = 1; $k < 4; $k++) {
+          $js .= "{$formName}['mapper[$i][$k]'].style.display = 'none';\n";
+        }
+      }
+    }
+    else {
+      // this load section to help mapping if we ran out of saved columns when doing Load Mapping
+      $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_0_');\n";
+
+      if ($hasColumnNames) {
+        $defaults["mapper[$i]"] = [$this->defaultFromColumnName($this->_columnNames[$i], $columnPatterns)];
+      }
+      else {
+        $defaults["mapper[$i]"] = [$this->defaultFromData($dataPatterns, $i)];
+      }
+    }
+    return [$defaults, $js];
+  }
+
 }