copyright and version fixes
[civicrm-core.git] / CRM / Activity / Import / Parser.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
06b69b18 4 | CiviCRM version 4.5 |
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 /**#@+
42 * @access protected
43 * @var integer
44 */
45
46 /**
47 * imported file size
48 */
49 protected $_fileSize;
50
51 /**
52 * seperator being used
53 */
54 protected $_seperator;
55
56 /**
57 * total number of lines in file
58 */
59 protected $_lineCount;
60
6a488035
TO
61 /**
62 * whether the file has a column header or not
63 *
64 * @var boolean
65 */
66 protected $_haveColumnHeader;
f813f78e 67
6a488035
TO
68 function run($fileName,
69 $seperator = ',',
70 &$mapper,
71 $skipColumnHeader = FALSE,
52892e8b
CW
72 $mode = self::MODE_PREVIEW,
73 $onDuplicate = self::DUPLICATE_SKIP
6a488035
TO
74 ) {
75 if (!is_array($fileName)) {
76 CRM_Core_Error::fatal();
77 }
78 $fileName = $fileName['name'];
79
80 $this->init();
81
82 $this->_haveColumnHeader = $skipColumnHeader;
83
84 $this->_seperator = $seperator;
85
86 $fd = fopen($fileName, "r");
87 if (!$fd) {
88 return FALSE;
89 }
90
91 $this->_lineCount = $this->_warningCount = 0;
92 $this->_invalidRowCount = $this->_validCount = 0;
93 $this->_totalCount = $this->_conflictCount = 0;
94
52892e8b
CW
95 $this->_errors = array();
96 $this->_warnings = array();
6a488035
TO
97 $this->_conflicts = array();
98
99 $this->_fileSize = number_format(filesize($fileName) / 1024.0, 2);
100
101 if ($mode == self::MODE_MAPFIELD) {
102 $this->_rows = array();
103 }
104 else {
105 $this->_activeFieldCount = count($this->_activeFields);
106 }
107
108 while (!feof($fd)) {
109 $this->_lineCount++;
110
111 $values = fgetcsv($fd, 8192, $seperator);
112 if (!$values) {
113 continue;
114 }
115
116 self::encloseScrub($values);
117
118 // skip column header if we're not in mapfield mode
119 if ($mode != self::MODE_MAPFIELD && $skipColumnHeader) {
120 $skipColumnHeader = FALSE;
121 continue;
122 }
123
124 /* trim whitespace around the values */
125
126 $empty = TRUE;
127 foreach ($values as $k => $v) {
128 $values[$k] = trim($v, " \t\r\n");
129 }
130
131 if (CRM_Utils_System::isNull($values)) {
132 continue;
133 }
134
135 $this->_totalCount++;
136
137 if ($mode == self::MODE_MAPFIELD) {
138 $returnCode = $this->mapField($values);
139 }
140 elseif ($mode == self::MODE_PREVIEW) {
141 $returnCode = $this->preview($values);
142 }
143 elseif ($mode == self::MODE_SUMMARY) {
144 $returnCode = $this->summary($values);
145 }
146 elseif ($mode == self::MODE_IMPORT) {
147 $returnCode = $this->import($onDuplicate, $values);
148 }
149 else {
150 $returnCode = self::ERROR;
151 }
152
153 // note that a line could be valid but still produce a warning
154 if ($returnCode & self::VALID) {
155 $this->_validCount++;
156 if ($mode == self::MODE_MAPFIELD) {
157 $this->_rows[] = $values;
158 $this->_activeFieldCount = max($this->_activeFieldCount, count($values));
159 }
160 }
161
162 if ($returnCode & self::WARNING) {
163 $this->_warningCount++;
164 if ($this->_warningCount < $this->_maxWarningCount) {
165 $this->_warningCount[] = $line;
166 }
167 }
168
169 if ($returnCode & self::ERROR) {
170 $this->_invalidRowCount++;
171 if ($this->_invalidRowCount < $this->_maxErrorCount) {
172 $recordNumber = $this->_lineCount;
173 if ($this->_haveColumnHeader) {
174 $recordNumber--;
175 }
176 array_unshift($values, $recordNumber);
177 $this->_errors[] = $values;
178 }
179 }
180
181 if ($returnCode & self::CONFLICT) {
182 $this->_conflictCount++;
183 $recordNumber = $this->_lineCount;
184 if ($this->_haveColumnHeader) {
185 $recordNumber--;
186 }
187 array_unshift($values, $recordNumber);
188 $this->_conflicts[] = $values;
189 }
190
191 if ($returnCode & self::DUPLICATE) {
192 if ($returnCode & self::MULTIPLE_DUPE) {
193 /* TODO: multi-dupes should be counted apart from singles
194 * on non-skip action */
195 }
196 $this->_duplicateCount++;
197 $recordNumber = $this->_lineCount;
198 if ($this->_haveColumnHeader) {
199 $recordNumber--;
200 }
201 array_unshift($values, $recordNumber);
202 $this->_duplicates[] = $values;
203 if ($onDuplicate != self::DUPLICATE_SKIP) {
204 $this->_validCount++;
205 }
206 }
207
208 // we give the derived class a way of aborting the process
209 // note that the return code could be multiple code or'ed together
210 if ($returnCode & self::STOP) {
211 break;
212 }
213
214 // if we are done processing the maxNumber of lines, break
215 if ($this->_maxLinesToProcess > 0 && $this->_validCount >= $this->_maxLinesToProcess) {
216 break;
217 }
218 }
219
220 fclose($fd);
221
222
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
234 $headers = array_merge(array(ts('Line Number'),
235 ts('Reason'),
236 ),
237 $customHeaders
238 );
239 $this->_errorFileName = self::errorFileName(self::ERROR);
240 self::exportCSV($this->_errorFileName, $headers, $this->_errors);
241 }
242 if ($this->_conflictCount) {
243 $headers = array_merge(array(ts('Line Number'),
244 ts('Reason'),
245 ),
246 $customHeaders
247 );
248 $this->_conflictFileName = self::errorFileName(self::CONFLICT);
249 self::exportCSV($this->_conflictFileName, $headers, $this->_conflicts);
250 }
251 if ($this->_duplicateCount) {
252 $headers = array_merge(array(ts('Line Number'),
253 ts('View Activity History URL'),
254 ),
255 $customHeaders
256 );
257
258 $this->_duplicateFileName = self::errorFileName(self::DUPLICATE);
259 self::exportCSV($this->_duplicateFileName, $headers, $this->_duplicates);
260 }
261 }
262 //echo "$this->_totalCount,$this->_invalidRowCount,$this->_conflictCount,$this->_duplicateCount";
263 return $this->fini();
264 }
265
6a488035
TO
266 /**
267 * Given a list of the importable field keys that the user has selected
268 * set the active fields array to this list
269 *
270 * @param array mapped array of values
271 *
272 * @return void
273 * @access public
274 */
275 function setActiveFields($fieldKeys) {
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
TO
287 /**
288 * function to format the field values for input to the api
289 *
290 * @return array (reference ) associative array of name/value pairs
291 * @access public
292 */
293 function &getActiveFieldParams() {
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
6a488035
TO
307 function addField($name, $title, $type = CRM_Utils_Type::T_INT, $headerPattern = '//', $dataPattern = '//') {
308 if (empty($name)) {
309 $this->_fields['doNotImport'] = new CRM_Activity_Import_Field($name, $title, $type, $headerPattern, $dataPattern);
310 }
311 else {
312
313 $tempField = CRM_Contact_BAO_Contact::importableFields('Individual', NULL);
314 if (!array_key_exists($name, $tempField)) {
315 $this->_fields[$name] = new CRM_Activity_Import_Field($name, $title, $type, $headerPattern, $dataPattern);
316 }
317 else {
719a6fec 318 $this->_fields[$name] = new CRM_Contact_Import_Field($name, $title, $type, $headerPattern, $dataPattern, CRM_Utils_Array::value('hasLocationType', $tempField[$name]));
6a488035
TO
319 }
320 }
321 }
322
6a488035
TO
323 /**
324 * Store parser values
325 *
326 * @param CRM_Core_Session $store
327 *
328 * @return void
329 * @access public
330 */
331 function set($store, $mode = self::MODE_SUMMARY) {
332 $store->set('fileSize', $this->_fileSize);
333 $store->set('lineCount', $this->_lineCount);
334 $store->set('seperator', $this->_seperator);
335 $store->set('fields', $this->getSelectValues());
336 $store->set('fieldTypes', $this->getSelectTypes());
337
338 $store->set('headerPatterns', $this->getHeaderPatterns());
339 $store->set('dataPatterns', $this->getDataPatterns());
340 $store->set('columnCount', $this->_activeFieldCount);
341
342 $store->set('totalRowCount', $this->_totalCount);
343 $store->set('validRowCount', $this->_validCount);
344 $store->set('invalidRowCount', $this->_invalidRowCount);
345 $store->set('conflictRowCount', $this->_conflictCount);
346
347 if ($this->_invalidRowCount) {
348 $store->set('errorsFileName', $this->_errorFileName);
349 }
350 if ($this->_conflictCount) {
351 $store->set('conflictsFileName', $this->_conflictFileName);
352 }
353 if (isset($this->_rows) && !empty($this->_rows)) {
354 $store->set('dataValues', $this->_rows);
355 }
356
357 if ($mode == self::MODE_IMPORT) {
358 $store->set('duplicateRowCount', $this->_duplicateCount);
359 if ($this->_duplicateCount) {
360 $store->set('duplicatesFileName', $this->_duplicateFileName);
361 }
362 }
363 //echo "$this->_totalCount,$this->_invalidRowCount,$this->_conflictCount,$this->_duplicateCount";
364 }
365
366 /**
367 * Export data to a CSV file
368 *
369 * @param string $filename
370 * @param array $header
371 * @param data $data
372 *
373 * @return void
374 * @access public
375 */
376 static function exportCSV($fileName, $header, $data) {
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
TO
396}
397