[REF] [Import] Remove always NULL parameter from private function
[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 \API_Exception
78 * @throws \CRM_Core_Exception
79 */
80 public function postProcess(&$params, &$db, &$form) {
81 $file = $params['uploadFile']['name'];
82 $firstRowIsColumnHeader = $params['skipColumnHeader'] ?? FALSE;
83 $result = self::_CsvToTable(
84 $file,
85 $firstRowIsColumnHeader,
86 CRM_Utils_Array::value('fieldSeparator', $params, ',')
87 );
88
89 $form->set('originalColHeader', CRM_Utils_Array::value('column_headers', $result));
90 $form->set('importTableName', $result['import_table_name']);
91 $this->updateUserJobMetadata('DataSource', [
92 'table_name' => $result['import_table_name'],
93 'column_headers' => $firstRowIsColumnHeader ? $result['column_headers'] : [],
94 'number_of_columns' => $result['number_of_columns'],
95 ]);
96 }
97
98 /**
99 * Create a table that matches the CSV file and populate it with the file's contents
100 *
101 * @param string $file
102 * File name to load.
103 * @param bool $headers
104 * Whether the first row contains headers.
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 $fieldSeparator = ','
116 ) {
117 $result = [];
118 $fd = fopen($file, 'r');
119 if (!$fd) {
120 throw new CRM_Core_Exception("Could not read $file");
121 }
122 if (filesize($file) == 0) {
123 throw new CRM_Core_Exception("$file is empty. Please upload a valid file.");
124 }
125
126 // support tab separated
127 if (strtolower($fieldSeparator) === 'tab' ||
128 strtolower($fieldSeparator) === '\t'
129 ) {
130 $fieldSeparator = "\t";
131 }
132
133 $firstrow = fgetcsv($fd, 0, $fieldSeparator);
134
135 // create the column names from the CSV header or as col_0, col_1, etc.
136 if ($headers) {
137 //need to get original headers.
138 $result['column_headers'] = $firstrow;
139
140 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
141 $columns = array_map($strtolower, $firstrow);
142 $columns = str_replace(' ', '_', $columns);
143 $columns = preg_replace('/[^a-z_]/', '', $columns);
144
145 // need to take care of null as well as duplicate col names.
146 $duplicateColName = FALSE;
147 if (count($columns) != count(array_unique($columns))) {
148 $duplicateColName = TRUE;
149 }
150
151 // need to truncate values per mysql field name length limits
152 // mysql allows 64, but we need to account for appending colKey
153 // CRM-9079
154 foreach ($columns as $colKey => & $colName) {
155 if (strlen($colName) > 58) {
156 $colName = substr($colName, 0, 58);
157 }
158 }
159
160 if (in_array('', $columns) || $duplicateColName) {
161 foreach ($columns as $colKey => & $colName) {
162 if (!$colName) {
163 $colName = "col_$colKey";
164 }
165 elseif ($duplicateColName) {
166 $colName .= "_$colKey";
167 }
168 }
169 }
170
171 // CRM-4881: we need to quote column names, as they may be MySQL reserved words
172 foreach ($columns as & $column) {
173 $column = "`$column`";
174 }
175 }
176 else {
177 $columns = [];
178 foreach ($firstrow as $i => $_) {
179 $columns[] = "col_$i";
180 }
181 }
182
183 $table = CRM_Utils_SQL_TempTable::build()->setDurable();
184 $tableName = $table->getName();
185 CRM_Core_DAO::executeQuery("DROP TABLE IF EXISTS $tableName");
186 $table->createWithColumns(implode(' text, ', $columns) . ' text');
187
188 $numColumns = count($columns);
189
190 // the proper approach, but some MySQL installs do not have this enabled
191 // $load = "LOAD DATA LOCAL INFILE '$file' INTO TABLE $table FIELDS TERMINATED BY '$fieldSeparator' OPTIONALLY ENCLOSED BY '\"'";
192 // if ($headers) { $load .= ' IGNORE 1 LINES'; }
193 // $db->query($load);
194
195 // parse the CSV line by line and build one big INSERT (while MySQL-escaping the CSV contents)
196 if (!$headers) {
197 rewind($fd);
198 }
199
200 $sql = NULL;
201 $first = TRUE;
202 $count = 0;
203 while ($row = fgetcsv($fd, 0, $fieldSeparator)) {
204 // skip rows that dont match column count, else we get a sql error
205 if (count($row) != $numColumns) {
206 continue;
207 }
208 // A blank line will be array(0 => NULL)
209 if ($row === [NULL]) {
210 continue;
211 }
212
213 if (!$first) {
214 $sql .= ', ';
215 }
216
217 $first = FALSE;
218
219 // CRM-17859 Trim non-breaking spaces from columns.
220 $row = array_map(['CRM_Import_DataSource_CSV', 'trimNonBreakingSpaces'], $row);
221 $row = array_map(['CRM_Core_DAO', 'escapeString'], $row);
222 $sql .= "('" . implode("', '", $row) . "')";
223 $count++;
224
225 if ($count >= self::NUM_ROWS_TO_INSERT && !empty($sql)) {
226 CRM_Core_DAO::executeQuery("INSERT IGNORE INTO $tableName VALUES $sql");
227
228 $sql = NULL;
229 $first = TRUE;
230 $count = 0;
231 }
232 }
233
234 if (!empty($sql)) {
235 CRM_Core_DAO::executeQuery("INSERT IGNORE INTO $tableName VALUES $sql");
236 }
237
238 fclose($fd);
239
240 //get the import tmp table name.
241 $result['import_table_name'] = $tableName;
242 $result['number_of_columns'] = $numColumns;
243 return $result;
244 }
245
246 /**
247 * Trim non-breaking spaces in a multibyte-safe way.
248 * See also dev/core#2127 - avoid breaking strings ending in à or any other
249 * unicode character sharing the same 0xA0 byte as a non-breaking space.
250 *
251 * @param string $string
252 * @return string The trimmed string
253 */
254 public static function trimNonBreakingSpaces(string $string): string {
255 $encoding = mb_detect_encoding($string, NULL, TRUE);
256 if ($encoding === FALSE) {
257 // This could mean a couple things. One is that the string is
258 // ASCII-encoded but contains a non-breaking space, which causes
259 // php to fail to detect the encoding. So let's just do what we
260 // did before which works in that situation and is at least no
261 // worse in other situations.
262 return trim($string, chr(0xC2) . chr(0xA0));
263 }
264 elseif ($encoding !== 'UTF-8') {
265 $string = mb_convert_encoding($string, 'UTF-8', [$encoding]);
266 }
267 return preg_replace("/^(\u{a0})+|(\u{a0})+$/", '', $string);
268 }
269
270 }