Merge pull request #15365 from samuelsov/userdashboard
[civicrm-core.git] / CRM / Activity / Import / Form / MapField.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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
31 * @copyright CiviCRM LLC (c) 2004-2019
32 */
33
34 /**
35 * This class gets the name of the file to upload.
36 */
37 class CRM_Activity_Import_Form_MapField extends CRM_Import_Form_MapField {
38
39 /**
40 * Set variables up before form is built.
41 */
42 public function preProcess() {
43 $this->_mapperFields = $this->get('fields');
44 unset($this->_mapperFields['id']);
45 asort($this->_mapperFields);
46
47 $this->_columnCount = $this->get('columnCount');
48 $this->assign('columnCount', $this->_columnCount);
49 $this->_dataValues = $this->get('dataValues');
50 $this->assign('dataValues', $this->_dataValues);
51
52 $skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
53
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.
58
59 $this->_columnHeaders = $this->_dataValues[0];
60 }
61 else {
62 $this->assign('rowDisplayCount', 2);
63 }
64 $highlightedFields = [];
65 $requiredFields = [
66 'activity_date_time',
67 'activity_type_id',
68 'activity_label',
69 'target_contact_id',
70 'activity_subject',
71 ];
72 foreach ($requiredFields as $val) {
73 $highlightedFields[] = $val;
74 }
75 $this->assign('highlightedFields', $highlightedFields);
76 }
77
78 /**
79 * Build the form object.
80 *
81 * @throws \CiviCRM_API3_Exception
82 */
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'));
90 }
91 else {
92 $savedMapping = $this->get('savedMapping');
93 // Mapping is to be loaded from database.
94
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');
97
98 $this->assign('loadedMapping', $savedMapping);
99 $this->set('loadedMapping', $savedMapping);
100
101 $params = ['id' => $savedMapping];
102 $temp = [];
103 $mappingDetails = CRM_Core_BAO_Mapping::retrieve($params, $temp);
104
105 $this->assign('savedName', $mappingDetails->name);
106
107 $this->add('hidden', 'mappingId', $savedMapping);
108
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'));
113 }
114
115 $this->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, ['onclick' => "showSaveDetails(this)"]);
116
117 $this->addFormRule(['CRM_Activity_Import_Form_MapField', 'formRule']);
118
119 //-------- end of saved mapping stuff ---------
120
121 $defaults = [];
122 $mapperKeys = array_keys($this->_mapperFields);
123
124 $hasHeaders = !empty($this->_columnHeaders);
125 $headerPatterns = $this->get('headerPatterns');
126 $dataPatterns = $this->get('dataPatterns');
127 $hasLocationTypes = $this->get('fieldTypes');
128
129 // Initialize all field usages to false.
130
131 foreach ($mapperKeys as $key) {
132 $this->_fieldUsed[$key] = FALSE;
133 }
134 $this->_location_types = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
135 $sel1 = $this->_mapperFields;
136
137 $sel2[''] = NULL;
138
139 $js = "<script type='text/javascript'>\n";
140 $formName = 'document.forms.' . $this->_name;
141
142 // Used to warn for mismatch column count or mismatch mapping.
143 $warning = 0;
144
145 for ($i = 0; $i < $this->_columnCount; $i++) {
146 $sel = &$this->addElement('hierselect', "mapper[$i]", ts('Mapper for Field %1', [1 => $i]), NULL);
147 $jsSet = FALSE;
148 if ($this->get('savedMapping')) {
149 if (isset($mappingName[$i])) {
150 if ($mappingName[$i] != ts('- do not import -')) {
151
152 $mappingHeader = array_keys($this->_mapperFields, $mappingName[$i]);
153
154 if (!isset($locationId) || !$locationId) {
155 $js .= "{$formName}['mapper[$i][1]'].style.display = 'none';\n";
156 }
157
158 if (!isset($phoneType) || !$phoneType) {
159 $js .= "{$formName}['mapper[$i][2]'].style.display = 'none';\n";
160 }
161
162 $js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
163 $defaults["mapper[$i]"] = [
164 $mappingHeader[0],
165 (isset($locationId)) ? $locationId : "",
166 (isset($phoneType)) ? $phoneType : "",
167 ];
168 $jsSet = TRUE;
169 }
170 else {
171 $defaults["mapper[$i]"] = [];
172 }
173 if (!$jsSet) {
174 for ($k = 1; $k < 4; $k++) {
175 $js .= "{$formName}['mapper[$i][$k]'].style.display = 'none';\n";
176 }
177 }
178 }
179 else {
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";
182
183 if ($hasHeaders) {
184 $defaults["mapper[$i]"] = [$this->defaultFromHeader($this->_columnHeaders[$i], $headerPatterns)];
185 }
186 else {
187 $defaults["mapper[$i]"] = [$this->defaultFromData($dataPatterns, $i)];
188 }
189 }
190 // End of load mapping.
191 }
192 else {
193 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
194 if ($hasHeaders) {
195 // Infer the default from the skipped headers if we have them
196 $defaults["mapper[$i]"] = [
197 $this->defaultFromHeader($this->_columnHeaders[$i], $headerPatterns),
198 0,
199 ];
200 }
201 else {
202 // Otherwise guess the default from the form of the data
203 $defaults["mapper[$i]"] = [$this->defaultFromData($dataPatterns, $i), 0];
204 }
205 }
206
207 $sel->setOptions([
208 $sel1,
209 $sel2,
210 (isset($sel3)) ? $sel3 : "",
211 (isset($sel4)) ? $sel4 : "",
212 ]);
213 }
214 $js .= "</script>\n";
215 $this->assign('initHideBoxes', $js);
216
217 // Set warning if mismatch in more than.
218 if (isset($mappingName)) {
219 if (($this->_columnCount != count($mappingName))) {
220 $warning++;
221 }
222 }
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.'));
226 }
227 else {
228 $session = CRM_Core_Session::singleton();
229 $session->setStatus(NULL);
230 }
231
232 $this->setDefaults($defaults);
233
234 $this->addButtons([
235 [
236 'type' => 'back',
237 'name' => ts('Previous'),
238 ],
239 [
240 'type' => 'next',
241 'name' => ts('Continue'),
242 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
243 'isDefault' => TRUE,
244 ],
245 [
246 'type' => 'cancel',
247 'name' => ts('Cancel'),
248 ],
249 ]
250 );
251 }
252
253 /**
254 * Global validation rules for the form.
255 *
256 * @param array $fields
257 * Posted values of the form.
258 *
259 * @return array
260 * list of errors to be posted back to the form
261 */
262 public static function formRule($fields) {
263 $errors = [];
264 // define so we avoid notices below
265 $errors['_qf_default'] = '';
266
267 $fieldMessage = NULL;
268 if (!array_key_exists('savedMapping', $fields)) {
269 $importKeys = [];
270 foreach ($fields['mapper'] as $mapperPart) {
271 $importKeys[] = $mapperPart[0];
272 }
273 // FIXME: should use the schema titles, not redeclare them
274 $requiredFields = [
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'),
279 ];
280
281 $params = [
282 'used' => 'Unsupervised',
283 'contact_type' => 'Individual',
284 ];
285 list($ruleFields, $threshold) = CRM_Dedupe_BAO_RuleGroup::dedupeRuleFieldsWeight($params);
286 $weightSum = 0;
287 foreach ($importKeys as $key => $val) {
288 if (array_key_exists($val, $ruleFields)) {
289 $weightSum += $ruleFields[$val];
290 }
291 }
292 foreach ($ruleFields as $field => $weight) {
293 $fieldMessage .= ' ' . $field . '(weight ' . $weight . ')';
294 }
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)) {
299 continue;
300 }
301 else {
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])
305 . '<br />';
306 }
307 }
308 elseif ($field == 'activity_type_id') {
309 if (in_array('activity_label', $importKeys)) {
310 continue;
311 }
312 else {
313 $errors['_qf_default'] .= ts('Missing required field: Provide %1 or %2',
314 [
315 1 => $title,
316 2 => 'Activity Type Label',
317 ]) . '<br />';
318 }
319 }
320 else {
321 $errors['_qf_default'] .= ts('Missing required field: %1', [1 => $title]) . '<br />';
322 }
323 }
324 }
325 }
326
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');
331 }
332 else {
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');
335 }
336 }
337 }
338
339 if (empty($errors['_qf_default'])) {
340 unset($errors['_qf_default']);
341 }
342 if (!empty($errors)) {
343 if (!empty($errors['saveMappingName'])) {
344 $_flag = 1;
345 $assignError = new CRM_Core_Page();
346 $assignError->assign('mappingDetailsError', $_flag);
347 }
348 return $errors;
349 }
350
351 return TRUE;
352 }
353
354 /**
355 * Process the mapped fields and map it into the uploaded file.
356 *
357 * Preview the file and extract some summary statistics
358 */
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);
365 return;
366 }
367
368 $fileName = $this->controller->exportValue('DataSource', 'uploadFile');
369 $seperator = $this->controller->exportValue('DataSource', 'fieldSeparator');
370 $skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
371
372 $mapperKeys = [];
373 $mapper = [];
374 $mapperKeys = $this->controller->exportValue($this->_name, 'mapper');
375 $mapperKeysMain = [];
376 $mapperLocType = [];
377 $mapperPhoneType = [];
378
379 for ($i = 0; $i < $this->_columnCount; $i++) {
380 $mapper[$i] = $this->_mapperFields[$mapperKeys[$i][0]];
381 $mapperKeysMain[$i] = $mapperKeys[$i][0];
382
383 if ((CRM_Utils_Array::value(1, $mapperKeys[$i])) && (is_numeric($mapperKeys[$i][1]))) {
384 $mapperLocType[$i] = $mapperKeys[$i][1];
385 }
386 else {
387 $mapperLocType[$i] = NULL;
388 }
389
390 if ((CRM_Utils_Array::value(2, $mapperKeys[$i])) && (!is_numeric($mapperKeys[$i][2]))) {
391 $mapperPhoneType[$i] = $mapperKeys[$i][2];
392 }
393 else {
394 $mapperPhoneType[$i] = NULL;
395 }
396 }
397
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']);
402 }
403
404 // Updating Mapping Records.
405 if (!empty($params['updateMapping'])) {
406
407 $mappingFields = new CRM_Core_DAO_MappingField();
408 $mappingFields->mapping_id = $params['mappingId'];
409 $mappingFields->find();
410
411 $mappingFieldsId = [];
412 while ($mappingFields->fetch()) {
413 if ($mappingFields->id) {
414 $mappingFieldsId[$mappingFields->column_number] = $mappingFields->id;
415 }
416 }
417
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;
423
424 $updateMappingFields->name = $mapper[$i];
425 $updateMappingFields->save();
426 }
427 }
428
429 // Saving Mapping Details and Records.
430 if (!empty($params['saveMapping'])) {
431 $mappingParams = [
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'),
435 ];
436 $saveMapping = CRM_Core_BAO_Mapping::add($mappingParams);
437
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;
442
443 $saveMappingFields->name = $mapper[$i];
444 $saveMappingFields->save();
445 }
446 $this->set('savedMapping', $saveMappingFields->mapping_id);
447 }
448
449 $parser = new CRM_Activity_Import_Parser_Activity($mapperKeysMain, $mapperLocType, $mapperPhoneType);
450 $parser->run($fileName, $seperator, $mapper, $skipColumnHeader,
451 CRM_Import_Parser::MODE_PREVIEW
452 );
453
454 // add all the necessary variables to the form
455 $parser->set($this);
456 }
457
458 }