INFRA-132 - Remove @static annotation
[civicrm-core.git] / CRM / Member / Import / Form / MapField.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/**
37 * This class gets the name of the file to upload
38 */
b26295b8 39class CRM_Member_Import_Form_MapField extends CRM_Import_Form_MapField {
6a488035 40
6a488035 41
6a488035 42 /**
dc195289 43 * store contactType
6a488035
TO
44 *
45 * @var int
6a488035
TO
46 */
47 static $_contactType = NULL;
48
6a488035
TO
49
50 /**
100fef9d 51 * Set variables up before form is built
6a488035
TO
52 *
53 * @return void
6a488035
TO
54 */
55 public function preProcess() {
56 $this->_mapperFields = $this->get('fields');
57 asort($this->_mapperFields);
58
59 $this->_columnCount = $this->get('columnCount');
60 $this->assign('columnCount', $this->_columnCount);
61 $this->_dataValues = $this->get('dataValues');
62 $this->assign('dataValues', $this->_dataValues);
63
de7b9b56 64 $skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
6a488035
TO
65 $this->_onDuplicate = $this->get('onDuplicate', isset($onDuplicate) ? $onDuplicate : "");
66
67 $highlightedFields = array();
68 if ($skipColumnHeader) {
69 $this->assign('skipColumnHeader', $skipColumnHeader);
70 $this->assign('rowDisplayCount', 3);
71 /* if we had a column header to skip, stash it for later */
72
73 $this->_columnHeaders = $this->_dataValues[0];
74 }
75 else {
76 $this->assign('rowDisplayCount', 2);
77 }
78
79 //CRM-2219 removing other required fields since for updation only
80 //membership id is required.
a05662ef 81 if ($this->_onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE) {
6a488035
TO
82 $remove = array('membership_contact_id', 'email', 'first_name', 'last_name', 'external_identifier');
83 foreach ($remove as $value) {
84 unset($this->_mapperFields[$value]);
85 }
86 $highlightedFieldsArray = array('membership_id', 'membership_start_date', 'membership_type_id');
87 foreach ($highlightedFieldsArray as $name) {
88 $highlightedFields[] = $name;
89 }
90 }
a05662ef 91 elseif ($this->_onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) {
6a488035 92 unset($this->_mapperFields['membership_id']);
353ffa53
TO
93 $highlightedFieldsArray = array(
94 'membership_contact_id',
95 'email',
96 'external_identifier',
97 'membership_start_date',
98 'membership_type_id'
99 );
6a488035
TO
100 foreach ($highlightedFieldsArray as $name) {
101 $highlightedFields[] = $name;
102 }
103 }
104
105 // modify field title
106 $this->_mapperFields['status_id'] = ts('Membership Status');
107 $this->_mapperFields['membership_type_id'] = ts('Membership Type');
108
109 self::$_contactType = $this->get('contactType');
110 $this->assign('highlightedFields', $highlightedFields);
111 }
112
113 /**
c490a46a 114 * Build the form object
6a488035
TO
115 *
116 * @return void
6a488035
TO
117 */
118 public function buildQuickForm() {
119 //to save the current mappings
120 if (!$this->get('savedMapping')) {
121 $saveDetailsName = ts('Save this field mapping');
122 $this->applyFilter('saveMappingName', 'trim');
123 $this->add('text', 'saveMappingName', ts('Name'));
124 $this->add('text', 'saveMappingDesc', ts('Description'));
125 }
126 else {
127 $savedMapping = $this->get('savedMapping');
128
129 list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingRelation) = CRM_Core_BAO_Mapping::getMappingFields($savedMapping);
130
353ffa53 131 $mappingName = $mappingName[1];
6a488035 132 $mappingContactType = $mappingContactType[1];
353ffa53
TO
133 $mappingLocation = CRM_Utils_Array::value('1', $mappingLocation);
134 $mappingPhoneType = CRM_Utils_Array::value('1', $mappingPhoneType);
135 $mappingRelation = CRM_Utils_Array::value('1', $mappingRelation);
6a488035
TO
136
137 //mapping is to be loaded from database
138
353ffa53
TO
139 $params = array('id' => $savedMapping);
140 $temp = array();
6a488035
TO
141 $mappingDetails = CRM_Core_BAO_Mapping::retrieve($params, $temp);
142
143 $this->assign('loadedMapping', $mappingDetails->name);
144 $this->set('loadedMapping', $savedMapping);
145
146 $getMappingName = new CRM_Core_DAO_Mapping();
147 $getMappingName->id = $savedMapping;
148 $getMappingName->mapping_type = 'Import Memberships';
149 $getMappingName->find();
150 while ($getMappingName->fetch()) {
151 $mapperName = $getMappingName->name;
152 }
153
154 $this->assign('savedName', $mapperName);
155
156 $this->add('hidden', 'mappingId', $savedMapping);
157
158 $this->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL);
159 $saveDetailsName = ts('Save as a new field mapping');
160 $this->add('text', 'saveMappingName', ts('Name'));
161 $this->add('text', 'saveMappingDesc', ts('Description'));
162 }
163
164 $this->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, array('onclick' => "showSaveDetails(this)"));
165
166 $this->addFormRule(array('CRM_Member_Import_Form_MapField', 'formRule'), $this);
167
168 //-------- end of saved mapping stuff ---------
169
353ffa53
TO
170 $defaults = array();
171 $mapperKeys = array_keys($this->_mapperFields);
172 $hasHeaders = !empty($this->_columnHeaders);
173 $headerPatterns = $this->get('headerPatterns');
174 $dataPatterns = $this->get('dataPatterns');
6a488035
TO
175 $hasLocationTypes = $this->get('fieldTypes');
176
6a488035
TO
177 /* Initialize all field usages to false */
178
179 foreach ($mapperKeys as $key) {
180 $this->_fieldUsed[$key] = FALSE;
181 }
b2b0530a 182 $this->_location_types = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
6a488035
TO
183 $sel1 = $this->_mapperFields;
184 if (!$this->get('onDuplicate')) {
185 unset($sel1['id']);
186 unset($sel1['membership_id']);
187 }
188
189 $sel2[''] = NULL;
190
191 $js = "<script type='text/javascript'>\n";
192 $formName = 'document.forms.' . $this->_name;
193
194 //used to warn for mismatch column count or mismatch mapping
195 $warning = 0;
196
197 for ($i = 0; $i < $this->_columnCount; $i++) {
198 $sel = &$this->addElement('hierselect', "mapper[$i]", ts('Mapper for Field %1', array(1 => $i)), NULL);
199 $jsSet = FALSE;
200 if ($this->get('savedMapping')) {
201 if (isset($mappingName[$i])) {
202 if ($mappingName[$i] != ts('- do not import -')) {
203
204 $mappingHeader = array_keys($this->_mapperFields, $mappingName[$i]);
205
206 //When locationType is not set
207 $js .= "{$formName}['mapper[$i][1]'].style.display = 'none';\n";
208
209 //When phoneType is not set
210 $js .= "{$formName}['mapper[$i][2]'].style.display = 'none';\n";
211
212 $js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
213
214 $defaults["mapper[$i]"] = array($mappingHeader[0]);
215 $jsSet = TRUE;
216 }
217 else {
218 $defaults["mapper[$i]"] = array();
219 }
220 if (!$jsSet) {
221 for ($k = 1; $k < 4; $k++) {
222 $js .= "{$formName}['mapper[$i][$k]'].style.display = 'none';\n";
223 }
224 }
225 }
226 else {
227 // this load section to help mapping if we ran out of saved columns when doing Load Mapping
228 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
229
230 if ($hasHeaders) {
231 $defaults["mapper[$i]"] = array($this->defaultFromHeader($this->_columnHeaders[$i], $headerPatterns));
232 }
233 else {
234 $defaults["mapper[$i]"] = array($this->defaultFromData($dataPatterns, $i));
235 }
236 }
237 //end of load mapping
238 }
239 else {
240 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
241 if ($hasHeaders) {
242 // Infer the default from the skipped headers if we have them
243 $defaults["mapper[$i]"] = array(
244 $this->defaultFromHeader($this->_columnHeaders[$i],
245 $headerPatterns
246 ),
247 // $defaultLocationType->id
248 0,
249 );
250 }
251 else {
252 // Otherwise guess the default from the form of the data
253 $defaults["mapper[$i]"] = array(
254 $this->defaultFromData($dataPatterns, $i),
255 // $defaultLocationType->id
256 0,
257 );
258 }
259 }
260 $sel->setOptions(array($sel1, $sel2, (isset($sel3)) ? $sel3 : "", (isset($sel4)) ? $sel4 : ""));
261 }
262 $js .= "</script>\n";
263 $this->assign('initHideBoxes', $js);
264
265 //set warning if mismatch in more than
266 if (isset($mappingName)) {
267 if (($this->_columnCount != count($mappingName))) {
268 $warning++;
269 }
270 }
271 if ($warning != 0 && $this->get('savedMapping')) {
272 $session = CRM_Core_Session::singleton();
273 $session->setStatus(ts('The data columns in this import file appear to be different from the saved mapping. Please verify that you have selected the correct saved mapping before continuing.'));
274 }
275 else {
276 $session = CRM_Core_Session::singleton();
277 $session->setStatus(NULL);
278 }
279
280 $this->setDefaults($defaults);
281
282 $this->addButtons(array(
283 array(
284 'type' => 'back',
f212d37d 285 'name' => ts('Previous'),
6a488035
TO
286 ),
287 array(
288 'type' => 'next',
f212d37d 289 'name' => ts('Continue'),
6a488035
TO
290 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
291 'isDefault' => TRUE,
292 ),
293 array(
294 'type' => 'cancel',
295 'name' => ts('Cancel'),
296 ),
297 )
298 );
299 }
300
301 /**
100fef9d 302 * Global validation rules for the form
6a488035 303 *
b2363ea8
TO
304 * @param array $fields
305 * Posted values of the form.
6a488035 306 *
fd31fa4c
EM
307 * @param $files
308 * @param $self
309 *
a6c01b45
CW
310 * @return array
311 * list of errors to be posted back to the form
6a488035 312 */
00be9182 313 public static function formRule($fields, $files, $self) {
6a488035
TO
314 $errors = array();
315
316 if (!array_key_exists('savedMapping', $fields)) {
317 $importKeys = array();
318 foreach ($fields['mapper'] as $mapperPart) {
319 $importKeys[] = $mapperPart[0];
320 }
321 // FIXME: should use the schema titles, not redeclare them
322 $requiredFields = array(
323 'membership_contact_id' => ts('Contact ID'),
324 'membership_type_id' => ts('Membership Type'),
325 'membership_start_date' => ts('Membership Start Date'),
326 );
327
328 $contactTypeId = $self->get('contactType');
329 $contactTypes = array(
a05662ef
CW
330 CRM_Import_Parser::CONTACT_INDIVIDUAL => 'Individual',
331 CRM_Import_Parser::CONTACT_HOUSEHOLD => 'Household',
332 CRM_Import_Parser::CONTACT_ORGANIZATION => 'Organization',
6a488035
TO
333 );
334 $params = array(
353ffa53 335 'used' => 'Unsupervised',
6a488035
TO
336 'contact_type' => $contactTypes[$contactTypeId],
337 );
338 list($ruleFields, $threshold) = CRM_Dedupe_BAO_RuleGroup::dedupeRuleFieldsWeight($params);
339 $weightSum = 0;
340 foreach ($importKeys as $key => $val) {
341 if (array_key_exists($val, $ruleFields)) {
342 $weightSum += $ruleFields[$val];
343 }
344 }
345 $fieldMessage = '';
346 foreach ($ruleFields as $field => $weight) {
347 $fieldMessage .= ' ' . $field . '(weight ' . $weight . ')';
348 }
349
350 foreach ($requiredFields as $field => $title) {
351 if (!in_array($field, $importKeys)) {
352 if ($field == 'membership_contact_id') {
353 if ((($weightSum >= $threshold || in_array('external_identifier', $importKeys)) &&
a05662ef 354 $self->_onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE
6a488035
TO
355 ) ||
356 in_array('membership_id', $importKeys)
357 ) {
358 continue;
359 }
360 else {
361 if (!isset($errors['_qf_default'])) {
362 $errors['_qf_default'] = '';
363 }
364 $errors['_qf_default'] .= ts('Missing required contact matching fields.') . " $fieldMessage " . ts('(Sum of all weights should be greater than or equal to threshold: %1).', array(
353ffa53
TO
365 1 => $threshold
366 )) . ' ' . ts('(OR Membership ID if update mode.)') . '<br />';
6a488035
TO
367 }
368 }
369 else {
370 if (!isset($errors['_qf_default'])) {
371 $errors['_qf_default'] = '';
372 }
373 $errors['_qf_default'] .= ts('Missing required field: %1', array(
353ffa53
TO
374 1 => $title
375 )) . '<br />';
6a488035
TO
376 }
377 }
378 }
379 }
380
a7488080 381 if (!empty($fields['saveMapping'])) {
6a488035
TO
382 $nameField = CRM_Utils_Array::value('saveMappingName', $fields);
383 if (empty($nameField)) {
384 $errors['saveMappingName'] = ts('Name is required to save Import Mapping');
385 }
386 else {
387 $mappingTypeId = CRM_Core_OptionGroup::getValue('mapping_type', 'Import Membership', 'name');
388
389 if (CRM_Core_BAO_Mapping::checkMapping($nameField, $mappingTypeId)) {
390 $errors['saveMappingName'] = ts('Duplicate Import Membership Mapping Name');
391 }
392 }
393 }
394
395 if (!empty($errors)) {
396 if (!empty($errors['saveMappingName'])) {
397 $_flag = 1;
398 $assignError = new CRM_Core_Page();
399 $assignError->assign('mappingDetailsError', $_flag);
400 }
401 return $errors;
402 }
403
404 return TRUE;
405 }
406
407 /**
408 * Process the mapped fields and map it into the uploaded file
409 * preview the file and extract some summary statistics
410 *
411 * @return void
6a488035
TO
412 */
413 public function postProcess() {
414 $params = $this->controller->exportValues('MapField');
415 //reload the mapfield if load mapping is pressed
416 if (!empty($params['savedMapping'])) {
417 $this->set('savedMapping', $params['savedMapping']);
418 $this->controller->resetPage($this->_name);
419 return;
420 }
421
de7b9b56
CW
422 $fileName = $this->controller->exportValue('DataSource', 'uploadFile');
423 $skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
6a488035
TO
424
425 $config = CRM_Core_Config::singleton();
426 $seperator = $config->fieldSeparator;
427
353ffa53
TO
428 $mapperKeys = array();
429 $mapper = array();
430 $mapperKeys = $this->controller->exportValue($this->_name, 'mapper');
431 $mapperKeysMain = array();
432 $mapperLocType = array();
6a488035
TO
433 $mapperPhoneType = array();
434
435 for ($i = 0; $i < $this->_columnCount; $i++) {
436 $mapper[$i] = $this->_mapperFields[$mapperKeys[$i][0]];
437 $mapperKeysMain[$i] = $mapperKeys[$i][0];
438
a7488080 439 if (!empty($mapperKeys[$i][1]) && is_numeric($mapperKeys[$i][1])) {
6a488035
TO
440 $mapperLocType[$i] = $mapperKeys[$i][1];
441 }
442 else {
443 $mapperLocType[$i] = NULL;
444 }
445
a7488080 446 if (!empty($mapperKeys[$i][2]) && (!is_numeric($mapperKeys[$i][2]))) {
6a488035
TO
447 $mapperPhoneType[$i] = $mapperKeys[$i][2];
448 }
449 else {
450 $mapperPhoneType[$i] = NULL;
451 }
452 }
453
454 $this->set('mapper', $mapper);
455
456 // store mapping Id to display it in the preview page
a7488080 457 if (!empty($params['mappingId'])) {
6a488035
TO
458 $this->set('loadMappingId', $params['mappingId']);
459 }
460 //Updating Mapping Records
a7488080 461 if (!empty($params['updateMapping'])) {
6a488035
TO
462 $mappingFields = new CRM_Core_DAO_MappingField();
463 $mappingFields->mapping_id = $params['mappingId'];
464 $mappingFields->find();
465
466 $mappingFieldsId = array();
467 while ($mappingFields->fetch()) {
468 if ($mappingFields->id) {
469 $mappingFieldsId[$mappingFields->column_number] = $mappingFields->id;
470 }
471 }
472
473 for ($i = 0; $i < $this->_columnCount; $i++) {
474 $updateMappingFields = new CRM_Core_DAO_MappingField();
475 $updateMappingFields->id = $mappingFieldsId[$i];
476 $updateMappingFields->mapping_id = $params['mappingId'];
477 $updateMappingFields->column_number = $i;
478
479 $mapperKeyParts = explode('_', $mapperKeys[$i][0], 3);
480 $id = isset($mapperKeyParts[0]) ? $mapperKeyParts[0] : NULL;
481 $first = isset($mapperKeyParts[1]) ? $mapperKeyParts[1] : NULL;
482 $second = isset($mapperKeyParts[2]) ? $mapperKeyParts[2] : NULL;
483 $updateMappingFields->name = $mapper[$i];
484 $updateMappingFields->save();
485 }
486 }
487
488 //Saving Mapping Details and Records
a7488080 489 if (!empty($params['saveMapping'])) {
6a488035
TO
490 $mappingParams = array(
491 'name' => $params['saveMappingName'],
492 'description' => $params['saveMappingDesc'],
493 'mapping_type_id' => CRM_Core_OptionGroup::getValue('mapping_type',
494 'Import Membership',
495 'name'
496 ),
497 );
498 $saveMapping = CRM_Core_BAO_Mapping::add($mappingParams);
499
500 for ($i = 0; $i < $this->_columnCount; $i++) {
501
502 $saveMappingFields = new CRM_Core_DAO_MappingField();
503 $saveMappingFields->mapping_id = $saveMapping->id;
504 $saveMappingFields->column_number = $i;
505
506 $mapperKeyParts = explode('_', $mapperKeys[$i][0], 3);
507 $id = isset($mapperKeyParts[0]) ? $mapperKeyParts[0] : NULL;
508 $first = isset($mapperKeyParts[1]) ? $mapperKeyParts[1] : NULL;
509 $second = isset($mapperKeyParts[2]) ? $mapperKeyParts[2] : NULL;
510 $saveMappingFields->name = $mapper[$i];
511 $saveMappingFields->save();
512 }
513 $this->set('savedMapping', $saveMappingFields->mapping_id);
514 }
515
516 $parser = new CRM_Member_Import_Parser_Membership($mapperKeysMain, $mapperLocType, $mapperPhoneType);
517 $parser->run($fileName, $seperator, $mapper, $skipColumnHeader,
a05662ef 518 CRM_Import_Parser::MODE_PREVIEW, $this->get('contactType')
6a488035
TO
519 );
520 // add all the necessary variables to the form
521 $parser->set($this);
522 }
6a488035 523}