6d76bf9fedee6077bdcef12787637f7dccf2bf52
[civicrm-core.git] / CRM / Import / DataSource / CSV.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17 class CRM_Import_DataSource_CSV extends CRM_Import_DataSource {
18 const
19 NUM_ROWS_TO_INSERT = 100;
20
21 /**
22 * Form fields declared for this datasource.
23 *
24 * @var string[]
25 */
26 protected $submittableFields = ['skipColumnHeader', 'uploadField'];
27
28 /**
29 * Provides information about the data source.
30 *
31 * @return array
32 * collection of info about this data source
33 */
34 public function getInfo(): array {
35 return ['title' => ts('Comma-Separated Values (CSV)')];
36 }
37
38 /**
39 * This is function is called by the form object to get the DataSource's form snippet.
40 *
41 * It should add all fields necessary to get the data
42 * uploaded to the temporary table in the DB.
43 *
44 * @param CRM_Core_Form $form
45 *
46 * @throws \CRM_Core_Exception
47 */
48 public function buildQuickForm(&$form) {
49 $form->add('hidden', 'hidden_dataSource', 'CRM_Import_DataSource_CSV');
50
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);
55 }
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)', [
61 1 => $uploadSize,
62 2 => $uploadFileSize,
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');
66
67 $form->addElement('checkbox', 'skipColumnHeader', ts('First row contains column headers'));
68 }
69
70 /**
71 * Process the form submission.
72 *
73 * @param array $params
74 * @param string $db
75 * @param \CRM_Core_Form $form
76 *
77 * @throws \CRM_Core_Exception
78 */
79 public function postProcess(&$params, &$db, &$form) {
80 $file = $params['uploadFile']['name'];
81 $result = self::_CsvToTable(
82 $file,
83 CRM_Utils_Array::value('skipColumnHeader', $params, FALSE),
84 CRM_Utils_Array::value('import_table_name', $params),
85 CRM_Utils_Array::value('fieldSeparator', $params, ',')
86 );
87
88 $form->set('originalColHeader', CRM_Utils_Array::value('column_headers', $result));
89 $form->set('importTableName', $result['import_table_name']);
90 $this->dataSourceMetadata = [
91 'table_name' => $result['import_table_name'],
92 'column_headers' => $result['column_headers'] ?? NULL,
93 ];
94 }
95
96 /**
97 * Create a table that matches the CSV file and populate it with the file's contents
98 *
99 * @param string $file
100 * File name to load.
101 * @param bool $headers
102 * Whether the first row contains headers.
103 * @param string $tableName
104 * Name of table from which data imported.
105 * @param string $fieldSeparator
106 * Character that separates the various columns in the file.
107 *
108 * @return array
109 * name of the created table
110 * @throws \CRM_Core_Exception
111 */
112 private static function _CsvToTable(
113 $file,
114 $headers = FALSE,
115 $tableName = NULL,
116 $fieldSeparator = ','
117 ) {
118 $result = [];
119 $fd = fopen($file, 'r');
120 if (!$fd) {
121 throw new CRM_Core_Exception("Could not read $file");
122 }
123 if (filesize($file) == 0) {
124 throw new CRM_Core_Exception("$file is empty. Please upload a valid file.");
125 }
126
127 // support tab separated
128 if (strtolower($fieldSeparator) === 'tab' ||
129 strtolower($fieldSeparator) === '\t'
130 ) {
131 $fieldSeparator = "\t";
132 }
133
134 $firstrow = fgetcsv($fd, 0, $fieldSeparator);
135
136 // create the column names from the CSV header or as col_0, col_1, etc.
137 if ($headers) {
138 //need to get original headers.
139 $result['column_headers'] = $firstrow;
140
141 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
142 $columns = array_map($strtolower, $firstrow);
143 $columns = str_replace(' ', '_', $columns);
144 $columns = preg_replace('/[^a-z_]/', '', $columns);
145
146 // need to take care of null as well as duplicate col names.
147 $duplicateColName = FALSE;
148 if (count($columns) != count(array_unique($columns))) {
149 $duplicateColName = TRUE;
150 }
151
152 // need to truncate values per mysql field name length limits
153 // mysql allows 64, but we need to account for appending colKey
154 // CRM-9079
155 foreach ($columns as $colKey => & $colName) {
156 if (strlen($colName) > 58) {
157 $colName = substr($colName, 0, 58);
158 }
159 }
160
161 if (in_array('', $columns) || $duplicateColName) {
162 foreach ($columns as $colKey => & $colName) {
163 if (!$colName) {
164 $colName = "col_$colKey";
165 }
166 elseif ($duplicateColName) {
167 $colName .= "_$colKey";
168 }
169 }
170 }
171
172 // CRM-4881: we need to quote column names, as they may be MySQL reserved words
173 foreach ($columns as & $column) {
174 $column = "`$column`";
175 }
176 }
177 else {
178 $columns = [];
179 foreach ($firstrow as $i => $_) {
180 $columns[] = "col_$i";
181 }
182 }
183
184 if ($tableName) {
185 CRM_Core_DAO::executeQuery("DROP TABLE IF EXISTS $tableName");
186 }
187 $table = CRM_Utils_SQL_TempTable::build()->setDurable();
188 $tableName = $table->getName();
189 CRM_Core_DAO::executeQuery("DROP TABLE IF EXISTS $tableName");
190 $table->createWithColumns(implode(' text, ', $columns) . ' text');
191
192 $numColumns = count($columns);
193
194 // the proper approach, but some MySQL installs do not have this enabled
195 // $load = "LOAD DATA LOCAL INFILE '$file' INTO TABLE $table FIELDS TERMINATED BY '$fieldSeparator' OPTIONALLY ENCLOSED BY '\"'";
196 // if ($headers) { $load .= ' IGNORE 1 LINES'; }
197 // $db->query($load);
198
199 // parse the CSV line by line and build one big INSERT (while MySQL-escaping the CSV contents)
200 if (!$headers) {
201 rewind($fd);
202 }
203
204 $sql = NULL;
205 $first = TRUE;
206 $count = 0;
207 while ($row = fgetcsv($fd, 0, $fieldSeparator)) {
208 // skip rows that dont match column count, else we get a sql error
209 if (count($row) != $numColumns) {
210 continue;
211 }
212 // A blank line will be array(0 => NULL)
213 if ($row === [NULL]) {
214 continue;
215 }
216
217 if (!$first) {
218 $sql .= ', ';
219 }
220
221 $first = FALSE;
222
223 // CRM-17859 Trim non-breaking spaces from columns.
224 $row = array_map(['CRM_Import_DataSource_CSV', 'trimNonBreakingSpaces'], $row);
225 $row = array_map(['CRM_Core_DAO', 'escapeString'], $row);
226 $sql .= "('" . implode("', '", $row) . "')";
227 $count++;
228
229 if ($count >= self::NUM_ROWS_TO_INSERT && !empty($sql)) {
230 CRM_Core_DAO::executeQuery("INSERT IGNORE INTO $tableName VALUES $sql");
231
232 $sql = NULL;
233 $first = TRUE;
234 $count = 0;
235 }
236 }
237
238 if (!empty($sql)) {
239 CRM_Core_DAO::executeQuery("INSERT IGNORE INTO $tableName VALUES $sql");
240 }
241
242 fclose($fd);
243
244 //get the import tmp table name.
245 $result['import_table_name'] = $tableName;
246 return $result;
247 }
248
249 /**
250 * Trim non-breaking spaces in a multibyte-safe way.
251 * See also dev/core#2127 - avoid breaking strings ending in à or any other
252 * unicode character sharing the same 0xA0 byte as a non-breaking space.
253 *
254 * @param string $string
255 * @return string The trimmed string
256 */
257 public static function trimNonBreakingSpaces(string $string): string {
258 $encoding = mb_detect_encoding($string, NULL, TRUE);
259 if ($encoding === FALSE) {
260 // This could mean a couple things. One is that the string is
261 // ASCII-encoded but contains a non-breaking space, which causes
262 // php to fail to detect the encoding. So let's just do what we
263 // did before which works in that situation and is at least no
264 // worse in other situations.
265 return trim($string, chr(0xC2) . chr(0xA0));
266 }
267 elseif ($encoding !== 'UTF-8') {
268 $string = mb_convert_encoding($string, 'UTF-8', [$encoding]);
269 }
270 return preg_replace("/^(\u{a0})+|(\u{a0})+$/", '', $string);
271 }
272
273 }