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