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