Merge pull request #23567 from kurund/honor-roll-fixes
[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 * @throws \API_Exception
34 * @throws \CRM_Core_Exception
35 */
36 public function preProcess() {
37 $columnNames = $this->getColumnHeaders();
38 $this->_disableUSPS = $this->getSubmittedValue('disableUSPS');
39
40 //assign column names
41 $this->assign('columnNames', $columnNames);
42
43 //get the mapping name displayed if the mappingId is set
44 $mappingId = $this->get('loadMappingId');
45 if ($mappingId) {
46 $mapDAO = new CRM_Core_DAO_Mapping();
47 $mapDAO->id = $mappingId;
48 $mapDAO->find(TRUE);
49 }
50 $this->assign('savedMappingName', $mappingId ? $mapDAO->name : NULL);
51
52 $this->assign('rowDisplayCount', 2);
53
54 $groups = CRM_Core_PseudoConstant::nestedGroup();
55 $this->set('groups', $groups);
56
57 $tag = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
58 if ($tag) {
59 $this->set('tag', $tag);
60 }
61
62 $this->assign('downloadErrorRecordsUrl', $this->getDownloadURL(CRM_Import_Parser::ERROR));
63 $this->assign('invalidRowCount', $this->getRowCount(CRM_Import_Parser::ERROR));
64 $this->assign('validRowCount', $this->getRowCount(CRM_Import_Parser::VALID));
65 $this->assign('totalRowCount', $this->getRowCount([]));
66 $this->assign('mapper', $this->getMappedFieldLabels());
67 $this->assign('dataValues', $this->getDataRows([], 2));
68
69 $this->setStatusUrl();
70 }
71
72 /**
73 * Build the form object.
74 */
75 public function buildQuickForm() {
76 $this->addElement('text', 'newGroupName', ts('Name for new group'), CRM_Core_DAO::getAttribute('CRM_Contact_DAO_Group', 'title'));
77 $this->addElement('text', 'newGroupDesc', ts('Description of new group'));
78 $groupTypes = CRM_Core_OptionGroup::values('group_type', TRUE);
79 if (!empty($groupTypes)) {
80 $this->addCheckBox('newGroupType',
81 ts('Group Type'),
82 $groupTypes,
83 NULL, NULL, NULL, NULL, '&nbsp;&nbsp;&nbsp;'
84 );
85 }
86
87 $groups = $this->get('groups');
88
89 if (!empty($groups)) {
90 $this->addElement('select', 'groups', ts('Add imported records to existing group(s)'), $groups, array(
91 'multiple' => "multiple",
92 'class' => 'crm-select2',
93 ));
94 }
95
96 //display new tag
97 $this->addElement('text', 'newTagName', ts('Tag'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_Tag', 'name'));
98 $this->addElement('text', 'newTagDesc', ts('Description'), CRM_Core_DAO::getAttribute('CRM_Core_DAO_Tag', 'description'));
99
100 $tag = $this->get('tag');
101 if (!empty($tag)) {
102 foreach ($tag as $tagID => $tagName) {
103 $this->addElement('checkbox', "tag[$tagID]", NULL, $tagName);
104 }
105 }
106
107 $this->addFormRule(array('CRM_Contact_Import_Form_Preview', 'formRule'), $this);
108
109 parent::buildQuickForm();
110 }
111
112 /**
113 * Global validation rules for the form.
114 *
115 * @param array $fields
116 * Posted values of the form.
117 *
118 * @param $files
119 * @param self $self
120 *
121 * @return array
122 * list of errors to be posted back to the form
123 */
124 public static function formRule($fields, $files, $self) {
125 $errors = [];
126 $invalidTagName = $invalidGroupName = FALSE;
127
128 if (!empty($fields['newTagName'])) {
129 if (!CRM_Utils_Rule::objectExists(trim($fields['newTagName']),
130 array('CRM_Core_DAO_Tag')
131 )
132 ) {
133 $errors['newTagName'] = ts('Tag \'%1\' already exists.',
134 array(1 => $fields['newTagName'])
135 );
136 $invalidTagName = TRUE;
137 }
138 }
139
140 if (!empty($fields['newGroupName'])) {
141 $title = trim($fields['newGroupName']);
142 $name = CRM_Utils_String::titleToVar($title);
143 $query = 'select count(*) from civicrm_group where name like %1 OR title like %2';
144 $grpCnt = CRM_Core_DAO::singleValueQuery(
145 $query,
146 array(
147 1 => array($name, 'String'),
148 2 => array($title, 'String'),
149 )
150 );
151 if ($grpCnt) {
152 $invalidGroupName = TRUE;
153 $errors['newGroupName'] = ts('Group \'%1\' already exists.', array(1 => $fields['newGroupName']));
154 }
155 }
156
157 $self->assign('invalidTagName', $invalidTagName);
158 $self->assign('invalidGroupName', $invalidGroupName);
159
160 return empty($errors) ? TRUE : $errors;
161 }
162
163 /**
164 * Process the mapped fields and map it into the uploaded file.
165 *
166 * @throws \API_Exception
167 */
168 public function postProcess() {
169
170 $importJobParams = array(
171 'doGeocodeAddress' => $this->getSubmittedValue('doGeocodeAddress'),
172 'invalidRowCount' => $this->getRowCount(CRM_Import_Parser::ERROR),
173 'onDuplicate' => $this->getSubmittedValue('onDuplicate'),
174 'dedupe' => $this->getSubmittedValue('dedupe_rule_id'),
175 'newGroupName' => $this->controller->exportValue($this->_name, 'newGroupName'),
176 'newGroupDesc' => $this->controller->exportValue($this->_name, 'newGroupDesc'),
177 'newGroupType' => $this->controller->exportValue($this->_name, 'newGroupType'),
178 'groups' => $this->controller->exportValue($this->_name, 'groups'),
179 'allGroups' => $this->get('groups'),
180 'newTagName' => $this->controller->exportValue($this->_name, 'newTagName'),
181 'newTagDesc' => $this->controller->exportValue($this->_name, 'newTagDesc'),
182 'tag' => $this->controller->exportValue($this->_name, 'tag'),
183 'allTags' => $this->get('tag'),
184 'mapper' => $this->controller->exportValue('MapField', 'mapper'),
185 'mapFields' => $this->getAvailableFields(),
186 'contactType' => $this->getContactType(),
187 'contactSubType' => $this->getSubmittedValue('contactSubType'),
188 'primaryKeyName' => '_id',
189 'statusFieldName' => '_status',
190 'statusID' => $this->get('statusID'),
191 'totalRowCount' => $this->getRowCount([]),
192 'userJobID' => $this->getUserJobID(),
193 );
194
195 $importJob = new CRM_Contact_Import_ImportJob();
196 $importJob->setJobParams($importJobParams);
197
198 // If ACL applies to the current user, update cache before running the import.
199 if (!CRM_Core_Permission::check('view all contacts')) {
200 $userID = CRM_Core_Session::getLoggedInContactID();
201 CRM_ACL_BAO_Cache::deleteEntry($userID);
202 CRM_ACL_BAO_Cache::deleteContactCacheEntry($userID);
203 }
204
205 CRM_Utils_Address_USPS::disable($this->_disableUSPS);
206
207 // run the import
208 $importJob->runImport($this);
209
210 // Clear all caches, forcing any searches to recheck the ACLs or group membership as the import
211 // may have changed it.
212 CRM_Contact_BAO_Contact_Utils::clearContactCaches(TRUE);
213
214 // add all the necessary variables to the form
215 $importJob->setFormVariables($this);
216
217 // check if there is any error occurred
218 $errorStack = CRM_Core_Error::singleton();
219 $errors = $errorStack->getErrors();
220 $errorMessage = [];
221
222 if (is_array($errors)) {
223 foreach ($errors as $key => $value) {
224 $errorMessage[] = $value['message'];
225 }
226
227 // there is no fileName since this is a sql import
228 // so fudge it
229 $config = CRM_Core_Config::singleton();
230 $errorFile = $config->uploadDir . "sqlImport.error.log";
231 if ($fd = fopen($errorFile, 'w')) {
232 fwrite($fd, implode('\n', $errorMessage));
233 }
234 fclose($fd);
235
236 $this->set('errorFile', $errorFile);
237 }
238
239 //hack to clean db
240 //if job complete drop table.
241 $importJob->isComplete();
242 }
243
244 /**
245 * @return \CRM_Contact_Import_Parser_Contact
246 */
247 protected function getParser(): CRM_Contact_Import_Parser_Contact {
248 if (!$this->parser) {
249 $this->parser = new CRM_Contact_Import_Parser_Contact();
250 $this->parser->setUserJobID($this->getUserJobID());
251 }
252 return $this->parser;
253 }
254
255 }