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 | ||
e0ef6999 | 21 | /** |
fe482240 | 22 | * Provides information about the data source. |
e0ef6999 | 23 | * |
a6c01b45 CW |
24 | * @return array |
25 | * collection of info about this data source | |
e0ef6999 | 26 | */ |
00be9182 | 27 | public function getInfo() { |
be2fb01f | 28 | return ['title' => ts('Comma-Separated Values (CSV)')]; |
6a488035 TO |
29 | } |
30 | ||
e0ef6999 | 31 | /** |
fe482240 | 32 | * Set variables up before form is built. |
3bdf1f3a | 33 | * |
34 | * @param CRM_Core_Form $form | |
e0ef6999 | 35 | */ |
3a05d67e TO |
36 | public function preProcess(&$form) { |
37 | } | |
6a488035 | 38 | |
e0ef6999 | 39 | /** |
b8c71ffa | 40 | * This is function is called by the form object to get the DataSource's form snippet. |
41 | * | |
42 | * It should add all fields necessary to get the data | |
e0ef6999 EM |
43 | * uploaded to the temporary table in the DB. |
44 | * | |
c490a46a | 45 | * @param CRM_Core_Form $form |
c4382285 | 46 | * |
47 | * @throws \CRM_Core_Exception | |
e0ef6999 | 48 | */ |
00be9182 | 49 | public function buildQuickForm(&$form) { |
6a488035 TO |
50 | $form->add('hidden', 'hidden_dataSource', 'CRM_Import_DataSource_CSV'); |
51 | ||
52 | $config = CRM_Core_Config::singleton(); | |
53 | ||
2e966dd5 | 54 | $uploadFileSize = CRM_Utils_Number::formatUnitSize($config->maxFileSize . 'm', TRUE); |
ebcf0a88 JP |
55 | //Fetch uploadFileSize from php_ini when $config->maxFileSize is set to "no limit". |
56 | if (empty($uploadFileSize)) { | |
57 | $uploadFileSize = CRM_Utils_Number::formatUnitSize(ini_get('upload_max_filesize'), TRUE); | |
58 | } | |
6a488035 TO |
59 | $uploadSize = round(($uploadFileSize / (1024 * 1024)), 2); |
60 | $form->assign('uploadSize', $uploadSize); | |
66dc6009 | 61 | $form->add('File', 'uploadFile', ts('Import Data File'), 'size=30 maxlength=255', TRUE); |
6a488035 | 62 | $form->setMaxFileSize($uploadFileSize); |
be2fb01f | 63 | $form->addRule('uploadFile', ts('File size should be less than %1 MBytes (%2 bytes)', [ |
971e129b SL |
64 | 1 => $uploadSize, |
65 | 2 => $uploadFileSize, | |
66 | ]), 'maxfilesize', $uploadFileSize); | |
6a488035 TO |
67 | $form->addRule('uploadFile', ts('Input file must be in CSV format'), 'utf8File'); |
68 | $form->addRule('uploadFile', ts('A valid file must be uploaded.'), 'uploadedfile'); | |
69 | ||
70 | $form->addElement('checkbox', 'skipColumnHeader', ts('First row contains column headers')); | |
71 | } | |
72 | ||
e0ef6999 | 73 | /** |
fe482240 | 74 | * Process the form submission. |
54957108 | 75 | * |
76 | * @param array $params | |
77 | * @param string $db | |
78 | * @param \CRM_Core_Form $form | |
e0ef6999 | 79 | */ |
00be9182 | 80 | public function postProcess(&$params, &$db, &$form) { |
6a488035 | 81 | $file = $params['uploadFile']['name']; |
6a488035 TO |
82 | $result = self::_CsvToTable($db, |
83 | $file, | |
84 | CRM_Utils_Array::value('skipColumnHeader', $params, FALSE), | |
85 | CRM_Utils_Array::value('import_table_name', $params), | |
86 | CRM_Utils_Array::value('fieldSeparator', $params, ',') | |
87 | ); | |
88 | ||
89 | $form->set('originalColHeader', CRM_Utils_Array::value('original_col_header', $result)); | |
90 | ||
91 | $table = $result['import_table_name']; | |
719a6fec | 92 | $importJob = new CRM_Contact_Import_ImportJob($table); |
6a488035 TO |
93 | $form->set('importTableName', $importJob->getTableName()); |
94 | } | |
95 | ||
96 | /** | |
97 | * Create a table that matches the CSV file and populate it with the file's contents | |
98 | * | |
6f69cc11 TO |
99 | * @param object $db |
100 | * Handle to the database connection. | |
101 | * @param string $file | |
102 | * File name to load. | |
103 | * @param bool $headers | |
104 | * Whether the first row contains headers. | |
105 | * @param string $table | |
106 | * Name of table from which data imported. | |
107 | * @param string $fieldSeparator | |
b44e3f84 | 108 | * Character that separates the various columns in the file. |
6a488035 | 109 | * |
a6c01b45 CW |
110 | * @return string |
111 | * name of the created table | |
6a488035 | 112 | */ |
bd5d7c2b TO |
113 | private static function _CsvToTable( |
114 | &$db, | |
6a488035 | 115 | $file, |
3a05d67e TO |
116 | $headers = FALSE, |
117 | $table = NULL, | |
6a488035 TO |
118 | $fieldSeparator = ',' |
119 | ) { | |
be2fb01f | 120 | $result = []; |
6a488035 TO |
121 | $fd = fopen($file, 'r'); |
122 | if (!$fd) { | |
7980012b | 123 | throw new CRM_Core_Exception("Could not read $file"); |
6a488035 | 124 | } |
3bf4c8a0 | 125 | if (filesize($file) == 0) { |
7980012b | 126 | throw new CRM_Core_Exception("$file is empty. Please upload a valid file."); |
3bf4c8a0 | 127 | } |
6a488035 TO |
128 | |
129 | $config = CRM_Core_Config::singleton(); | |
130 | // support tab separated | |
131 | if (strtolower($fieldSeparator) == 'tab' || | |
132 | strtolower($fieldSeparator) == '\t' | |
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. | |
142 | $result['original_col_header'] = $firstrow; | |
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 | ||
187 | // FIXME: we should regen this table's name if it exists rather than drop it | |
188 | if (!$table) { | |
189 | $table = 'civicrm_import_job_' . md5(uniqid(rand(), TRUE)); | |
190 | } | |
191 | ||
192 | $db->query("DROP TABLE IF EXISTS $table"); | |
193 | ||
194 | $numColumns = count($columns); | |
195 | $create = "CREATE TABLE $table (" . implode(' text, ', $columns) . " text) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci"; | |
196 | $db->query($create); | |
197 | ||
198 | // the proper approach, but some MySQL installs do not have this enabled | |
199 | // $load = "LOAD DATA LOCAL INFILE '$file' INTO TABLE $table FIELDS TERMINATED BY '$fieldSeparator' OPTIONALLY ENCLOSED BY '\"'"; | |
200 | // if ($headers) { $load .= ' IGNORE 1 LINES'; } | |
201 | // $db->query($load); | |
202 | ||
203 | // parse the CSV line by line and build one big INSERT (while MySQL-escaping the CSV contents) | |
204 | if (!$headers) { | |
205 | rewind($fd); | |
206 | } | |
207 | ||
353ffa53 | 208 | $sql = NULL; |
6a488035 TO |
209 | $first = TRUE; |
210 | $count = 0; | |
211 | while ($row = fgetcsv($fd, 0, $fieldSeparator)) { | |
212 | // skip rows that dont match column count, else we get a sql error | |
213 | if (count($row) != $numColumns) { | |
214 | continue; | |
215 | } | |
216 | ||
217 | if (!$first) { | |
218 | $sql .= ', '; | |
219 | } | |
220 | ||
221 | $first = FALSE; | |
5dcdc4d6 SB |
222 | |
223 | // CRM-17859 Trim non-breaking spaces from columns. | |
224 | $row = array_map( | |
225 | function($string) { | |
226 | return trim($string, chr(0xC2) . chr(0xA0)); | |
227 | }, $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)) { | |
233 | $sql = "INSERT IGNORE INTO $table VALUES $sql"; | |
234 | $db->query($sql); | |
235 | ||
353ffa53 | 236 | $sql = NULL; |
6a488035 TO |
237 | $first = TRUE; |
238 | $count = 0; | |
239 | } | |
240 | } | |
241 | ||
242 | if (!empty($sql)) { | |
243 | $sql = "INSERT IGNORE INTO $table VALUES $sql"; | |
244 | $db->query($sql); | |
245 | } | |
246 | ||
247 | fclose($fd); | |
248 | ||
249 | //get the import tmp table name. | |
250 | $result['import_table_name'] = $table; | |
251 | ||
252 | return $result; | |
253 | } | |
96025800 | 254 | |
6a488035 | 255 | } |