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