3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
35 * This class gets the name of the file to upload.
37 class CRM_Activity_Import_Form_MapField
extends CRM_Import_Form_MapField
{
41 * Set variables up before form is built.
43 public function preProcess() {
44 $this->_mapperFields
= $this->get('fields');
45 unset($this->_mapperFields
['id']);
46 asort($this->_mapperFields
);
48 $this->_columnCount
= $this->get('columnCount');
49 $this->assign('columnCount', $this->_columnCount
);
50 $this->_dataValues
= $this->get('dataValues');
51 $this->assign('dataValues', $this->_dataValues
);
53 $skipColumnHeader = $this->controller
->exportValue('DataSource', 'skipColumnHeader');
55 if ($skipColumnHeader) {
56 $this->assign('skipColumnHeader', $skipColumnHeader);
57 $this->assign('rowDisplayCount', 3);
58 // If we had a column header to skip, stash it for later.
60 $this->_columnHeaders
= $this->_dataValues
[0];
63 $this->assign('rowDisplayCount', 2);
65 $highlightedFields = [];
73 foreach ($requiredFields as $val) {
74 $highlightedFields[] = $val;
76 $this->assign('highlightedFields', $highlightedFields);
80 * Build the form object.
82 public function buildQuickForm() {
83 // To save the current mappings.
84 if (!$this->get('savedMapping')) {
85 $saveDetailsName = ts('Save this field mapping');
86 $this->applyFilter('saveMappingName', 'trim');
87 $this->add('text', 'saveMappingName', ts('Name'));
88 $this->add('text', 'saveMappingDesc', ts('Description'));
91 $savedMapping = $this->get('savedMapping');
92 // Mapping is to be loaded from database.
94 list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingRelation) = CRM_Core_BAO_Mapping
::getMappingFields($savedMapping);
96 // Get loaded Mapping Fields.
97 $mappingName = CRM_Utils_Array
::value('1', $mappingName);
98 $mappingContactType = CRM_Utils_Array
::value('1', $mappingContactType);
99 $mappingLocation = CRM_Utils_Array
::value('1', $mappingLocation);
100 $mappingPhoneType = CRM_Utils_Array
::value('1', $mappingPhoneType);
101 $mappingRelation = CRM_Utils_Array
::value('1', $mappingRelation);
103 $this->assign('loadedMapping', $savedMapping);
104 $this->set('loadedMapping', $savedMapping);
106 $params = ['id' => $savedMapping];
108 $mappingDetails = CRM_Core_BAO_Mapping
::retrieve($params, $temp);
110 $this->assign('savedName', $mappingDetails->name
);
112 $this->add('hidden', 'mappingId', $savedMapping);
114 $this->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL);
115 $saveDetailsName = ts('Save as a new field mapping');
116 $this->add('text', 'saveMappingName', ts('Name'));
117 $this->add('text', 'saveMappingDesc', ts('Description'));
120 $this->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, ['onclick' => "showSaveDetails(this)"]);
122 $this->addFormRule(['CRM_Activity_Import_Form_MapField', 'formRule']);
124 //-------- end of saved mapping stuff ---------
127 $mapperKeys = array_keys($this->_mapperFields
);
129 $hasHeaders = !empty($this->_columnHeaders
);
130 $headerPatterns = $this->get('headerPatterns');
131 $dataPatterns = $this->get('dataPatterns');
132 $hasLocationTypes = $this->get('fieldTypes');
134 // Initialize all field usages to false.
136 foreach ($mapperKeys as $key) {
137 $this->_fieldUsed
[$key] = FALSE;
139 $this->_location_types
= CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
140 $sel1 = $this->_mapperFields
;
144 $js = "<script type='text/javascript'>\n";
145 $formName = 'document.forms.' . $this->_name
;
147 // Used to warn for mismatch column count or mismatch mapping.
150 for ($i = 0; $i < $this->_columnCount
; $i++
) {
151 $sel = &$this->addElement('hierselect', "mapper[$i]", ts('Mapper for Field %1', [1 => $i]), NULL);
153 if ($this->get('savedMapping')) {
154 if (isset($mappingName[$i])) {
155 if ($mappingName[$i] != ts('- do not import -')) {
157 $mappingHeader = array_keys($this->_mapperFields
, $mappingName[$i]);
159 if (!isset($locationId) ||
!$locationId) {
160 $js .= "{$formName}['mapper[$i][1]'].style.display = 'none';\n";
163 if (!isset($phoneType) ||
!$phoneType) {
164 $js .= "{$formName}['mapper[$i][2]'].style.display = 'none';\n";
167 $js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
168 $defaults["mapper[$i]"] = [
170 (isset($locationId)) ?
$locationId : "",
171 (isset($phoneType)) ?
$phoneType : "",
176 $defaults["mapper[$i]"] = [];
179 for ($k = 1; $k < 4; $k++
) {
180 $js .= "{$formName}['mapper[$i][$k]'].style.display = 'none';\n";
185 // this load section to help mapping if we ran out of saved columns when doing Load Mapping
186 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
189 $defaults["mapper[$i]"] = [$this->defaultFromHeader($this->_columnHeaders
[$i], $headerPatterns)];
192 $defaults["mapper[$i]"] = [$this->defaultFromData($dataPatterns, $i)];
195 // End of load mapping.
198 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
200 // Infer the default from the skipped headers if we have them
201 $defaults["mapper[$i]"] = [
202 $this->defaultFromHeader($this->_columnHeaders
[$i], $headerPatterns),
207 // Otherwise guess the default from the form of the data
208 $defaults["mapper[$i]"] = [$this->defaultFromData($dataPatterns, $i), 0];
215 (isset($sel3)) ?
$sel3 : "",
216 (isset($sel4)) ?
$sel4 : "",
219 $js .= "</script>\n";
220 $this->assign('initHideBoxes', $js);
222 // Set warning if mismatch in more than.
223 if (isset($mappingName)) {
224 if (($this->_columnCount
!= count($mappingName))) {
228 if ($warning != 0 && $this->get('savedMapping')) {
229 $session = CRM_Core_Session
::singleton();
230 $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.'));
233 $session = CRM_Core_Session
::singleton();
234 $session->setStatus(NULL);
237 $this->setDefaults($defaults);
242 'name' => ts('Previous'),
246 'name' => ts('Continue'),
247 'spacing' => ' ',
252 'name' => ts('Cancel'),
259 * Global validation rules for the form.
261 * @param array $fields
262 * Posted values of the form.
265 * list of errors to be posted back to the form
267 public static function formRule($fields) {
269 // define so we avoid notices below
270 $errors['_qf_default'] = '';
272 $fieldMessage = NULL;
273 if (!array_key_exists('savedMapping', $fields)) {
275 foreach ($fields['mapper'] as $mapperPart) {
276 $importKeys[] = $mapperPart[0];
278 // FIXME: should use the schema titles, not redeclare them
280 'target_contact_id' => ts('Contact ID'),
281 'activity_date_time' => ts('Activity Date'),
282 'activity_subject' => ts('Activity Subject'),
283 'activity_type_id' => ts('Activity Type ID'),
287 'used' => 'Unsupervised',
288 'contact_type' => 'Individual',
290 list($ruleFields, $threshold) = CRM_Dedupe_BAO_RuleGroup
::dedupeRuleFieldsWeight($params);
292 foreach ($importKeys as $key => $val) {
293 if (array_key_exists($val, $ruleFields)) {
294 $weightSum +
= $ruleFields[$val];
297 foreach ($ruleFields as $field => $weight) {
298 $fieldMessage .= ' ' . $field . '(weight ' . $weight . ')';
300 foreach ($requiredFields as $field => $title) {
301 if (!in_array($field, $importKeys)) {
302 if ($field == 'target_contact_id') {
303 if ($weightSum >= $threshold ||
in_array('external_identifier', $importKeys)) {
307 $errors['_qf_default'] .= ts('Missing required contact matching fields.')
308 . $fieldMessage . ' '
309 . ts('(Sum of all weights should be greater than or equal to threshold: %1).', [1 => $threshold])
313 elseif ($field == 'activity_type_id') {
314 if (in_array('activity_label', $importKeys)) {
318 $errors['_qf_default'] .= ts('Missing required field: Provide %1 or %2',
321 2 => 'Activity Type Label',
326 $errors['_qf_default'] .= ts('Missing required field: %1', [1 => $title]) . '<br />';
332 if (!empty($fields['saveMapping'])) {
333 $nameField = CRM_Utils_Array
::value('saveMappingName', $fields);
334 if (empty($nameField)) {
335 $errors['saveMappingName'] = ts('Name is required to save Import Mapping');
338 if (CRM_Core_BAO_Mapping
::checkMapping($nameField, CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Activity'))) {
339 $errors['saveMappingName'] = ts('Duplicate Import Mapping Name');
344 if (empty($errors['_qf_default'])) {
345 unset($errors['_qf_default']);
347 if (!empty($errors)) {
348 if (!empty($errors['saveMappingName'])) {
350 $assignError = new CRM_Core_Page();
351 $assignError->assign('mappingDetailsError', $_flag);
360 * Process the mapped fields and map it into the uploaded file.
362 * Preview the file and extract some summary statistics
364 public function postProcess() {
365 $params = $this->controller
->exportValues('MapField');
366 // Reload the mapfield if load mapping is pressed.
367 if (!empty($params['savedMapping'])) {
368 $this->set('savedMapping', $params['savedMapping']);
369 $this->controller
->resetPage($this->_name
);
373 $fileName = $this->controller
->exportValue('DataSource', 'uploadFile');
374 $seperator = $this->controller
->exportValue('DataSource', 'fieldSeparator');
375 $skipColumnHeader = $this->controller
->exportValue('DataSource', 'skipColumnHeader');
379 $mapperKeys = $this->controller
->exportValue($this->_name
, 'mapper');
380 $mapperKeysMain = [];
382 $mapperPhoneType = [];
384 for ($i = 0; $i < $this->_columnCount
; $i++
) {
385 $mapper[$i] = $this->_mapperFields
[$mapperKeys[$i][0]];
386 $mapperKeysMain[$i] = $mapperKeys[$i][0];
388 if ((CRM_Utils_Array
::value(1, $mapperKeys[$i])) && (is_numeric($mapperKeys[$i][1]))) {
389 $mapperLocType[$i] = $mapperKeys[$i][1];
392 $mapperLocType[$i] = NULL;
395 if ((CRM_Utils_Array
::value(2, $mapperKeys[$i])) && (!is_numeric($mapperKeys[$i][2]))) {
396 $mapperPhoneType[$i] = $mapperKeys[$i][2];
399 $mapperPhoneType[$i] = NULL;
403 $this->set('mapper', $mapper);
404 // store mapping Id to display it in the preview page
405 if (!empty($params['mappingId'])) {
406 $this->set('loadMappingId', $params['mappingId']);
409 // Updating Mapping Records.
410 if (!empty($params['updateMapping'])) {
412 $mappingFields = new CRM_Core_DAO_MappingField();
413 $mappingFields->mapping_id
= $params['mappingId'];
414 $mappingFields->find();
416 $mappingFieldsId = [];
417 while ($mappingFields->fetch()) {
418 if ($mappingFields->id
) {
419 $mappingFieldsId[$mappingFields->column_number
] = $mappingFields->id
;
423 for ($i = 0; $i < $this->_columnCount
; $i++
) {
424 $updateMappingFields = new CRM_Core_DAO_MappingField();
425 $updateMappingFields->id
= $mappingFieldsId[$i];
426 $updateMappingFields->mapping_id
= $params['mappingId'];
427 $updateMappingFields->column_number
= $i;
429 $updateMappingFields->name
= $mapper[$i];
430 $updateMappingFields->save();
434 // Saving Mapping Details and Records.
435 if (!empty($params['saveMapping'])) {
437 'name' => $params['saveMappingName'],
438 'description' => $params['saveMappingDesc'],
439 'mapping_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Activity'),
441 $saveMapping = CRM_Core_BAO_Mapping
::add($mappingParams);
443 for ($i = 0; $i < $this->_columnCount
; $i++
) {
444 $saveMappingFields = new CRM_Core_DAO_MappingField();
445 $saveMappingFields->mapping_id
= $saveMapping->id
;
446 $saveMappingFields->column_number
= $i;
448 $saveMappingFields->name
= $mapper[$i];
449 $saveMappingFields->save();
451 $this->set('savedMapping', $saveMappingFields->mapping_id
);
454 $parser = new CRM_Activity_Import_Parser_Activity($mapperKeysMain, $mapperLocType, $mapperPhoneType);
455 $parser->run($fileName, $seperator, $mapper, $skipColumnHeader,
456 CRM_Import_Parser
::MODE_PREVIEW
459 // add all the necessary variables to the form