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