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