3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * This class gets the name of the file to upload.
21 class CRM_Activity_Import_Form_MapField
extends CRM_Import_Form_MapField
{
24 * Set variables up before form is built.
26 public function preProcess() {
27 $this->_mapperFields
= $this->get('fields');
28 unset($this->_mapperFields
['id']);
29 asort($this->_mapperFields
);
31 $this->_columnCount
= $this->get('columnCount');
32 $this->assign('columnCount', $this->_columnCount
);
33 $this->_dataValues
= $this->get('dataValues');
34 $this->assign('dataValues', $this->_dataValues
);
36 $skipColumnHeader = $this->controller
->exportValue('DataSource', 'skipColumnHeader');
38 if ($skipColumnHeader) {
39 $this->assign('skipColumnHeader', $skipColumnHeader);
40 $this->assign('rowDisplayCount', 3);
41 // If we had a column header to skip, stash it for later.
43 $this->_columnHeaders
= $this->_dataValues
[0];
46 $this->assign('rowDisplayCount', 2);
48 $highlightedFields = [];
56 foreach ($requiredFields as $val) {
57 $highlightedFields[] = $val;
59 $this->assign('highlightedFields', $highlightedFields);
63 * Build the form object.
65 * @throws \CiviCRM_API3_Exception
67 public function buildQuickForm() {
68 // To save the current mappings.
69 if (!$this->get('savedMapping')) {
70 $saveDetailsName = ts('Save this field mapping');
71 $this->applyFilter('saveMappingName', 'trim');
72 $this->add('text', 'saveMappingName', ts('Name'));
73 $this->add('text', 'saveMappingDesc', ts('Description'));
76 $savedMapping = $this->get('savedMapping');
77 // Mapping is to be loaded from database.
79 // Get an array of the name values for mapping fields associated with this mapping_id.
80 $mappingName = CRM_Core_BAO_Mapping
::getMappingFieldValues($savedMapping, 'name');
82 $this->assign('loadedMapping', $savedMapping);
83 $this->set('loadedMapping', $savedMapping);
85 $params = ['id' => $savedMapping];
87 $mappingDetails = CRM_Core_BAO_Mapping
::retrieve($params, $temp);
89 $this->assign('savedName', $mappingDetails->name
);
91 $this->add('hidden', 'mappingId', $savedMapping);
93 $this->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL);
94 $saveDetailsName = ts('Save as a new field mapping');
95 $this->add('text', 'saveMappingName', ts('Name'));
96 $this->add('text', 'saveMappingDesc', ts('Description'));
99 $this->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, ['onclick' => "showSaveDetails(this)"]);
101 $this->addFormRule(['CRM_Activity_Import_Form_MapField', 'formRule']);
103 //-------- end of saved mapping stuff ---------
106 $mapperKeys = array_keys($this->_mapperFields
);
108 $hasHeaders = !empty($this->_columnHeaders
);
109 $headerPatterns = $this->get('headerPatterns');
110 $dataPatterns = $this->get('dataPatterns');
111 $hasLocationTypes = $this->get('fieldTypes');
113 // Initialize all field usages to false.
115 foreach ($mapperKeys as $key) {
116 $this->_fieldUsed
[$key] = FALSE;
118 $this->_location_types
= CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
119 $sel1 = $this->_mapperFields
;
123 $js = "<script type='text/javascript'>\n";
124 $formName = 'document.forms.' . $this->_name
;
126 // Used to warn for mismatch column count or mismatch mapping.
129 for ($i = 0; $i < $this->_columnCount
; $i++
) {
130 $sel = &$this->addElement('hierselect', "mapper[$i]", ts('Mapper for Field %1', [1 => $i]), NULL);
132 if ($this->get('savedMapping')) {
133 if (isset($mappingName[$i])) {
134 if ($mappingName[$i] != ts('- do not import -')) {
136 $mappingHeader = array_keys($this->_mapperFields
, $mappingName[$i]);
138 if (!isset($locationId) ||
!$locationId) {
139 $js .= "{$formName}['mapper[$i][1]'].style.display = 'none';\n";
142 if (!isset($phoneType) ||
!$phoneType) {
143 $js .= "{$formName}['mapper[$i][2]'].style.display = 'none';\n";
146 $js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
147 $defaults["mapper[$i]"] = [
149 (isset($locationId)) ?
$locationId : "",
150 (isset($phoneType)) ?
$phoneType : "",
155 $defaults["mapper[$i]"] = [];
158 for ($k = 1; $k < 4; $k++
) {
159 $js .= "{$formName}['mapper[$i][$k]'].style.display = 'none';\n";
164 // this load section to help mapping if we ran out of saved columns when doing Load Mapping
165 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
168 $defaults["mapper[$i]"] = [$this->defaultFromHeader($this->_columnHeaders
[$i], $headerPatterns)];
171 $defaults["mapper[$i]"] = [$this->defaultFromData($dataPatterns, $i)];
174 // End of load mapping.
177 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
179 // Infer the default from the skipped headers if we have them
180 $defaults["mapper[$i]"] = [
181 $this->defaultFromHeader($this->_columnHeaders
[$i], $headerPatterns),
186 // Otherwise guess the default from the form of the data
187 $defaults["mapper[$i]"] = [$this->defaultFromData($dataPatterns, $i), 0];
194 (isset($sel3)) ?
$sel3 : "",
195 (isset($sel4)) ?
$sel4 : "",
198 $js .= "</script>\n";
199 $this->assign('initHideBoxes', $js);
201 // Set warning if mismatch in more than.
202 if (isset($mappingName)) {
203 if (($this->_columnCount
!= count($mappingName))) {
207 if ($warning != 0 && $this->get('savedMapping')) {
208 $session = CRM_Core_Session
::singleton();
209 $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.'));
212 $session = CRM_Core_Session
::singleton();
213 $session->setStatus(NULL);
216 $this->setDefaults($defaults);
221 'name' => ts('Previous'),
225 'name' => ts('Continue'),
226 'spacing' => ' ',
231 'name' => ts('Cancel'),
238 * Global validation rules for the form.
240 * @param array $fields
241 * Posted values of the form.
244 * list of errors to be posted back to the form
246 public static function formRule($fields) {
248 // define so we avoid notices below
249 $errors['_qf_default'] = '';
251 $fieldMessage = NULL;
252 if (!array_key_exists('savedMapping', $fields)) {
254 foreach ($fields['mapper'] as $mapperPart) {
255 $importKeys[] = $mapperPart[0];
257 // FIXME: should use the schema titles, not redeclare them
259 'target_contact_id' => ts('Contact ID'),
260 'activity_date_time' => ts('Activity Date'),
261 'activity_subject' => ts('Activity Subject'),
262 'activity_type_id' => ts('Activity Type ID'),
266 'used' => 'Unsupervised',
267 'contact_type' => 'Individual',
269 list($ruleFields, $threshold) = CRM_Dedupe_BAO_RuleGroup
::dedupeRuleFieldsWeight($params);
271 foreach ($importKeys as $key => $val) {
272 if (array_key_exists($val, $ruleFields)) {
273 $weightSum +
= $ruleFields[$val];
276 foreach ($ruleFields as $field => $weight) {
277 $fieldMessage .= ' ' . $field . '(weight ' . $weight . ')';
279 foreach ($requiredFields as $field => $title) {
280 if (!in_array($field, $importKeys)) {
281 if ($field == 'target_contact_id') {
282 if ($weightSum >= $threshold ||
in_array('external_identifier', $importKeys)) {
286 $errors['_qf_default'] .= ts('Missing required contact matching fields.')
287 . $fieldMessage . ' '
288 . ts('(Sum of all weights should be greater than or equal to threshold: %1).', [1 => $threshold])
292 elseif ($field == 'activity_type_id') {
293 if (in_array('activity_label', $importKeys)) {
297 $errors['_qf_default'] .= ts('Missing required field: Provide %1 or %2',
300 2 => 'Activity Type Label',
305 $errors['_qf_default'] .= ts('Missing required field: %1', [1 => $title]) . '<br />';
311 if (!empty($fields['saveMapping'])) {
312 $nameField = $fields['saveMappingName'] ??
NULL;
313 if (empty($nameField)) {
314 $errors['saveMappingName'] = ts('Name is required to save Import Mapping');
317 if (CRM_Core_BAO_Mapping
::checkMapping($nameField, CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Activity'))) {
318 $errors['saveMappingName'] = ts('Duplicate Import Mapping Name');
323 if (empty($errors['_qf_default'])) {
324 unset($errors['_qf_default']);
326 if (!empty($errors)) {
327 if (!empty($errors['saveMappingName'])) {
329 $assignError = new CRM_Core_Page();
330 $assignError->assign('mappingDetailsError', $_flag);
339 * Process the mapped fields and map it into the uploaded file.
341 * Preview the file and extract some summary statistics
343 public function postProcess() {
344 $params = $this->controller
->exportValues('MapField');
345 // Reload the mapfield if load mapping is pressed.
346 if (!empty($params['savedMapping'])) {
347 $this->set('savedMapping', $params['savedMapping']);
348 $this->controller
->resetPage($this->_name
);
352 $fileName = $this->controller
->exportValue('DataSource', 'uploadFile');
353 $separator = $this->controller
->exportValue('DataSource', 'fieldSeparator');
354 $skipColumnHeader = $this->controller
->exportValue('DataSource', 'skipColumnHeader');
358 $mapperKeys = $this->controller
->exportValue($this->_name
, 'mapper');
359 $mapperKeysMain = [];
361 $mapperPhoneType = [];
363 for ($i = 0; $i < $this->_columnCount
; $i++
) {
364 $mapper[$i] = $this->_mapperFields
[$mapperKeys[$i][0]];
365 $mapperKeysMain[$i] = $mapperKeys[$i][0];
367 if ((CRM_Utils_Array
::value(1, $mapperKeys[$i])) && (is_numeric($mapperKeys[$i][1]))) {
368 $mapperLocType[$i] = $mapperKeys[$i][1];
371 $mapperLocType[$i] = NULL;
374 if ((CRM_Utils_Array
::value(2, $mapperKeys[$i])) && (!is_numeric($mapperKeys[$i][2]))) {
375 $mapperPhoneType[$i] = $mapperKeys[$i][2];
378 $mapperPhoneType[$i] = NULL;
382 $this->set('mapper', $mapper);
383 // store mapping Id to display it in the preview page
384 if (!empty($params['mappingId'])) {
385 $this->set('loadMappingId', $params['mappingId']);
388 // Updating Mapping Records.
389 if (!empty($params['updateMapping'])) {
391 $mappingFields = new CRM_Core_DAO_MappingField();
392 $mappingFields->mapping_id
= $params['mappingId'];
393 $mappingFields->find();
395 $mappingFieldsId = [];
396 while ($mappingFields->fetch()) {
397 if ($mappingFields->id
) {
398 $mappingFieldsId[$mappingFields->column_number
] = $mappingFields->id
;
402 for ($i = 0; $i < $this->_columnCount
; $i++
) {
403 $updateMappingFields = new CRM_Core_DAO_MappingField();
404 $updateMappingFields->id
= $mappingFieldsId[$i];
405 $updateMappingFields->mapping_id
= $params['mappingId'];
406 $updateMappingFields->column_number
= $i;
408 $updateMappingFields->name
= $mapper[$i];
409 $updateMappingFields->save();
413 // Saving Mapping Details and Records.
414 if (!empty($params['saveMapping'])) {
416 'name' => $params['saveMappingName'],
417 'description' => $params['saveMappingDesc'],
418 'mapping_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Activity'),
420 $saveMapping = CRM_Core_BAO_Mapping
::add($mappingParams);
422 for ($i = 0; $i < $this->_columnCount
; $i++
) {
423 $saveMappingFields = new CRM_Core_DAO_MappingField();
424 $saveMappingFields->mapping_id
= $saveMapping->id
;
425 $saveMappingFields->column_number
= $i;
427 $saveMappingFields->name
= $mapper[$i];
428 $saveMappingFields->save();
430 $this->set('savedMapping', $saveMappingFields->mapping_id
);
433 $parser = new CRM_Activity_Import_Parser_Activity($mapperKeysMain, $mapperLocType, $mapperPhoneType);
434 $parser->run($fileName, $separator, $mapper, $skipColumnHeader,
435 CRM_Import_Parser
::MODE_PREVIEW
438 // add all the necessary variables to the form