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