Merge pull request #11019 from DanielvV/CRM-21214
[civicrm-core.git] / CRM / Dedupe / Finder.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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
31 * @copyright CiviCRM LLC (c) 2004-2017
32 * $Id$
33 *
34 */
35
36 /**
37 * The CiviCRM duplicate discovery engine is based on an
38 * algorithm designed by David Strauss <david@fourkitchens.com>.
39 */
40 class CRM_Dedupe_Finder {
41
42 /**
43 * Return a contact_id-keyed array of arrays of possible dupes
44 * (of the key contact_id) - limited to dupes of $cids if provided.
45 *
46 * @param int $rgid
47 * Rule group id.
48 * @param array $cids
49 * Contact ids to limit the search to.
50 *
51 * @param bool $checkPermissions
52 * Respect logged in user permissions.
53 *
54 * @param int $limit
55 * Optional limit. This limits the number of contacts for which the code will
56 * attempt to find matches.
57 *
58 * @return array
59 * Array of (cid1, cid2, weight) dupe triples
60 *
61 * @throws CiviCRM_API3_Exception
62 * @throws Exception
63 */
64 public static function dupes($rgid, $cids = array(), $checkPermissions = TRUE, $limit = NULL) {
65 $rgBao = new CRM_Dedupe_BAO_RuleGroup();
66 $rgBao->id = $rgid;
67 $rgBao->contactIds = $cids;
68 if (!$rgBao->find(TRUE)) {
69 CRM_Core_Error::fatal("Dedupe rule not found for selected contacts");
70 }
71 if (empty($rgBao->contactIds) && !empty($limit)) {
72 $limitedContacts = civicrm_api3('Contact', 'get', array(
73 'return' => 'id',
74 'contact_type' => $rgBao->contact_type,
75 'options' => array('limit' => $limit),
76 ));
77 $rgBao->contactIds = array_keys($limitedContacts['values']);
78 }
79
80 $rgBao->fillTable();
81 $dao = new CRM_Core_DAO();
82 $dao->query($rgBao->thresholdQuery($checkPermissions));
83 $dupes = array();
84 while ($dao->fetch()) {
85 $dupes[] = array($dao->id1, $dao->id2, $dao->weight);
86 }
87 $dao->query($rgBao->tableDropQuery());
88
89 return $dupes;
90 }
91
92 /**
93 * Return an array of possible dupes, based on the provided array of
94 * params, using the default rule group for the given contact type and
95 * usage.
96 *
97 * check_permission is a boolean flag to indicate if permission should be considered.
98 * default is to always check permissioning but public pages for example might not want
99 * permission to be checked for anonymous users. Refer CRM-6211. We might be beaking
100 * Multi-Site dedupe for public pages.
101 *
102 * @param array $params
103 * Array of params of the form $params[$table][$field] == $value.
104 * @param string $ctype
105 * Contact type to match against.
106 * @param string $used
107 * Dedupe rule group usage ('Unsupervised' or 'Supervised' or 'General').
108 * @param array $except
109 * Array of contacts that shouldn't be considered dupes.
110 * @param int $ruleGroupID
111 * The id of the dedupe rule we should be using.
112 *
113 * @return array
114 * matching contact ids
115 */
116 public static function dupesByParams(
117 $params,
118 $ctype,
119 $used = 'Unsupervised',
120 $except = array(),
121 $ruleGroupID = NULL
122 ) {
123 // If $params is empty there is zero reason to proceed.
124 if (!$params) {
125 return array();
126 }
127
128 $foundByID = FALSE;
129 if ($ruleGroupID) {
130 $rgBao = new CRM_Dedupe_BAO_RuleGroup();
131 $rgBao->id = $ruleGroupID;
132 $rgBao->contact_type = $ctype;
133 if ($rgBao->find(TRUE)) {
134 $foundByID = TRUE;
135 }
136 }
137
138 if (!$foundByID) {
139 $rgBao = new CRM_Dedupe_BAO_RuleGroup();
140 $rgBao->contact_type = $ctype;
141 $rgBao->used = $used;
142 if (!$rgBao->find(TRUE)) {
143 CRM_Core_Error::fatal("$used rule for $ctype does not exist");
144 }
145 }
146 $params['check_permission'] = CRM_Utils_Array::value('check_permission', $params, TRUE);
147
148 if (isset($params['civicrm_phone']['phone_numeric'])) {
149 $orig = $params['civicrm_phone']['phone_numeric'];
150 $params['civicrm_phone']['phone_numeric'] = preg_replace('/[^\d]/', '', $orig);
151 }
152 $rgBao->params = $params;
153 $rgBao->fillTable();
154 $dao = new CRM_Core_DAO();
155 $dao->query($rgBao->thresholdQuery($params['check_permission']));
156 $dupes = array();
157 while ($dao->fetch()) {
158 if (isset($dao->id) && $dao->id) {
159 $dupes[] = $dao->id;
160 }
161 }
162 $dao->query($rgBao->tableDropQuery());
163 return array_diff($dupes, $except);
164 }
165
166 /**
167 * Return a contact_id-keyed array of arrays of possible dupes in the given group.
168 *
169 * @param int $rgid
170 * Rule group id.
171 * @param int $gid
172 * Contact group id (currently, works only with non-smart groups).
173 *
174 * @param int $limit
175 * @return array
176 * array of (cid1, cid2, weight) dupe triples
177 */
178 public static function dupesInGroup($rgid, $gid, $limit = NULL) {
179 $cids = array_keys(CRM_Contact_BAO_Group::getMember($gid, $limit));
180 if (!empty($cids)) {
181 return self::dupes($rgid, $cids);
182 }
183 return array();
184 }
185
186 /**
187 * A hackish function needed to massage CRM_Contact_Form_$ctype::formRule()
188 * object into a valid $params array for dedupe
189 *
190 * @param array $fields
191 * Contact structure from formRule().
192 * @param string $ctype
193 * Contact type of the given contact.
194 *
195 * @return array
196 * valid $params array for dedupe
197 */
198 public static function formatParams($fields, $ctype) {
199 $flat = array();
200 CRM_Utils_Array::flatten($fields, $flat);
201
202 // FIXME: This may no longer be necessary - check inputs
203 $replace_these = array(
204 'individual_prefix' => 'prefix_id',
205 'individual_suffix' => 'suffix_id',
206 'gender' => 'gender_id',
207 );
208 foreach (array('individual_suffix', 'individual_prefix', 'gender') as $name) {
209 if (!empty($fields[$name])) {
210 $flat[$replace_these[$name]] = $flat[$name];
211 unset($flat[$name]);
212 }
213 }
214
215 // handle {birth,deceased}_date
216 foreach (array(
217 'birth_date',
218 'deceased_date',
219 ) as $date) {
220 if (!empty($fields[$date])) {
221 $flat[$date] = $fields[$date];
222 if (is_array($flat[$date])) {
223 $flat[$date] = CRM_Utils_Date::format($flat[$date]);
224 }
225 $flat[$date] = CRM_Utils_Date::processDate($flat[$date]);
226 }
227 }
228
229 if (!empty($flat['contact_source'])) {
230 $flat['source'] = $flat['contact_source'];
231 unset($flat['contact_source']);
232 }
233
234 // handle preferred_communication_method
235 if (!empty($fields['preferred_communication_method'])) {
236 $methods = array_intersect($fields['preferred_communication_method'], array('1'));
237 $methods = array_keys($methods);
238 sort($methods);
239 if ($methods) {
240 $flat['preferred_communication_method'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $methods) . CRM_Core_DAO::VALUE_SEPARATOR;
241 }
242 }
243
244 // handle custom data
245 $tree = CRM_Core_BAO_CustomGroup::getTree($ctype, NULL, NULL, -1);
246 CRM_Core_BAO_CustomGroup::postProcess($tree, $fields, TRUE);
247 foreach ($tree as $key => $cg) {
248 if (!is_int($key)) {
249 continue;
250 }
251 foreach ($cg['fields'] as $cf) {
252 $flat[$cf['column_name']] = CRM_Utils_Array::value('data', $cf['customValue']);
253 }
254 }
255
256 // if the key is dotted, keep just the last part of it
257 foreach ($flat as $key => $value) {
258 if (substr_count($key, '.')) {
259 $last = explode('.', $key);
260 $last = array_pop($last);
261 // make sure the first occurrence is kept, not the last
262 if (!isset($flat[$last])) {
263 $flat[$last] = $value;
264 }
265 unset($flat[$key]);
266 }
267 }
268
269 // drop the -digit (and -Primary, for CRM-3902) postfixes (so event registration's $flat['email-5'] becomes $flat['email'])
270 // FIXME: CRM-5026 should be fixed here; the below clobbers all address info; we should split off address fields and match
271 // the -digit to civicrm_address.location_type_id and -Primary to civicrm_address.is_primary
272 foreach ($flat as $key => $value) {
273 $matches = array();
274 if (preg_match('/(.*)-(Primary-[\d+])$|(.*)-(\d+|Primary)$/', $key, $matches)) {
275 $return = array_values(array_filter($matches));
276 $flat[$return[1]] = $value;
277 unset($flat[$key]);
278 }
279 }
280
281 $params = array();
282 $supportedFields = CRM_Dedupe_BAO_RuleGroup::supportedFields($ctype);
283 if (is_array($supportedFields)) {
284 foreach ($supportedFields as $table => $fields) {
285 if ($table == 'civicrm_address') {
286 // for matching on civicrm_address fields, we also need the location_type_id
287 $fields['location_type_id'] = '';
288 // FIXME: we also need to do some hacking for id and name fields, see CRM-3902’s comments
289 $fixes = array(
290 'address_name' => 'name',
291 'country' => 'country_id',
292 'state_province' => 'state_province_id',
293 'county' => 'county_id',
294 );
295 foreach ($fixes as $orig => $target) {
296 if (!empty($flat[$orig])) {
297 $params[$table][$target] = $flat[$orig];
298 }
299 }
300 }
301 if ($table == 'civicrm_phone') {
302 $fixes = array(
303 'phone' => 'phone_numeric',
304 );
305 foreach ($fixes as $orig => $target) {
306 if (!empty($flat[$orig])) {
307 $params[$table][$target] = $flat[$orig];
308 }
309 }
310 }
311 foreach ($fields as $field => $title) {
312 if (!empty($flat[$field])) {
313 $params[$table][$field] = $flat[$field];
314 }
315 }
316 }
317 }
318 return $params;
319 }
320
321 /**
322 * Parse duplicate pairs into a standardised array and store in the prev_next_cache.
323 *
324 * @param array $foundDupes
325 * @param string $cacheKeyString
326 *
327 * @return array Dupe pairs with the keys
328 * Dupe pairs with the keys
329 * -srcID
330 * -srcName
331 * -dstID
332 * -dstName
333 * -weight
334 * -canMerge
335 *
336 * @throws CRM_Core_Exception
337 */
338 public static function parseAndStoreDupePairs($foundDupes, $cacheKeyString) {
339 $cids = array();
340 foreach ($foundDupes as $dupe) {
341 $cids[$dupe[0]] = 1;
342 $cids[$dupe[1]] = 1;
343 }
344 $cidString = implode(', ', array_keys($cids));
345
346 $dao = CRM_Core_DAO::executeQuery("SELECT id, display_name FROM civicrm_contact WHERE id IN ($cidString) ORDER BY sort_name");
347 $displayNames = array();
348 while ($dao->fetch()) {
349 $displayNames[$dao->id] = $dao->display_name;
350 }
351
352 $userId = CRM_Core_Session::getLoggedInContactID();
353 foreach ($foundDupes as $dupes) {
354 $srcID = $dupes[1];
355 $dstID = $dupes[0];
356 // The logged in user should never be the src (ie. the contact to be removed).
357 if ($srcID == $userId) {
358 $srcID = $dstID;
359 $dstID = $userId;
360 }
361
362 $mainContacts[] = $row = array(
363 'dstID' => $dstID,
364 'dstName' => $displayNames[$dstID],
365 'srcID' => $srcID,
366 'srcName' => $displayNames[$srcID],
367 'weight' => $dupes[2],
368 'canMerge' => TRUE,
369 );
370
371 $data = CRM_Core_DAO::escapeString(serialize($row));
372 $values[] = " ( 'civicrm_contact', $dstID, $srcID, '$cacheKeyString', '$data' ) ";
373 }
374 CRM_Core_BAO_PrevNextCache::setItem($values);
375 return $mainContacts;
376 }
377
378 }