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