Merge remote-tracking branch 'upstream/4.4' into 4.4-4.5-2014-10-01-19-08-00
[civicrm-core.git] / CRM / Member / Import / Parser.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
32 * $Id$
33 *
34 */
35
36
37 abstract class CRM_Member_Import_Parser extends CRM_Import_Parser {
38
39 protected $_fileName;
40
41 /**#@+
42 * @access protected
43 * @var integer
44 */
45
46 /**
47 * imported file size
48 */
49 protected $_fileSize;
50
51 /**
52 * seperator being used
53 */
54 protected $_seperator;
55
56 /**
57 * total number of lines in file
58 */
59 protected $_lineCount;
60
61 /**
62 * whether the file has a column header or not
63 *
64 * @var boolean
65 */
66 protected $_haveColumnHeader;
67
68 /**
69 * @param $fileName
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 */
80 function run($fileName,
81 $seperator = ',',
82 &$mapper,
83 $skipColumnHeader = FALSE,
84 $mode = self::MODE_PREVIEW,
85 $contactType = self::CONTACT_INDIVIDUAL,
86 $onDuplicate = self::DUPLICATE_SKIP
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
121 $this->_errors = array();
122 $this->_warnings = array();
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
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
288 * @access public
289 */
290 function setActiveFields($fieldKeys) {
291 $this->_activeFieldCount = count($fieldKeys);
292 foreach ($fieldKeys as $key) {
293 if (empty($this->_fields[$key])) {
294 $this->_activeFields[] = new CRM_Member_Import_Field('', ts('- do not import -'));
295 }
296 else {
297 $this->_activeFields[] = clone($this->_fields[$key]);
298 }
299 }
300 }
301
302 /**
303 * function to format the field values for input to the api
304 *
305 * @return array (reference ) associative array of name/value pairs
306 * @access public
307 */
308 function &getActiveFieldParams() {
309 $params = array();
310 for ($i = 0; $i < $this->_activeFieldCount; $i++) {
311 if (isset($this->_activeFields[$i]->_value)
312 && !isset($params[$this->_activeFields[$i]->_name])
313 && !isset($this->_activeFields[$i]->_related)
314 ) {
315
316 $params[$this->_activeFields[$i]->_name] = $this->_activeFields[$i]->_value;
317 }
318 }
319 return $params;
320 }
321
322 /**
323 * @param $name
324 * @param $title
325 * @param int $type
326 * @param string $headerPattern
327 * @param string $dataPattern
328 */
329 function addField($name, $title, $type = CRM_Utils_Type::T_INT, $headerPattern = '//', $dataPattern = '//') {
330 if (empty($name)) {
331 $this->_fields['doNotImport'] = new CRM_Member_Import_Field($name, $title, $type, $headerPattern, $dataPattern);
332 }
333 else {
334
335 //$tempField = CRM_Contact_BAO_Contact::importableFields('Individual', null );
336 $tempField = CRM_Contact_BAO_Contact::importableFields('All', NULL);
337 if (!array_key_exists($name, $tempField)) {
338 $this->_fields[$name] = new CRM_Member_Import_Field($name, $title, $type, $headerPattern, $dataPattern);
339 }
340 else {
341 $this->_fields[$name] = new CRM_Contact_Import_Field($name, $title, $type, $headerPattern, $dataPattern,
342 CRM_Utils_Array::value('hasLocationType', $tempField[$name])
343 );
344 }
345 }
346 }
347
348 /**
349 * Store parser values
350 *
351 * @param CRM_Core_Session $store
352 *
353 * @param int $mode
354 *
355 * @return void
356 * @access public
357 */
358 function set($store, $mode = self::MODE_SUMMARY) {
359 $store->set('fileSize', $this->_fileSize);
360 $store->set('lineCount', $this->_lineCount);
361 $store->set('seperator', $this->_seperator);
362 $store->set('fields', $this->getSelectValues());
363 $store->set('fieldTypes', $this->getSelectTypes());
364
365 $store->set('headerPatterns', $this->getHeaderPatterns());
366 $store->set('dataPatterns', $this->getDataPatterns());
367 $store->set('columnCount', $this->_activeFieldCount);
368
369 $store->set('totalRowCount', $this->_totalCount);
370 $store->set('validRowCount', $this->_validCount);
371 $store->set('invalidRowCount', $this->_invalidRowCount);
372 $store->set('conflictRowCount', $this->_conflictCount);
373
374 switch ($this->_contactType) {
375 case 'Individual':
376 $store->set('contactType', CRM_Import_Parser::CONTACT_INDIVIDUAL);
377 break;
378
379 case 'Household':
380 $store->set('contactType', CRM_Import_Parser::CONTACT_HOUSEHOLD);
381 break;
382
383 case 'Organization':
384 $store->set('contactType', CRM_Import_Parser::CONTACT_ORGANIZATION);
385 }
386
387 if ($this->_invalidRowCount) {
388 $store->set('errorsFileName', $this->_errorFileName);
389 }
390 if ($this->_conflictCount) {
391 $store->set('conflictsFileName', $this->_conflictFileName);
392 }
393 if (isset($this->_rows) && !empty($this->_rows)) {
394 $store->set('dataValues', $this->_rows);
395 }
396
397 if ($mode == self::MODE_IMPORT) {
398 $store->set('duplicateRowCount', $this->_duplicateCount);
399 if ($this->_duplicateCount) {
400 $store->set('duplicatesFileName', $this->_duplicateFileName);
401 }
402 }
403 }
404
405 /**
406 * Export data to a CSV file
407 *
408 * @param $fileName
409 * @param array $header
410 * @param data $data
411 *
412 * @internal param string $filename
413 * @return void
414 * @access public
415 */
416 static function exportCSV($fileName, $header, $data) {
417 $output = array();
418 $fd = fopen($fileName, 'w');
419
420 foreach ($header as $key => $value) {
421 $header[$key] = "\"$value\"";
422 }
423 $config = CRM_Core_Config::singleton();
424 $output[] = implode($config->fieldSeparator, $header);
425
426 foreach ($data as $datum) {
427 foreach ($datum as $key => $value) {
428 if (is_array($value)) {
429 foreach ($value[0] as $k1 => $v1) {
430 if ($k1 == 'location_type_id') {
431 continue;
432 }
433 $datum[$k1] = $v1;
434 }
435 }
436 else {
437 $datum[$key] = "\"$value\"";
438 }
439 }
440 $output[] = implode($config->fieldSeparator, $datum);
441 }
442 fwrite($fd, implode("\n", $output));
443 fclose($fd);
444 }
445
446 }
447