805bfd1376d2fae374cd515ae26b47b170e02e7f
[civicrm-core.git] / CRM / Contact / Import / Form / Preview.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * This class previews the uploaded file and returns summary statistics.
20 */
21 class CRM_Contact_Import_Form_Preview extends CRM_Import_Form_Preview {
22
23 /**
24 * Whether USPS validation should be disabled during import.
25 *
26 * @var bool
27 */
28 protected $_disableUSPS;
29
30 /**
31 * Set variables up before form is built.
32 */
33 public function preProcess() {
34 $mapper = $this->get('mapper');
35 $invalidRowCount = $this->get('invalidRowCount');
36 $conflictRowCount = $this->get('conflictRowCount');
37 $mismatchCount = $this->get('unMatchCount');
38 $columnNames = $this->get('columnNames');
39 $this->_disableUSPS = $this->get('disableUSPS');
40
41 //assign column names
42 $this->assign('columnNames', $columnNames);
43
44 //get the mapping name displayed if the mappingId is set
45 $mappingId = $this->get('loadMappingId');
46 if ($mappingId) {
47 $mapDAO = new CRM_Core_DAO_Mapping();
48 $mapDAO->id = $mappingId;
49 $mapDAO->find(TRUE);
50 }
51 $this->assign('savedMappingName', $mappingId ? $mapDAO->name : NULL);
52
53 $this->assign('rowDisplayCount', 2);
54
55 $groups = CRM_Core_PseudoConstant::nestedGroup();
56 $this->set('groups', $groups);
57
58 $tag = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
59 if ($tag) {
60 $this->set('tag', $tag);
61 }
62
63 if ($invalidRowCount) {
64 $urlParams = 'type=' . CRM_Import_Parser::ERROR . '&parser=CRM_Contact_Import_Parser_Contact';
65 $this->set('downloadErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
66 }
67
68 if ($conflictRowCount) {
69 $urlParams = 'type=' . CRM_Import_Parser::CONFLICT . '&parser=CRM_Contact_Import_Parser_Contact';
70 $this->set('downloadConflictRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
71 }
72
73 if ($mismatchCount) {
74 $urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . '&parser=CRM_Contact_Import_Parser_Contact';
75 $this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
76 }
77
78 $properties = array(
79 'mapper',
80 'locations',
81 'phones',
82 'ims',
83 'columnCount',
84 'totalRowCount',
85 'validRowCount',
86 'invalidRowCount',
87 'conflictRowCount',
88 'downloadErrorRecordsUrl',
89 'downloadConflictRecordsUrl',
90 'downloadMismatchRecordsUrl',
91 'related',
92 'relatedContactDetails',
93 'relatedContactLocType',
94 'relatedContactPhoneType',
95 'relatedContactImProvider',
96 'websites',
97 'relatedContactWebsiteType',
98 );
99
100 foreach ($properties as $property) {
101 $this->assign($property, $this->get($property));
102 }
103 $this->assign('dataValues', $this->getDataRows(2));
104
105 $this->setStatusUrl();
106
107 $showColNames = TRUE;
108 if ('CRM_Import_DataSource_CSV' == $this->get('dataSource') &&
109 !$this->getSubmittedValue('skipColumnHeader')
110 ) {
111 $showColNames = FALSE;
112 }
113 $this->assign('showColNames', $showColNames);
114 }
115
116 /**
117 * Build the form object.
118 */
119 public function buildQuickForm() {
120 $this->addElement('text', 'newGroupName', ts('Name for new group'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Group', 'title'));
121 $this->addElement('text', 'newGroupDesc', ts('Description of new group'));
122 $groupTypes = CRM_Core_OptionGroup::values('group_type', TRUE);
123 if (!empty($groupTypes)) {
124 $this->addCheckBox('newGroupType',
125 ts('Group Type'),
126 $groupTypes,
127 NULL, NULL, NULL, NULL, '&nbsp;&nbsp;&nbsp;'
128 );
129 }
130
131 $groups = $this->get('groups');
132
133 if (!empty($groups)) {
134 $this->addElement('select', 'groups', ts('Add imported records to existing group(s)'), $groups, array(
135 'multiple' => "multiple",
136 'class' => 'crm-select2',
137 ));
138 }
139
140 //display new tag
141 $this->addElement('text', 'newTagName', ts('Tag'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_Tag', 'name'));
142 $this->addElement('text', 'newTagDesc', ts('Description'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_Tag', 'description'));
143
144 $tag = $this->get('tag');
145 if (!empty($tag)) {
146 foreach ($tag as $tagID => $tagName) {
147 $this->addElement('checkbox', "tag[$tagID]", NULL, $tagName);
148 }
149 }
150
151 $this->addFormRule(array('CRM_Contact_Import_Form_Preview', 'formRule'), $this);
152
153 parent::buildQuickForm();
154 }
155
156 /**
157 * Global validation rules for the form.
158 *
159 * @param array $fields
160 * Posted values of the form.
161 *
162 * @param $files
163 * @param self $self
164 *
165 * @return array
166 * list of errors to be posted back to the form
167 */
168 public static function formRule($fields, $files, $self) {
169 $errors = [];
170 $invalidTagName = $invalidGroupName = FALSE;
171
172 if (!empty($fields['newTagName'])) {
173 if (!CRM_Utils_Rule::objectExists(trim($fields['newTagName']),
174 array('CRM_Core_DAO_Tag')
175 )
176 ) {
177 $errors['newTagName'] = ts('Tag \'%1\' already exists.',
178 array(1 => $fields['newTagName'])
179 );
180 $invalidTagName = TRUE;
181 }
182 }
183
184 if (!empty($fields['newGroupName'])) {
185 $title = trim($fields['newGroupName']);
186 $name = CRM_Utils_String::titleToVar($title);
187 $query = 'select count(*) from civicrm_group where name like %1 OR title like %2';
188 $grpCnt = CRM_Core_DAO::singleValueQuery(
189 $query,
190 array(
191 1 => array($name, 'String'),
192 2 => array($title, 'String'),
193 )
194 );
195 if ($grpCnt) {
196 $invalidGroupName = TRUE;
197 $errors['newGroupName'] = ts('Group \'%1\' already exists.', array(1 => $fields['newGroupName']));
198 }
199 }
200
201 $self->assign('invalidTagName', $invalidTagName);
202 $self->assign('invalidGroupName', $invalidGroupName);
203
204 return empty($errors) ? TRUE : $errors;
205 }
206
207 /**
208 * Process the mapped fields and map it into the uploaded file.
209 *
210 * @throws \API_Exception
211 */
212 public function postProcess() {
213
214 $importJobParams = array(
215 'doGeocodeAddress' => $this->controller->exportValue('DataSource', 'doGeocodeAddress'),
216 'invalidRowCount' => $this->get('invalidRowCount'),
217 'conflictRowCount' => $this->get('conflictRowCount'),
218 'onDuplicate' => $this->get('onDuplicate'),
219 'dedupe' => $this->getSubmittedValue('dedupe_rule_id'),
220 'newGroupName' => $this->controller->exportValue($this->_name, 'newGroupName'),
221 'newGroupDesc' => $this->controller->exportValue($this->_name, 'newGroupDesc'),
222 'newGroupType' => $this->controller->exportValue($this->_name, 'newGroupType'),
223 'groups' => $this->controller->exportValue($this->_name, 'groups'),
224 'allGroups' => $this->get('groups'),
225 'newTagName' => $this->controller->exportValue($this->_name, 'newTagName'),
226 'newTagDesc' => $this->controller->exportValue($this->_name, 'newTagDesc'),
227 'tag' => $this->controller->exportValue($this->_name, 'tag'),
228 'allTags' => $this->get('tag'),
229 'mapper' => $this->controller->exportValue('MapField', 'mapper'),
230 'mapFields' => $this->getAvailableFields(),
231 'contactType' => $this->get('contactType'),
232 'contactSubType' => $this->getSubmittedValue('contactSubType'),
233 'primaryKeyName' => $this->get('primaryKeyName'),
234 'statusFieldName' => $this->get('statusFieldName'),
235 'statusID' => $this->get('statusID'),
236 'totalRowCount' => $this->get('totalRowCount'),
237 'userJobID' => $this->getUserJobID(),
238 );
239
240 $tableName = $this->get('importTableName');
241 $importJob = new CRM_Contact_Import_ImportJob($tableName);
242 $importJob->setJobParams($importJobParams);
243
244 // If ACL applies to the current user, update cache before running the import.
245 if (!CRM_Core_Permission::check('view all contacts')) {
246 $userID = CRM_Core_Session::getLoggedInContactID();
247 CRM_ACL_BAO_Cache::deleteEntry($userID);
248 CRM_ACL_BAO_Cache::deleteContactCacheEntry($userID);
249 }
250
251 CRM_Utils_Address_USPS::disable($this->_disableUSPS);
252
253 // run the import
254 $importJob->runImport($this);
255
256 // Clear all caches, forcing any searches to recheck the ACLs or group membership as the import
257 // may have changed it.
258 CRM_Contact_BAO_Contact_Utils::clearContactCaches(TRUE);
259
260 // add all the necessary variables to the form
261 $importJob->setFormVariables($this);
262
263 // check if there is any error occurred
264 $errorStack = CRM_Core_Error::singleton();
265 $errors = $errorStack->getErrors();
266 $errorMessage = [];
267
268 if (is_array($errors)) {
269 foreach ($errors as $key => $value) {
270 $errorMessage[] = $value['message'];
271 }
272
273 // there is no fileName since this is a sql import
274 // so fudge it
275 $config = CRM_Core_Config::singleton();
276 $errorFile = $config->uploadDir . "sqlImport.error.log";
277 if ($fd = fopen($errorFile, 'w')) {
278 fwrite($fd, implode('\n', $errorMessage));
279 }
280 fclose($fd);
281
282 $this->set('errorFile', $errorFile);
283
284 $urlParams = 'type=' . CRM_Import_Parser::ERROR . '&parser=CRM_Contact_Import_Parser_Contact';
285 $this->set('downloadErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
286
287 $urlParams = 'type=' . CRM_Import_Parser::CONFLICT . '&parser=CRM_Contact_Import_Parser_Contact';
288 $this->set('downloadConflictRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
289
290 $urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . '&parser=CRM_Contact_Import_Parser_Contact';
291 $this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
292 }
293
294 //hack to clean db
295 //if job complete drop table.
296 $importJob->isComplete();
297 }
298
299 }