INFRA-132 - Spaces around "."
[civicrm-core.git] / CRM / Import / DataSource / CSV.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2009. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35 class CRM_Import_DataSource_CSV extends CRM_Import_DataSource {
36 const
37 NUM_ROWS_TO_INSERT = 100;
38
39 /**
40 * Provides information about the data source
41 *
42 * @return array collection of info about this data source
43 *
44 *
45 */
46 public function getInfo() {
47 return array('title' => ts('Comma-Separated Values (CSV)'));
48 }
49
50 /**
51 * Set variables up before form is built
52 *
53 */
54 public function preProcess(&$form) {
55 }
56
57 /**
58 * This is function is called by the form object to get the DataSource's
59 * form snippet. It should add all fields necesarry to get the data
60 * uploaded to the temporary table in the DB.
61 *
62 * @param CRM_Core_Form $form
63 *
64 * @return void (operates directly on form argument)
65 */
66 public function buildQuickForm(&$form) {
67 $form->add('hidden', 'hidden_dataSource', 'CRM_Import_DataSource_CSV');
68
69 $config = CRM_Core_Config::singleton();
70
71 $uploadFileSize = CRM_Core_Config_Defaults::formatUnitSize($config->maxFileSize . 'm', TRUE);
72 $uploadSize = round(($uploadFileSize / (1024 * 1024)), 2);
73 $form->assign('uploadSize', $uploadSize);
74 $form->add('File', 'uploadFile', ts('Import Data File'), 'size=30 maxlength=255', TRUE);
75 $form->setMaxFileSize($uploadFileSize);
76 $form->addRule('uploadFile', ts('File size should be less than %1 MBytes (%2 bytes)', array(1 => $uploadSize, 2 => $uploadFileSize)), 'maxfilesize', $uploadFileSize);
77 $form->addRule('uploadFile', ts('Input file must be in CSV format'), 'utf8File');
78 $form->addRule('uploadFile', ts('A valid file must be uploaded.'), 'uploadedfile');
79
80 $form->addElement('checkbox', 'skipColumnHeader', ts('First row contains column headers'));
81 }
82
83 /**
84 * Process the form submission
85 *
86 */
87 public function postProcess(&$params, &$db, &$form) {
88 $file = $params['uploadFile']['name'];
89 $result = self::_CsvToTable($db,
90 $file,
91 CRM_Utils_Array::value('skipColumnHeader', $params, FALSE),
92 CRM_Utils_Array::value('import_table_name', $params),
93 CRM_Utils_Array::value('fieldSeparator', $params, ',')
94 );
95
96 $form->set('originalColHeader', CRM_Utils_Array::value('original_col_header', $result));
97
98 $table = $result['import_table_name'];
99 $importJob = new CRM_Contact_Import_ImportJob($table);
100 $form->set('importTableName', $importJob->getTableName());
101 }
102
103 /**
104 * Create a table that matches the CSV file and populate it with the file's contents
105 *
106 * @param object $db
107 * Handle to the database connection.
108 * @param string $file
109 * File name to load.
110 * @param bool $headers
111 * Whether the first row contains headers.
112 * @param string $table
113 * Name of table from which data imported.
114 * @param string $fieldSeparator
115 * Character that seperates the various columns in the file.
116 *
117 * @return string name of the created table
118 */
119 private static function _CsvToTable(
120 &$db,
121 $file,
122 $headers = FALSE,
123 $table = NULL,
124 $fieldSeparator = ','
125 ) {
126 $result = array();
127 $fd = fopen($file, 'r');
128 if (!$fd) {
129 CRM_Core_Error::fatal("Could not read $file");
130 }
131
132 $config = CRM_Core_Config::singleton();
133 // support tab separated
134 if (strtolower($fieldSeparator) == 'tab' ||
135 strtolower($fieldSeparator) == '\t'
136 ) {
137 $fieldSeparator = "\t";
138 }
139
140 $firstrow = fgetcsv($fd, 0, $fieldSeparator);
141
142 // create the column names from the CSV header or as col_0, col_1, etc.
143 if ($headers) {
144 //need to get original headers.
145 $result['original_col_header'] = $firstrow;
146
147 $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
148 $columns = array_map($strtolower, $firstrow);
149 $columns = str_replace(' ', '_', $columns);
150 $columns = preg_replace('/[^a-z_]/', '', $columns);
151
152 // need to take care of null as well as duplicate col names.
153 $duplicateColName = FALSE;
154 if (count($columns) != count(array_unique($columns))) {
155 $duplicateColName = TRUE;
156 }
157
158 // need to truncate values per mysql field name length limits
159 // mysql allows 64, but we need to account for appending colKey
160 // CRM-9079
161 foreach ($columns as $colKey => & $colName) {
162 if (strlen($colName) > 58) {
163 $colName = substr($colName, 0, 58);
164 }
165 }
166
167 if (in_array('', $columns) || $duplicateColName) {
168 foreach ($columns as $colKey => & $colName) {
169 if (!$colName) {
170 $colName = "col_$colKey";
171 }
172 elseif ($duplicateColName) {
173 $colName .= "_$colKey";
174 }
175 }
176 }
177
178 // CRM-4881: we need to quote column names, as they may be MySQL reserved words
179 foreach ($columns as & $column) {
180 $column = "`$column`";
181 }
182 }
183 else {
184 $columns = array();
185 foreach ($firstrow as $i => $_) {
186 $columns[] = "col_$i";
187 }
188 }
189
190 // FIXME: we should regen this table's name if it exists rather than drop it
191 if (!$table) {
192 $table = 'civicrm_import_job_' . md5(uniqid(rand(), TRUE));
193 }
194
195 $db->query("DROP TABLE IF EXISTS $table");
196
197 $numColumns = count($columns);
198 $create = "CREATE TABLE $table (" . implode(' text, ', $columns) . " text) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
199 $db->query($create);
200
201 // the proper approach, but some MySQL installs do not have this enabled
202 // $load = "LOAD DATA LOCAL INFILE '$file' INTO TABLE $table FIELDS TERMINATED BY '$fieldSeparator' OPTIONALLY ENCLOSED BY '\"'";
203 // if ($headers) { $load .= ' IGNORE 1 LINES'; }
204 // $db->query($load);
205
206 // parse the CSV line by line and build one big INSERT (while MySQL-escaping the CSV contents)
207 if (!$headers) {
208 rewind($fd);
209 }
210
211 $sql = NULL;
212 $first = TRUE;
213 $count = 0;
214 while ($row = fgetcsv($fd, 0, $fieldSeparator)) {
215 // skip rows that dont match column count, else we get a sql error
216 if (count($row) != $numColumns) {
217 continue;
218 }
219
220 if (!$first) {
221 $sql .= ', ';
222 }
223
224 $first = FALSE;
225 $row = array_map('civicrm_mysql_real_escape_string', $row);
226 $sql .= "('" . implode("', '", $row) . "')";
227 $count++;
228
229 if ($count >= self::NUM_ROWS_TO_INSERT && !empty($sql)) {
230 $sql = "INSERT IGNORE INTO $table VALUES $sql";
231 $db->query($sql);
232
233 $sql = NULL;
234 $first = TRUE;
235 $count = 0;
236 }
237 }
238
239 if (!empty($sql)) {
240 $sql = "INSERT IGNORE INTO $table VALUES $sql";
241 $db->query($sql);
242 }
243
244 fclose($fd);
245
246 //get the import tmp table name.
247 $result['import_table_name'] = $table;
248
249 return $result;
250 }
251 }
252
253 /**
254 * @param $string
255 *
256 * @return string
257 */
258 function civicrm_mysql_real_escape_string($string) {
259 static $dao = NULL;
260 if (!$dao) {
261 $dao = new CRM_Core_DAO();
262 }
263 return $dao->escape($string);
264 }