Merge pull request #17866 from colemanw/customFix
[civicrm-core.git] / CRM / Dedupe / BAO / Rule.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 * The CiviCRM duplicate discovery engine is based on an
20 * algorithm designed by David Strauss <david@fourkitchens.com>.
21 */
22 class CRM_Dedupe_BAO_Rule extends CRM_Dedupe_DAO_Rule {
23
24 /**
25 * Ids of the contacts to limit the SQL queries (whole-database queries otherwise)
26 * @var array
27 */
28 public $contactIds = [];
29
30 /**
31 * Params to dedupe against (queries against the whole contact set otherwise)
32 * @var array
33 */
34 public $params = [];
35
36 /**
37 * Return the SQL query for the given rule - either for finding matching
38 * pairs of contacts, or for matching against the $params variable (if set).
39 *
40 * @return string
41 * SQL query performing the search
42 *
43 * @throws \CRM_Core_Exception
44 * @throws \CiviCRM_API3_Exception
45 */
46 public function sql() {
47 if ($this->params &&
48 (!array_key_exists($this->rule_table, $this->params) ||
49 !array_key_exists($this->rule_field, $this->params[$this->rule_table])
50 )
51 ) {
52 // if params is present and doesn't have an entry for a field, don't construct the clause.
53 return NULL;
54 }
55
56 // we need to initialise WHERE, ON and USING here, as some table types
57 // extend them; $where is an array of required conditions, $on and
58 // $using are arrays of required field matchings (for substring and
59 // full matches, respectively)
60 $where = [];
61 $on = ["SUBSTR(t1.{$this->rule_field}, 1, {$this->rule_length}) = SUBSTR(t2.{$this->rule_field}, 1, {$this->rule_length})"];
62
63 $innerJoinClauses = [
64 "t1.{$this->rule_field} IS NOT NULL",
65 "t2.{$this->rule_field} IS NOT NULL",
66 "t1.{$this->rule_field} = t2.{$this->rule_field}",
67 ];
68 if ($this->getFieldType($this->rule_field) === CRM_Utils_Type::T_DATE) {
69 $innerJoinClauses[] = "t1.{$this->rule_field} > '1000-01-01'";
70 $innerJoinClauses[] = "t2.{$this->rule_field} > '1000-01-01'";
71 }
72 else {
73 $innerJoinClauses[] = "t1.{$this->rule_field} <> ''";
74 $innerJoinClauses[] = "t2.{$this->rule_field} <> ''";
75 }
76
77 switch ($this->rule_table) {
78 case 'civicrm_contact':
79 $id = 'id';
80 //we should restrict by contact type in the first step
81 $sql = "SELECT contact_type FROM civicrm_dedupe_rule_group WHERE id = {$this->dedupe_rule_group_id};";
82 $ct = CRM_Core_DAO::singleValueQuery($sql);
83 if ($this->params) {
84 $where[] = "t1.contact_type = '{$ct}'";
85 }
86 else {
87 $where[] = "t1.contact_type = '{$ct}'";
88 $where[] = "t2.contact_type = '{$ct}'";
89 }
90 break;
91
92 case 'civicrm_address':
93 case 'civicrm_email':
94 case 'civicrm_im':
95 case 'civicrm_openid':
96 case 'civicrm_phone':
97 $id = 'contact_id';
98 break;
99
100 case 'civicrm_note':
101 $id = 'entity_id';
102 if ($this->params) {
103 $where[] = "t1.entity_table = 'civicrm_contact'";
104 }
105 else {
106 $where[] = "t1.entity_table = 'civicrm_contact'";
107 $where[] = "t2.entity_table = 'civicrm_contact'";
108 }
109 break;
110
111 default:
112 // custom data tables
113 if (preg_match('/^civicrm_value_/', $this->rule_table) || preg_match('/^custom_value_/', $this->rule_table)) {
114 $id = 'entity_id';
115 }
116 else {
117 throw new CRM_Core_Exception("Unsupported rule_table for civicrm_dedupe_rule.id of {$this->id}");
118 }
119 break;
120 }
121
122 // build SELECT based on the field names containing contact ids
123 // if there are params provided, id1 should be 0
124 if ($this->params) {
125 $select = "t1.$id id1, {$this->rule_weight} weight";
126 $subSelect = 'id1, weight';
127 }
128 else {
129 $select = "t1.$id id1, t2.$id id2, {$this->rule_weight} weight";
130 $subSelect = 'id1, id2, weight';
131 }
132
133 // build FROM (and WHERE, if it's a parametrised search)
134 // based on whether the rule is about substrings or not
135 if ($this->params) {
136 $from = "{$this->rule_table} t1";
137 $str = 'NULL';
138 if (isset($this->params[$this->rule_table][$this->rule_field])) {
139 $str = CRM_Utils_Type::escape($this->params[$this->rule_table][$this->rule_field], 'String');
140 }
141 if ($this->rule_length) {
142 $where[] = "SUBSTR(t1.{$this->rule_field}, 1, {$this->rule_length}) = SUBSTR('$str', 1, {$this->rule_length})";
143 $where[] = "t1.{$this->rule_field} IS NOT NULL";
144 }
145 else {
146 $where[] = "t1.{$this->rule_field} = '$str'";
147 }
148 }
149 else {
150 if ($this->rule_length) {
151 $from = "{$this->rule_table} t1 JOIN {$this->rule_table} t2 ON (" . implode(' AND ', $on) . ")";
152 }
153 else {
154 $from = "{$this->rule_table} t1 INNER JOIN {$this->rule_table} t2 ON (" . implode(' AND ', $innerJoinClauses) . ")";
155 }
156 }
157
158 // finish building WHERE, also limit the results if requested
159 if (!$this->params) {
160 $where[] = "t1.$id < t2.$id";
161 }
162 $query = "SELECT $select FROM $from WHERE " . implode(' AND ', $where);
163 if ($this->contactIds) {
164 $cids = [];
165 foreach ($this->contactIds as $cid) {
166 $cids[] = CRM_Utils_Type::escape($cid, 'Integer');
167 }
168 if (count($cids) == 1) {
169 $query .= " AND (t1.$id = {$cids[0]}) UNION $query AND t2.$id = {$cids[0]}";
170 }
171 else {
172 $query .= " AND t1.$id IN (" . implode(',', $cids) . ")
173 UNION $query AND t2.$id IN (" . implode(',', $cids) . ")";
174 }
175 // The `weight` is ambiguous in the context of the union; put the whole
176 // thing in a subquery.
177 $query = "SELECT $subSelect FROM ($query) subunion";
178 }
179
180 return $query;
181 }
182
183 /**
184 * find fields related to a rule group.
185 *
186 * @param array $params contains the rule group property to identify rule group
187 *
188 * @return array
189 * rule fields array associated to rule group
190 */
191 public static function dedupeRuleFields($params) {
192 $rgBao = new CRM_Dedupe_BAO_RuleGroup();
193 $rgBao->used = $params['used'];
194 $rgBao->contact_type = $params['contact_type'];
195 $rgBao->find(TRUE);
196
197 $ruleBao = new CRM_Dedupe_BAO_Rule();
198 $ruleBao->dedupe_rule_group_id = $rgBao->id;
199 $ruleBao->find();
200 $ruleFields = [];
201 while ($ruleBao->fetch()) {
202 $field_name = $ruleBao->rule_field;
203 if ($field_name == 'phone_numeric') {
204 $field_name = 'phone';
205 }
206 $ruleFields[] = $field_name;
207 }
208 return $ruleFields;
209 }
210
211 /**
212 * @param int $cid
213 * @param int $oid
214 *
215 * @return bool
216 */
217 public static function validateContacts($cid, $oid) {
218 if (!$cid || !$oid) {
219 return NULL;
220 }
221 $exception = new CRM_Dedupe_DAO_Exception();
222 $exception->contact_id1 = $cid;
223 $exception->contact_id2 = $oid;
224 //make sure contact2 > contact1.
225 if ($cid > $oid) {
226 $exception->contact_id1 = $oid;
227 $exception->contact_id2 = $cid;
228 }
229
230 return !$exception->find(TRUE);
231 }
232
233 /**
234 * Get the specification for the given field.
235 *
236 * @param string $fieldName
237 *
238 * @return array
239 * @throws \CiviCRM_API3_Exception
240 */
241 public function getFieldType($fieldName) {
242 $entity = CRM_Core_DAO_AllCoreTables::getBriefName(CRM_Core_DAO_AllCoreTables::getClassForTable($this->rule_table));
243 if (!$entity) {
244 // This means we have stored a custom field rather than an entity name in rule_table, figure out the entity.
245 $entity = civicrm_api3('CustomGroup', 'getvalue', ['table_name' => $this->rule_table, 'return' => 'extends']);
246 if (in_array($entity, ['Individual', 'Household', 'Organization'])) {
247 $entity = 'Contact';
248 }
249 $fieldName = 'custom_' . civicrm_api3('CustomField', 'getvalue', ['column_name' => $fieldName, 'return' => 'id']);
250 }
251 $fields = civicrm_api3($entity, 'getfields', ['action' => 'create'])['values'];
252 return $fields[$fieldName]['type'];
253 }
254
255 }