ed441b13ba5edf7c786f486b9e61d78575b65f44
[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 * We only need one instance of this object, so we use the
39 * singleton pattern and cache the instance in this variable
40 *
41 * @var object
42 */
43 static private $_singleton = NULL;
44
45 /**
46 * Provide static instance of CRM_Utils_Check.
47 *
48 * @return CRM_Utils_Check
49 */
50 public static function &singleton() {
51 if (!isset(self::$_singleton)) {
52 self::$_singleton = new CRM_Utils_Check();
53 }
54 return self::$_singleton;
55 }
56
57 /**
58 * Execute "checkAll".
59 *
60 * @param array|NULL $messages
61 * List of CRM_Utils_Check_Message; or NULL if the default list should be fetched.
62 * @param array|string|callable $filter
63 * Restrict messages using a callback filter.
64 * By default, only show warnings and errors.
65 * Set TRUE to show all messages.
66 */
67 public function showPeriodicAlerts($messages = NULL, $filter = array(__CLASS__, 'severityMap')) {
68 if (CRM_Core_Permission::check('administer CiviCRM')
69 && CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'securityAlert', NULL, TRUE)
70 ) {
71 $session = CRM_Core_Session::singleton();
72 if ($session->timer('check_' . __CLASS__, self::CHECK_TIMER)) {
73
74 // Best attempt at re-securing folders
75 $config = CRM_Core_Config::singleton();
76 $config->cleanup(0, FALSE);
77
78 if ($messages === NULL) {
79 $messages = $this->checkAll();
80 }
81 $statusMessages = array();
82 $statusType = 'alert';
83 foreach ($messages as $message) {
84 if (!$message->isVisible()) {
85 continue;
86 }
87 if ($filter === TRUE || $message->getSeverity() >= 3) {
88 $statusType = $message->getSeverity() >= 4 ? 'error' : $statusType;
89 $statusMessage = $message->getMessage();
90 $statusMessages[] = $statusTitle = $message->getTitle();
91 }
92 }
93
94 if (count($statusMessages)) {
95 if (count($statusMessages) > 1) {
96 $statusTitle = ts('Multiple Alerts');
97 $statusMessage = ts('Please check your <a href="%1">status page</a> for a full list and further details.', array(1 => CRM_Utils_System::url('civicrm/a/#/status'))) . '<ul><li>' . implode('</li><li>', $statusMessages) . '</li></ul>';
98 }
99
100 // @todo add link to status page
101 CRM_Core_Session::setStatus($statusMessage, $statusTitle, $statusType);
102 }
103 }
104 }
105 }
106
107 /**
108 * Sort messages based upon severity
109 *
110 * @param CRM_Utils_Check_Message $a
111 * @param CRM_Utils_Check_Message $b
112 * @return int
113 */
114 public static function severitySort($a, $b) {
115 $aSeverity = $a->getSeverity();
116 $bSeverity = $b->getSeverity();
117 if ($aSeverity == $bSeverity) {
118 return strcmp($a->getName(), $b->getName());
119 }
120 // The Message constructor guarantees that these will always be integers.
121 return ($aSeverity < $bSeverity);
122 }
123
124 /**
125 * Get the integer value (useful for thresholds) of the severity.
126 *
127 * @param int|const $severity
128 * the value to look up
129 * @param bool $reverse
130 * whether to find the constant from the integer
131 * @return bool
132 */
133 public static function severityMap($severity, $reverse = FALSE) {
134 // Lowercase string-based severities
135 if (!$reverse) {
136 $severity = strtolower($severity);
137 }
138
139 // See https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md
140 $levels = array(
141 \Psr\Log\LogLevel::EMERGENCY => 7,
142 \Psr\Log\LogLevel::ALERT => 6,
143 \Psr\Log\LogLevel::CRITICAL => 5,
144 \Psr\Log\LogLevel::ERROR => 4,
145 \Psr\Log\LogLevel::WARNING => 3,
146 \Psr\Log\LogLevel::NOTICE => 2,
147 \Psr\Log\LogLevel::INFO => 1,
148 \Psr\Log\LogLevel::DEBUG => 0,
149 );
150 return ($reverse) ? array_search($severity, $levels) : $levels[$severity];
151 }
152
153 /**
154 * Throw an exception if any of the checks fail.
155 *
156 * @param array|NULL $messages list of CRM_Utils_Check_Message; or NULL if the default list should be fetched
157 *
158 * @throws Exception
159 */
160 public function assertValid($messages = NULL) {
161 if ($messages === NULL) {
162 $messages = $this->checkAll();
163 }
164 if (!empty($messages)) {
165 $messagesAsArray = array();
166 foreach ($messages as $message) {
167 $messagesAsArray[] = $message->toArray();
168 }
169 throw new Exception('There are configuration problems with this installation: ' . print_r($messagesAsArray, TRUE));
170 }
171 }
172
173 /**
174 * Run all system checks.
175 *
176 * This functon is wrapped by the System.check api.
177 *
178 * Calls hook_civicrm_check() for extensions to add or modify messages.
179 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_check
180 *
181 * @param bool $max
182 * Whether to return just the maximum non-hushed severity
183 *
184 * @return array
185 * Array of CRM_Utils_Check_Message objects
186 */
187 public static function checkAll($max = FALSE) {
188 $checks = array();
189 $checks[] = new CRM_Utils_Check_Security();
190 $checks[] = new CRM_Utils_Check_Env();
191
192 $compInfo = CRM_Core_Component::getEnabledComponents();
193 foreach ($compInfo as $compObj) {
194 switch ($compObj->info['name']) {
195 case 'CiviCase':
196 $checks[] = new CRM_Utils_Check_Case(CRM_Case_XMLRepository::singleton(), CRM_Case_PseudoConstant::caseType('name'));
197 break;
198
199 default:
200 }
201 }
202
203 $messages = array();
204 foreach ($checks as $check) {
205 $messages = array_merge($messages, $check->checkAll());
206 }
207
208 CRM_Utils_Hook::check($messages);
209
210 foreach ($messages as $key => $message) {
211 $hush = self::checkHushSnooze($message);
212 $messages[$key]->setVisible(!$hush);
213 }
214 uasort($messages, array(__CLASS__, 'severitySort'));
215
216 $maxSeverity = 1;
217 foreach ($messages as $message) {
218 if (!$message->isVisible()) {
219 continue;
220 }
221 $maxSeverity = max(1, $message->getLevel());
222 break;
223 }
224
225 Civi::cache()->set('systemCheckSeverity', $maxSeverity);
226 $timestamp = time();
227 Civi::cache()->set('systemCheckDate', $timestamp);
228
229 return ($max) ? $maxSeverity : $messages;
230 }
231
232 /**
233 * Evaluate if a system check should be hushed/snoozed.
234 *
235 * @param CRM_Utils_Check_Message $message
236 * The message to evaluate.
237 *
238 * @return bool
239 * TRUE means hush/snooze, FALSE means display.
240 * @throws \CiviCRM_API3_Exception
241 */
242 public static function checkHushSnooze($message) {
243 $statusPreferenceParams = array(
244 'name' => $message->getName(),
245 'domain_id' => CRM_Core_Config::domainID(),
246 );
247 // Check if there's a StatusPreference matching this name/domain.
248 $statusPreference = civicrm_api3('StatusPreference', 'get', $statusPreferenceParams);
249 $spid = FALSE;
250 if (isset($statusPreference['id'])) {
251 $spid = $statusPreference['id'];
252 }
253 if ($spid) {
254 // If so, compare severity to StatusPreference->severity.
255 $severity = $message->getSeverity();
256 if ($severity <= $statusPreference['values'][$spid]['ignore_severity']) {
257 // A hush or a snooze has been set. Find out which.
258 if (isset($statusPreference['values'][$spid]['hush_until'])) {
259 // Snooze is set.
260 $today = new DateTime();
261 $snoozeDate = new DateTime($statusPreference['values'][$spid]['hush_until']);
262 if ($today > $snoozeDate) {
263 // Snooze is expired.
264 return FALSE;
265 }
266 else {
267 // Snooze is active.
268 return TRUE;
269 }
270 }
271 else {
272 // Hush.
273 return TRUE;
274 }
275 }
276 }
277 return FALSE;
278 }
279
280 }