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
{
40 * Set variables up before form is built.
42 public function preProcess() {
43 $this->_mapperFields
= $this->get('fields');
44 unset($this->_mapperFields
['id']);
45 asort($this->_mapperFields
);
47 $this->_columnCount
= $this->get('columnCount');
48 $this->assign('columnCount', $this->_columnCount
);
49 $this->_dataValues
= $this->get('dataValues');
50 $this->assign('dataValues', $this->_dataValues
);
52 $skipColumnHeader = $this->controller
->exportValue('DataSource', 'skipColumnHeader');
54 if ($skipColumnHeader) {
55 $this->assign('skipColumnHeader', $skipColumnHeader);
56 $this->assign('rowDisplayCount', 3);
57 // If we had a column header to skip, stash it for later.
59 $this->_columnHeaders
= $this->_dataValues
[0];
62 $this->assign('rowDisplayCount', 2);
64 $highlightedFields = [];
72 foreach ($requiredFields as $val) {
73 $highlightedFields[] = $val;
75 $this->assign('highlightedFields', $highlightedFields);
79 * Build the form object.
81 public function buildQuickForm() {
82 // To save the current mappings.
83 if (!$this->get('savedMapping')) {
84 $saveDetailsName = ts('Save this field mapping');
85 $this->applyFilter('saveMappingName', 'trim');
86 $this->add('text', 'saveMappingName', ts('Name'));
87 $this->add('text', 'saveMappingDesc', ts('Description'));
90 $savedMapping = $this->get('savedMapping');
91 // Mapping is to be loaded from database.
93 list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingRelation) = CRM_Core_BAO_Mapping
::getMappingFields($savedMapping);
95 // Get loaded Mapping Fields.
96 $mappingName = CRM_Utils_Array
::value('1', $mappingName);
97 $mappingContactType = CRM_Utils_Array
::value('1', $mappingContactType);
98 $mappingLocation = CRM_Utils_Array
::value('1', $mappingLocation);
99 $mappingPhoneType = CRM_Utils_Array
::value('1', $mappingPhoneType);
100 $mappingRelation = CRM_Utils_Array
::value('1', $mappingRelation);
102 $this->assign('loadedMapping', $savedMapping);
103 $this->set('loadedMapping', $savedMapping);
105 $params = ['id' => $savedMapping];
107 $mappingDetails = CRM_Core_BAO_Mapping
::retrieve($params, $temp);
109 $this->assign('savedName', $mappingDetails->name
);
111 $this->add('hidden', 'mappingId', $savedMapping);
113 $this->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL);
114 $saveDetailsName = ts('Save as a new field mapping');
115 $this->add('text', 'saveMappingName', ts('Name'));
116 $this->add('text', 'saveMappingDesc', ts('Description'));
119 $this->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, ['onclick' => "showSaveDetails(this)"]);
121 $this->addFormRule(['CRM_Activity_Import_Form_MapField', 'formRule']);
123 //-------- end of saved mapping stuff ---------
126 $mapperKeys = array_keys($this->_mapperFields
);
128 $hasHeaders = !empty($this->_columnHeaders
);
129 $headerPatterns = $this->get('headerPatterns');
130 $dataPatterns = $this->get('dataPatterns');
131 $hasLocationTypes = $this->get('fieldTypes');
133 // Initialize all field usages to false.
135 foreach ($mapperKeys as $key) {
136 $this->_fieldUsed
[$key] = FALSE;
138 $this->_location_types
= CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
139 $sel1 = $this->_mapperFields
;
143 $js = "<script type='text/javascript'>\n";
144 $formName = 'document.forms.' . $this->_name
;
146 // Used to warn for mismatch column count or mismatch mapping.
149 for ($i = 0; $i < $this->_columnCount
; $i++
) {
150 $sel = &$this->addElement('hierselect', "mapper[$i]", ts('Mapper for Field %1', [1 => $i]), NULL);
152 if ($this->get('savedMapping')) {
153 if (isset($mappingName[$i])) {
154 if ($mappingName[$i] != ts('- do not import -')) {
156 $mappingHeader = array_keys($this->_mapperFields
, $mappingName[$i]);
158 if (!isset($locationId) ||
!$locationId) {
159 $js .= "{$formName}['mapper[$i][1]'].style.display = 'none';\n";
162 if (!isset($phoneType) ||
!$phoneType) {
163 $js .= "{$formName}['mapper[$i][2]'].style.display = 'none';\n";
166 $js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
167 $defaults["mapper[$i]"] = [
169 (isset($locationId)) ?
$locationId : "",
170 (isset($phoneType)) ?
$phoneType : "",
175 $defaults["mapper[$i]"] = [];
178 for ($k = 1; $k < 4; $k++
) {
179 $js .= "{$formName}['mapper[$i][$k]'].style.display = 'none';\n";
184 // this load section to help mapping if we ran out of saved columns when doing Load Mapping
185 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
188 $defaults["mapper[$i]"] = [$this->defaultFromHeader($this->_columnHeaders
[$i], $headerPatterns)];
191 $defaults["mapper[$i]"] = [$this->defaultFromData($dataPatterns, $i)];
194 // End of load mapping.
197 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
199 // Infer the default from the skipped headers if we have them
200 $defaults["mapper[$i]"] = [
201 $this->defaultFromHeader($this->_columnHeaders
[$i], $headerPatterns),
206 // Otherwise guess the default from the form of the data
207 $defaults["mapper[$i]"] = [$this->defaultFromData($dataPatterns, $i), 0];
214 (isset($sel3)) ?
$sel3 : "",
215 (isset($sel4)) ?
$sel4 : "",
218 $js .= "</script>\n";
219 $this->assign('initHideBoxes', $js);
221 // Set warning if mismatch in more than.
222 if (isset($mappingName)) {
223 if (($this->_columnCount
!= count($mappingName))) {
227 if ($warning != 0 && $this->get('savedMapping')) {
228 $session = CRM_Core_Session
::singleton();
229 $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.'));
232 $session = CRM_Core_Session
::singleton();
233 $session->setStatus(NULL);
236 $this->setDefaults($defaults);
241 'name' => ts('Previous'),
245 'name' => ts('Continue'),
246 'spacing' => ' ',
251 'name' => ts('Cancel'),
258 * Global validation rules for the form.
260 * @param array $fields
261 * Posted values of the form.
264 * list of errors to be posted back to the form
266 public static function formRule($fields) {
268 // define so we avoid notices below
269 $errors['_qf_default'] = '';
271 $fieldMessage = NULL;
272 if (!array_key_exists('savedMapping', $fields)) {
274 foreach ($fields['mapper'] as $mapperPart) {
275 $importKeys[] = $mapperPart[0];
277 // FIXME: should use the schema titles, not redeclare them
279 'target_contact_id' => ts('Contact ID'),
280 'activity_date_time' => ts('Activity Date'),
281 'activity_subject' => ts('Activity Subject'),
282 'activity_type_id' => ts('Activity Type ID'),
286 'used' => 'Unsupervised',
287 'contact_type' => 'Individual',
289 list($ruleFields, $threshold) = CRM_Dedupe_BAO_RuleGroup
::dedupeRuleFieldsWeight($params);
291 foreach ($importKeys as $key => $val) {
292 if (array_key_exists($val, $ruleFields)) {
293 $weightSum +
= $ruleFields[$val];
296 foreach ($ruleFields as $field => $weight) {
297 $fieldMessage .= ' ' . $field . '(weight ' . $weight . ')';
299 foreach ($requiredFields as $field => $title) {
300 if (!in_array($field, $importKeys)) {
301 if ($field == 'target_contact_id') {
302 if ($weightSum >= $threshold ||
in_array('external_identifier', $importKeys)) {
306 $errors['_qf_default'] .= ts('Missing required contact matching fields.')
307 . $fieldMessage . ' '
308 . ts('(Sum of all weights should be greater than or equal to threshold: %1).', [1 => $threshold])
312 elseif ($field == 'activity_type_id') {
313 if (in_array('activity_label', $importKeys)) {
317 $errors['_qf_default'] .= ts('Missing required field: Provide %1 or %2',
320 2 => 'Activity Type Label',
325 $errors['_qf_default'] .= ts('Missing required field: %1', [1 => $title]) . '<br />';
331 if (!empty($fields['saveMapping'])) {
332 $nameField = CRM_Utils_Array
::value('saveMappingName', $fields);
333 if (empty($nameField)) {
334 $errors['saveMappingName'] = ts('Name is required to save Import Mapping');
337 if (CRM_Core_BAO_Mapping
::checkMapping($nameField, CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Activity'))) {
338 $errors['saveMappingName'] = ts('Duplicate Import Mapping Name');
343 if (empty($errors['_qf_default'])) {
344 unset($errors['_qf_default']);
346 if (!empty($errors)) {
347 if (!empty($errors['saveMappingName'])) {
349 $assignError = new CRM_Core_Page();
350 $assignError->assign('mappingDetailsError', $_flag);
359 * Process the mapped fields and map it into the uploaded file.
361 * Preview the file and extract some summary statistics
363 public function postProcess() {
364 $params = $this->controller
->exportValues('MapField');
365 // Reload the mapfield if load mapping is pressed.
366 if (!empty($params['savedMapping'])) {
367 $this->set('savedMapping', $params['savedMapping']);
368 $this->controller
->resetPage($this->_name
);
372 $fileName = $this->controller
->exportValue('DataSource', 'uploadFile');
373 $seperator = $this->controller
->exportValue('DataSource', 'fieldSeparator');
374 $skipColumnHeader = $this->controller
->exportValue('DataSource', 'skipColumnHeader');
378 $mapperKeys = $this->controller
->exportValue($this->_name
, 'mapper');
379 $mapperKeysMain = [];
381 $mapperPhoneType = [];
383 for ($i = 0; $i < $this->_columnCount
; $i++
) {
384 $mapper[$i] = $this->_mapperFields
[$mapperKeys[$i][0]];
385 $mapperKeysMain[$i] = $mapperKeys[$i][0];
387 if ((CRM_Utils_Array
::value(1, $mapperKeys[$i])) && (is_numeric($mapperKeys[$i][1]))) {
388 $mapperLocType[$i] = $mapperKeys[$i][1];
391 $mapperLocType[$i] = NULL;
394 if ((CRM_Utils_Array
::value(2, $mapperKeys[$i])) && (!is_numeric($mapperKeys[$i][2]))) {
395 $mapperPhoneType[$i] = $mapperKeys[$i][2];
398 $mapperPhoneType[$i] = NULL;
402 $this->set('mapper', $mapper);
403 // store mapping Id to display it in the preview page
404 if (!empty($params['mappingId'])) {
405 $this->set('loadMappingId', $params['mappingId']);
408 // Updating Mapping Records.
409 if (!empty($params['updateMapping'])) {
411 $mappingFields = new CRM_Core_DAO_MappingField();
412 $mappingFields->mapping_id
= $params['mappingId'];
413 $mappingFields->find();
415 $mappingFieldsId = [];
416 while ($mappingFields->fetch()) {
417 if ($mappingFields->id
) {
418 $mappingFieldsId[$mappingFields->column_number
] = $mappingFields->id
;
422 for ($i = 0; $i < $this->_columnCount
; $i++
) {
423 $updateMappingFields = new CRM_Core_DAO_MappingField();
424 $updateMappingFields->id
= $mappingFieldsId[$i];
425 $updateMappingFields->mapping_id
= $params['mappingId'];
426 $updateMappingFields->column_number
= $i;
428 $updateMappingFields->name
= $mapper[$i];
429 $updateMappingFields->save();
433 // Saving Mapping Details and Records.
434 if (!empty($params['saveMapping'])) {
436 'name' => $params['saveMappingName'],
437 'description' => $params['saveMappingDesc'],
438 'mapping_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Activity'),
440 $saveMapping = CRM_Core_BAO_Mapping
::add($mappingParams);
442 for ($i = 0; $i < $this->_columnCount
; $i++
) {
443 $saveMappingFields = new CRM_Core_DAO_MappingField();
444 $saveMappingFields->mapping_id
= $saveMapping->id
;
445 $saveMappingFields->column_number
= $i;
447 $saveMappingFields->name
= $mapper[$i];
448 $saveMappingFields->save();
450 $this->set('savedMapping', $saveMappingFields->mapping_id
);
453 $parser = new CRM_Activity_Import_Parser_Activity($mapperKeysMain, $mapperLocType, $mapperPhoneType);
454 $parser->run($fileName, $seperator, $mapper, $skipColumnHeader,
455 CRM_Import_Parser
::MODE_PREVIEW
458 // add all the necessary variables to the form