3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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 2007 and the CiviCRM Licensing Exception. |
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-2015
33 class CRM_Import_DataSource_CSV
extends CRM_Import_DataSource
{
35 NUM_ROWS_TO_INSERT
= 100;
38 * Provides information about the data source.
41 * collection of info about this data source
43 public function getInfo() {
44 return array('title' => ts('Comma-Separated Values (CSV)'));
48 * Set variables up before form is built.
50 public function preProcess(&$form) {
54 * This is function is called by the form object to get the DataSource's form snippet.
56 * It should add all fields necessary to get the data
57 * uploaded to the temporary table in the DB.
59 * @param CRM_Core_Form $form
61 public function buildQuickForm(&$form) {
62 $form->add('hidden', 'hidden_dataSource', 'CRM_Import_DataSource_CSV');
64 $config = CRM_Core_Config
::singleton();
66 $uploadFileSize = CRM_Utils_Number
::formatUnitSize($config->maxFileSize
. 'm', TRUE);
67 $uploadSize = round(($uploadFileSize / (1024 * 1024)), 2);
68 $form->assign('uploadSize', $uploadSize);
69 $form->add('File', 'uploadFile', ts('Import Data File'), 'size=30 maxlength=255', TRUE);
70 $form->setMaxFileSize($uploadFileSize);
71 $form->addRule('uploadFile', ts('File size should be less than %1 MBytes (%2 bytes)', array(
74 )), 'maxfilesize', $uploadFileSize);
75 $form->addRule('uploadFile', ts('Input file must be in CSV format'), 'utf8File');
76 $form->addRule('uploadFile', ts('A valid file must be uploaded.'), 'uploadedfile');
78 $form->addElement('checkbox', 'skipColumnHeader', ts('First row contains column headers'));
82 * Process the form submission.
84 public function postProcess(&$params, &$db, &$form) {
85 $file = $params['uploadFile']['name'];
86 $result = self
::_CsvToTable($db,
88 CRM_Utils_Array
::value('skipColumnHeader', $params, FALSE),
89 CRM_Utils_Array
::value('import_table_name', $params),
90 CRM_Utils_Array
::value('fieldSeparator', $params, ',')
93 $form->set('originalColHeader', CRM_Utils_Array
::value('original_col_header', $result));
95 $table = $result['import_table_name'];
96 $importJob = new CRM_Contact_Import_ImportJob($table);
97 $form->set('importTableName', $importJob->getTableName());
101 * Create a table that matches the CSV file and populate it with the file's contents
104 * Handle to the database connection.
105 * @param string $file
107 * @param bool $headers
108 * Whether the first row contains headers.
109 * @param string $table
110 * Name of table from which data imported.
111 * @param string $fieldSeparator
112 * Character that separates the various columns in the file.
115 * name of the created table
117 private static function _CsvToTable(
122 $fieldSeparator = ','
125 $fd = fopen($file, 'r');
127 CRM_Core_Error
::fatal("Could not read $file");
130 $config = CRM_Core_Config
::singleton();
131 // support tab separated
132 if (strtolower($fieldSeparator) == 'tab' ||
133 strtolower($fieldSeparator) == '\t'
135 $fieldSeparator = "\t";
138 $firstrow = fgetcsv($fd, 0, $fieldSeparator);
140 // create the column names from the CSV header or as col_0, col_1, etc.
142 //need to get original headers.
143 $result['original_col_header'] = $firstrow;
145 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
146 $columns = array_map($strtolower, $firstrow);
147 $columns = str_replace(' ', '_', $columns);
148 $columns = preg_replace('/[^a-z_]/', '', $columns);
150 // need to take care of null as well as duplicate col names.
151 $duplicateColName = FALSE;
152 if (count($columns) != count(array_unique($columns))) {
153 $duplicateColName = TRUE;
156 // need to truncate values per mysql field name length limits
157 // mysql allows 64, but we need to account for appending colKey
159 foreach ($columns as $colKey => & $colName) {
160 if (strlen($colName) > 58) {
161 $colName = substr($colName, 0, 58);
165 if (in_array('', $columns) ||
$duplicateColName) {
166 foreach ($columns as $colKey => & $colName) {
168 $colName = "col_$colKey";
170 elseif ($duplicateColName) {
171 $colName .= "_$colKey";
176 // CRM-4881: we need to quote column names, as they may be MySQL reserved words
177 foreach ($columns as & $column) {
178 $column = "`$column`";
183 foreach ($firstrow as $i => $_) {
184 $columns[] = "col_$i";
188 // FIXME: we should regen this table's name if it exists rather than drop it
190 $table = 'civicrm_import_job_' . md5(uniqid(rand(), TRUE));
193 $db->query("DROP TABLE IF EXISTS $table");
195 $numColumns = count($columns);
196 $create = "CREATE TABLE $table (" . implode(' text, ', $columns) . " text) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
199 // the proper approach, but some MySQL installs do not have this enabled
200 // $load = "LOAD DATA LOCAL INFILE '$file' INTO TABLE $table FIELDS TERMINATED BY '$fieldSeparator' OPTIONALLY ENCLOSED BY '\"'";
201 // if ($headers) { $load .= ' IGNORE 1 LINES'; }
202 // $db->query($load);
204 // parse the CSV line by line and build one big INSERT (while MySQL-escaping the CSV contents)
212 while ($row = fgetcsv($fd, 0, $fieldSeparator)) {
213 // skip rows that dont match column count, else we get a sql error
214 if (count($row) != $numColumns) {
223 $row = array_map('civicrm_mysql_real_escape_string', $row);
224 $sql .= "('" . implode("', '", $row) . "')";
227 if ($count >= self
::NUM_ROWS_TO_INSERT
&& !empty($sql)) {
228 $sql = "INSERT IGNORE INTO $table VALUES $sql";
238 $sql = "INSERT IGNORE INTO $table VALUES $sql";
244 //get the import tmp table name.
245 $result['import_table_name'] = $table;
257 function civicrm_mysql_real_escape_string($string) {
260 $dao = new CRM_Core_DAO();
262 return $dao->escape($string);