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