Merge pull request #16541 from bhahumanists/subtype-issue-991
[civicrm-core.git] / CRM / Contact / Import / Form / DataSource.php
index 0c8f1061bcbb6176ab42bed4000f23c0b20d3671..97ffa8453d8880fedc7e704b2df34faa01a4491d 100644 (file)
@@ -1,34 +1,20 @@
 <?php
 /*
  +--------------------------------------------------------------------+
- | CiviCRM version 5                                                  |
- +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2019                                |
- +--------------------------------------------------------------------+
- | This file is a part of CiviCRM.                                    |
- |                                                                    |
- | CiviCRM is free software; you can copy, modify, and distribute it  |
- | under the terms of the GNU Affero General Public License           |
- | Version 3, 19 November 2009 and the CiviCRM Licensing Exception.   |
- |                                                                    |
- | CiviCRM is distributed in the hope that it will be useful, but     |
- | WITHOUT ANY WARRANTY; without even the implied warranty of         |
- | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
- | See the GNU Affero General Public License for more details.        |
+ | Copyright CiviCRM LLC. All rights reserved.                        |
  |                                                                    |
- | You should have received a copy of the GNU Affero General Public   |
- | License and the CiviCRM Licensing Exception along                  |
- | with this program; if not, contact CiviCRM LLC                     |
- | at info[AT]civicrm[DOT]org. If you have questions about the        |
- | GNU Affero General Public License or the licensing of CiviCRM,     |
- | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+ | 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       |
  +--------------------------------------------------------------------+
  */
 
 /**
  *
  * @package CRM
- * @copyright CiviCRM LLC (c) 2004-2019
+ * @copyright CiviCRM LLC https://civicrm.org/licensing
+ * $Id$
+ *
  */
 
 /**
@@ -46,19 +32,23 @@ class CRM_Contact_Import_Form_DataSource extends CRM_Core_Form {
 
   /**
    * Set variables up before form is built.
+   *
+   * @throws \CRM_Core_Exception
    */
   public function preProcess() {
 
     //Test database user privilege to create table(Temporary) CRM-4725
     $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
     $daoTestPrivilege = new CRM_Core_DAO();
-    $daoTestPrivilege->query("CREATE TEMPORARY TABLE import_job_permission_one(test int) ENGINE=InnoDB");
-    $daoTestPrivilege->query("CREATE TEMPORARY TABLE import_job_permission_two(test int) ENGINE=InnoDB");
-    $daoTestPrivilege->query("DROP TEMPORARY TABLE IF EXISTS import_job_permission_one, import_job_permission_two");
+    $tempTable1 = CRM_Utils_SQL_TempTable::build()->getName();
+    $tempTable2 = CRM_Utils_SQL_TempTable::build()->getName();
+    $daoTestPrivilege->query("CREATE TEMPORARY TABLE {$tempTable1} (test int) ENGINE=InnoDB");
+    $daoTestPrivilege->query("CREATE TEMPORARY TABLE {$tempTable2} (test int) ENGINE=InnoDB");
+    $daoTestPrivilege->query("DROP TEMPORARY TABLE IF EXISTS {$tempTable1}, {$tempTable2}");
     unset($errorScope);
 
     if ($daoTestPrivilege->_lastError) {
-      CRM_Core_Error::fatal(ts('Database Configuration Error: Insufficient permissions. Import requires that the CiviCRM database user has permission to create temporary tables. Contact your site administrator for assistance.'));
+      $this->invalidConfig(ts('Database Configuration Error: Insufficient permissions. Import requires that the CiviCRM database user has permission to create temporary tables. Contact your site administrator for assistance.'));
     }
 
     $results = [];
@@ -67,7 +57,7 @@ class CRM_Contact_Import_Form_DataSource extends CRM_Core_Form {
     $errorFiles = ['sqlImport.errors', 'sqlImport.conflicts', 'sqlImport.duplicates', 'sqlImport.mismatch'];
 
     // check for post max size avoid when called twice
-    $snippet = CRM_Utils_Array::value('snippet', $_GET, 0);
+    $snippet = $_GET['snippet'] ?? 0;
     if (empty($snippet)) {
       CRM_Utils_Number::formatUnitSize(ini_get('post_max_size'), TRUE);
     }
@@ -81,19 +71,18 @@ class CRM_Contact_Import_Form_DataSource extends CRM_Core_Form {
     }
     closedir($handler);
     if (!empty($results)) {
-      CRM_Core_Error::fatal(ts('<b>%1</b> file(s) in %2 directory are not writable. Listed file(s) might be used during the import to log the errors occurred during Import process. Contact your site administrator for assistance.', [
-            1 => implode(', ', $results),
-            2 => $config->uploadDir,
-          ]));
+      $this->invalidConfig(ts('<b>%1</b> file(s) in %2 directory are not writable. Listed file(s) might be used during the import to log the errors occurred during Import process. Contact your site administrator for assistance.', [
+        1 => implode(', ', $results),
+        2 => $config->uploadDir,
+      ]));
     }
 
     $this->_dataSourceIsValid = FALSE;
-    $this->_dataSource = CRM_Utils_Request::retrieve(
+    $this->_dataSource = CRM_Utils_Request::retrieveValue(
       'dataSource',
       'String',
-      CRM_Core_DAO::$_nullObject,
-      FALSE,
       NULL,
+      FALSE,
       'GET'
     );
 
@@ -121,7 +110,7 @@ class CRM_Contact_Import_Form_DataSource extends CRM_Core_Form {
       $this->assign('dataSourceFormTemplateFile', $templateFile);
     }
     elseif ($this->_dataSource) {
-      throw new \CRM_Core_Exception("Invalid data source");
+      $this->invalidConfig('Invalid data source');
     }
   }
 
@@ -216,18 +205,17 @@ class CRM_Contact_Import_Form_DataSource extends CRM_Core_Form {
     }
 
     $this->addButtons([
-        [
-          'type' => 'upload',
-          'name' => ts('Continue'),
-          'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
-          'isDefault' => TRUE,
-        ],
-        [
-          'type' => 'cancel',
-          'name' => ts('Cancel'),
-        ],
-      ]
-    );
+      [
+        'type' => 'upload',
+        'name' => ts('Continue'),
+        'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
+        'isDefault' => TRUE,
+      ],
+      [
+        'type' => 'cancel',
+        'name' => ts('Cancel'),
+      ],
+    ]);
   }
 
   /**
@@ -270,10 +258,10 @@ class CRM_Contact_Import_Form_DataSource extends CRM_Core_Form {
     $dataSourceDir = $civicrm_root . DIRECTORY_SEPARATOR . 'CRM' . DIRECTORY_SEPARATOR . 'Import' . DIRECTORY_SEPARATOR . 'DataSource' . DIRECTORY_SEPARATOR;
     $dataSources = [];
     if (!is_dir($dataSourceDir)) {
-      CRM_Core_Error::fatal("Import DataSource directory $dataSourceDir does not exist");
+      $this->invalidConfig("Import DataSource directory $dataSourceDir does not exist");
     }
     if (!$dataSourceHandle = opendir($dataSourceDir)) {
-      CRM_Core_Error::fatal("Unable to access DataSource directory $dataSourceDir");
+      $this->invalidConfig("Unable to access DataSource directory $dataSourceDir");
     }
 
     while (($dataSourceFile = readdir($dataSourceHandle)) !== FALSE) {
@@ -308,17 +296,16 @@ class CRM_Contact_Import_Form_DataSource extends CRM_Core_Form {
       $this->_params = $this->controller->exportValues($this->_name);
 
       $storeParams = [
-        'onDuplicate' => 'onDuplicate',
-        'dedupe' => 'dedupe',
-        'contactType' => 'contactType',
-        'contactSubType' => 'subType',
-        'dateFormats' => 'dateFormats',
-        'savedMapping' => 'savedMapping',
+        'onDuplicate' => $this->exportValue('onDuplicate'),
+        'dedupe' => $this->exportValue('dedupe'),
+        'contactType' => $this->exportValue('contactType'),
+        'contactSubType' => $this->exportValue('subType'),
+        'dateFormats' => $this->exportValue('dateFormats'),
+        'savedMapping' => $this->exportValue('savedMapping'),
       ];
 
-      foreach ($storeParams as $storeName => $storeValueName) {
-        $$storeName = $this->exportValue($storeValueName);
-        $this->set($storeName, $$storeName);
+      foreach ($storeParams as $storeName => $value) {
+        $this->set($storeName, $value);
       }
       $this->set('disableUSPS', !empty($this->_params['disableUSPS']));
 
@@ -326,7 +313,7 @@ class CRM_Contact_Import_Form_DataSource extends CRM_Core_Form {
       $this->set('skipColumnHeader', CRM_Utils_Array::value('skipColumnHeader', $this->_params));
 
       $session = CRM_Core_Session::singleton();
-      $session->set('dateTypes', $dateFormats);
+      $session->set('dateTypes', $storeParams['dateFormats']);
 
       // Get the PEAR::DB object
       $dao = new CRM_Core_DAO();
@@ -350,21 +337,21 @@ class CRM_Contact_Import_Form_DataSource extends CRM_Core_Form {
       $parser->run($importTableName,
         $mapper,
         CRM_Import_Parser::MODE_MAPFIELD,
-        $contactType,
+        $storeParams['contactType'],
         $fieldNames['pk'],
         $fieldNames['status'],
         CRM_Import_Parser::DUPLICATE_SKIP,
         NULL, NULL, FALSE,
         CRM_Contact_Import_Parser::DEFAULT_TIMEOUT,
-        $contactSubType,
-        $dedupe
+        $storeParams['contactSubType'],
+        $storeParams['dedupe']
       );
 
       // add all the necessary variables to the form
       $parser->set($this);
     }
     else {
-      CRM_Core_Error::fatal("Invalid DataSource on form post. This shouldn't happen!");
+      $this->invalidConfig("Invalid DataSource on form post. This shouldn't happen!");
     }
   }
 
@@ -407,6 +394,21 @@ class CRM_Contact_Import_Form_DataSource extends CRM_Core_Form {
     return ['status' => $statusFieldName, 'pk' => $primaryKeyName];
   }
 
+  /**
+   * General function for handling invalid configuration.
+   *
+   * I was going to statusBounce them all but when I tested I was 'bouncing' to weird places
+   * whereas throwing an exception gave no behaviour change. So, I decided to centralise
+   * and we can 'flip the switch' later.
+   *
+   * @param $message
+   *
+   * @throws \CRM_Core_Exception
+   */
+  protected function invalidConfig($message) {
+    throw new CRM_Core_Exception($message);
+  }
+
   /**
    * Return a descriptive name for the page, used in wizard header
    *