3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2017
37 * The CiviCRM duplicate discovery engine is based on an
38 * algorithm designed by David Strauss <david@fourkitchens.com>.
40 class CRM_Dedupe_Finder
{
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.
49 * Contact ids to limit the search to.
51 * @param bool $checkPermissions
52 * Respect logged in user permissions.
55 * Optional limit. This limits the number of contacts for which the code will
56 * attempt to find matches.
59 * Array of (cid1, cid2, weight) dupe triples
61 * @throws CiviCRM_API3_Exception
64 public static function dupes($rgid, $cids = array(), $checkPermissions = TRUE, $limit = NULL) {
65 $rgBao = new CRM_Dedupe_BAO_RuleGroup();
67 $rgBao->contactIds
= $cids;
68 if (!$rgBao->find(TRUE)) {
69 CRM_Core_Error
::fatal("Dedupe rule not found for selected contacts");
71 if (empty($rgBao->contactIds
) && !empty($limit)) {
72 $limitedContacts = civicrm_api3('Contact', 'get', array(
74 'contact_type' => $rgBao->contact_type
,
75 'options' => array('limit' => $limit),
77 $rgBao->contactIds
= array_keys($limitedContacts['values']);
81 $dao = new CRM_Core_DAO();
82 $dao->query($rgBao->thresholdQuery($checkPermissions));
84 while ($dao->fetch()) {
85 $dupes[] = array($dao->id1
, $dao->id2
, $dao->weight
);
87 $dao->query($rgBao->tableDropQuery());
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
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.
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.
114 * matching contact ids
116 public static function dupesByParams(
119 $used = 'Unsupervised',
123 // If $params is empty there is zero reason to proceed.
130 $rgBao = new CRM_Dedupe_BAO_RuleGroup();
131 $rgBao->id
= $ruleGroupID;
132 $rgBao->contact_type
= $ctype;
133 if ($rgBao->find(TRUE)) {
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");
146 $params['check_permission'] = CRM_Utils_Array
::value('check_permission', $params, TRUE);
148 $rgBao->params
= $params;
150 $dao = new CRM_Core_DAO();
151 $dao->query($rgBao->thresholdQuery($params['check_permission']));
153 while ($dao->fetch()) {
154 if (isset($dao->id
) && $dao->id
) {
158 $dao->query($rgBao->tableDropQuery());
159 return array_diff($dupes, $except);
163 * Return a contact_id-keyed array of arrays of possible dupes in the given group.
168 * Contact group id (currently, works only with non-smart groups).
172 * array of (cid1, cid2, weight) dupe triples
174 public static function dupesInGroup($rgid, $gid, $limit = NULL) {
175 $cids = array_keys(CRM_Contact_BAO_Group
::getMember($gid, $limit));
177 return self
::dupes($rgid, $cids);
183 * A hackish function needed to massage CRM_Contact_Form_$ctype::formRule()
184 * object into a valid $params array for dedupe
186 * @param array $fields
187 * Contact structure from formRule().
188 * @param string $ctype
189 * Contact type of the given contact.
192 * valid $params array for dedupe
194 public static function formatParams($fields, $ctype) {
196 CRM_Utils_Array
::flatten($fields, $flat);
198 // FIXME: This may no longer be necessary - check inputs
199 $replace_these = array(
200 'individual_prefix' => 'prefix_id',
201 'individual_suffix' => 'suffix_id',
202 'gender' => 'gender_id',
204 foreach (array('individual_suffix', 'individual_prefix', 'gender') as $name) {
205 if (!empty($fields[$name])) {
206 $flat[$replace_these[$name]] = $flat[$name];
211 // handle {birth,deceased}_date
216 if (!empty($fields[$date])) {
217 $flat[$date] = $fields[$date];
218 if (is_array($flat[$date])) {
219 $flat[$date] = CRM_Utils_Date
::format($flat[$date]);
221 $flat[$date] = CRM_Utils_Date
::processDate($flat[$date]);
225 if (!empty($flat['contact_source'])) {
226 $flat['source'] = $flat['contact_source'];
227 unset($flat['contact_source']);
230 // handle preferred_communication_method
231 if (!empty($fields['preferred_communication_method'])) {
232 $methods = array_intersect($fields['preferred_communication_method'], array('1'));
233 $methods = array_keys($methods);
236 $flat['preferred_communication_method'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $methods) . CRM_Core_DAO
::VALUE_SEPARATOR
;
240 // handle custom data
241 $tree = CRM_Core_BAO_CustomGroup
::getTree($ctype, CRM_Core_DAO
::$_nullObject, NULL, -1);
242 CRM_Core_BAO_CustomGroup
::postProcess($tree, $fields, TRUE);
243 foreach ($tree as $key => $cg) {
247 foreach ($cg['fields'] as $cf) {
248 $flat[$cf['column_name']] = CRM_Utils_Array
::value('data', $cf['customValue']);
252 // if the key is dotted, keep just the last part of it
253 foreach ($flat as $key => $value) {
254 if (substr_count($key, '.')) {
255 $last = explode('.', $key);
256 $last = array_pop($last);
257 // make sure the first occurrence is kept, not the last
258 if (!isset($flat[$last])) {
259 $flat[$last] = $value;
265 // drop the -digit (and -Primary, for CRM-3902) postfixes (so event registration's $flat['email-5'] becomes $flat['email'])
266 // FIXME: CRM-5026 should be fixed here; the below clobbers all address info; we should split off address fields and match
267 // the -digit to civicrm_address.location_type_id and -Primary to civicrm_address.is_primary
268 foreach ($flat as $key => $value) {
270 if (preg_match('/(.*)-(Primary-[\d+])$|(.*)-(\d+|Primary)$/', $key, $matches)) {
271 $return = array_values(array_filter($matches));
272 $flat[$return[1]] = $value;
278 $supportedFields = CRM_Dedupe_BAO_RuleGroup
::supportedFields($ctype);
279 if (is_array($supportedFields)) {
280 foreach ($supportedFields as $table => $fields) {
281 if ($table == 'civicrm_address') {
282 // for matching on civicrm_address fields, we also need the location_type_id
283 $fields['location_type_id'] = '';
284 // FIXME: we also need to do some hacking for id and name fields, see CRM-3902’s comments
286 'address_name' => 'name',
287 'country' => 'country_id',
288 'state_province' => 'state_province_id',
289 'county' => 'county_id',
291 foreach ($fixes as $orig => $target) {
292 if (!empty($flat[$orig])) {
293 $params[$table][$target] = $flat[$orig];
297 foreach ($fields as $field => $title) {
298 if (!empty($flat[$field])) {
299 $params[$table][$field] = $flat[$field];
308 * Parse duplicate pairs into a standardised array and store in the prev_next_cache.
310 * @param array $foundDupes
311 * @param string $cacheKeyString
313 * @return array Dupe pairs with the keys
314 * Dupe pairs with the keys
322 * @throws CRM_Core_Exception
324 public static function parseAndStoreDupePairs($foundDupes, $cacheKeyString) {
326 foreach ($foundDupes as $dupe) {
330 $cidString = implode(', ', array_keys($cids));
332 $dao = CRM_Core_DAO
::executeQuery("SELECT id, display_name FROM civicrm_contact WHERE id IN ($cidString) ORDER BY sort_name");
333 $displayNames = array();
334 while ($dao->fetch()) {
335 $displayNames[$dao->id
] = $dao->display_name
;
338 $userId = CRM_Core_Session
::getLoggedInContactID();
339 foreach ($foundDupes as $dupes) {
342 // The logged in user should never be the src (ie. the contact to be removed).
343 if ($srcID == $userId) {
348 $mainContacts[] = $row = array(
350 'dstName' => $displayNames[$dstID],
352 'srcName' => $displayNames[$srcID],
353 'weight' => $dupes[2],
357 $data = CRM_Core_DAO
::escapeString(serialize($row));
358 $values[] = " ( 'civicrm_contact', $dstID, $srcID, '$cacheKeyString', '$data' ) ";
360 CRM_Core_BAO_PrevNextCache
::setItem($values);
361 return $mainContacts;