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