Fix dedupe check to not require elevated permissions
[civicrm-core.git] / CRM / Utils / Check / Component / DedupeRules.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 * @package CRM
14 * @copyright CiviCRM LLC https://civicrm.org/licensing
15 */
16 class CRM_Utils_Check_Component_DedupeRules extends CRM_Utils_Check_Component {
17
18 /**
19 * Get dedupe rules, grouped by contact type, for a specific usage
20 *
21 * @param string $used (Supervised, Unsupervised, General)
22 * @return string[]
23 */
24 private static function getContactTypesForRule($used) {
25 $dedupeRules = \Civi\Api4\DedupeRuleGroup::get(FALSE)
26 ->addSelect('contact_type')
27 ->addGroupBy('contact_type')
28 ->addWhere('used', '=', $used)
29 ->execute();
30
31 $types = [];
32 foreach ($dedupeRules as $rule) {
33 if (!in_array($rule, $types)) {
34 $types[] = $rule['contact_type'];
35 }
36 }
37 return $types;
38 }
39
40 /**
41 * Returns an array of missing expected contact types
42 *
43 * @param string[] $rules
44 * @return array
45 */
46 private static function getMissingRules($rules) {
47 $types = array_column(CRM_Contact_BAO_ContactType::basicTypeInfo(), 'label', 'name');
48 return array_diff_key($types, array_flip($rules));
49 }
50
51 /**
52 * @return CRM_Utils_Check_Message[]
53 */
54 public static function checkDedupeRulesExist() {
55 $messages = [];
56
57 $ruleTypes = ['Supervised' => ts('Supervised'), 'Unsupervised' => ts('Unsupervised')];
58 foreach ($ruleTypes as $ruleType => $ruleLabel) {
59 $rules = self::getContactTypesForRule($ruleType);
60 $missingRules = self::getMissingRules($rules);
61 if ($missingRules) {
62 $message = new CRM_Utils_Check_Message(
63 __FUNCTION__ . $ruleType,
64 ts('For CiviCRM to function correctly you must have at least 2 dedupe rules configured for each contact type. You are missing a rule of type %1 for: %2', [1 => $ruleLabel, 2 => implode(', ', $missingRules)]),
65 ts('%1 dedupe rules missing', [1 => $ruleLabel]),
66 \Psr\Log\LogLevel::WARNING,
67 'fa-server'
68 );
69 $message->addAction(
70 ts('Configure dedupe rules'),
71 FALSE,
72 'href',
73 ['path' => 'civicrm/contact/deduperules', 'query' => ['reset' => 1]]
74 );
75 $messages[] = $message;
76 }
77 }
78 return $messages;
79 }
80
81 }