forked from eS-IT/es_webcheck
-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMonitoring.php
More file actions
416 lines (359 loc) · 12 KB
/
Copy pathMonitoring.php
File metadata and controls
416 lines (359 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
<?php
/**
* Contao Open Source CMS
* Copyright (C) 2005-2019 Leo Feyer
*
* Formerly known as TYPOlight Open Source CMS.
*
* This program is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program. If not, please visit the Free
* Software Foundation website at <http://www.gnu.org/licenses/>.
*
* PHP version 5
* @copyright Cliff Parnitzky 2014-2019
* @author Cliff Parnitzky
* @package Monitoring
* @license LGPL
* @filesource [eS_Webcheck] by Patrick Froch
*/
/**
* Run in a custom namespace, so the class can be replaced
*/
namespace Monitoring;
/**
* Class Monitoring
*
* Read the text from the given url and compare with test string.
* @copyright Cliff Parnitzky 2014-2019
* @author Cliff Parnitzky
* @package Controller
*/
class Monitoring extends \Backend
{
const STATUS_OKAY = 'OKAY';
const STATUS_INCOMPLETE = 'INCOMPLETE';
const STATUS_ERROR = 'ERROR';
const STATUS_UNTESTED = 'UNTESTED';
const CHECK_TYPE_MANUAL = 'MANUAL';
const CHECK_TYPE_AUTOMATIC = 'AUTOMATIC';
const ERROR_MESSAGE_START = "Scheduled monitoring check ended.\n\nThe following checks ended erroneous:\n\n";
const ERROR_MESSAGE_ENTRY = "- %s %s %s [%s] (%s)\n";
const TEST_CIRCULATION = 1;
const TEST_CIRCULATION_DELAY = 10;
/**
* Constructor
*/
public function __construct()
{
parent::__construct();
$this->loadLanguageFile("tl_monitoring");
}
/**
* Executes a check
*/
public function checkOne()
{
$status = $this->checkSingle(\Input::get('id'), self::CHECK_TYPE_MANUAL);
$this->logDebugMsg("Checking one monitoring entry for ID " . \Input::get('id') . " ended with status: " . $status, __METHOD__);
$urlParam = \Input::get('do');
if (\Input::get('table') == "tl_monitoring_test" && \Input::get('id'))
{
$urlParam .= "&table=tl_monitoring_test&id=" . \Input::get('id');
}
$this->addCheckMessage(\Input::get('id'), $status);
$this->returnToList($urlParam);
}
/**
* Check all monitoring entries
*/
public function checkAll()
{
$status = $this->checkMultiple(self::CHECK_TYPE_MANUAL, true);
$this->logDebugMsg("Checking all monitoring entries ended with status: " . $status, __METHOD__);
$this->returnToList(\Input::get('do'));
}
/**
* Check all monitoring entries triggered by cron
*/
public function checkScheduled()
{
$mailSender = new MonitoringMailSender();
$oldErroneousCheckEntries = $this->removeMailingDeactivatedEntries($this->getErroneousCheckEntries());
$status = $this->checkMultiple(self::CHECK_TYPE_AUTOMATIC);
$this->logDebugMsg("Scheduled checking all monitoring entries ended with status: " . $status, __METHOD__);
$allErroneousCheckEntries = $this->getErroneousCheckEntries();
$newErroneousCheckEntries = $this->removeMailingDeactivatedEntries($allErroneousCheckEntries);
// only needed when there where errors detected
if ($status != self::STATUS_OKAY)
{
$errorMsg = self::ERROR_MESSAGE_START . $this->getCheckEntriesAsString($allErroneousCheckEntries);
$this->log($errorMsg, __METHOD__, TL_ERROR);
if (!empty($newErroneousCheckEntries) && \Config::get('monitoringMailingActive') && \Config::get('monitoringAdminEmail') != '')
{
foreach($newErroneousCheckEntries as $entry)
{
$mailSender->sendErrorEmail($entry);
}
$this->logDebugMsg("Scheduled monitoring check ended. Some checks ended erroneous. The monitoring admin was informed via email (" . \Config::get('monitoringAdminEmail') . ").", __METHOD__);
}
else
{
$this->logDebugMsg('No "error" email send ... check monitoring settings.', __METHOD__);
}
}
// send an email, if previously erroneous checks are okay again
$againOkayCheckEntries = array_diff_key($oldErroneousCheckEntries, $newErroneousCheckEntries);
if (!empty($againOkayCheckEntries) && \Config::get('monitoringMailingActive') && \Config::get('monitoringAdminEmail') != '')
{
foreach($againOkayCheckEntries as $entry)
{
$mailSender->sendAgainOkayEmail($entry);
}
$this->logDebugMsg("Scheduled monitoring check ended. Some checks are okay again. The monitoring admin was informed via email (" . \Config::get('monitoringAdminEmail') . ").", __METHOD__);
}
}
/**
* Remove all entries from the array, that have mailing deactivated.
*/
private function removeMailingDeactivatedEntries($arrEntries)
{
return array_filter(
$arrEntries,
function ($entry)
{
return $entry->disableMailing == "";
}
);
}
/**
* Executes a check
*/
private function checkSingle($id, $checkType)
{
$objMonitoringEntry = \MonitoringModel::findByPk($id);
if ($objMonitoringEntry !== null)
{
$status = self::STATUS_UNTESTED;
$url = $this->valString($objMonitoringEntry->url, false);
$testString = $this->valString($objMonitoringEntry->test_string, true);
$repitition = 0;
$maxRepititions = \Config::get('monitoringTestCirculation');
if (!is_int($maxRepititions) || $maxRepititions < 1)
{
$maxRepititions = self::TEST_CIRCULATION;
}
$delay = \Config::get('monitoringTestCirculationDelay');
if (!is_int($delay) || $delay < 1 || $delay > 99)
{
$delay = self::TEST_CIRCULATION_DELAY;
}
$arrSetEntry = array();
$arrSetTest = array();
do
{
if ($repitition > 0)
{
$this->logDebugMsg("Repeating single check for entry with ID " . $id . " because status was: " . $status, __METHOD__);
sleep($delay);
}
$time = time();
$microtime = microtime(true);
$responseString = $this->loadSite($url);
$responseTime = round(microtime(true) - $microtime, 3);
$status = $this->compareSite($responseString, $testString);
$repitition++;
$arrSetEntry['tstamp'] = $time;
$arrSetEntry['last_test_date'] = $time;
$arrSetEntry['last_test_status'] = $status;
$arrSetEntry['last_test_response_time'] = $responseTime;
$arrSetTest['pid'] = $id;
$arrSetTest['tstamp'] = $time;
$arrSetTest['date'] = $time;
$arrSetTest['type'] = $checkType;
$arrSetTest['status'] = $status;
$arrSetTest['response_time'] = $responseTime;
$arrSetTest['repetitions'] = $repitition;
$arrSetTest['response_string'] = $responseString; //substr($responseString, 0, 255);
} while ($status != self::STATUS_OKAY && $repitition < $maxRepititions);
$this->saveMonitoringEntry($id, $arrSetEntry);
$this->saveMonitoringTest($arrSetTest);
$this->logDebugMsg("Returning status for entry with ID " . $id . " after single check is: " . $status, __METHOD__);
return $status;
}
// no data, no test ... no error !!!
return null;
}
/**
* Check all monitoring entries
*/
private function checkMultiple($checkType, $blnAddTestMessage=false)
{
$status = self::STATUS_UNTESTED;
$objMonitoringEntry = \MonitoringModel::findAllActive();
if ($objMonitoringEntry !== null)
{
while ($objMonitoringEntry->next())
{
$id = $objMonitoringEntry->id;
$tmpStatus = $this->checkSingle($id, $checkType);
if ($tmpStatus == self::STATUS_ERROR)
{
$status = self::STATUS_ERROR;
}
else if ($tmpStatus == self::STATUS_INCOMPLETE && $status != self::STATUS_ERROR)
{
$status = self::STATUS_ERROR;
}
else if ($tmpStatus == self::STATUS_OKAY && $status != self::STATUS_INCOMPLETE && $status != self::STATUS_ERROR)
{
$status = self::STATUS_OKAY;
}
$this->logDebugMsg("Multiple checking status after entry ID " . $id . " is: " . $status, __METHOD__);
if ($blnAddTestMessage)
{
$this->addCheckMessage($id, $tmpStatus);
}
}
}
$this->logDebugMsg("Multiple checking monitoring entries ended with status: " . $status, __METHOD__);
return $status;
}
/**
* Return the list of erroneous check entries
*/
private function getErroneousCheckEntries()
{
$arrResult = array();
$objMonitoringEntry = \MonitoringModel::findAllActiveErroneous();
if ($objMonitoringEntry !== null)
{
while ($objMonitoringEntry->next())
{
$arrResult[$objMonitoringEntry->id] = $objMonitoringEntry->current();
}
}
return $arrResult;
}
/**
* Return the list of erroneous check entries as string
*/
private function getCheckEntriesAsString($arrErroneousCheckEntries)
{
$strReturn = '';
foreach ($arrErroneousCheckEntries as $key=>$entry)
{
$strReturn .= sprintf(self::ERROR_MESSAGE_ENTRY, $entry->customer, $entry->website, $entry->system, $entry->last_test_status, $entry->url);
}
return $strReturn;
}
/**
* Save data of entry to database
*/
private function saveMonitoringEntry($intId, $arrSet)
{
\Database::getInstance()->prepare("UPDATE tl_monitoring %s WHERE id=?")
->set($arrSet)
->execute($intId);
}
/**
* Save data of test to database
*/
private function saveMonitoringTest($arrSet)
{
\Database::getInstance()->prepare("INSERT INTO tl_monitoring_test %s")
->set($arrSet)
->execute();
}
/**
* Load the url and return the response text
*/
private function loadSite($url)
{
if ($url != '' && !preg_match('@^https?://@', $url))
{
$url = 'http://' . $url;
}
$opts = array
(
'http'=>array
(
'user_agent' => \Config::get('MONITORING_AGENT_NAME')
)
);
$context = stream_context_create($opts);
if ($responseText = @file_get_contents($url, false, $context))
{
return $this->valString($responseText, true);
}
return false;
}
/**
* Check the test string against the server response
*/
private function compareSite($source, $search)
{
if (!empty($source) && !empty($search))
{
if (substr_count($source, $search) != 0)
{
return self::STATUS_OKAY;
}
else
{
return self::STATUS_INCOMPLETE;
}
}
return self::STATUS_ERROR;
}
/**
* Validate the given string.
*/
private function valString($str, $toLower)
{
if ($toLower)
{
$str = strtolower($str);
}
$str = strip_tags($str);
$str = str_replace(' ', '', $str);
$str = str_replace("\n", '', $str);
$str = \StringUtil::decodeEntities($str);
return $str;
}
/**
* Redirect to the list.
*/
private function returnToList($act)
{
$path = \Environment::get('base') . 'contao/main.php?do=' . $act;
$this->redirect($path, 301);
}
/**
* Logs the given message if the debug mode is anabled.
*/
private function logDebugMsg($msg, $origin)
{
if (\Config::get('monitoringDebugMode') === TRUE)
{
$this->log($msg, $origin, TL_GENERAL);
}
}
/**
* Logs the given message if the debug mode is anabled.
*/
private function addCheckMessage($intEntryId, $strStatus)
{
$this->addRawMessage('<p class="tl_message_monitoring_status monitoring_status_' . strtolower($strStatus) . '">' . sprintf($GLOBALS['TL_LANG']['MSC']['monitoringCheckResult'], $intEntryId, $GLOBALS['TL_LANG']['tl_monitoring']['statusTypes'][$strStatus][0]) . '</p>');
}
}
?>