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 * @throws \CiviCRM_API3_Exception
83 public function buildQuickForm() {
84 // To save the current mappings.
85 if (!$this->get('savedMapping')) {
86 $saveDetailsName = ts('Save this field mapping');
87 $this->applyFilter('saveMappingName', 'trim');
88 $this->add('text', 'saveMappingName', ts('Name'));
89 $this->add('text', 'saveMappingDesc', ts('Description'));
92 $savedMapping = $this->get('savedMapping');
93 // Mapping is to be loaded from database.
95 // Get an array of the name values for mapping fields associated with this mapping_id.
96 $mappingName = CRM_Core_BAO_Mapping
::getMappingFieldValues($savedMapping, 'name');
98 $this->assign('loadedMapping', $savedMapping);
99 $this->set('loadedMapping', $savedMapping);
101 $params = ['id' => $savedMapping];
103 $mappingDetails = CRM_Core_BAO_Mapping
::retrieve($params, $temp);
105 $this->assign('savedName', $mappingDetails->name
);
107 $this->add('hidden', 'mappingId', $savedMapping);
109 $this->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL);
110 $saveDetailsName = ts('Save as a new field mapping');
111 $this->add('text', 'saveMappingName', ts('Name'));
112 $this->add('text', 'saveMappingDesc', ts('Description'));
115 $this->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, ['onclick' => "showSaveDetails(this)"]);
117 $this->addFormRule(['CRM_Activity_Import_Form_MapField', 'formRule']);
119 //-------- end of saved mapping stuff ---------
122 $mapperKeys = array_keys($this->_mapperFields
);
124 $hasHeaders = !empty($this->_columnHeaders
);
125 $headerPatterns = $this->get('headerPatterns');
126 $dataPatterns = $this->get('dataPatterns');
127 $hasLocationTypes = $this->get('fieldTypes');
129 // Initialize all field usages to false.
131 foreach ($mapperKeys as $key) {
132 $this->_fieldUsed
[$key] = FALSE;
134 $this->_location_types
= CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
135 $sel1 = $this->_mapperFields
;
139 $js = "<script type='text/javascript'>\n";
140 $formName = 'document.forms.' . $this->_name
;
142 // Used to warn for mismatch column count or mismatch mapping.
145 for ($i = 0; $i < $this->_columnCount
; $i++
) {
146 $sel = &$this->addElement('hierselect', "mapper[$i]", ts('Mapper for Field %1', [1 => $i]), NULL);
148 if ($this->get('savedMapping')) {
149 if (isset($mappingName[$i])) {
150 if ($mappingName[$i] != ts('- do not import -')) {
152 $mappingHeader = array_keys($this->_mapperFields
, $mappingName[$i]);
154 if (!isset($locationId) ||
!$locationId) {
155 $js .= "{$formName}['mapper[$i][1]'].style.display = 'none';\n";
158 if (!isset($phoneType) ||
!$phoneType) {
159 $js .= "{$formName}['mapper[$i][2]'].style.display = 'none';\n";
162 $js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
163 $defaults["mapper[$i]"] = [
165 (isset($locationId)) ?
$locationId : "",
166 (isset($phoneType)) ?
$phoneType : "",
171 $defaults["mapper[$i]"] = [];
174 for ($k = 1; $k < 4; $k++
) {
175 $js .= "{$formName}['mapper[$i][$k]'].style.display = 'none';\n";
180 // this load section to help mapping if we ran out of saved columns when doing Load Mapping
181 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
184 $defaults["mapper[$i]"] = [$this->defaultFromHeader($this->_columnHeaders
[$i], $headerPatterns)];
187 $defaults["mapper[$i]"] = [$this->defaultFromData($dataPatterns, $i)];
190 // End of load mapping.
193 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
195 // Infer the default from the skipped headers if we have them
196 $defaults["mapper[$i]"] = [
197 $this->defaultFromHeader($this->_columnHeaders
[$i], $headerPatterns),
202 // Otherwise guess the default from the form of the data
203 $defaults["mapper[$i]"] = [$this->defaultFromData($dataPatterns, $i), 0];
210 (isset($sel3)) ?
$sel3 : "",
211 (isset($sel4)) ?
$sel4 : "",
214 $js .= "</script>\n";
215 $this->assign('initHideBoxes', $js);
217 // Set warning if mismatch in more than.
218 if (isset($mappingName)) {
219 if (($this->_columnCount
!= count($mappingName))) {
223 if ($warning != 0 && $this->get('savedMapping')) {
224 $session = CRM_Core_Session
::singleton();
225 $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.'));
228 $session = CRM_Core_Session
::singleton();
229 $session->setStatus(NULL);
232 $this->setDefaults($defaults);
237 'name' => ts('Previous'),
241 'name' => ts('Continue'),
242 'spacing' => ' ',
247 'name' => ts('Cancel'),
254 * Global validation rules for the form.
256 * @param array $fields
257 * Posted values of the form.
260 * list of errors to be posted back to the form
262 public static function formRule($fields) {
264 // define so we avoid notices below
265 $errors['_qf_default'] = '';
267 $fieldMessage = NULL;
268 if (!array_key_exists('savedMapping', $fields)) {
270 foreach ($fields['mapper'] as $mapperPart) {
271 $importKeys[] = $mapperPart[0];
273 // FIXME: should use the schema titles, not redeclare them
275 'target_contact_id' => ts('Contact ID'),
276 'activity_date_time' => ts('Activity Date'),
277 'activity_subject' => ts('Activity Subject'),
278 'activity_type_id' => ts('Activity Type ID'),
282 'used' => 'Unsupervised',
283 'contact_type' => 'Individual',
285 list($ruleFields, $threshold) = CRM_Dedupe_BAO_RuleGroup
::dedupeRuleFieldsWeight($params);
287 foreach ($importKeys as $key => $val) {
288 if (array_key_exists($val, $ruleFields)) {
289 $weightSum +
= $ruleFields[$val];
292 foreach ($ruleFields as $field => $weight) {
293 $fieldMessage .= ' ' . $field . '(weight ' . $weight . ')';
295 foreach ($requiredFields as $field => $title) {
296 if (!in_array($field, $importKeys)) {
297 if ($field == 'target_contact_id') {
298 if ($weightSum >= $threshold ||
in_array('external_identifier', $importKeys)) {
302 $errors['_qf_default'] .= ts('Missing required contact matching fields.')
303 . $fieldMessage . ' '
304 . ts('(Sum of all weights should be greater than or equal to threshold: %1).', [1 => $threshold])
308 elseif ($field == 'activity_type_id') {
309 if (in_array('activity_label', $importKeys)) {
313 $errors['_qf_default'] .= ts('Missing required field: Provide %1 or %2',
316 2 => 'Activity Type Label',
321 $errors['_qf_default'] .= ts('Missing required field: %1', [1 => $title]) . '<br />';
327 if (!empty($fields['saveMapping'])) {
328 $nameField = CRM_Utils_Array
::value('saveMappingName', $fields);
329 if (empty($nameField)) {
330 $errors['saveMappingName'] = ts('Name is required to save Import Mapping');
333 if (CRM_Core_BAO_Mapping
::checkMapping($nameField, CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Activity'))) {
334 $errors['saveMappingName'] = ts('Duplicate Import Mapping Name');
339 if (empty($errors['_qf_default'])) {
340 unset($errors['_qf_default']);
342 if (!empty($errors)) {
343 if (!empty($errors['saveMappingName'])) {
345 $assignError = new CRM_Core_Page();
346 $assignError->assign('mappingDetailsError', $_flag);
355 * Process the mapped fields and map it into the uploaded file.
357 * Preview the file and extract some summary statistics
359 public function postProcess() {
360 $params = $this->controller
->exportValues('MapField');
361 // Reload the mapfield if load mapping is pressed.
362 if (!empty($params['savedMapping'])) {
363 $this->set('savedMapping', $params['savedMapping']);
364 $this->controller
->resetPage($this->_name
);
368 $fileName = $this->controller
->exportValue('DataSource', 'uploadFile');
369 $seperator = $this->controller
->exportValue('DataSource', 'fieldSeparator');
370 $skipColumnHeader = $this->controller
->exportValue('DataSource', 'skipColumnHeader');
374 $mapperKeys = $this->controller
->exportValue($this->_name
, 'mapper');
375 $mapperKeysMain = [];
377 $mapperPhoneType = [];
379 for ($i = 0; $i < $this->_columnCount
; $i++
) {
380 $mapper[$i] = $this->_mapperFields
[$mapperKeys[$i][0]];
381 $mapperKeysMain[$i] = $mapperKeys[$i][0];
383 if ((CRM_Utils_Array
::value(1, $mapperKeys[$i])) && (is_numeric($mapperKeys[$i][1]))) {
384 $mapperLocType[$i] = $mapperKeys[$i][1];
387 $mapperLocType[$i] = NULL;
390 if ((CRM_Utils_Array
::value(2, $mapperKeys[$i])) && (!is_numeric($mapperKeys[$i][2]))) {
391 $mapperPhoneType[$i] = $mapperKeys[$i][2];
394 $mapperPhoneType[$i] = NULL;
398 $this->set('mapper', $mapper);
399 // store mapping Id to display it in the preview page
400 if (!empty($params['mappingId'])) {
401 $this->set('loadMappingId', $params['mappingId']);
404 // Updating Mapping Records.
405 if (!empty($params['updateMapping'])) {
407 $mappingFields = new CRM_Core_DAO_MappingField();
408 $mappingFields->mapping_id
= $params['mappingId'];
409 $mappingFields->find();
411 $mappingFieldsId = [];
412 while ($mappingFields->fetch()) {
413 if ($mappingFields->id
) {
414 $mappingFieldsId[$mappingFields->column_number
] = $mappingFields->id
;
418 for ($i = 0; $i < $this->_columnCount
; $i++
) {
419 $updateMappingFields = new CRM_Core_DAO_MappingField();
420 $updateMappingFields->id
= $mappingFieldsId[$i];
421 $updateMappingFields->mapping_id
= $params['mappingId'];
422 $updateMappingFields->column_number
= $i;
424 $updateMappingFields->name
= $mapper[$i];
425 $updateMappingFields->save();
429 // Saving Mapping Details and Records.
430 if (!empty($params['saveMapping'])) {
432 'name' => $params['saveMappingName'],
433 'description' => $params['saveMappingDesc'],
434 'mapping_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Activity'),
436 $saveMapping = CRM_Core_BAO_Mapping
::add($mappingParams);
438 for ($i = 0; $i < $this->_columnCount
; $i++
) {
439 $saveMappingFields = new CRM_Core_DAO_MappingField();
440 $saveMappingFields->mapping_id
= $saveMapping->id
;
441 $saveMappingFields->column_number
= $i;
443 $saveMappingFields->name
= $mapper[$i];
444 $saveMappingFields->save();
446 $this->set('savedMapping', $saveMappingFields->mapping_id
);
449 $parser = new CRM_Activity_Import_Parser_Activity($mapperKeysMain, $mapperLocType, $mapperPhoneType);
450 $parser->run($fileName, $seperator, $mapper, $skipColumnHeader,
451 CRM_Import_Parser
::MODE_PREVIEW
454 // add all the necessary variables to the form