Merge remote-tracking branch 'upstream/4.5' into 4.5-master-2015-01-05-23-28-33
[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
137 /* Initialize all field usages to false */
138
139 foreach ($mapperKeys as $key) {
140 $this->_fieldUsed[$key] = FALSE;
141 }
142 $this->_location_types = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
143 $sel1 = $this->_mapperFields;
144
145 $sel2[''] = NULL;
146
147 $js = "<script type='text/javascript'>\n";
148 $formName = 'document.forms.' . $this->_name;
149
150 //used to warn for mismatch column count or mismatch mapping
151 $warning = 0;
152
153
154 for ($i = 0; $i < $this->_columnCount; $i++) {
155 $sel = &$this->addElement('hierselect', "mapper[$i]", ts('Mapper for Field %1', array(1 => $i)), NULL);
156 $jsSet = FALSE;
157 if ($this->get('savedMapping')) {
158 if (isset($mappingName[$i])) {
159 if ($mappingName[$i] != ts('- do not import -')) {
160
161 $mappingHeader = array_keys($this->_mapperFields, $mappingName[$i]);
162
163 if (!isset($locationId) || !$locationId) {
164 $js .= "{$formName}['mapper[$i][1]'].style.display = 'none';\n";
165 }
166
167 if (!isset($phoneType) || !$phoneType) {
168 $js .= "{$formName}['mapper[$i][2]'].style.display = 'none';\n";
169 }
170
171 $js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
172 $defaults["mapper[$i]"] = array(
173 $mappingHeader[0],
174 (isset($locationId)) ? $locationId : "",
175 (isset($phoneType)) ? $phoneType : "",
176 );
177 $jsSet = TRUE;
178 }
179 else {
180 $defaults["mapper[$i]"] = array();
181 }
182 if (!$jsSet) {
183 for ($k = 1; $k < 4; $k++) {
184 $js .= "{$formName}['mapper[$i][$k]'].style.display = 'none';\n";
185 }
186 }
187 }
188 else {
189 // this load section to help mapping if we ran out of saved columns when doing Load Mapping
190 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
191
192 if ($hasHeaders) {
193 $defaults["mapper[$i]"] = array(
194 $this->defaultFromHeader($this->_columnHeaders[$i],
195 $headerPatterns
196 ));
197 }
198 else {
199 $defaults["mapper[$i]"] = array($this->defaultFromData($dataPatterns, $i));
200 }
201 }
202 //end of load mapping
203 }
204 else {
205 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
206 if ($hasHeaders) {
207 // Infer the default from the skipped headers if we have them
208 $defaults["mapper[$i]"] = array(
209 $this->defaultFromHeader($this->_columnHeaders[$i],
210 $headerPatterns
211 ),
212 // $defaultLocationType->id
213 0,
214 );
215 }
216 else {
217 // Otherwise guess the default from the form of the data
218 $defaults["mapper[$i]"] = array(
219 $this->defaultFromData($dataPatterns, $i),
220 // $defaultLocationType->id
221 0,
222 );
223 }
224 }
225
226 $sel->setOptions(array($sel1, $sel2, (isset($sel3)) ? $sel3 : "", (isset($sel4)) ? $sel4 : ""));
227 }
228 $js .= "</script>\n";
229 $this->assign('initHideBoxes', $js);
230
231 //set warning if mismatch in more than
232 if (isset($mappingName)) {
233 if (($this->_columnCount != count($mappingName))) {
234 $warning++;
235 }
236 }
237 if ($warning != 0 && $this->get('savedMapping')) {
238 $session = CRM_Core_Session::singleton();
239 $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.'));
240 }
241 else {
242 $session = CRM_Core_Session::singleton();
243 $session->setStatus(NULL);
244 }
245
246 $this->setDefaults($defaults);
247
248 $this->addButtons(array(
249 array(
250 'type' => 'back',
251 'name' => ts('<< Previous'),
252 ),
253 array(
254 'type' => 'next',
255 'name' => ts('Continue >>'),
256 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
257 'isDefault' => TRUE,
258 ),
259 array(
260 'type' => 'cancel',
261 'name' => ts('Cancel'),
262 ),
263 )
264 );
265 }
266
267 /**
268 * Global validation rules for the form
269 *
270 * @param array $fields posted values of the form
271 *
272 * @return array list of errors to be posted back to the form
273 * @static
274 */
275 public static function formRule($fields) {
276 $errors = array();
277 // define so we avoid notices below
278 $errors['_qf_default'] = '';
279
280 $fieldMessage = NULL;
281 if (!array_key_exists('savedMapping', $fields)) {
282 $importKeys = array();
283 foreach ($fields['mapper'] as $mapperPart) {
284 $importKeys[] = $mapperPart[0];
285 }
286 // FIXME: should use the schema titles, not redeclare them
287 $requiredFields = array(
288 'target_contact_id' => ts('Contact ID'),
289 'activity_date_time' => ts('Activity Date'),
290 'activity_subject' => ts('Activity Subject'),
291 'activity_type_id' => ts('Activity Type ID'),
292 );
293
294 $params = array(
295 'used' => 'Unsupervised',
296 'contact_type' => 'Individual',
297 );
298 list($ruleFields, $threshold) = CRM_Dedupe_BAO_RuleGroup::dedupeRuleFieldsWeight($params);
299 $weightSum = 0;
300 foreach ($importKeys as $key => $val) {
301 if (array_key_exists($val, $ruleFields)) {
302 $weightSum += $ruleFields[$val];
303 }
304 }
305 foreach ($ruleFields as $field => $weight) {
306 $fieldMessage .= ' ' . $field . '(weight ' . $weight . ')';
307 }
308 foreach ($requiredFields as $field => $title) {
309 if (!in_array($field, $importKeys)) {
310 if ($field == 'target_contact_id') {
311 if ($weightSum >= $threshold || in_array('external_identifier', $importKeys)) {
312 continue;
313 }
314 else {
315 $errors['_qf_default'] .= ts('Missing required contact matching fields.')
316 . $fieldMessage . ' '
317 . ts('(Sum of all weights should be greater than or equal to threshold: %1).', array(1 => $threshold))
318 . '<br />';
319 }
320 }
321 elseif ($field == 'activity_type_id') {
322 if (in_array('activity_label', $importKeys)) {
323 continue;
324 }
325 else {
326 $errors['_qf_default'] .= ts('Missing required field: Provide %1 or %2',
327 array(
328 1 => $title,
329 2 => 'Activity Type Label'
330 )) . '<br />';
331 }
332 }
333 else {
334 $errors['_qf_default'] .= ts('Missing required field: %1', array(1 => $title)) . '<br />';
335 }
336 }
337 }
338 }
339
340 if (!empty($fields['saveMapping'])) {
341 $nameField = CRM_Utils_Array::value('saveMappingName', $fields);
342 if (empty($nameField)) {
343 $errors['saveMappingName'] = ts('Name is required to save Import Mapping');
344 }
345 else {
346 $mappingTypeId = CRM_Core_OptionGroup::getValue('mapping_type', 'Import Activity', 'name');
347 if (CRM_Core_BAO_Mapping::checkMapping($nameField, $mappingTypeId)) {
348 $errors['saveMappingName'] = ts('Duplicate Import Mapping Name');
349 }
350 }
351 }
352
353 if (empty($errors['_qf_default'])) {
354 unset($errors['_qf_default']);
355 }
356 if (!empty($errors)) {
357 if (!empty($errors['saveMappingName'])) {
358 $_flag = 1;
359 $assignError = new CRM_Core_Page();
360 $assignError->assign('mappingDetailsError', $_flag);
361 }
362 return $errors;
363 }
364
365 return TRUE;
366 }
367
368 /**
369 * Process the mapped fields and map it into the uploaded file
370 * preview the file and extract some summary statistics
371 *
372 * @return void
373 */
374 public function postProcess() {
375 $params = $this->controller->exportValues('MapField');
376 //reload the mapfield if load mapping is pressed
377 if (!empty($params['savedMapping'])) {
378 $this->set('savedMapping', $params['savedMapping']);
379 $this->controller->resetPage($this->_name);
380 return;
381 }
382
383 $fileName = $this->controller->exportValue('DataSource', 'uploadFile');
384 $skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
385
386 $config = CRM_Core_Config::singleton();
387 $seperator = $config->fieldSeparator;
388
389 $mapperKeys = array();
390 $mapper = array();
391 $mapperKeys = $this->controller->exportValue($this->_name, 'mapper');
392 $mapperKeysMain = array();
393 $mapperLocType = array();
394 $mapperPhoneType = array();
395
396 for ($i = 0; $i < $this->_columnCount; $i++) {
397 $mapper[$i] = $this->_mapperFields[$mapperKeys[$i][0]];
398 $mapperKeysMain[$i] = $mapperKeys[$i][0];
399
400 if ((CRM_Utils_Array::value(1, $mapperKeys[$i])) && (is_numeric($mapperKeys[$i][1]))) {
401 $mapperLocType[$i] = $mapperKeys[$i][1];
402 }
403 else {
404 $mapperLocType[$i] = NULL;
405 }
406
407 if ((CRM_Utils_Array::value(2, $mapperKeys[$i])) && (!is_numeric($mapperKeys[$i][2]))) {
408 $mapperPhoneType[$i] = $mapperKeys[$i][2];
409 }
410 else {
411 $mapperPhoneType[$i] = NULL;
412 }
413 }
414
415 $this->set('mapper', $mapper);
416 // store mapping Id to display it in the preview page
417 if (!empty($params['mappingId'])) {
418 $this->set('loadMappingId', $params['mappingId']);
419 }
420
421 //Updating Mapping Records
422 if (!empty($params['updateMapping'])) {
423
424 $mappingFields = new CRM_Core_DAO_MappingField();
425 $mappingFields->mapping_id = $params['mappingId'];
426 $mappingFields->find();
427
428 $mappingFieldsId = array();
429 while ($mappingFields->fetch()) {
430 if ($mappingFields->id) {
431 $mappingFieldsId[$mappingFields->column_number] = $mappingFields->id;
432 }
433 }
434
435 for ($i = 0; $i < $this->_columnCount; $i++) {
436 $updateMappingFields = new CRM_Core_DAO_MappingField();
437 $updateMappingFields->id = $mappingFieldsId[$i];
438 $updateMappingFields->mapping_id = $params['mappingId'];
439 $updateMappingFields->column_number = $i;
440
441 $updateMappingFields->name = $mapper[$i];
442 $updateMappingFields->save();
443 }
444 }
445
446 //Saving Mapping Details and Records
447 if (!empty($params['saveMapping'])) {
448 $mappingParams = array(
449 'name' => $params['saveMappingName'],
450 'description' => $params['saveMappingDesc'],
451 'mapping_type_id' => CRM_Core_OptionGroup::getValue('mapping_type',
452 'Import Activity',
453 'name'
454 ),
455 );
456 $saveMapping = CRM_Core_BAO_Mapping::add($mappingParams);
457
458 for ($i = 0; $i < $this->_columnCount; $i++) {
459 $saveMappingFields = new CRM_Core_DAO_MappingField();
460 $saveMappingFields->mapping_id = $saveMapping->id;
461 $saveMappingFields->column_number = $i;
462
463 $saveMappingFields->name = $mapper[$i];
464 $saveMappingFields->save();
465 }
466 $this->set('savedMapping', $saveMappingFields->mapping_id);
467 }
468
469
470 $parser = new CRM_Activity_Import_Parser_Activity($mapperKeysMain, $mapperLocType, $mapperPhoneType);
471 $parser->run($fileName, $seperator, $mapper, $skipColumnHeader,
472 CRM_Import_Parser::MODE_PREVIEW
473 );
474
475 // add all the necessary variables to the form
476 $parser->set($this);
477 }
478 }