3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
37 * This class gets the name of the file to upload
39 class CRM_Activity_Import_Form_MapField
extends CRM_Import_Form_MapField
{
45 * Function to set variables up before form is built
50 public function preProcess() {
51 $this->_mapperFields
= $this->get('fields');
52 unset($this->_mapperFields
['id']);
53 asort($this->_mapperFields
);
55 $this->_columnCount
= $this->get('columnCount');
56 $this->assign('columnCount', $this->_columnCount
);
57 $this->_dataValues
= $this->get('dataValues');
58 $this->assign('dataValues', $this->_dataValues
);
60 $skipColumnHeader = $this->controller
->exportValue('DataSource', 'skipColumnHeader');
62 if ($skipColumnHeader) {
63 $this->assign('skipColumnHeader', $skipColumnHeader);
64 $this->assign('rowDisplayCount', 3);
65 /* if we had a column header to skip, stash it for later */
67 $this->_columnHeaders
= $this->_dataValues
[0];
70 $this->assign('rowDisplayCount', 2);
72 $highlightedFields = array();
73 $requiredFields = array('activity_date_time', 'activity_type_id', 'activity_label', 'target_contact_id', 'activity_subject');
74 foreach ($requiredFields as $val) {
75 $highlightedFields[] = $val;
77 $this->assign('highlightedFields', $highlightedFields);
81 * Function to actually build the form
86 public function buildQuickForm() {
87 //to save the current mappings
88 if (!$this->get('savedMapping')) {
89 $saveDetailsName = ts('Save this field mapping');
90 $this->applyFilter('saveMappingName', 'trim');
91 $this->add('text', 'saveMappingName', ts('Name'));
92 $this->add('text', 'saveMappingDesc', ts('Description'));
95 $savedMapping = $this->get('savedMapping');
96 //mapping is to be loaded from database
98 list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingRelation) = CRM_Core_BAO_Mapping
::getMappingFields($savedMapping);
100 //get loaded Mapping Fields
101 $mappingName = CRM_Utils_Array
::value('1', $mappingName);
102 $mappingContactType = CRM_Utils_Array
::value('1', $mappingContactType);
103 $mappingLocation = CRM_Utils_Array
::value('1', $mappingLocation);
104 $mappingPhoneType = CRM_Utils_Array
::value('1', $mappingPhoneType);
105 $mappingRelation = CRM_Utils_Array
::value('1', $mappingRelation);
107 $this->assign('loadedMapping', $savedMapping);
108 $this->set('loadedMapping', $savedMapping);
110 $params = array('id' => $savedMapping);
112 $mappingDetails = CRM_Core_BAO_Mapping
::retrieve($params, $temp);
114 $this->assign('savedName', $mappingDetails->name
);
116 $this->add('hidden', 'mappingId', $savedMapping);
118 $this->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL);
119 $saveDetailsName = ts('Save as a new field mapping');
120 $this->add('text', 'saveMappingName', ts('Name'));
121 $this->add('text', 'saveMappingDesc', ts('Description'));
124 $this->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, array('onclick' => "showSaveDetails(this)"));
126 $this->addFormRule(array('CRM_Activity_Import_Form_MapField', 'formRule'));
128 //-------- end of saved mapping stuff ---------
131 $mapperKeys = array_keys($this->_mapperFields
);
133 $hasHeaders = !empty($this->_columnHeaders
);
134 $headerPatterns = $this->get('headerPatterns');
135 $dataPatterns = $this->get('dataPatterns');
136 $hasLocationTypes = $this->get('fieldTypes');
139 /* Initialize all field usages to false */
141 foreach ($mapperKeys as $key) {
142 $this->_fieldUsed
[$key] = FALSE;
144 $this->_location_types
= CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
145 $sel1 = $this->_mapperFields
;
149 $js = "<script type='text/javascript'>\n";
150 $formName = 'document.forms.' . $this->_name
;
152 //used to warn for mismatch column count or mismatch mapping
156 for ($i = 0; $i < $this->_columnCount
; $i++
) {
157 $sel = &$this->addElement('hierselect', "mapper[$i]", ts('Mapper for Field %1', array(1 => $i)), NULL);
159 if ($this->get('savedMapping')) {
160 if (isset($mappingName[$i])) {
161 if ($mappingName[$i] != ts('- do not import -')) {
163 $mappingHeader = array_keys($this->_mapperFields
, $mappingName[$i]);
165 if (!isset($locationId) ||
!$locationId) {
166 $js .= "{$formName}['mapper[$i][1]'].style.display = 'none';\n";
169 if (!isset($phoneType) ||
!$phoneType) {
170 $js .= "{$formName}['mapper[$i][2]'].style.display = 'none';\n";
173 $js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
174 $defaults["mapper[$i]"] = array(
176 (isset($locationId)) ?
$locationId : "",
177 (isset($phoneType)) ?
$phoneType : "",
182 $defaults["mapper[$i]"] = array();
185 for ($k = 1; $k < 4; $k++
) {
186 $js .= "{$formName}['mapper[$i][$k]'].style.display = 'none';\n";
191 // this load section to help mapping if we ran out of saved columns when doing Load Mapping
192 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
195 $defaults["mapper[$i]"] = array(
196 $this->defaultFromHeader($this->_columnHeaders
[$i],
201 $defaults["mapper[$i]"] = array($this->defaultFromData($dataPatterns, $i));
204 //end of load mapping
207 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
209 // Infer the default from the skipped headers if we have them
210 $defaults["mapper[$i]"] = array(
211 $this->defaultFromHeader($this->_columnHeaders
[$i],
214 // $defaultLocationType->id
219 // Otherwise guess the default from the form of the data
220 $defaults["mapper[$i]"] = array(
221 $this->defaultFromData($dataPatterns, $i),
222 // $defaultLocationType->id
228 $sel->setOptions(array($sel1, $sel2, (isset($sel3)) ?
$sel3 : "", (isset($sel4)) ?
$sel4 : ""));
230 $js .= "</script>\n";
231 $this->assign('initHideBoxes', $js);
233 //set warning if mismatch in more than
234 if (isset($mappingName)) {
235 if (($this->_columnCount
!= count($mappingName))) {
239 if ($warning != 0 && $this->get('savedMapping')) {
240 $session = CRM_Core_Session
::singleton();
241 $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.'));
244 $session = CRM_Core_Session
::singleton();
245 $session->setStatus(NULL);
248 $this->setDefaults($defaults);
250 $this->addButtons(array(
253 'name' => ts('<< Previous'),
257 'name' => ts('Continue >>'),
258 'spacing' => ' ',
263 'name' => ts('Cancel'),
270 * global validation rules for the form
272 * @param array $fields posted values of the form
274 * @return array list of errors to be posted back to the form
278 static function formRule($fields) {
280 // define so we avoid notices below
281 $errors['_qf_default'] = '';
283 $fieldMessage = NULL;
284 if (!array_key_exists('savedMapping', $fields)) {
285 $importKeys = array();
286 foreach ($fields['mapper'] as $mapperPart) {
287 $importKeys[] = $mapperPart[0];
289 // FIXME: should use the schema titles, not redeclare them
290 $requiredFields = array(
291 'target_contact_id' => ts('Contact ID'),
292 'activity_date_time' => ts('Activity Date'),
293 'activity_subject' => ts('Activity Subject'),
294 'activity_type_id' => ts('Activity Type Id'),
298 'used' => 'Unsupervised',
299 'contact_type' => 'Individual',
301 list($ruleFields, $threshold) = CRM_Dedupe_BAO_RuleGroup
::dedupeRuleFieldsWeight($params);
303 foreach ($importKeys as $key => $val) {
304 if (array_key_exists($val, $ruleFields)) {
305 $weightSum +
= $ruleFields[$val];
308 foreach ($ruleFields as $field => $weight) {
309 $fieldMessage .= ' ' . $field . '(weight ' . $weight . ')';
311 foreach ($requiredFields as $field => $title) {
312 if (!in_array($field, $importKeys)) {
313 if ($field == 'target_contact_id') {
314 if ($weightSum >= $threshold ||
in_array('external_identifier', $importKeys)) {
318 $errors['_qf_default'] .= ts('Missing required contact matching fields.')
319 . $fieldMessage . ' '
320 . ts('(Sum of all weights should be greater than or equal to threshold: %1).', array(1 => $threshold))
324 elseif ($field == 'activity_type_id') {
325 if (in_array('activity_label', $importKeys)) {
329 $errors['_qf_default'] .= ts('Missing required field: Provide %1 or %2',
332 2 => 'Activity Type Label'
337 $errors['_qf_default'] .= ts('Missing required field: %1', array(1 => $title)) . '<br />';
343 if (CRM_Utils_Array
::value('saveMapping', $fields)) {
344 $nameField = CRM_Utils_Array
::value('saveMappingName', $fields);
345 if (empty($nameField)) {
346 $errors['saveMappingName'] = ts('Name is required to save Import Mapping');
349 $mappingTypeId = CRM_Core_OptionGroup
::getValue('mapping_type', 'Import Activity', 'name');
350 if (CRM_Core_BAO_Mapping
::checkMapping($nameField, $mappingTypeId)) {
351 $errors['saveMappingName'] = ts('Duplicate Import Mapping Name');
356 if (empty($errors['_qf_default'])) {
357 unset($errors['_qf_default']);
359 if (!empty($errors)) {
360 if (!empty($errors['saveMappingName'])) {
362 $assignError = new CRM_Core_Page();
363 $assignError->assign('mappingDetailsError', $_flag);
372 * Process the mapped fields and map it into the uploaded file
373 * preview the file and extract some summary statistics
378 public function postProcess() {
379 $params = $this->controller
->exportValues('MapField');
380 //reload the mapfield if load mapping is pressed
381 if (!empty($params['savedMapping'])) {
382 $this->set('savedMapping', $params['savedMapping']);
383 $this->controller
->resetPage($this->_name
);
387 $fileName = $this->controller
->exportValue('DataSource', 'uploadFile');
388 $skipColumnHeader = $this->controller
->exportValue('DataSource', 'skipColumnHeader');
390 $config = CRM_Core_Config
::singleton();
391 $seperator = $config->fieldSeparator
;
393 $mapperKeys = array();
395 $mapperKeys = $this->controller
->exportValue($this->_name
, 'mapper');
396 $mapperKeysMain = array();
397 $mapperLocType = array();
398 $mapperPhoneType = array();
400 for ($i = 0; $i < $this->_columnCount
; $i++
) {
401 $mapper[$i] = $this->_mapperFields
[$mapperKeys[$i][0]];
402 $mapperKeysMain[$i] = $mapperKeys[$i][0];
404 if ((CRM_Utils_Array
::value(1, $mapperKeys[$i])) && (is_numeric($mapperKeys[$i][1]))) {
405 $mapperLocType[$i] = $mapperKeys[$i][1];
408 $mapperLocType[$i] = NULL;
411 if ((CRM_Utils_Array
::value(2, $mapperKeys[$i])) && (!is_numeric($mapperKeys[$i][2]))) {
412 $mapperPhoneType[$i] = $mapperKeys[$i][2];
415 $mapperPhoneType[$i] = NULL;
419 $this->set('mapper', $mapper);
420 // store mapping Id to display it in the preview page
421 if (CRM_Utils_Array
::value('mappingId', $params)) {
422 $this->set('loadMappingId', $params['mappingId']);
425 //Updating Mapping Records
426 if (CRM_Utils_Array
::value('updateMapping', $params)) {
428 $mappingFields = new CRM_Core_DAO_MappingField();
429 $mappingFields->mapping_id
= $params['mappingId'];
430 $mappingFields->find();
432 $mappingFieldsId = array();
433 while ($mappingFields->fetch()) {
434 if ($mappingFields->id
) {
435 $mappingFieldsId[$mappingFields->column_number
] = $mappingFields->id
;
439 for ($i = 0; $i < $this->_columnCount
; $i++
) {
440 $updateMappingFields = new CRM_Core_DAO_MappingField();
441 $updateMappingFields->id
= $mappingFieldsId[$i];
442 $updateMappingFields->mapping_id
= $params['mappingId'];
443 $updateMappingFields->column_number
= $i;
445 $updateMappingFields->name
= $mapper[$i];
446 $updateMappingFields->save();
450 //Saving Mapping Details and Records
451 if (CRM_Utils_Array
::value('saveMapping', $params)) {
452 $mappingParams = array(
453 'name' => $params['saveMappingName'],
454 'description' => $params['saveMappingDesc'],
455 'mapping_type_id' => CRM_Core_OptionGroup
::getValue('mapping_type',
460 $saveMapping = CRM_Core_BAO_Mapping
::add($mappingParams);
462 for ($i = 0; $i < $this->_columnCount
; $i++
) {
463 $saveMappingFields = new CRM_Core_DAO_MappingField();
464 $saveMappingFields->mapping_id
= $saveMapping->id
;
465 $saveMappingFields->column_number
= $i;
467 $saveMappingFields->name
= $mapper[$i];
468 $saveMappingFields->save();
470 $this->set('savedMapping', $saveMappingFields->mapping_id
);
474 $parser = new CRM_Activity_Import_Parser_Activity($mapperKeysMain, $mapperLocType, $mapperPhoneType);
475 $parser->run($fileName, $seperator, $mapper, $skipColumnHeader,
476 CRM_Import_Parser
::MODE_PREVIEW
479 // add all the necessary variables to the form