Merge remote-tracking branch 'upstream/4.4' into 4.4-master-2014-07-16-12-52-48
[civicrm-core.git] / CRM / Import / DataSource / CSV.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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 * @access public
45 *
46 */
47 function getInfo() {
48 return array('title' => ts('Comma-Separated Values (CSV)'));
49 }
50
51 /**
52 * Function to set variables up before form is built
53 *
54 * @access public
55 */
56 function preProcess(&$form) {}
57
58 /**
59 * This is function is called by the form object to get the DataSource's
60 * form snippet. It should add all fields necesarry to get the data
61 * uploaded to the temporary table in the DB.
62 *
63 * @param $form
64 *
65 * @return void (operates directly on form argument)
66 * @access public
67 */
68 function buildQuickForm(&$form) {
69 $form->add('hidden', 'hidden_dataSource', 'CRM_Import_DataSource_CSV');
70
71 $config = CRM_Core_Config::singleton();
72
73 $uploadFileSize = CRM_Core_Config_Defaults::formatUnitSize($config->maxFileSize.'m');
74 $uploadSize = round(($uploadFileSize / (1024 * 1024)), 2);
75 $form->assign('uploadSize', $uploadSize);
76 $form->add('File', 'uploadFile', ts('Import Data File'), 'size=30 maxlength=255', TRUE);
77 $form->setMaxFileSize($uploadFileSize);
78 $form->addRule('uploadFile', ts('File size should be less than %1 MBytes (%2 bytes)', array(1 => $uploadSize, 2 => $uploadFileSize)), 'maxfilesize', $uploadFileSize);
79 $form->addRule('uploadFile', ts('Input file must be in CSV format'), 'utf8File');
80 $form->addRule('uploadFile', ts('A valid file must be uploaded.'), 'uploadedfile');
81
82 $form->addElement('checkbox', 'skipColumnHeader', ts('First row contains column headers'));
83 }
84
85 /**
86 * Function to process the form
87 *
88 * @access public
89 */
90 function postProcess(&$params, &$db, &$form) {
91 $file = $params['uploadFile']['name'];
92 $result = self::_CsvToTable($db,
93 $file,
94 CRM_Utils_Array::value('skipColumnHeader', $params, FALSE),
95 CRM_Utils_Array::value('import_table_name', $params),
96 CRM_Utils_Array::value('fieldSeparator', $params, ',')
97 );
98
99 $form->set('originalColHeader', CRM_Utils_Array::value('original_col_header', $result));
100
101 $table = $result['import_table_name'];
102 $importJob = new CRM_Contact_Import_ImportJob($table);
103 $form->set('importTableName', $importJob->getTableName());
104 }
105
106 /**
107 * Create a table that matches the CSV file and populate it with the file's contents
108 *
109 * @param object $db handle to the database connection
110 * @param string $file file name to load
111 * @param bool $headers whether the first row contains headers
112 * @param string $table Name of table from which data imported.
113 * @param string $fieldSeparator Character that seperates the various columns in the file
114 *
115 * @return string name of the created table
116 */
117 private static function _CsvToTable(&$db,
118 $file,
119 $headers = FALSE,
120 $table = NULL,
121 $fieldSeparator = ','
122 ) {
123 $result = array();
124 $fd = fopen($file, 'r');
125 if (!$fd) {
126 CRM_Core_Error::fatal("Could not read $file");
127 }
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';
145 $columns = array_map($strtolower, $firstrow);
146 $columns = str_replace(' ', '_', $columns);
147 $columns = preg_replace('/[^a-z_]/', '', $columns);
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
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) $column = "`$column`";
178 }
179 else {
180 $columns = array();
181 foreach ($firstrow as $i => $_) $columns[] = "col_$i";
182 }
183
184 // FIXME: we should regen this table's name if it exists rather than drop it
185 if (!$table) {
186 $table = 'civicrm_import_job_' . md5(uniqid(rand(), TRUE));
187 }
188
189 $db->query("DROP TABLE IF EXISTS $table");
190
191 $numColumns = count($columns);
192 $create = "CREATE TABLE $table (" . implode(' text, ', $columns) . " text) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci";
193 $db->query($create);
194
195 // the proper approach, but some MySQL installs do not have this enabled
196 // $load = "LOAD DATA LOCAL INFILE '$file' INTO TABLE $table FIELDS TERMINATED BY '$fieldSeparator' OPTIONALLY ENCLOSED BY '\"'";
197 // if ($headers) { $load .= ' IGNORE 1 LINES'; }
198 // $db->query($load);
199
200 // parse the CSV line by line and build one big INSERT (while MySQL-escaping the CSV contents)
201 if (!$headers) {
202 rewind($fd);
203 }
204
205 $sql = NULL;
206 $first = TRUE;
207 $count = 0;
208 while ($row = fgetcsv($fd, 0, $fieldSeparator)) {
209 // skip rows that dont match column count, else we get a sql error
210 if (count($row) != $numColumns) {
211 continue;
212 }
213
214 if (!$first) {
215 $sql .= ', ';
216 }
217
218 $first = FALSE;
219 $row = array_map('civicrm_mysql_real_escape_string', $row);
220 $sql .= "('" . implode("', '", $row) . "')";
221 $count++;
222
223 if ($count >= self::NUM_ROWS_TO_INSERT && !empty($sql)) {
224 $sql = "INSERT IGNORE INTO $table VALUES $sql";
225 $db->query($sql);
226
227 $sql = NULL;
228 $first = TRUE;
229 $count = 0;
230 }
231 }
232
233 if (!empty($sql)) {
234 $sql = "INSERT IGNORE INTO $table VALUES $sql";
235 $db->query($sql);
236 }
237
238 fclose($fd);
239
240 //get the import tmp table name.
241 $result['import_table_name'] = $table;
242
243 return $result;
244 }
245 }
246
247 /**
248 * @param $string
249 *
250 * @return string
251 */
252 function civicrm_mysql_real_escape_string($string) {
253 static $dao = NULL;
254 if (!$dao) {
255 $dao = new CRM_Core_DAO();
256 }
257 return $dao->escape($string);
258 }
259