Merge pull request #4627 from colemanw/docblocks
[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
ffd93213
EM
68 /**
69 * @param $fileName
70 * @param string $seperator
71 * @param $mapper
72 * @param bool $skipColumnHeader
73 * @param int $mode
74 * @param int $onDuplicate
75 *
76 * @return mixed
77 * @throws Exception
78 */
6a488035
TO
79 function run($fileName,
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
233
234 if ($mode == self::MODE_PREVIEW || $mode == self::MODE_IMPORT) {
235 $customHeaders = $mapper;
236
237 $customfields = CRM_Core_BAO_CustomField::getFields('Activity');
238 foreach ($customHeaders as $key => $value) {
239 if ($id = CRM_Core_BAO_CustomField::getKeyID($value)) {
240 $customHeaders[$key] = $customfields[$id][0];
241 }
242 }
243 if ($this->_invalidRowCount) {
244 // removed view url for invlaid contacts
245 $headers = array_merge(array(ts('Line Number'),
246 ts('Reason'),
247 ),
248 $customHeaders
249 );
250 $this->_errorFileName = self::errorFileName(self::ERROR);
251 self::exportCSV($this->_errorFileName, $headers, $this->_errors);
252 }
253 if ($this->_conflictCount) {
254 $headers = array_merge(array(ts('Line Number'),
255 ts('Reason'),
256 ),
257 $customHeaders
258 );
259 $this->_conflictFileName = self::errorFileName(self::CONFLICT);
260 self::exportCSV($this->_conflictFileName, $headers, $this->_conflicts);
261 }
262 if ($this->_duplicateCount) {
263 $headers = array_merge(array(ts('Line Number'),
264 ts('View Activity History URL'),
265 ),
266 $customHeaders
267 );
268
269 $this->_duplicateFileName = self::errorFileName(self::DUPLICATE);
270 self::exportCSV($this->_duplicateFileName, $headers, $this->_duplicates);
271 }
272 }
273 //echo "$this->_totalCount,$this->_invalidRowCount,$this->_conflictCount,$this->_duplicateCount";
274 return $this->fini();
275 }
276
6a488035
TO
277 /**
278 * Given a list of the importable field keys that the user has selected
279 * set the active fields array to this list
280 *
281 * @param array mapped array of values
282 *
283 * @return void
284 * @access public
285 */
286 function setActiveFields($fieldKeys) {
287 $this->_activeFieldCount = count($fieldKeys);
288 foreach ($fieldKeys as $key) {
289 if (empty($this->_fields[$key])) {
290 $this->_activeFields[] = new CRM_Activity_Import_Field('', ts('- do not import -'));
291 }
292 else {
293 $this->_activeFields[] = clone($this->_fields[$key]);
294 }
295 }
296 }
297
6a488035 298 /**
c490a46a 299 * format the field values for input to the api
6a488035
TO
300 *
301 * @return array (reference ) associative array of name/value pairs
302 * @access public
303 */
304 function &getActiveFieldParams() {
305 $params = array();
306 for ($i = 0; $i < $this->_activeFieldCount; $i++) {
307 if (isset($this->_activeFields[$i]->_value)
308 && !isset($params[$this->_activeFields[$i]->_name])
309 && !isset($this->_activeFields[$i]->_related)
310 ) {
311
312 $params[$this->_activeFields[$i]->_name] = $this->_activeFields[$i]->_value;
313 }
314 }
315 return $params;
316 }
317
ffd93213
EM
318 /**
319 * @param $name
320 * @param $title
321 * @param int $type
322 * @param string $headerPattern
323 * @param string $dataPattern
324 */
6a488035
TO
325 function addField($name, $title, $type = CRM_Utils_Type::T_INT, $headerPattern = '//', $dataPattern = '//') {
326 if (empty($name)) {
327 $this->_fields['doNotImport'] = new CRM_Activity_Import_Field($name, $title, $type, $headerPattern, $dataPattern);
328 }
329 else {
330
331 $tempField = CRM_Contact_BAO_Contact::importableFields('Individual', NULL);
332 if (!array_key_exists($name, $tempField)) {
333 $this->_fields[$name] = new CRM_Activity_Import_Field($name, $title, $type, $headerPattern, $dataPattern);
334 }
335 else {
719a6fec 336 $this->_fields[$name] = new CRM_Contact_Import_Field($name, $title, $type, $headerPattern, $dataPattern, CRM_Utils_Array::value('hasLocationType', $tempField[$name]));
6a488035
TO
337 }
338 }
339 }
340
6a488035
TO
341 /**
342 * Store parser values
343 *
344 * @param CRM_Core_Session $store
345 *
fd31fa4c
EM
346 * @param int $mode
347 *
6a488035
TO
348 * @return void
349 * @access public
350 */
351 function set($store, $mode = self::MODE_SUMMARY) {
352 $store->set('fileSize', $this->_fileSize);
353 $store->set('lineCount', $this->_lineCount);
354 $store->set('seperator', $this->_seperator);
355 $store->set('fields', $this->getSelectValues());
356 $store->set('fieldTypes', $this->getSelectTypes());
357
358 $store->set('headerPatterns', $this->getHeaderPatterns());
359 $store->set('dataPatterns', $this->getDataPatterns());
360 $store->set('columnCount', $this->_activeFieldCount);
361
362 $store->set('totalRowCount', $this->_totalCount);
363 $store->set('validRowCount', $this->_validCount);
364 $store->set('invalidRowCount', $this->_invalidRowCount);
365 $store->set('conflictRowCount', $this->_conflictCount);
366
367 if ($this->_invalidRowCount) {
368 $store->set('errorsFileName', $this->_errorFileName);
369 }
370 if ($this->_conflictCount) {
371 $store->set('conflictsFileName', $this->_conflictFileName);
372 }
373 if (isset($this->_rows) && !empty($this->_rows)) {
374 $store->set('dataValues', $this->_rows);
375 }
376
377 if ($mode == self::MODE_IMPORT) {
378 $store->set('duplicateRowCount', $this->_duplicateCount);
379 if ($this->_duplicateCount) {
380 $store->set('duplicatesFileName', $this->_duplicateFileName);
381 }
382 }
383 //echo "$this->_totalCount,$this->_invalidRowCount,$this->_conflictCount,$this->_duplicateCount";
384 }
385
386 /**
387 * Export data to a CSV file
388 *
c490a46a 389 * @param string $fileName
6a488035 390 * @param array $header
c490a46a 391 * @param array $data
6a488035
TO
392 *
393 * @return void
394 * @access public
395 */
396 static function exportCSV($fileName, $header, $data) {
397 $output = array();
398 $fd = fopen($fileName, 'w');
399
400 foreach ($header as $key => $value) {
401 $header[$key] = "\"$value\"";
402 }
403 $config = CRM_Core_Config::singleton();
404 $output[] = implode($config->fieldSeparator, $header);
405
406 foreach ($data as $datum) {
407 foreach ($datum as $key => $value) {
408 $datum[$key] = "\"$value\"";
409 }
410 $output[] = implode($config->fieldSeparator, $datum);
411 }
412 fwrite($fd, implode("\n", $output));
413 fclose($fd);
414 }
415
6a488035
TO
416}
417