Merge pull request #22664 from braders/membershipview-default-values
[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 * @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
79 /**
80 * Display daily system status alerts (admin only).
81 */
82 public function showPeriodicAlerts() {
83 if (CRM_Core_Permission::check('administer CiviCRM system')) {
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
91 $statusMessages = [];
92 $maxSeverity = 0;
93 foreach ($this->checkAll() as $message) {
94 if (!$message->isVisible()) {
95 continue;
96 }
97 if ($message->getLevel() >= 3) {
98 $maxSeverity = max($maxSeverity, $message->getLevel());
99 $statusMessage = $message->getMessage();
100 $statusMessages[] = $statusTitle = $message->getTitle();
101 }
102 }
103
104 if ($statusMessages) {
105 if (count($statusMessages) > 1) {
106 $statusTitle = self::toStatusLabel($maxSeverity);
107 $statusMessage = '<ul><li>' . implode('</li><li>', $statusMessages) . '</li></ul>';
108 }
109
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';
113 CRM_Core_Session::setStatus($statusMessage, $statusTitle, $statusType);
114 }
115 }
116 }
117 }
118
119 /**
120 * Sort messages based upon severity
121 *
122 * @param CRM_Utils_Check_Message $a
123 * @param CRM_Utils_Check_Message $b
124 * @return int
125 */
126 public static function severitySort($a, $b) {
127 $aSeverity = $a->getLevel();
128 $bSeverity = $b->getLevel();
129 if ($aSeverity == $bSeverity) {
130 return strcmp($a->getName(), $b->getName());
131 }
132 // The Message constructor guarantees that these will always be integers.
133 return ($aSeverity <=> $bSeverity);
134 }
135
136 /**
137 * Get the integer value (useful for thresholds) of the severity.
138 *
139 * @param int|string $severity
140 * the value to look up
141 * @param bool $reverse
142 * whether to find the constant from the integer
143 * @return string|int
144 * @throws \CRM_Core_Exception
145 */
146 public static function severityMap($severity, $reverse = FALSE) {
147 if ($reverse) {
148 if (isset(self::$severityList[$severity])) {
149 return self::$severityList[$severity];
150 }
151 }
152 else {
153 // Lowercase string-based severities
154 $severity = strtolower($severity);
155 if (in_array($severity, self::$severityList)) {
156 return array_search($severity, self::$severityList);
157 }
158 }
159 throw new CRM_Core_Exception('Invalid PSR Severity Level');
160 }
161
162 /**
163 * Throw an exception if any of the checks fail.
164 *
165 * @param array|null $messages
166 * [CRM_Utils_Check_Message]
167 * @param string $threshold
168 *
169 * @throws \CRM_Core_Exception
170 * @throws \Exception
171 */
172 public function assertValid($messages = NULL, $threshold = \Psr\Log\LogLevel::ERROR) {
173 if ($messages === NULL) {
174 $messages = $this->checkAll();
175 }
176 $minLevel = self::severityMap($threshold);
177 $errors = [];
178 foreach ($messages as $message) {
179 if ($message->getLevel() >= $minLevel) {
180 $errors[] = $message->toArray();
181 }
182 }
183 if ($errors) {
184 throw new Exception("System $threshold: " . print_r($errors, TRUE));
185 }
186 }
187
188 /**
189 * Run all enabled system checks.
190 *
191 * This functon is wrapped by the System.check api.
192 *
193 * Calls hook_civicrm_check() for extensions to add or modify messages.
194 * @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_check/
195 *
196 * @param bool $max
197 * Whether to return just the maximum non-hushed severity
198 *
199 * @return CRM_Utils_Check_Message[]
200 */
201 public static function checkAll($max = FALSE) {
202 $messages = self::checkStatus();
203
204 uasort($messages, [__CLASS__, 'severitySort']);
205
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
215 Civi::cache('checks')->set('systemStatusCheckResult', $maxSeverity);
216
217 return ($max) ? $maxSeverity : $messages;
218 }
219
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
252 /**
253 * @param int $level
254 * @return string
255 */
256 public static function toStatusLabel($level) {
257 if ($level > 1) {
258 $options = array_column(self::getSeverityOptions(), 'label', 'id');
259 return ts('System Status: %1', [1 => $options[$level]]);
260 }
261 return ts('System Status: Ok');
262 }
263
264 }