Merge pull request #10962 from eileenmcnaughton/fitems
[civicrm-core.git] / CRM / Activity / Import / Parser.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
0f03f337 6 | Copyright CiviCRM LLC (c) 2004-2017 |
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
0f03f337 31 * @copyright CiviCRM LLC (c) 2004-2017
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++;
ca2057ea
SM
174 $recordNumber = $this->_lineCount;
175 if ($this->_haveColumnHeader) {
176 $recordNumber--;
6a488035 177 }
ca2057ea
SM
178 array_unshift($values, $recordNumber);
179 $this->_errors[] = $values;
6a488035
TO
180 }
181
182 if ($returnCode & self::CONFLICT) {
183 $this->_conflictCount++;
184 $recordNumber = $this->_lineCount;
185 if ($this->_haveColumnHeader) {
186 $recordNumber--;
187 }
188 array_unshift($values, $recordNumber);
189 $this->_conflicts[] = $values;
190 }
191
192 if ($returnCode & self::DUPLICATE) {
193 if ($returnCode & self::MULTIPLE_DUPE) {
7808aae6
SB
194 // TODO: multi-dupes should be counted apart from singles
195 // on non-skip action.
6a488035
TO
196 }
197 $this->_duplicateCount++;
198 $recordNumber = $this->_lineCount;
199 if ($this->_haveColumnHeader) {
200 $recordNumber--;
201 }
202 array_unshift($values, $recordNumber);
203 $this->_duplicates[] = $values;
204 if ($onDuplicate != self::DUPLICATE_SKIP) {
205 $this->_validCount++;
206 }
207 }
208
209 // we give the derived class a way of aborting the process
210 // note that the return code could be multiple code or'ed together
211 if ($returnCode & self::STOP) {
212 break;
213 }
214
215 // if we are done processing the maxNumber of lines, break
216 if ($this->_maxLinesToProcess > 0 && $this->_validCount >= $this->_maxLinesToProcess) {
217 break;
218 }
219 }
220
221 fclose($fd);
222
6a488035
TO
223 if ($mode == self::MODE_PREVIEW || $mode == self::MODE_IMPORT) {
224 $customHeaders = $mapper;
225
226 $customfields = CRM_Core_BAO_CustomField::getFields('Activity');
227 foreach ($customHeaders as $key => $value) {
228 if ($id = CRM_Core_BAO_CustomField::getKeyID($value)) {
229 $customHeaders[$key] = $customfields[$id][0];
230 }
231 }
232 if ($this->_invalidRowCount) {
233 // removed view url for invlaid contacts
353ffa53
TO
234 $headers = array_merge(array(
235 ts('Line Number'),
6a488035
TO
236 ts('Reason'),
237 ),
238 $customHeaders
239 );
240 $this->_errorFileName = self::errorFileName(self::ERROR);
241 self::exportCSV($this->_errorFileName, $headers, $this->_errors);
242 }
243 if ($this->_conflictCount) {
353ffa53
TO
244 $headers = array_merge(array(
245 ts('Line Number'),
6a488035
TO
246 ts('Reason'),
247 ),
248 $customHeaders
249 );
250 $this->_conflictFileName = self::errorFileName(self::CONFLICT);
251 self::exportCSV($this->_conflictFileName, $headers, $this->_conflicts);
252 }
253 if ($this->_duplicateCount) {
353ffa53
TO
254 $headers = array_merge(array(
255 ts('Line Number'),
6a488035
TO
256 ts('View Activity History URL'),
257 ),
258 $customHeaders
259 );
260
261 $this->_duplicateFileName = self::errorFileName(self::DUPLICATE);
262 self::exportCSV($this->_duplicateFileName, $headers, $this->_duplicates);
263 }
264 }
6a488035
TO
265 return $this->fini();
266 }
267
6a488035 268 /**
b6c94f42 269 * Given a list of the importable field keys that the user has selected set the active fields array to this list.
6a488035 270 *
6c552737 271 * @param array $fieldKeys
6a488035 272 */
00be9182 273 public function setActiveFields($fieldKeys) {
6a488035
TO
274 $this->_activeFieldCount = count($fieldKeys);
275 foreach ($fieldKeys as $key) {
276 if (empty($this->_fields[$key])) {
277 $this->_activeFields[] = new CRM_Activity_Import_Field('', ts('- do not import -'));
278 }
279 else {
280 $this->_activeFields[] = clone($this->_fields[$key]);
281 }
282 }
283 }
284
6a488035 285 /**
fe482240 286 * Format the field values for input to the api.
6a488035 287 *
a6c01b45
CW
288 * @return array
289 * (reference ) associative array of name/value pairs
6a488035 290 */
00be9182 291 public function &getActiveFieldParams() {
6a488035
TO
292 $params = array();
293 for ($i = 0; $i < $this->_activeFieldCount; $i++) {
294 if (isset($this->_activeFields[$i]->_value)
295 && !isset($params[$this->_activeFields[$i]->_name])
296 && !isset($this->_activeFields[$i]->_related)
297 ) {
298
299 $params[$this->_activeFields[$i]->_name] = $this->_activeFields[$i]->_value;
300 }
301 }
302 return $params;
303 }
304
ffd93213 305 /**
100fef9d 306 * @param string $name
ffd93213
EM
307 * @param $title
308 * @param int $type
309 * @param string $headerPattern
310 * @param string $dataPattern
311 */
00be9182 312 public function addField($name, $title, $type = CRM_Utils_Type::T_INT, $headerPattern = '//', $dataPattern = '//') {
6a488035
TO
313 if (empty($name)) {
314 $this->_fields['doNotImport'] = new CRM_Activity_Import_Field($name, $title, $type, $headerPattern, $dataPattern);
315 }
316 else {
317
318 $tempField = CRM_Contact_BAO_Contact::importableFields('Individual', NULL);
319 if (!array_key_exists($name, $tempField)) {
320 $this->_fields[$name] = new CRM_Activity_Import_Field($name, $title, $type, $headerPattern, $dataPattern);
321 }
322 else {
719a6fec 323 $this->_fields[$name] = new CRM_Contact_Import_Field($name, $title, $type, $headerPattern, $dataPattern, CRM_Utils_Array::value('hasLocationType', $tempField[$name]));
6a488035
TO
324 }
325 }
326 }
327
6a488035 328 /**
fe482240 329 * Store parser values.
6a488035
TO
330 *
331 * @param CRM_Core_Session $store
332 *
fd31fa4c 333 * @param int $mode
6a488035 334 */
00be9182 335 public function set($store, $mode = self::MODE_SUMMARY) {
6a488035
TO
336 $store->set('fileSize', $this->_fileSize);
337 $store->set('lineCount', $this->_lineCount);
338 $store->set('seperator', $this->_seperator);
339 $store->set('fields', $this->getSelectValues());
340 $store->set('fieldTypes', $this->getSelectTypes());
341
342 $store->set('headerPatterns', $this->getHeaderPatterns());
343 $store->set('dataPatterns', $this->getDataPatterns());
344 $store->set('columnCount', $this->_activeFieldCount);
345
346 $store->set('totalRowCount', $this->_totalCount);
347 $store->set('validRowCount', $this->_validCount);
348 $store->set('invalidRowCount', $this->_invalidRowCount);
349 $store->set('conflictRowCount', $this->_conflictCount);
350
351 if ($this->_invalidRowCount) {
352 $store->set('errorsFileName', $this->_errorFileName);
353 }
354 if ($this->_conflictCount) {
355 $store->set('conflictsFileName', $this->_conflictFileName);
356 }
357 if (isset($this->_rows) && !empty($this->_rows)) {
358 $store->set('dataValues', $this->_rows);
359 }
360
361 if ($mode == self::MODE_IMPORT) {
362 $store->set('duplicateRowCount', $this->_duplicateCount);
363 if ($this->_duplicateCount) {
364 $store->set('duplicatesFileName', $this->_duplicateFileName);
365 }
366 }
6a488035
TO
367 }
368
369 /**
fe482240 370 * Export data to a CSV file.
6a488035 371 *
c490a46a 372 * @param string $fileName
6a488035 373 * @param array $header
c490a46a 374 * @param array $data
6a488035 375 */
00be9182 376 public static function exportCSV($fileName, $header, $data) {
6a488035
TO
377 $output = array();
378 $fd = fopen($fileName, 'w');
379
380 foreach ($header as $key => $value) {
381 $header[$key] = "\"$value\"";
382 }
383 $config = CRM_Core_Config::singleton();
384 $output[] = implode($config->fieldSeparator, $header);
385
386 foreach ($data as $datum) {
387 foreach ($datum as $key => $value) {
388 $datum[$key] = "\"$value\"";
389 }
390 $output[] = implode($config->fieldSeparator, $datum);
391 }
392 fwrite($fd, implode("\n", $output));
393 fclose($fd);
394 }
395
6a488035 396}