3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
21 * This class delegates to the chosen DataSource to grab the data to be imported.
23 class CRM_Contact_Import_Form_DataSource
extends CRM_Core_Form
{
27 private $_dataSourceIsValid = FALSE;
29 private $_dataSourceClassFile;
31 private $_dataSourceClass;
34 * Set variables up before form is built.
36 * @throws \CRM_Core_Exception
38 public function preProcess() {
40 //Test database user privilege to create table(Temporary) CRM-4725
41 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
42 $daoTestPrivilege = new CRM_Core_DAO();
43 $tempTable1 = CRM_Utils_SQL_TempTable
::build()->getName();
44 $tempTable2 = CRM_Utils_SQL_TempTable
::build()->getName();
45 $daoTestPrivilege->query("CREATE TEMPORARY TABLE {$tempTable1} (test int) ENGINE=InnoDB");
46 $daoTestPrivilege->query("CREATE TEMPORARY TABLE {$tempTable2} (test int) ENGINE=InnoDB");
47 $daoTestPrivilege->query("DROP TEMPORARY TABLE IF EXISTS {$tempTable1}, {$tempTable2}");
50 if ($daoTestPrivilege->_lastError
) {
51 $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.'));
55 $config = CRM_Core_Config
::singleton();
56 $handler = opendir($config->uploadDir
);
57 $errorFiles = ['sqlImport.errors', 'sqlImport.conflicts', 'sqlImport.duplicates', 'sqlImport.mismatch'];
59 // check for post max size avoid when called twice
60 $snippet = $_GET['snippet'] ??
0;
61 if (empty($snippet)) {
62 CRM_Utils_Number
::formatUnitSize(ini_get('post_max_size'), TRUE);
65 while ($file = readdir($handler)) {
66 if ($file != '.' && $file != '..' &&
67 in_array($file, $errorFiles) && !is_writable($config->uploadDir
. $file)
73 if (!empty($results)) {
74 $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.', [
75 1 => implode(', ', $results),
76 2 => $config->uploadDir
,
80 $this->_dataSourceIsValid
= FALSE;
81 $this->_dataSource
= CRM_Utils_Request
::retrieveValue(
89 $this->_params
= $this->controller
->exportValues($this->_name
);
90 if (!$this->_dataSource
) {
91 //considering dataSource as base criteria instead of hidden_dataSource.
92 $this->_dataSource
= CRM_Utils_Array
::value('dataSource',
94 CRM_Utils_Array
::value('dataSource',
98 $this->assign('showOnlyDataSourceFormPane', FALSE);
101 $this->assign('showOnlyDataSourceFormPane', TRUE);
104 $dataSources = $this->_getDataSources();
105 if ($this->_dataSource
&& isset($dataSources[$this->_dataSource
])) {
106 $this->_dataSourceIsValid
= TRUE;
107 $this->assign('showDataSourceFormPane', TRUE);
108 $dataSourcePath = explode('_', $this->_dataSource
);
109 $templateFile = "CRM/Contact/Import/Form/" . $dataSourcePath[3] . ".tpl";
110 $this->assign('dataSourceFormTemplateFile', $templateFile);
112 elseif ($this->_dataSource
) {
113 $this->invalidConfig('Invalid data source');
118 * Build the form object.
120 public function buildQuickForm() {
122 // If there's a dataSource in the query string, we need to load
123 // the form from the chosen DataSource class
124 if ($this->_dataSourceIsValid
) {
125 $this->_dataSourceClassFile
= str_replace('_', '/', $this->_dataSource
) . ".php";
126 require_once $this->_dataSourceClassFile
;
127 $this->_dataSourceClass
= new $this->_dataSource();
128 $this->_dataSourceClass
->buildQuickForm($this);
131 // Get list of data sources and display them as options
132 $dataSources = $this->_getDataSources();
134 $this->assign('urlPath', "civicrm/import");
135 $this->assign('urlPathVar', 'snippet=4');
137 $this->add('select', 'dataSource', ts('Data Source'), $dataSources, TRUE,
138 ['onchange' => 'buildDataSourceFormBlock(this.value);']
141 // duplicate handling options
142 $duplicateOptions = [];
143 $duplicateOptions[] = $this->createElement('radio',
144 NULL, NULL, ts('Skip'), CRM_Import_Parser
::DUPLICATE_SKIP
146 $duplicateOptions[] = $this->createElement('radio',
147 NULL, NULL, ts('Update'), CRM_Import_Parser
::DUPLICATE_UPDATE
149 $duplicateOptions[] = $this->createElement('radio',
150 NULL, NULL, ts('Fill'), CRM_Import_Parser
::DUPLICATE_FILL
152 $duplicateOptions[] = $this->createElement('radio',
153 NULL, NULL, ts('No Duplicate Checking'), CRM_Import_Parser
::DUPLICATE_NOCHECK
156 $this->addGroup($duplicateOptions, 'onDuplicate',
157 ts('For Duplicate Contacts')
160 $mappingArray = CRM_Core_BAO_Mapping
::getMappings('Import Contact');
162 $this->assign('savedMapping', $mappingArray);
163 $this->addElement('select', 'savedMapping', ts('Mapping Option'), ['' => ts('- select -')] +
$mappingArray);
165 $js = ['onClick' => "buildSubTypes();buildDedupeRules();"];
166 // contact types option
167 $contactOptions = [];
168 if (CRM_Contact_BAO_ContactType
::isActive('Individual')) {
169 $contactOptions[] = $this->createElement('radio',
170 NULL, NULL, ts('Individual'), CRM_Import_Parser
::CONTACT_INDIVIDUAL
, $js
173 if (CRM_Contact_BAO_ContactType
::isActive('Household')) {
174 $contactOptions[] = $this->createElement('radio',
175 NULL, NULL, ts('Household'), CRM_Import_Parser
::CONTACT_HOUSEHOLD
, $js
178 if (CRM_Contact_BAO_ContactType
::isActive('Organization')) {
179 $contactOptions[] = $this->createElement('radio',
180 NULL, NULL, ts('Organization'), CRM_Import_Parser
::CONTACT_ORGANIZATION
, $js
184 $this->addGroup($contactOptions, 'contactType',
188 $this->addElement('select', 'subType', ts('Subtype'));
189 $this->addElement('select', 'dedupe', ts('Dedupe Rule'));
191 CRM_Core_Form_Date
::buildAllowedDateFormats($this);
193 $config = CRM_Core_Config
::singleton();
195 if (CRM_Utils_GeocodeProvider
::getUsableClassName()) {
197 $this->addElement('checkbox', 'doGeocodeAddress', ts('Geocode addresses during import?'));
199 $this->assign('geoCode', $geoCode);
201 $this->addElement('text', 'fieldSeparator', ts('Import Field Separator'), ['size' => 2]);
203 if (Civi
::settings()->get('address_standardization_provider') == 'USPS') {
204 $this->addElement('checkbox', 'disableUSPS', ts('Disable USPS address validation during import?'));
210 'name' => ts('Continue'),
211 'spacing' => ' ',
216 'name' => ts('Cancel'),
222 * Set the default values of various form elements.
227 * reference to the array of default values
229 public function setDefaultValues() {
230 $config = CRM_Core_Config
::singleton();
232 'dataSource' => 'CRM_Import_DataSource_CSV',
233 'onDuplicate' => CRM_Import_Parser
::DUPLICATE_SKIP
,
234 'contactType' => CRM_Import_Parser
::CONTACT_INDIVIDUAL
,
235 'fieldSeparator' => $config->fieldSeparator
,
238 if ($loadeMapping = $this->get('loadedMapping')) {
239 $this->assign('loadedMapping', $loadeMapping);
240 $defaults['savedMapping'] = $loadeMapping;
250 private function _getDataSources() {
251 // Hmm... file-system scanners don't really belong in forms...
252 if (isset(Civi
::$statics[__CLASS__
]['datasources'])) {
253 return Civi
::$statics[__CLASS__
]['datasources'];
256 // Open the data source dir and scan it for class files
257 global $civicrm_root;
258 $dataSourceDir = $civicrm_root . DIRECTORY_SEPARATOR
. 'CRM' . DIRECTORY_SEPARATOR
. 'Import' . DIRECTORY_SEPARATOR
. 'DataSource' . DIRECTORY_SEPARATOR
;
260 if (!is_dir($dataSourceDir)) {
261 $this->invalidConfig("Import DataSource directory $dataSourceDir does not exist");
263 if (!$dataSourceHandle = opendir($dataSourceDir)) {
264 $this->invalidConfig("Unable to access DataSource directory $dataSourceDir");
267 while (($dataSourceFile = readdir($dataSourceHandle)) !== FALSE) {
268 $fileType = filetype($dataSourceDir . $dataSourceFile);
270 if (($fileType == 'file' ||
$fileType == 'link') &&
271 preg_match('/^(.+)\.php$/', $dataSourceFile, $matches)
273 $dataSourceClass = "CRM_Import_DataSource_" . $matches[1];
274 require_once $dataSourceDir . DIRECTORY_SEPARATOR
. $dataSourceFile;
275 $object = new $dataSourceClass();
276 $info = $object->getInfo();
277 if ($object->checkPermission()) {
278 $dataSources[$dataSourceClass] = $info['title'];
282 closedir($dataSourceHandle);
284 Civi
::$statics[__CLASS__
]['datasources'] = $dataSources;
289 * Call the DataSource's postProcess method.
291 public function postProcess() {
292 $this->controller
->resetPage('MapField');
294 if ($this->_dataSourceIsValid
) {
295 // Setup the params array
296 $this->_params
= $this->controller
->exportValues($this->_name
);
299 'onDuplicate' => $this->exportValue('onDuplicate'),
300 'dedupe' => $this->exportValue('dedupe'),
301 'contactType' => $this->exportValue('contactType'),
302 'contactSubType' => $this->exportValue('subType'),
303 'dateFormats' => $this->exportValue('dateFormats'),
304 'savedMapping' => $this->exportValue('savedMapping'),
307 foreach ($storeParams as $storeName => $value) {
308 $this->set($storeName, $value);
310 $this->set('disableUSPS', !empty($this->_params
['disableUSPS']));
312 $this->set('dataSource', $this->_params
['dataSource']);
313 $this->set('skipColumnHeader', CRM_Utils_Array
::value('skipColumnHeader', $this->_params
));
315 $session = CRM_Core_Session
::singleton();
316 $session->set('dateTypes', $storeParams['dateFormats']);
318 // Get the PEAR::DB object
319 $dao = new CRM_Core_DAO();
320 $db = $dao->getDatabaseConnection();
322 //hack to prevent multiple tables.
323 $this->_params
['import_table_name'] = $this->get('importTableName');
324 if (!$this->_params
['import_table_name']) {
325 $this->_params
['import_table_name'] = 'civicrm_import_job_' . md5(uniqid(rand(), TRUE));
328 $this->_dataSourceClass
->postProcess($this->_params
, $db, $this);
330 // We should have the data in the DB now, parse it
331 $importTableName = $this->get('importTableName');
332 $fieldNames = $this->_prepareImportTable($db, $importTableName);
335 $parser = new CRM_Contact_Import_Parser_Contact($mapper);
336 $parser->setMaxLinesToProcess(100);
337 $parser->run($importTableName,
339 CRM_Import_Parser
::MODE_MAPFIELD
,
340 $storeParams['contactType'],
342 $fieldNames['status'],
343 CRM_Import_Parser
::DUPLICATE_SKIP
,
345 CRM_Contact_Import_Parser
::DEFAULT_TIMEOUT
,
346 $storeParams['contactSubType'],
347 $storeParams['dedupe']
350 // add all the necessary variables to the form
354 $this->invalidConfig("Invalid DataSource on form post. This shouldn't happen!");
359 * Add a PK and status column to the import table so we can track our progress.
360 * Returns the name of the primary key and status columns
363 * @param string $importTableName
367 private function _prepareImportTable($db, $importTableName) {
368 /* TODO: Add a check for an existing _status field;
369 * if it exists, create __status instead and return that
372 $statusFieldName = '_status';
373 $primaryKeyName = '_id';
375 $this->set('primaryKeyName', $primaryKeyName);
376 $this->set('statusFieldName', $statusFieldName);
378 /* Make sure the PK is always last! We rely on this later.
379 * Should probably stop doing that at some point, but it
380 * would require moving to associative arrays rather than
381 * relying on numerical order of the fields. This could in
382 * turn complicate matters for some DataSources, which
383 * would also not be good. Decisions, decisions...
386 $alterQuery = "ALTER TABLE $importTableName
387 ADD COLUMN $statusFieldName VARCHAR(32)
388 DEFAULT 'NEW' NOT NULL,
389 ADD COLUMN ${statusFieldName}Msg TEXT,
390 ADD COLUMN $primaryKeyName INT PRIMARY KEY NOT NULL
392 $db->query($alterQuery);
394 return ['status' => $statusFieldName, 'pk' => $primaryKeyName];
398 * General function for handling invalid configuration.
400 * I was going to statusBounce them all but when I tested I was 'bouncing' to weird places
401 * whereas throwing an exception gave no behaviour change. So, I decided to centralise
402 * and we can 'flip the switch' later.
406 * @throws \CRM_Core_Exception
408 protected function invalidConfig($message) {
409 throw new CRM_Core_Exception($message);
413 * Return a descriptive name for the page, used in wizard header
418 public function getTitle() {
419 return ts('Choose Data Source');