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