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