3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2009. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
37 * This class delegates to the chosen DataSource to grab the data to be
40 class CRM_Contact_Import_Form_DataSource
extends CRM_Core_Form
{
44 private $_dataSourceIsValid = FALSE;
46 private $_dataSourceClassFile;
48 private $_dataSourceClass;
51 * Function to set variables up before form is built
56 public function preProcess() {
58 //Test database user privilege to create table(Temporary) CRM-4725
59 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
60 $daoTestPrivilege = new CRM_Core_DAO
;
61 $daoTestPrivilege->query("CREATE TEMPORARY TABLE import_job_permission_one(test int) ENGINE=InnoDB");
62 $daoTestPrivilege->query("CREATE TEMPORARY TABLE import_job_permission_two(test int) ENGINE=InnoDB");
63 $daoTestPrivilege->query("DROP TABLE IF EXISTS import_job_permission_one, import_job_permission_two");
66 if ($daoTestPrivilege->_lastError
) {
67 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.'));
71 $config = CRM_Core_Config
::singleton();
72 $handler = opendir($config->uploadDir
);
73 $errorFiles = array('sqlImport.errors', 'sqlImport.conflicts', 'sqlImport.duplicates', 'sqlImport.mismatch');
75 while ($file = readdir($handler)) {
76 if ($file != '.' && $file != '..' &&
77 in_array($file, $errorFiles) && !is_writable($config->uploadDir
. $file)
83 if (!empty($results)) {
84 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.', array(1 => implode(', ', $results), 2 => $config->uploadDir
)));
87 $this->_dataSourceIsValid
= FALSE;
88 $this->_dataSource
= CRM_Utils_Request
::retrieve(
91 CRM_Core_DAO
::$_nullObject,
97 $this->_params
= $this->controller
->exportValues($this->_name
);
98 if (!$this->_dataSource
) {
99 //considering dataSource as base criteria instead of hidden_dataSource.
100 $this->_dataSource
= CRM_Utils_Array
::value('dataSource',
102 CRM_Utils_Array
::value('dataSource',
106 $this->assign('showOnlyDataSourceFormPane', FALSE);
109 $this->assign('showOnlyDataSourceFormPane', TRUE);
112 if (strpos($this->_dataSource
, 'CRM_Import_DataSource_') === 0) {
113 $this->_dataSourceIsValid
= TRUE;
114 $this->assign('showDataSourceFormPane', TRUE);
115 $dataSourcePath = explode('_', $this->_dataSource
);
116 $templateFile = "CRM/Contact/Import/Form/" . $dataSourcePath[3] . ".tpl";
117 $this->assign('dataSourceFormTemplateFile', $templateFile);
122 * Function to actually build the form
128 public function buildQuickForm() {
130 // If there's a dataSource in the query string, we need to load
131 // the form from the chosen DataSource class
132 if ($this->_dataSourceIsValid
) {
133 $this->_dataSourceClassFile
= str_replace('_', '/', $this->_dataSource
) . ".php";
134 require_once $this->_dataSourceClassFile
;
135 $this->_dataSourceClass
= new $this->_dataSource
;
136 $this->_dataSourceClass
->buildQuickForm( $this );
139 // Get list of data sources and display them as options
140 $dataSources = $this->_getDataSources();
142 $this->assign('urlPath', "civicrm/import");
143 $this->assign('urlPathVar', 'snippet=4');
145 $this->add('select', 'dataSource', ts('Data Source'), $dataSources, TRUE,
146 array('onchange' => 'buildDataSourceFormBlock(this.value);')
149 // duplicate handling options
150 $duplicateOptions = array();
151 $duplicateOptions[] = $this->createElement('radio',
152 NULL, NULL, ts('Skip'), CRM_Import_Parser
::DUPLICATE_SKIP
154 $duplicateOptions[] = $this->createElement('radio',
155 NULL, NULL, ts('Update'), CRM_Import_Parser
::DUPLICATE_UPDATE
157 $duplicateOptions[] = $this->createElement('radio',
158 NULL, NULL, ts('Fill'), CRM_Import_Parser
::DUPLICATE_FILL
160 $duplicateOptions[] = $this->createElement('radio',
161 NULL, NULL, ts('No Duplicate Checking'), CRM_Import_Parser
::DUPLICATE_NOCHECK
164 $this->addGroup($duplicateOptions, 'onDuplicate',
165 ts('For Duplicate Contacts')
168 $mappingArray = CRM_Core_BAO_Mapping
::getMappings(CRM_Core_OptionGroup
::getValue('mapping_type',
173 $this->assign('savedMapping', $mappingArray);
174 $this->addElement('select', 'savedMapping', ts('Mapping Option'), array('' => ts('- select -')) +
$mappingArray);
177 $js = array('onClick' => "buildSubTypes();buildDedupeRules();");
178 // contact types option
179 $contactOptions = array();
180 if (CRM_Contact_BAO_ContactType
::isActive('Individual')) {
181 $contactOptions[] = $this->createElement('radio',
182 NULL, NULL, ts('Individual'), CRM_Import_Parser
::CONTACT_INDIVIDUAL
, $js
185 if (CRM_Contact_BAO_ContactType
::isActive('Household')) {
186 $contactOptions[] = $this->createElement('radio',
187 NULL, NULL, ts('Household'), CRM_Import_Parser
::CONTACT_HOUSEHOLD
, $js
190 if (CRM_Contact_BAO_ContactType
::isActive('Organization')) {
191 $contactOptions[] = $this->createElement('radio',
192 NULL, NULL, ts('Organization'), CRM_Import_Parser
::CONTACT_ORGANIZATION
, $js
196 $this->addGroup($contactOptions, 'contactType',
200 $this->addElement('select', 'subType', ts('Subtype'));
201 $this->addElement('select', 'dedupe', ts('Dedupe Rule'));
203 CRM_Core_Form_Date
::buildAllowedDateFormats($this);
205 $config = CRM_Core_Config
::singleton();
207 if (!empty($config->geocodeMethod
)) {
209 $this->addElement('checkbox', 'doGeocodeAddress', ts('Lookup mapping info during import?'));
211 $this->assign('geoCode', $geoCode);
213 $this->addElement('text', 'fieldSeparator', ts('Import Field Separator'), array('size' => 2));
215 $this->addButtons(array(
218 'name' => ts('Continue >>'),
219 'spacing' => ' ',
224 'name' => ts('Cancel'),
230 function setDefaultValues() {
231 $config = CRM_Core_Config
::singleton();
233 'dataSource' => 'CRM_Import_DataSource_CSV',
234 'onDuplicate' => CRM_Import_Parser
::DUPLICATE_SKIP
,
235 'contactType' => CRM_Import_Parser
::CONTACT_INDIVIDUAL
,
236 'fieldSeparator' => $config->fieldSeparator
,
239 if ($loadeMapping = $this->get('loadedMapping')) {
240 $this->assign('loadedMapping', $loadeMapping);
241 $defaults['savedMapping'] = $loadeMapping;
247 private function _getDataSources() {
248 // Open the data source dir and scan it for class files
249 $config = CRM_Core_Config
::singleton();
250 $dataSourceDir = $config->importDataSourceDir
;
251 $dataSources = array();
252 if (!is_dir($dataSourceDir)) {
253 CRM_Core_Error
::fatal("Import DataSource directory $dataSourceDir does not exist");
255 if (!$dataSourceHandle = opendir($dataSourceDir)) {
256 CRM_Core_Error
::fatal("Unable to access DataSource directory $dataSourceDir");
259 while (($dataSourceFile = readdir($dataSourceHandle)) !== FALSE) {
260 $fileType = filetype($dataSourceDir . $dataSourceFile);
262 if (($fileType == 'file' ||
$fileType == 'link') &&
263 preg_match('/^(.+)\.php$/', $dataSourceFile, $matches)
265 $dataSourceClass = "CRM_Import_DataSource_" . $matches[1];
266 require_once $dataSourceDir . DIRECTORY_SEPARATOR
. $dataSourceFile;
267 $object = new $dataSourceClass;
268 $info = $object->getInfo();
269 $dataSources[$dataSourceClass] = $info['title'];
272 closedir($dataSourceHandle);
277 * Call the DataSource's postProcess method to take over
278 * and then setup some common data structures for the next step
283 public function postProcess() {
284 $this->controller
->resetPage('MapField');
286 if ($this->_dataSourceIsValid
) {
287 // Setup the params array
288 $this->_params
= $this->controller
->exportValues($this->_name
);
290 $storeParams = array(
291 'onDuplicate' => 'onDuplicate',
292 'dedupe' => 'dedupe',
293 'contactType' => 'contactType',
294 'contactSubType' => 'subType',
295 'dateFormats' => 'dateFormats',
296 'savedMapping' => 'savedMapping',
299 foreach ($storeParams as $storeName => $storeValueName) {
300 $
$storeName = $this->exportValue($storeValueName);
301 $this->set($storeName, $
$storeName);
304 $this->set('dataSource', $this->_params
['dataSource']);
305 $this->set('skipColumnHeader', CRM_Utils_Array
::value('skipColumnHeader', $this->_params
));
307 $session = CRM_Core_Session
::singleton();
308 $session->set('dateTypes', $dateFormats);
310 // Get the PEAR::DB object
311 $dao = new CRM_Core_DAO();
312 $db = $dao->getDatabaseConnection();
314 //hack to prevent multiple tables.
315 $this->_params
['import_table_name'] = $this->get('importTableName');
316 if (!$this->_params
['import_table_name']) {
317 $this->_params
['import_table_name'] = 'civicrm_import_job_' . md5(uniqid(rand(), TRUE));
320 $this->_dataSourceClass
->postProcess( $this->_params
, $db, $this );
322 // We should have the data in the DB now, parse it
323 $importTableName = $this->get('importTableName');
324 $fieldNames = $this->_prepareImportTable($db, $importTableName);
327 $parser = new CRM_Contact_Import_Parser_Contact($mapper);
328 $parser->setMaxLinesToProcess(100);
329 $parser->run($importTableName,
331 CRM_Import_Parser
::MODE_MAPFIELD
,
334 $fieldNames['status'],
335 CRM_Import_Parser
::DUPLICATE_SKIP
,
337 CRM_Contact_Import_Parser
::DEFAULT_TIMEOUT
,
342 // add all the necessary variables to the form
346 CRM_Core_Error
::fatal("Invalid DataSource on form post. This shouldn't happen!");
351 * Add a PK and status column to the import table so we can track our progress
352 * Returns the name of the primary key and status columns
355 * @param $importTableName
360 private function _prepareImportTable($db, $importTableName) {
361 /* TODO: Add a check for an existing _status field;
362 * if it exists, create __status instead and return that
365 $statusFieldName = '_status';
366 $primaryKeyName = '_id';
368 $this->set('primaryKeyName', $primaryKeyName);
369 $this->set('statusFieldName', $statusFieldName);
371 /* Make sure the PK is always last! We rely on this later.
372 * Should probably stop doing that at some point, but it
373 * would require moving to associative arrays rather than
374 * relying on numerical order of the fields. This could in
375 * turn complicate matters for some DataSources, which
376 * would also not be good. Decisions, decisions...
379 $alterQuery = "ALTER TABLE $importTableName
380 ADD COLUMN $statusFieldName VARCHAR(32)
381 DEFAULT 'NEW' NOT NULL,
382 ADD COLUMN ${statusFieldName}Msg TEXT,
383 ADD COLUMN $primaryKeyName INT PRIMARY KEY NOT NULL
385 $db->query($alterQuery);
387 return array('status' => $statusFieldName, 'pk' => $primaryKeyName);
391 * Return a descriptive name for the page, used in wizard header
397 public function getTitle() {
398 return ts('Choose Data Source');