improvement
[civicrm-core.git] / CRM / Utils / Check.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2015
32 */
33 class CRM_Utils_Check {
34 // How often to run checks and notify admins about issues.
35 const CHECK_TIMER = 86400;
36
37 /**
38 * @var array
39 * @link https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md
40 */
41 protected static $severityList = array(
42 \Psr\Log\LogLevel::DEBUG,
43 \Psr\Log\LogLevel::INFO,
44 \Psr\Log\LogLevel::NOTICE,
45 \Psr\Log\LogLevel::WARNING,
46 \Psr\Log\LogLevel::ERROR,
47 \Psr\Log\LogLevel::CRITICAL,
48 \Psr\Log\LogLevel::ALERT,
49 \Psr\Log\LogLevel::EMERGENCY,
50 );
51
52 /**
53 * We only need one instance of this object, so we use the
54 * singleton pattern and cache the instance in this variable
55 *
56 * @var object
57 */
58 static private $_singleton = NULL;
59
60 /**
61 * Provide static instance of CRM_Utils_Check.
62 *
63 * @return CRM_Utils_Check
64 */
65 public static function &singleton() {
66 if (!isset(self::$_singleton)) {
67 self::$_singleton = new CRM_Utils_Check();
68 }
69 return self::$_singleton;
70 }
71
72 /**
73 * @return array
74 */
75 public static function getSeverityList() {
76 return self::$severityList;
77 }
78
79 /**
80 * Display daily system status alerts (admin only).
81 */
82 public function showPeriodicAlerts() {
83 if (CRM_Core_Permission::check('administer CiviCRM')) {
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 = array();
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 = array();
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 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 http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_check
195 *
196 * @param bool $max
197 * Whether to return just the maximum non-hushed severity
198 *
199 * @return array
200 * Array of CRM_Utils_Check_Message objects
201 */
202 public static function checkAll($max = FALSE) {
203 $messages = array();
204 foreach (glob(__DIR__ . '/Check/Component/*.php') as $filePath) {
205 $className = 'CRM_Utils_Check_Component_' . basename($filePath, '.php');
206 /* @var CRM_Utils_Check_Component $check */
207 $check = new $className();
208 if ($check->isEnabled()) {
209 $messages = array_merge($messages, $check->checkAll());
210 }
211 }
212
213 CRM_Utils_Hook::check($messages);
214
215 uasort($messages, array(__CLASS__, 'severitySort'));
216
217 $maxSeverity = 1;
218 foreach ($messages as $message) {
219 if (!$message->isVisible()) {
220 continue;
221 }
222 $maxSeverity = max(1, $message->getLevel());
223 break;
224 }
225
226 Civi::settings()->set('systemStatusCheckResult', $maxSeverity);
227
228 return ($max) ? $maxSeverity : $messages;
229 }
230
231 /**
232 * @param int $level
233 * @return string
234 */
235 public static function toStatusLabel($level) {
236 switch ($level) {
237 case 7:
238 return ts('System Status: Emergency');
239
240 case 6:
241 return ts('System Status: Alert');
242
243 case 5:
244 return ts('System Status: Critical');
245
246 case 4:
247 return ts('System Status: Error');
248
249 case 3:
250 return ts('System Status: Warning');
251
252 case 2:
253 return ts('System Status: Notice');
254
255 default:
256 return ts('System Status: Ok');
257 }
258 }
259
260 }