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
17 class CRM_Import_DataSource_CSV
extends CRM_Import_DataSource
{
19 NUM_ROWS_TO_INSERT
= 100;
22 * Form fields declared for this datasource.
26 protected $submittableFields = ['skipColumnHeader', 'uploadField'];
29 * Provides information about the data source.
32 * collection of info about this data source
34 public function getInfo(): array {
35 return ['title' => ts('Comma-Separated Values (CSV)')];
39 * This is function is called by the form object to get the DataSource's form snippet.
41 * It should add all fields necessary to get the data
42 * uploaded to the temporary table in the DB.
44 * @param CRM_Core_Form $form
46 * @throws \CRM_Core_Exception
48 public function buildQuickForm(&$form) {
49 $form->add('hidden', 'hidden_dataSource', 'CRM_Import_DataSource_CSV');
51 $uploadFileSize = CRM_Utils_Number
::formatUnitSize(Civi
::settings()->get('maxFileSize') . 'm', TRUE);
52 //Fetch uploadFileSize from php_ini when $config->maxFileSize is set to "no limit".
53 if (empty($uploadFileSize)) {
54 $uploadFileSize = CRM_Utils_Number
::formatUnitSize(ini_get('upload_max_filesize'), TRUE);
56 $uploadSize = round(($uploadFileSize / (1024 * 1024)), 2);
57 $form->assign('uploadSize', $uploadSize);
58 $form->add('File', 'uploadFile', ts('Import Data File'), NULL, TRUE);
59 $form->setMaxFileSize($uploadFileSize);
60 $form->addRule('uploadFile', ts('File size should be less than %1 MBytes (%2 bytes)', [
63 ]), 'maxfilesize', $uploadFileSize);
64 $form->addRule('uploadFile', ts('Input file must be in CSV format'), 'utf8File');
65 $form->addRule('uploadFile', ts('A valid file must be uploaded.'), 'uploadedfile');
67 $form->addElement('checkbox', 'skipColumnHeader', ts('First row contains column headers'));
71 * Initialize the datasource, based on the submitted values stored in the user job.
73 * @throws \API_Exception
74 * @throws \CRM_Core_Exception
76 public function initialize(): void
{
77 $result = $this->csvToTable(
78 $this->getSubmittedValue('uploadFile')['name'],
79 $this->getSubmittedValue('skipColumnHeader'),
80 $this->getSubmittedValue('fieldSeparator') ??
','
82 $this->addTrackingFieldsToTable($result['import_table_name']);
84 $this->updateUserJobMetadata('DataSource', [
85 'table_name' => $result['import_table_name'],
86 'column_headers' => $result['column_headers'],
87 'number_of_columns' => $result['number_of_columns'],
92 * Create a table that matches the CSV file and populate it with the file's contents
96 * @param bool $headers
97 * Whether the first row contains headers.
98 * @param string $fieldSeparator
99 * Character that separates the various columns in the file.
102 * name of the created table
103 * @throws \CRM_Core_Exception
105 private function csvToTable(
108 $fieldSeparator = ','
111 $fd = fopen($file, 'r');
113 throw new CRM_Core_Exception("Could not read $file");
115 if (filesize($file) == 0) {
116 throw new CRM_Core_Exception("$file is empty. Please upload a valid file.");
119 // support tab separated
120 if (strtolower($fieldSeparator) === 'tab' ||
121 strtolower($fieldSeparator) === '\t'
123 $fieldSeparator = "\t";
126 $firstrow = fgetcsv($fd, 0, $fieldSeparator);
127 $result['column_headers'] = array_fill(0, count($firstrow), '');
128 // create the column names from the CSV header or as col_0, col_1, etc.
130 //need to get original headers.
131 $result['column_headers'] = $firstrow;
133 $strtolower = function_exists('mb_strtolower') ?
'mb_strtolower' : 'strtolower';
134 $columns = array_map($strtolower, $firstrow);
135 $columns = str_replace(' ', '_', $columns);
136 $columns = preg_replace('/[^a-z_]/', '', $columns);
138 // need to take care of null as well as duplicate col names.
139 $duplicateColName = FALSE;
140 if (count($columns) != count(array_unique($columns))) {
141 $duplicateColName = TRUE;
144 // need to truncate values per mysql field name length limits
145 // mysql allows 64, but we need to account for appending colKey
147 foreach ($columns as $colKey => & $colName) {
148 if (strlen($colName) > 58) {
149 $colName = substr($colName, 0, 58);
153 if (in_array('', $columns) ||
$duplicateColName) {
154 foreach ($columns as $colKey => & $colName) {
156 $colName = "col_$colKey";
158 elseif ($duplicateColName) {
159 $colName .= "_$colKey";
164 // CRM-4881: we need to quote column names, as they may be MySQL reserved words
165 foreach ($columns as & $column) {
166 $column = "`$column`";
171 foreach ($firstrow as $i => $_) {
172 $columns[] = "col_$i";
176 $table = CRM_Utils_SQL_TempTable
::build()->setDurable();
177 $tableName = $table->getName();
178 CRM_Core_DAO
::executeQuery("DROP TABLE IF EXISTS $tableName");
179 $table->createWithColumns(implode(' text, ', $columns) . ' text');
181 $numColumns = count($columns);
183 // the proper approach, but some MySQL installs do not have this enabled
184 // $load = "LOAD DATA LOCAL INFILE '$file' INTO TABLE $table FIELDS TERMINATED BY '$fieldSeparator' OPTIONALLY ENCLOSED BY '\"'";
185 // if ($headers) { $load .= ' IGNORE 1 LINES'; }
186 // $db->query($load);
188 // parse the CSV line by line and build one big INSERT (while MySQL-escaping the CSV contents)
196 while ($row = fgetcsv($fd, 0, $fieldSeparator)) {
197 // skip rows that dont match column count, else we get a sql error
198 if (count($row) != $numColumns) {
201 // A blank line will be array(0 => NULL)
202 if ($row === [NULL]) {
212 // CRM-17859 Trim non-breaking spaces from columns.
213 $row = array_map(['CRM_Import_DataSource_CSV', 'trimNonBreakingSpaces'], $row);
214 $row = array_map(['CRM_Core_DAO', 'escapeString'], $row);
215 $sql .= "('" . implode("', '", $row) . "')";
218 if ($count >= self
::NUM_ROWS_TO_INSERT
&& !empty($sql)) {
219 CRM_Core_DAO
::executeQuery("INSERT IGNORE INTO $tableName VALUES $sql");
228 CRM_Core_DAO
::executeQuery("INSERT IGNORE INTO $tableName VALUES $sql");
233 //get the import tmp table name.
234 $result['import_table_name'] = $tableName;
235 $result['number_of_columns'] = $numColumns;
240 * Trim non-breaking spaces in a multibyte-safe way.
241 * See also dev/core#2127 - avoid breaking strings ending in à or any other
242 * unicode character sharing the same 0xA0 byte as a non-breaking space.
244 * @param string $string
245 * @return string The trimmed string
247 public static function trimNonBreakingSpaces(string $string): string {
248 $encoding = mb_detect_encoding($string, NULL, TRUE);
249 if ($encoding === FALSE) {
250 // This could mean a couple things. One is that the string is
251 // ASCII-encoded but contains a non-breaking space, which causes
252 // php to fail to detect the encoding. So let's just do what we
253 // did before which works in that situation and is at least no
254 // worse in other situations.
255 return trim($string, chr(0xC2) . chr(0xA0));
257 elseif ($encoding !== 'UTF-8') {
258 $string = mb_convert_encoding($string, 'UTF-8', [$encoding]);
260 return preg_replace("/^(\u{a0})+|(\u{a0})+$/", '', $string);