Update copyright date for 2020
[civicrm-core.git] / CRM / Custom / Import / Parser.php
CommitLineData
9ff5f6c0
N
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
9ff5f6c0 5 +--------------------------------------------------------------------+
f299f7db 6 | Copyright CiviCRM LLC (c) 2004-2020 |
9ff5f6c0
N
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
9ff5f6c0
N
27
28/**
29 *
30 * @package CRM
f299f7db 31 * @copyright CiviCRM LLC (c) 2004-2020
9ff5f6c0
N
32 * $Id$
33 *
34 */
9ff5f6c0
N
35abstract class CRM_Custom_Import_Parser extends CRM_Contact_Import_Parser {
36
37 protected $_fileName;
38
518fa0ee 39 /**
9f266042 40 * Imported file size.
41 *
518fa0ee 42 * @var int
9ff5f6c0
N
43 */
44 protected $_fileSize;
45
46 /**
100fef9d 47 * Separator being used
518fa0ee 48 * @var string
9ff5f6c0
N
49 */
50 protected $_separator;
51
52 /**
100fef9d 53 * Total number of lines in file
518fa0ee 54 * @var int
9ff5f6c0
N
55 */
56 protected $_lineCount;
57
58 /**
100fef9d 59 * Whether the file has a column header or not
9ff5f6c0 60 *
d51c6add 61 * @var bool
9ff5f6c0
N
62 */
63 protected $_haveColumnHeader;
64
e0ef6999 65 /**
100fef9d 66 * @param string $fileName
e0ef6999
EM
67 * @param string $separator
68 * @param int $mapper
69 * @param bool $skipColumnHeader
70 * @param int|string $mode
71 * @param int|string $contactType
72 * @param int $onDuplicate
73 *
74 * @return mixed
75 * @throws Exception
76 */
389bcebf 77 public function run(
40b55be5 78 $fileName,
9ff5f6c0
N
79 $separator = ',',
80 &$mapper,
81 $skipColumnHeader = FALSE,
82 $mode = self::MODE_PREVIEW,
83 $contactType = self::CONTACT_INDIVIDUAL,
84 $onDuplicate = self::DUPLICATE_SKIP
85 ) {
86 if (!is_array($fileName)) {
87 CRM_Core_Error::fatal();
88 }
89 $fileName = $fileName['name'];
90
91 switch ($contactType) {
92 case CRM_Import_Parser::CONTACT_INDIVIDUAL:
93 $this->_contactType = 'Individual';
94 break;
95
96 case CRM_Import_Parser::CONTACT_HOUSEHOLD:
97 $this->_contactType = 'Household';
98 break;
99
100 case CRM_Import_Parser::CONTACT_ORGANIZATION:
101 $this->_contactType = 'Organization';
102 }
103 $this->init();
104
105 $this->_haveColumnHeader = $skipColumnHeader;
106
107 $this->_separator = $separator;
108
109 $fd = fopen($fileName, "r");
110 if (!$fd) {
111 return FALSE;
112 }
113
114 $this->_lineCount = $this->_warningCount = 0;
115 $this->_invalidRowCount = $this->_validCount = 0;
116 $this->_totalCount = $this->_conflictCount = 0;
117
be2fb01f
CW
118 $this->_errors = [];
119 $this->_warnings = [];
120 $this->_conflicts = [];
9ff5f6c0
N
121
122 $this->_fileSize = number_format(filesize($fileName) / 1024.0, 2);
123
124 if ($mode == self::MODE_MAPFIELD) {
be2fb01f 125 $this->_rows = [];
9ff5f6c0
N
126 }
127 else {
128 $this->_activeFieldCount = count($this->_activeFields);
129 }
130
131 while (!feof($fd)) {
132 $this->_lineCount++;
133
134 $values = fgetcsv($fd, 8192, $separator);
135 if (!$values) {
136 continue;
137 }
138
139 self::encloseScrub($values);
140
141 // skip column header if we're not in mapfield mode
142 if ($mode != self::MODE_MAPFIELD && $skipColumnHeader) {
143 $skipColumnHeader = FALSE;
144 continue;
145 }
146
147 /* trim whitespace around the values */
148
149 $empty = TRUE;
150 foreach ($values as $k => $v) {
151 $values[$k] = trim($v, " \t\r\n");
152 }
153
154 if (CRM_Utils_System::isNull($values)) {
155 continue;
156 }
157
158 $this->_totalCount++;
159
160 if ($mode == self::MODE_MAPFIELD) {
161 $returnCode = $this->mapField($values);
162 }
163 elseif ($mode == self::MODE_PREVIEW) {
164 $returnCode = $this->preview($values);
165 }
166 elseif ($mode == self::MODE_SUMMARY) {
167 $returnCode = $this->summary($values);
168 }
169 elseif ($mode == self::MODE_IMPORT) {
170 $returnCode = $this->import($onDuplicate, $values);
171 }
172 else {
173 $returnCode = self::ERROR;
174 }
175
176 // note that a line could be valid but still produce a warning
177 if ($returnCode & self::VALID) {
178 $this->_validCount++;
179 if ($mode == self::MODE_MAPFIELD) {
180 $this->_rows[] = $values;
181 $this->_activeFieldCount = max($this->_activeFieldCount, count($values));
182 }
183 }
184
185 if ($returnCode & self::WARNING) {
186 $this->_warningCount++;
187 if ($this->_warningCount < $this->_maxWarningCount) {
188 $this->_warningCount[] = $line;
189 }
190 }
191
192 if ($returnCode & self::ERROR) {
193 $this->_invalidRowCount++;
ca2057ea
SM
194 $recordNumber = $this->_lineCount;
195 if ($this->_haveColumnHeader) {
196 $recordNumber--;
9ff5f6c0 197 }
ca2057ea
SM
198 array_unshift($values, $recordNumber);
199 $this->_errors[] = $values;
9ff5f6c0
N
200 }
201
202 if ($returnCode & self::CONFLICT) {
203 $this->_conflictCount++;
204 $recordNumber = $this->_lineCount;
205 if ($this->_haveColumnHeader) {
206 $recordNumber--;
207 }
208 array_unshift($values, $recordNumber);
209 $this->_conflicts[] = $values;
210 }
211
212 if ($returnCode & self::DUPLICATE) {
213 if ($returnCode & self::MULTIPLE_DUPE) {
214 /* TODO: multi-dupes should be counted apart from singles
e70a7fc0 215 * on non-skip action */
9ff5f6c0
N
216 }
217 $this->_duplicateCount++;
218 $recordNumber = $this->_lineCount;
219 if ($this->_haveColumnHeader) {
220 $recordNumber--;
221 }
222 array_unshift($values, $recordNumber);
223 $this->_duplicates[] = $values;
224 if ($onDuplicate != self::DUPLICATE_SKIP) {
225 $this->_validCount++;
226 }
227 }
228
229 // we give the derived class a way of aborting the process
230 // note that the return code could be multiple code or'ed together
231 if ($returnCode & self::STOP) {
232 break;
233 }
234
235 // if we are done processing the maxNumber of lines, break
236 if ($this->_maxLinesToProcess > 0 && $this->_validCount >= $this->_maxLinesToProcess) {
237 break;
238 }
239 }
240
241 fclose($fd);
242
9ff5f6c0
N
243 if ($mode == self::MODE_PREVIEW || $mode == self::MODE_IMPORT) {
244 $customHeaders = $mapper;
245
246 $customfields = CRM_Core_BAO_CustomField::getFields('Activity');
247 foreach ($customHeaders as $key => $value) {
248 if ($id = CRM_Core_BAO_CustomField::getKeyID($value)) {
249 $customHeaders[$key] = $customfields[$id][0];
250 }
251 }
252 if ($this->_invalidRowCount) {
253 // removed view url for invlaid contacts
be2fb01f 254 $headers = array_merge([
518fa0ee
SL
255 ts('Line Number'),
256 ts('Reason'),
257 ], $customHeaders);
9ff5f6c0
N
258 $this->_errorFileName = self::errorFileName(self::ERROR);
259 self::exportCSV($this->_errorFileName, $headers, $this->_errors);
260 }
261 if ($this->_conflictCount) {
be2fb01f 262 $headers = array_merge([
518fa0ee
SL
263 ts('Line Number'),
264 ts('Reason'),
265 ], $customHeaders);
9ff5f6c0
N
266 $this->_conflictFileName = self::errorFileName(self::CONFLICT);
267 self::exportCSV($this->_conflictFileName, $headers, $this->_conflicts);
268 }
269 if ($this->_duplicateCount) {
be2fb01f 270 $headers = array_merge([
518fa0ee
SL
271 ts('Line Number'),
272 ts('View Activity History URL'),
273 ], $customHeaders);
9ff5f6c0
N
274
275 $this->_duplicateFileName = self::errorFileName(self::DUPLICATE);
276 self::exportCSV($this->_duplicateFileName, $headers, $this->_duplicates);
277 }
278 }
279 return $this->fini();
280 }
281
282 /**
283 * Given a list of the importable field keys that the user has selected
284 * set the active fields array to this list
285 *
389bcebf 286 * @param array $fieldKeys mapped array of values
9ff5f6c0
N
287 *
288 * @return void
9ff5f6c0 289 */
00be9182 290 public function setActiveFields($fieldKeys) {
9ff5f6c0
N
291 $this->_activeFieldCount = count($fieldKeys);
292 foreach ($fieldKeys as $key) {
293 if (empty($this->_fields[$key])) {
294 $this->_activeFields[] = new CRM_Custom_Import_Field('', ts('- do not import -'));
295 }
296 else {
297 $this->_activeFields[] = clone($this->_fields[$key]);
298 }
299 }
300 }
301
302 /**
fe482240 303 * Format the field values for input to the api.
9ff5f6c0 304 *
a6c01b45
CW
305 * @return array
306 * (reference ) associative array of name/value pairs
9ff5f6c0 307 */
00be9182 308 public function &getActiveFieldParams() {
be2fb01f 309 $params = [];
9ff5f6c0
N
310 for ($i = 0; $i < $this->_activeFieldCount; $i++) {
311 if (isset($this->_activeFields[$i]->_value)
312 && !isset($params[$this->_activeFields[$i]->_name])
313 && !isset($this->_activeFields[$i]->_related)
314 ) {
315 $params[$this->_activeFields[$i]->_name] = $this->_activeFields[$i]->_value;
316 }
317 }
318 return $params;
319 }
320
321 /**
fe482240 322 * Store parser values.
9ff5f6c0
N
323 *
324 * @param CRM_Core_Session $store
325 *
da6b46f4
EM
326 * @param int $mode
327 *
9ff5f6c0 328 * @return void
9ff5f6c0 329 */
00be9182 330 public function set($store, $mode = self::MODE_SUMMARY) {
9ff5f6c0
N
331 $store->set('fileSize', $this->_fileSize);
332 $store->set('lineCount', $this->_lineCount);
333 $store->set('seperator', $this->_separator);
334 $store->set('fields', $this->getSelectValues());
335 $store->set('fieldTypes', $this->getSelectTypes());
336
337 $store->set('headerPatterns', $this->getHeaderPatterns());
338 $store->set('dataPatterns', $this->getDataPatterns());
339 $store->set('columnCount', $this->_activeFieldCount);
340 $store->set('_entity', $this->_entity);
341 $store->set('totalRowCount', $this->_totalCount);
342 $store->set('validRowCount', $this->_validCount);
343 $store->set('invalidRowCount', $this->_invalidRowCount);
344 $store->set('conflictRowCount', $this->_conflictCount);
345
346 switch ($this->_contactType) {
347 case 'Individual':
348 $store->set('contactType', CRM_Import_Parser::CONTACT_INDIVIDUAL);
349 break;
350
351 case 'Household':
352 $store->set('contactType', CRM_Import_Parser::CONTACT_HOUSEHOLD);
353 break;
354
355 case 'Organization':
356 $store->set('contactType', CRM_Import_Parser::CONTACT_ORGANIZATION);
357 }
358
359 if ($this->_invalidRowCount) {
360 $store->set('errorsFileName', $this->_errorFileName);
361 }
362 if ($this->_conflictCount) {
363 $store->set('conflictsFileName', $this->_conflictFileName);
364 }
365 if (isset($this->_rows) && !empty($this->_rows)) {
366 $store->set('dataValues', $this->_rows);
367 }
368
369 if ($mode == self::MODE_IMPORT) {
370 $store->set('duplicateRowCount', $this->_duplicateCount);
371 if ($this->_duplicateCount) {
372 $store->set('duplicatesFileName', $this->_duplicateFileName);
373 }
374 }
375 }
96025800 376
9ff5f6c0 377}