Merge pull request #6131 from JKingsnorth/CRM-16784
[civicrm-core.git] / CRM / Contact / Form / DedupeRules.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
6a488035 5 +--------------------------------------------------------------------+
e7112fa7 6 | Copyright CiviCRM LLC (c) 2004-2015 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
e7112fa7 31 * @copyright CiviCRM LLC (c) 2004-2015
6a488035
TO
32 * $Id$
33 *
34 */
35
36/**
37 * This class generates form components for DedupeRules
38 *
39 */
40class CRM_Contact_Form_DedupeRules extends CRM_Admin_Form {
7da04cde 41 const RULES_COUNT = 5;
6a488035
TO
42 protected $_contactType;
43 protected $_defaults = array();
44 protected $_fields = array();
45 protected $_rgid;
46
a4969aee
TM
47 /**
48 * Explicitly declare the entity api name.
49 */
50 public function getDefaultEntity() {
51 return 'RuleGroup';
52 }
53
6a488035 54 /**
fe482240 55 * Pre processing.
6a488035 56 *
355ba699 57 * @return void
8ef12e64 58 */
00be9182 59 public function preProcess() {
6a488035
TO
60 // Ensure user has permission to be here
61 if (!CRM_Core_Permission::check('administer dedupe rules')) {
62 CRM_Utils_System::permissionDenied();
63 CRM_Utils_System::civiExit();
64 }
77d0b1f8 65 $this->_options = CRM_Core_SelectValues::getDedupeRuleTypes();
6a488035
TO
66 $this->_rgid = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE, 0);
67 $this->_contactType = CRM_Utils_Request::retrieve('contact_type', 'String', $this, FALSE, 0);
68 if ($this->_rgid) {
69 $rgDao = new CRM_Dedupe_DAO_RuleGroup();
70 $rgDao->id = $this->_rgid;
71 $rgDao->find(TRUE);
72
73 $this->_defaults['threshold'] = $rgDao->threshold;
74 $this->_contactType = $rgDao->contact_type;
75 $this->_defaults['used'] = CRM_Utils_Array::key($rgDao->used, $this->_options);
76 $this->_defaults['title'] = $rgDao->title;
77 $this->_defaults['name'] = $rgDao->name;
78 $this->_defaults['is_reserved'] = $rgDao->is_reserved;
79 $this->assign('isReserved', $rgDao->is_reserved);
80 $this->assign('ruleName', $rgDao->name);
81 $ruleDao = new CRM_Dedupe_DAO_Rule();
82 $ruleDao->dedupe_rule_group_id = $this->_rgid;
83 $ruleDao->find();
84 $count = 0;
85 while ($ruleDao->fetch()) {
86 $this->_defaults["where_$count"] = "{$ruleDao->rule_table}.{$ruleDao->rule_field}";
87 $this->_defaults["length_$count"] = $ruleDao->rule_length;
88 $this->_defaults["weight_$count"] = $ruleDao->rule_weight;
89 $count++;
90 }
91 }
92 $supported = CRM_Dedupe_BAO_RuleGroup::supportedFields($this->_contactType);
93 if (is_array($supported)) {
94 foreach ($supported as $table => $fields) {
95 foreach ($fields as $field => $title) {
96 $this->_fields["$table.$field"] = $title;
97 }
98 }
99 }
100 asort($this->_fields);
101 }
102
103 /**
fe482240 104 * Build the form object.
6a488035 105 *
355ba699 106 * @return void
6a488035
TO
107 */
108 public function buildQuickForm() {
a4969aee 109 $this->addField('title', array('label' => ts('Rule Name')), TRUE);
6a488035
TO
110 $this->addRule('title', ts('A duplicate matching rule with this name already exists. Please select another name.'),
111 'objectExists', array('CRM_Dedupe_DAO_RuleGroup', $this->_rgid, 'title')
112 );
113
72c010fd 114 $this->addField('used', array('label' => ts('Usage')), TRUE);
6a488035 115 $disabled = array();
a4969aee 116 $reserved = $this->addField('is_reserved', array('label' => ts('Reserved?')));
a7488080 117 if (!empty($this->_defaults['is_reserved'])) {
2a300b65 118 $reserved->freeze();
6a488035
TO
119 }
120
121 $attributes = array('class' => 'two');
122 if (!empty($disabled)) {
123 $attributes = array_merge($attributes, $disabled);
124 }
125
126 for ($count = 0; $count < self::RULES_COUNT; $count++) {
127 $this->add('select', "where_$count", ts('Field'),
128 array(
21dfd5f5 129 NULL => ts('- none -'),
6432bd67 130 ) + $this->_fields, FALSE, $disabled
6a488035 131 );
9f645101
TM
132 $this->addField("length_$count", array('entity' => 'Rule', 'name' => 'rule_length') + $attributes);
133 $this->addField("weight_$count", array('entity' => 'Rule', 'name' => 'rule_weight') + $attributes);
6a488035
TO
134 }
135
a4969aee 136 $this->addField('threshold', array('label' => ts("Weight Threshold to Consider Contacts 'Matching':")) + $attributes);
6a488035
TO
137
138 $this->assign('contact_type', $this->_contactType);
139
140 $this->addFormRule(array('CRM_Contact_Form_DedupeRules', 'formRule'), $this);
a1f552a9
CW
141
142 parent::buildQuickForm();
6a488035
TO
143 }
144
145 /**
fe482240 146 * Global validation rules for the form.
6a488035 147 *
77c5b619
TO
148 * @param array $fields
149 * Posted values of the form.
6a488035 150 *
da6b46f4
EM
151 * @param $files
152 * @param $self
153 *
a6c01b45
CW
154 * @return array
155 * list of errors to be posted back to the form
6a488035 156 */
00be9182 157 public static function formRule($fields, $files, $self) {
6a488035 158 $errors = array();
a7488080 159 if (!empty($fields['is_reserved'])) {
6a488035
TO
160 return TRUE;
161 }
162
163 $fieldSelected = FALSE;
164 for ($count = 0; $count < self::RULES_COUNT; $count++) {
a7488080 165 if (!empty($fields["where_$count"])) {
6a488035
TO
166 $fieldSelected = TRUE;
167 break;
168 }
169 }
170
171 if (!$fieldSelected) {
172 $errors['_qf_default'] = ts('Please select at least one field.');
173 }
174
175 return empty($errors) ? TRUE : $errors;
176 }
177
86538308 178 /**
c490a46a 179 * Set default values for the form. MobileProvider that in edit/view mode
86538308
EM
180 * the default values are retrieved from the database
181 *
86538308
EM
182 *
183 * @return array
184 */
185 /**
186 * @return array
187 */
00be9182 188 public function setDefaultValues() {
6a488035
TO
189 return $this->_defaults;
190 }
191
192 /**
fe482240 193 * Process the form submission.
6a488035 194 *
6a488035 195 *
355ba699 196 * @return void
6a488035
TO
197 */
198 public function postProcess() {
199 $values = $this->exportValues();
8ef12e64 200
6a488035 201 //FIXME: Handle logic to replace is_default column by usage
6a488035
TO
202 // reset used column to General (since there can only
203 // be one 'Supervised' or 'Unsupervised' rule)
77d0b1f8 204 if ($values['used'] != 'General') {
6a488035 205 $query = "
8ef12e64 206UPDATE civicrm_dedupe_rule_group
6a488035 207 SET used = 'General'
8ef12e64 208 WHERE contact_type = %1
6a488035 209 AND used = %2";
77d0b1f8 210 $queryParams = array(
211 1 => array($this->_contactType, 'String'),
03390e26 212 2 => array($values['used'], 'String'),
6a488035
TO
213 );
214
215 CRM_Core_DAO::executeQuery($query, $queryParams);
216 }
217
218 $rgDao = new CRM_Dedupe_DAO_RuleGroup();
219 if ($this->_action & CRM_Core_Action::UPDATE) {
220 $rgDao->id = $this->_rgid;
221 }
222
353ffa53
TO
223 $rgDao->title = $values['title'];
224 $rgDao->is_reserved = CRM_Utils_Array::value('is_reserved', $values, FALSE);
225 $rgDao->used = $values['used'];
6a488035 226 $rgDao->contact_type = $this->_contactType;
353ffa53 227 $rgDao->threshold = $values['threshold'];
6a488035
TO
228 $rgDao->save();
229
230 // make sure name is set only during insert
231 if ($this->_action & CRM_Core_Action::ADD) {
232 // generate name based on title
233 $rgDao->name = CRM_Utils_String::titleToVar($values['title']) . "_{$rgDao->id}";
234 $rgDao->save();
235 }
236
237 // lets skip updating of fields for reserved dedupe group
238 if ($rgDao->is_reserved) {
239 CRM_Core_Session::setStatus(ts("The rule '%1' has been saved.", array(1 => $rgDao->title)), ts('Saved'), 'success');
240 return;
241 }
242
243 $ruleDao = new CRM_Dedupe_DAO_Rule();
244 $ruleDao->dedupe_rule_group_id = $rgDao->id;
245 $ruleDao->delete();
246 $ruleDao->free();
247
248 $substrLenghts = array();
249
250 $tables = array();
b0c27559
RN
251 $daoObj = new CRM_Core_DAO();
252 $database = $daoObj->database();
6a488035 253 for ($count = 0; $count < self::RULES_COUNT; $count++) {
a7488080 254 if (empty($values["where_$count"])) {
6a488035
TO
255 continue;
256 }
257 list($table, $field) = explode('.', CRM_Utils_Array::value("where_$count", $values));
0d8afee2 258 $length = !empty($values["length_$count"]) ? CRM_Utils_Array::value("length_$count", $values) : NULL;
6a488035
TO
259 $weight = $values["weight_$count"];
260 if ($table and $field) {
261 $ruleDao = new CRM_Dedupe_DAO_Rule();
262 $ruleDao->dedupe_rule_group_id = $rgDao->id;
263 $ruleDao->rule_table = $table;
264 $ruleDao->rule_field = $field;
265 $ruleDao->rule_length = $length;
266 $ruleDao->rule_weight = $weight;
267 $ruleDao->save();
268 $ruleDao->free();
269
270 if (!array_key_exists($table, $tables)) {
271 $tables[$table] = array();
272 }
273 $tables[$table][] = $field;
274 }
275
276 // CRM-6245: we must pass table/field/length triples to the createIndexes() call below
277 if ($length) {
278 if (!isset($substrLenghts[$table])) {
279 $substrLenghts[$table] = array();
280 }
f41b3f7e
RN
281
282 //CRM-13417 to avoid fatal error "Incorrect prefix key; the used key part isn't a string, the used length is longer than the key part, or the storage engine doesn't support unique prefix keys, 1089"
f41b3f7e
RN
283 $schemaQuery = "SELECT * FROM INFORMATION_SCHEMA.COLUMNS
284 WHERE TABLE_SCHEMA = '{$database}' AND
285 TABLE_NAME = '{$table}' AND COLUMN_NAME = '{$field}';";
286 $dao = CRM_Core_DAO::executeQuery($schemaQuery);
287
b0c27559 288 if ($dao->fetch()) {
f41b3f7e 289 // set the length to null for all the fields where prefix length is not supported. eg. int,tinyint,date,enum etc dataTypes.
353ffa53
TO
290 if ($dao->COLUMN_NAME == $field && !in_array($dao->DATA_TYPE, array(
291 'char',
292 'varchar',
293 'binary',
294 'varbinary',
295 'text',
af9b09df 296 'blob',
353ffa53
TO
297 ))
298 ) {
f41b3f7e
RN
299 $length = NULL;
300 }
301 elseif ($dao->COLUMN_NAME == $field && !empty($dao->CHARACTER_MAXIMUM_LENGTH) && ($length > $dao->CHARACTER_MAXIMUM_LENGTH)) {
302 //set the length to CHARACTER_MAXIMUM_LENGTH in case the length provided by the user is greater than the limit
303 $length = $dao->CHARACTER_MAXIMUM_LENGTH;
304 }
305 }
6a488035
TO
306 $substrLenghts[$table][$field] = $length;
307 }
308 }
309
310 // also create an index for this dedupe rule
311 // CRM-3837
1cf05c3e 312 CRM_Utils_Hook::dupeQuery($ruleDao, 'dedupeIndexes', $tables);
6a488035
TO
313 CRM_Core_BAO_SchemaHandler::createIndexes($tables, 'dedupe_index', $substrLenghts);
314
315 //need to clear cache of deduped contacts
316 //based on the previous rule
317 $cacheKey = "merge {$this->_contactType}_{$this->_rgid}_%";
318
319 CRM_Core_BAO_PrevNextCache::deleteItem(NULL, $cacheKey);
320
321 CRM_Core_Session::setStatus(ts("The rule '%1' has been saved.", array(1 => $rgDao->title)), ts('Saved'), 'success');
322 }
96025800 323
6a488035 324}