Merge pull request #23309 from civicrm/5.49
[civicrm-core.git] / CRM / Utils / Check.php
CommitLineData
1248c859
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
1248c859 5 | |
bc77d7c0
TO
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 |
1248c859 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
1248c859
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
1248c859
TO
16 */
17class CRM_Utils_Check {
50bfb460 18 // How often to run checks and notify admins about issues.
7d029160 19 const CHECK_TIMER = 86400;
1248c859 20
e5e4a5b2
CW
21 /**
22 * @var array
23 * @link https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md
24 */
be2fb01f 25 protected static $severityList = [
e5e4a5b2
CW
26 \Psr\Log\LogLevel::DEBUG,
27 \Psr\Log\LogLevel::INFO,
28 \Psr\Log\LogLevel::NOTICE,
29 \Psr\Log\LogLevel::WARNING,
30 \Psr\Log\LogLevel::ERROR,
31 \Psr\Log\LogLevel::CRITICAL,
32 \Psr\Log\LogLevel::ALERT,
33 \Psr\Log\LogLevel::EMERGENCY,
be2fb01f 34 ];
e5e4a5b2 35
1248c859
TO
36 /**
37 * We only need one instance of this object, so we use the
38 * singleton pattern and cache the instance in this variable
39 *
40 * @var object
1248c859
TO
41 */
42 static private $_singleton = NULL;
43
44 /**
45 * Provide static instance of CRM_Utils_Check.
46 *
47 * @return CRM_Utils_Check
48 */
00be9182 49 public static function &singleton() {
1248c859
TO
50 if (!isset(self::$_singleton)) {
51 self::$_singleton = new CRM_Utils_Check();
52 }
53 return self::$_singleton;
54 }
55
0e1b333f
CW
56 /**
57 * @return array
58 */
59 public static function getSeverityList() {
60 return self::$severityList;
61 }
62
c44d3d25
CW
63 /**
64 * @return array[]
65 */
66 public static function getSeverityOptions() {
67 return [
68 ['id' => 0, 'name' => \Psr\Log\LogLevel::DEBUG, 'label' => ts('Debug')],
69 ['id' => 1, 'name' => \Psr\Log\LogLevel::INFO, 'label' => ts('Info')],
70 ['id' => 2, 'name' => \Psr\Log\LogLevel::NOTICE, 'label' => ts('Notice')],
71 ['id' => 3, 'name' => \Psr\Log\LogLevel::WARNING, 'label' => ts('Warning')],
72 ['id' => 4, 'name' => \Psr\Log\LogLevel::ERROR, 'label' => ts('Error')],
73 ['id' => 5, 'name' => \Psr\Log\LogLevel::CRITICAL, 'label' => ts('Critical')],
74 ['id' => 6, 'name' => \Psr\Log\LogLevel::ALERT, 'label' => ts('Alert')],
75 ['id' => 7, 'name' => \Psr\Log\LogLevel::EMERGENCY, 'label' => ts('Emergency')],
76 ];
77 }
78
1248c859 79 /**
f608a24a 80 * Display daily system status alerts (admin only).
1248c859 81 */
f608a24a 82 public function showPeriodicAlerts() {
755a1835 83 if (CRM_Core_Permission::check('administer CiviCRM system')) {
1248c859
TO
84 $session = CRM_Core_Session::singleton();
85 if ($session->timer('check_' . __CLASS__, self::CHECK_TIMER)) {
86
87 // Best attempt at re-securing folders
88 $config = CRM_Core_Config::singleton();
89 $config->cleanup(0, FALSE);
90
be2fb01f 91 $statusMessages = [];
f608a24a
CW
92 $maxSeverity = 0;
93 foreach ($this->checkAll() as $message) {
00eef683
AH
94 if (!$message->isVisible()) {
95 continue;
96 }
f608a24a
CW
97 if ($message->getLevel() >= 3) {
98 $maxSeverity = max($maxSeverity, $message->getLevel());
47e2b515
AH
99 $statusMessage = $message->getMessage();
100 $statusMessages[] = $statusTitle = $message->getTitle();
f0f49b45 101 }
1248c859 102 }
848577e3 103
f608a24a 104 if ($statusMessages) {
848577e3 105 if (count($statusMessages) > 1) {
f608a24a
CW
106 $statusTitle = self::toStatusLabel($maxSeverity);
107 $statusMessage = '<ul><li>' . implode('</li><li>', $statusMessages) . '</li></ul>';
848577e3 108 }
1b366958 109
f608a24a
CW
110 $statusMessage .= '<p><a href="' . CRM_Utils_System::url('civicrm/a/#/status') . '">' . ts('View details and manage alerts') . '</a></p>';
111
112 $statusType = $maxSeverity >= 4 ? 'error' : 'alert';
77fe66d6 113 CRM_Core_Session::setStatus($statusMessage, $statusTitle, $statusType);
848577e3 114 }
1248c859
TO
115 }
116 }
117 }
118
1b366958
AH
119 /**
120 * Sort messages based upon severity
121 *
122 * @param CRM_Utils_Check_Message $a
123 * @param CRM_Utils_Check_Message $b
fd66a333 124 * @return int
1b366958 125 */
7d029160 126 public static function severitySort($a, $b) {
fe8bdad8
CW
127 $aSeverity = $a->getLevel();
128 $bSeverity = $b->getLevel();
1b366958 129 if ($aSeverity == $bSeverity) {
47e2b515 130 return strcmp($a->getName(), $b->getName());
1b366958 131 }
4f2714af 132 // The Message constructor guarantees that these will always be integers.
11d593ed 133 return ($aSeverity <=> $bSeverity);
1b366958
AH
134 }
135
f0f49b45 136 /**
6ea8408d 137 * Get the integer value (useful for thresholds) of the severity.
f0f49b45 138 *
3860d465 139 * @param int|string $severity
6ea8408d
AH
140 * the value to look up
141 * @param bool $reverse
142 * whether to find the constant from the integer
3860d465
CW
143 * @return string|int
144 * @throws \CRM_Core_Exception
f0f49b45 145 */
6ea8408d 146 public static function severityMap($severity, $reverse = FALSE) {
3860d465
CW
147 if ($reverse) {
148 if (isset(self::$severityList[$severity])) {
149 return self::$severityList[$severity];
150 }
151 }
152 else {
153 // Lowercase string-based severities
bc84da84 154 $severity = strtolower($severity);
3860d465
CW
155 if (in_array($severity, self::$severityList)) {
156 return array_search($severity, self::$severityList);
157 }
bc84da84 158 }
3860d465 159 throw new CRM_Core_Exception('Invalid PSR Severity Level');
f0f49b45
TO
160 }
161
c0bc3902 162 /**
fe482240 163 * Throw an exception if any of the checks fail.
7c42ee33 164 *
2024d5b9 165 * @param array|null $messages
c3850204
CW
166 * [CRM_Utils_Check_Message]
167 * @param string $threshold
f4aaa82a 168 *
c3850204
CW
169 * @throws \CRM_Core_Exception
170 * @throws \Exception
c0bc3902 171 */
c3850204 172 public function assertValid($messages = NULL, $threshold = \Psr\Log\LogLevel::ERROR) {
7c42ee33
TO
173 if ($messages === NULL) {
174 $messages = $this->checkAll();
175 }
c3850204 176 $minLevel = self::severityMap($threshold);
be2fb01f 177 $errors = [];
c3850204
CW
178 foreach ($messages as $message) {
179 if ($message->getLevel() >= $minLevel) {
180 $errors[] = $message->toArray();
c0bc3902 181 }
c3850204
CW
182 }
183 if ($errors) {
184 throw new Exception("System $threshold: " . print_r($errors, TRUE));
c0bc3902
TO
185 }
186 }
187
1248c859 188 /**
675e2573 189 * Run all enabled system checks.
1248c859 190 *
5f3c0af5 191 * This functon is wrapped by the System.check api.
1248c859 192 *
5f3c0af5 193 * Calls hook_civicrm_check() for extensions to add or modify messages.
d05f3550 194 * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_check/
1248c859 195 *
7d029160
NM
196 * @param bool $max
197 * Whether to return just the maximum non-hushed severity
198 *
675e2573 199 * @return CRM_Utils_Check_Message[]
1248c859 200 */
7d029160 201 public static function checkAll($max = FALSE) {
675e2573 202 $messages = self::checkStatus();
260e353b 203
be2fb01f 204 uasort($messages, [__CLASS__, 'severitySort']);
47e2b515 205
7d029160
NM
206 $maxSeverity = 1;
207 foreach ($messages as $message) {
208 if (!$message->isVisible()) {
209 continue;
210 }
211 $maxSeverity = max(1, $message->getLevel());
212 break;
213 }
214
b1fc1ab0 215 Civi::cache('checks')->set('systemStatusCheckResult', $maxSeverity);
7d029160
NM
216
217 return ($max) ? $maxSeverity : $messages;
1248c859
TO
218 }
219
675e2573
CW
220 /**
221 * @param array $statusNames
222 * Optionally specify the names of specific checks to run, or leave empty to run all
223 * @param bool $includeDisabled
224 * Run checks that have been explicitly disabled (default false)
225 *
226 * @return CRM_Utils_Check_Message[]
227 */
228 public static function checkStatus($statusNames = [], $includeDisabled = FALSE) {
229 $messages = [];
230 $checksNeeded = $statusNames;
231 foreach (glob(__DIR__ . '/Check/Component/*.php') as $filePath) {
232 $className = 'CRM_Utils_Check_Component_' . basename($filePath, '.php');
233 /* @var CRM_Utils_Check_Component $component */
234 $component = new $className();
235 if ($includeDisabled || $component->isEnabled()) {
236 $messages = array_merge($messages, $component->checkAll($statusNames, $includeDisabled));
237 }
238 if ($statusNames) {
239 // Early return if we have already run (or skipped) all the requested checks.
240 $checksNeeded = array_diff($checksNeeded, $component->getAllChecks());
241 if (!$checksNeeded) {
242 return $messages;
243 }
244 }
245 }
246
247 CRM_Utils_Hook::check($messages, $statusNames, $includeDisabled);
248
249 return $messages;
250 }
251
f608a24a
CW
252 /**
253 * @param int $level
254 * @return string
255 */
256 public static function toStatusLabel($level) {
c44d3d25
CW
257 if ($level > 1) {
258 $options = array_column(self::getSeverityOptions(), 'label', 'id');
259 return ts('System Status: %1', [1 => $options[$level]]);
f608a24a 260 }
c44d3d25 261 return ts('System Status: Ok');
f608a24a
CW
262 }
263
f4aaa82a 264}