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