3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
37 * The CiviCRM duplicate discovery engine is based on an
38 * algorithm designed by David Strauss <david@fourkitchens.com>.
40 class CRM_Dedupe_BAO_RuleGroup
extends CRM_Dedupe_DAO_RuleGroup
{
43 * Ids of the contacts to limit the SQL queries (whole-database queries otherwise)
45 var $contactIds = array();
48 * Set the contact IDs to restrict the dedupe to.
50 * @param array $contactIds
52 public function setContactIds($contactIds) {
53 $this->contactIds
= $contactIds;
57 * Params to dedupe against (queries against the whole contact set otherwise)
59 var $params = array();
62 * If there are no rules in rule group.
67 * Return a structure holding the supported tables, fields and their titles
69 * @param string $requestedType
70 * The requested contact type.
73 * a table-keyed array of field-keyed arrays holding supported fields' titles
75 public static function &supportedFields($requestedType) {
76 static $fields = NULL;
78 // this is needed, as we're piggy-backing importableFields() below
79 $replacements = array(
80 'civicrm_country.name' => 'civicrm_address.country_id',
81 'civicrm_county.name' => 'civicrm_address.county_id',
82 'civicrm_state_province.name' => 'civicrm_address.state_province_id',
83 'gender.label' => 'civicrm_contact.gender_id',
84 'individual_prefix.label' => 'civicrm_contact.prefix_id',
85 'individual_suffix.label' => 'civicrm_contact.suffix_id',
86 'addressee.label' => 'civicrm_contact.addressee_id',
87 'email_greeting.label' => 'civicrm_contact.email_greeting_id',
88 'postal_greeting.label' => 'civicrm_contact.postal_greeting_id',
89 'civicrm_phone.phone' => 'civicrm_phone.phone_numeric',
91 // the table names we support in dedupe rules - a filter for importableFields()
92 $supportedTables = array(
102 foreach (array('Individual', 'Organization', 'Household') as $ctype) {
103 // take the table.field pairs and their titles from importableFields() if the table is supported
104 foreach (CRM_Contact_BAO_Contact
::importableFields($ctype) as $iField) {
105 if (isset($iField['where'])) {
106 $where = $iField['where'];
107 if (isset($replacements[$where])) {
108 $where = $replacements[$where];
110 list($table, $field) = explode('.', $where);
111 if (!in_array($table, $supportedTables)) {
114 $fields[$ctype][$table][$field] = $iField['title'];
117 // add custom data fields
118 foreach (CRM_Core_BAO_CustomGroup
::getTree($ctype, CRM_Core_DAO
::$_nullObject, NULL, -1) as $key => $cg) {
122 foreach ($cg['fields'] as $cf) {
123 $fields[$ctype][$cg['table_name']][$cf['column_name']] = $cf['label'];
128 CRM_Utils_Hook
::dupeQuery(CRM_Core_DAO
::$_nullObject, 'supportedFields', $fields);
129 return $fields[$requestedType];
133 * Return the SQL query for dropping the temporary table.
135 public function tableDropQuery() {
136 return 'DROP TEMPORARY TABLE IF EXISTS dedupe';
140 * Return a set of SQL queries whose cummulative weights will mark matched
141 * records for the RuleGroup::threasholdQuery() to retrieve.
143 public function tableQuery() {
144 // make sure we've got a fetched dbrecord, not sure if this is enforced
145 if (!$this->name
== NULL ||
$this->is_reserved
== NULL) {
149 // Reserved Rule Groups can optionally get special treatment by
150 // implementing an optimization class and returning a query array.
151 if ($this->is_reserved
&&
152 CRM_Utils_File
::isIncludable("CRM/Dedupe/BAO/QueryBuilder/{$this->name}.php")
154 $command = empty($this->params
) ?
'internal' : 'record';
155 $queries = call_user_func(array("CRM_Dedupe_BAO_QueryBuilder_{$this->name}", $command), $this);
158 // All other rule groups have queries generated by the member dedupe
159 // rules defined in the administrative interface.
161 // Find all rules contained by this script sorted by weight so that
162 // their execution can be short circuited on RuleGroup::fillTable()
163 $bao = new CRM_Dedupe_BAO_Rule();
164 $bao->dedupe_rule_group_id
= $this->id
;
165 $bao->orderBy('rule_weight DESC');
168 // Generate a SQL query for each rule in the rule group that is
169 // tailored to respect the param and contactId options provided.
171 while ($bao->fetch()) {
172 $bao->contactIds
= $this->contactIds
;
173 $bao->params
= $this->params
;
175 // Skipping empty rules? Empty rules shouldn't exist; why check?
176 if ($query = $bao->sql()) {
177 $queries["{$bao->rule_table}.{$bao->rule_field}.{$bao->rule_weight}"] = $query;
182 // if there are no rules in this rule group
183 // add an empty query fulfilling the pattern
185 $this->noRules
= TRUE;
192 public function fillTable() {
193 // get the list of queries handy
194 $tableQueries = $this->tableQuery();
196 if ($this->params
&& !$this->noRules
) {
197 $tempTableQuery = "CREATE TEMPORARY TABLE dedupe (id1 int, weight int, UNIQUE UI_id1 (id1)) ENGINE=MyISAM";
198 $insertClause = "INSERT INTO dedupe (id1, weight)";
199 $groupByClause = "GROUP BY id1";
200 $dupeCopyJoin = " JOIN dedupe_copy ON dedupe_copy.id1 = t1.column WHERE ";
203 $tempTableQuery = "CREATE TEMPORARY TABLE dedupe (id1 int, id2 int, weight int, UNIQUE UI_id1_id2 (id1, id2)) ENGINE=MyISAM";
204 $insertClause = "INSERT INTO dedupe (id1, id2, weight)";
205 $groupByClause = "GROUP BY id1, id2";
206 $dupeCopyJoin = " JOIN dedupe_copy ON dedupe_copy.id1 = t1.column AND dedupe_copy.id2 = t2.column WHERE ";
208 $patternColumn = '/t1.(\w+)/';
209 $exclWeightSum = array();
212 $dao = new CRM_Core_DAO();
213 $dao->query($tempTableQuery);
215 CRM_Utils_Hook
::dupeQuery($this, 'table', $tableQueries);
217 while (!empty($tableQueries)) {
218 list($isInclusive, $isDie) = self
::isQuerySetInclusive($tableQueries, $this->threshold
, $exclWeightSum);
221 // order queries by table count
222 self
::orderByTableCount($tableQueries);
224 $weightSum = array_sum($exclWeightSum);
225 $searchWithinDupes = !empty($exclWeightSum) ?
1 : 0;
227 while (!empty($tableQueries)) {
228 // extract the next query ( and weight ) to be executed
229 $fieldWeight = array_keys($tableQueries);
230 $fieldWeight = $fieldWeight[0];
231 $query = array_shift($tableQueries);
233 if ($searchWithinDupes) {
234 // get prepared to search within already found dupes if $searchWithinDupes flag is set
235 $dao->query("DROP TEMPORARY TABLE IF EXISTS dedupe_copy");
236 $dao->query("CREATE TEMPORARY TABLE dedupe_copy SELECT * FROM dedupe WHERE weight >= {$weightSum}");
239 preg_match($patternColumn, $query, $matches);
240 $query = str_replace(' WHERE ', str_replace('column', $matches[1], $dupeCopyJoin), $query);
242 $searchWithinDupes = 1;
244 // construct and execute the intermediate query
245 $query = "{$insertClause} {$query} {$groupByClause} ON DUPLICATE KEY UPDATE weight = weight + VALUES(weight)";
248 // FIXME: we need to be more acurate with affected rows, especially for insert vs duplicate insert.
249 // And that will help optimize further.
250 $affectedRows = $dao->affectedRows();
253 // In an inclusive situation, failure of any query means no further processing -
254 if ($affectedRows == 0) {
255 // reset to make sure no further execution is done.
256 $tableQueries = array();
259 $weightSum = substr($fieldWeight, strrpos($fieldWeight, '.') +
1) +
$weightSum;
261 // An exclusive situation -
264 // since queries are already sorted by weights, we can continue as is
265 $fieldWeight = array_keys($tableQueries);
266 $fieldWeight = $fieldWeight[0];
267 $query = array_shift($tableQueries);
268 $query = "{$insertClause} {$query} {$groupByClause} ON DUPLICATE KEY UPDATE weight = weight + VALUES(weight)";
270 if ($dao->affectedRows() >= 1) {
271 $exclWeightSum[] = substr($fieldWeight, strrpos($fieldWeight, '.') +
1);
276 // its a die situation
283 * Function to determine if a given query set contains inclusive or exclusive set of weights.
284 * The function assumes that the query set is already ordered by weight in desc order.
285 * @param $tableQueries
287 * @param array $exclWeightSum
291 public static function isQuerySetInclusive($tableQueries, $threshold, $exclWeightSum = array()) {
293 foreach ($tableQueries as $key => $query) {
294 $input[] = substr($key, strrpos($key, '.') +
1);
297 if (!empty($exclWeightSum)) {
298 $input = array_merge($input, $exclWeightSum);
302 if (count($input) == 1) {
303 return array(FALSE, $input[0] < $threshold);
306 $totalCombinations = 0;
307 for ($i = 0; $i < count($input); $i++
) {
308 $combination = array($input[$i]);
309 if (array_sum($combination) >= $threshold) {
310 $totalCombinations++
;
313 for ($j = $i +
1; $j < count($input); $j++
) {
314 $combination[] = $input[$j];
315 if (array_sum($combination) >= $threshold) {
316 $totalCombinations++
;
320 return array($totalCombinations == 1, $totalCombinations <= 0);
324 * sort queries by number of records for the table associated with them.
325 * @param $tableQueries
327 public static function orderByTableCount(&$tableQueries) {
328 static $tableCount = array();
330 $tempArray = array();
331 foreach ($tableQueries as $key => $query) {
332 $table = explode(".", $key);
334 if (!array_key_exists($table, $tableCount)) {
335 $query = "SELECT COUNT(*) FROM {$table}";
336 $tableCount[$table] = CRM_Core_DAO
::singleValueQuery($query);
338 $tempArray[$key] = $tableCount[$table];
342 foreach ($tempArray as $key => $count) {
343 $tempArray[$key] = $tableQueries[$key];
345 $tableQueries = $tempArray;
349 * Return the SQL query for getting only the interesting results out of the dedupe table.
351 * @$checkPermission boolean $params a flag to indicate if permission should be considered.
352 * default is to always check permissioning but public pages for example might not want
353 * permission to be checked for anonymous users. Refer CRM-6211. We might be beaking
354 * Multi-Site dedupe for public pages.
356 * @param bool $checkPermission
360 public function thresholdQuery($checkPermission = TRUE) {
361 $this->_aclFrom
= '';
362 // CRM-6603: anonymous dupechecks side-step ACLs
363 $this->_aclWhere
= ' AND is_deleted = 0 ';
365 if ($this->params
&& !$this->noRules
) {
366 if ($checkPermission) {
367 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause('civicrm_contact');
368 $this->_aclWhere
= $this->_aclWhere ?
"AND {$this->_aclWhere}" : '';
370 $query = "SELECT dedupe.id1 as id
371 FROM dedupe JOIN civicrm_contact ON dedupe.id1 = civicrm_contact.id {$this->_aclFrom}
372 WHERE contact_type = '{$this->contact_type}' {$this->_aclWhere}
373 AND weight >= {$this->threshold}";
376 $this->_aclWhere
= ' AND c1.is_deleted = 0 AND c2.is_deleted = 0';
377 if ($checkPermission) {
378 list($this->_aclFrom
, $this->_aclWhere
) = CRM_Contact_BAO_Contact_Permission
::cacheClause(array('c1', 'c2'));
379 $this->_aclWhere
= $this->_aclWhere ?
"AND {$this->_aclWhere}" : '';
381 $query = "SELECT dedupe.id1, dedupe.id2, dedupe.weight
382 FROM dedupe JOIN civicrm_contact c1 ON dedupe.id1 = c1.id
383 JOIN civicrm_contact c2 ON dedupe.id2 = c2.id {$this->_aclFrom}
384 LEFT JOIN civicrm_dedupe_exception exc ON dedupe.id1 = exc.contact_id1 AND dedupe.id2 = exc.contact_id2
385 WHERE c1.contact_type = '{$this->contact_type}' AND
386 c2.contact_type = '{$this->contact_type}' {$this->_aclWhere}
387 AND weight >= {$this->threshold} AND exc.contact_id1 IS NULL";
390 CRM_Utils_Hook
::dupeQuery($this, 'threshold', $query);
395 * find fields related to a rule group.
397 * @param array $params
400 * (rule field => weight) array and threshold associated to rule group
402 public static function dedupeRuleFieldsWeight($params) {
403 $rgBao = new CRM_Dedupe_BAO_RuleGroup();
404 $rgBao->contact_type
= $params['contact_type'];
405 if (!empty($params['id'])) {
406 // accept an ID if provided
407 $rgBao->id
= $params['id'];
410 $rgBao->used
= $params['used'];
414 $ruleBao = new CRM_Dedupe_BAO_Rule();
415 $ruleBao->dedupe_rule_group_id
= $rgBao->id
;
417 $ruleFields = array();
418 while ($ruleBao->fetch()) {
419 $ruleFields[$ruleBao->rule_field
] = $ruleBao->rule_weight
;
422 return array($ruleFields, $rgBao->threshold
);
426 * Get all of the combinations of fields that would work with a rule.
428 * @param array $rgFields
429 * @param int $threshold
430 * @param array $combos
431 * @param array $running
433 public static function combos($rgFields, $threshold, &$combos, $running = array()) {
434 foreach ($rgFields as $rgField => $weight) {
435 unset($rgFields[$rgField]);
436 $diff = $threshold - $weight;
437 $runningnow = $running;
438 $runningnow[] = $rgField;
440 self
::combos($rgFields, $diff, $combos, $runningnow);
443 $combos[] = $runningnow;
449 * Get an array of rule group id to rule group name
450 * for all th groups for that contactType. If contactType
451 * not specified, do it for all
453 * @param string $contactType
454 * Individual, Household or Organization.
458 * id => "nice name" of rule group
460 public static function getByType($contactType = NULL) {
461 $dao = new CRM_Dedupe_DAO_RuleGroup();
464 $dao->contact_type
= $contactType;
469 while ($dao->fetch()) {
470 $title = !empty($dao->title
) ?
$dao->title
: (!empty($dao->name
) ?
$dao->name
: $dao->contact_type
);
472 $name = "$title - {$dao->used}";
473 $result[$dao->id
] = $name;
480 * Get the cached contact type for a particular rule group.
482 * @param int $rule_group_id
486 public static function getContactTypeForRuleGroup($rule_group_id) {
487 if (!isset(\Civi
::$statics[__CLASS__
]) ||
!isset(\Civi
::$statics[__CLASS__
]['rule_groups'])) {
488 \Civi
::$statics[__CLASS__
]['rule_groups'] = array();
490 if (empty(\Civi
::$statics[__CLASS__
]['rule_groups'][$rule_group_id])) {
491 \Civi
::$statics[__CLASS__
]['rule_groups'][$rule_group_id]['contact_type'] = CRM_Core_DAO
::getFieldValue(
492 'CRM_Dedupe_DAO_RuleGroup',
498 return \Civi
::$statics[__CLASS__
]['rule_groups'][$rule_group_id]['contact_type'];