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