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