Merge branch 'develop' of https://github.com/sadortun/phpservermon into sadortun-develop

# Conflicts:
#	src/psm/Module/Server/Controller/ServerController.php
#	src/psm/Util/Install/Installer.php
#	src/psm/Util/Server/ServerValidator.php
#	src/psm/Util/Server/Updater/StatusUpdater.php
#	src/templates/server/server.tpl.html
pull/292/head
Samuel Denis-D'Ortun 2016-05-19 01:12:57 -04:00
commit ccada24e0a
15 changed files with 568 additions and 196 deletions

Binary file not shown.

View File

@ -29,7 +29,7 @@
/**
* Current PSM version
*/
define('PSM_VERSION', '3.2.0');
define('PSM_VERSION', '3.2.1');
/**
* URL to check for updates. Will not be checked if turned off on config page.

View File

@ -172,6 +172,7 @@ $sm_lang = array(
'error_server_ip_bad_length' => 'The domain / IP must be between 1 and 255 characters.',
'error_server_ip_bad_service' => 'The IP address is not valid.',
'error_server_ip_bad_website' => 'The website URL is not valid.',
'error_server_ip_bad_imap' => 'The IMAP URL need to be in format imap://username:password@hostname/options ',
'error_server_type_invalid' => 'The selected server type is invalid.',
'error_server_warning_threshold_invalid' => 'The warning threshold must be a valid integer greater than 0.',
),

View File

@ -63,6 +63,9 @@ class LogController extends AbstractServerController {
// get users
$users = $this->db->select(PSM_DB_PREFIX.'users', null, array('user_id','name'));
$statusUpdater = new \psm\Util\Server\Updater\StatusUpdater($this->db);
$users_labels = array();
foreach ($users as $user) {
$users_labels[$user['user_id']] = $user['name'];
@ -84,7 +87,7 @@ class LogController extends AbstractServerController {
$record['class'] = ($x & 1) ? 'odd' : 'even';
$record['users'] = '';
$record['server'] = $record['label'];
$record['type_icon'] = ($record['server_type'] == 'website') ? 'icon-globe' : 'icon-cog';
$record['type_icon'] = $statusUpdater->GetHandler($record['server_type'])->GetIcon() ;
$record['type_title'] = psm_get_lang('servers', 'type_' . $record['server_type']);
$ip = '(' . $record['ip'];
if(!empty($record['port']) && (($record['server_type'] != 'website') || ($record['port'] != 80))) {

View File

@ -81,7 +81,9 @@ class ServerController extends AbstractServerController {
);
}
$sidebar->addButton(
$sidebar->addButton(
'update',
psm_get_lang('menu', 'server_update'),
psm_build_url(array('mod' => 'server_update')),
@ -97,11 +99,14 @@ class ServerController extends AbstractServerController {
$servers = $this->getServers();
$server_count = count($servers);
$statusUpdater = new \psm\Util\Server\Updater\StatusUpdater($this->db);
for ($x = 0; $x < $server_count; $x++) {
$servers[$x]['class'] = ($x & 1) ? 'odd' : 'even';
$servers[$x]['type_icon'] = $statusUpdater->GetHandler($servers[$x]['type'])->GetIcon() ;
if($servers[$x]['type'] == 'website') {
$servers[$x]['type_icon'] = 'icon-globe';
// add link to label
$ip = $servers[$x]['ip'];
if(!empty($servers[$x]['port']) && ($servers[$x]['port'] != 80)) {
@ -110,7 +115,6 @@ class ServerController extends AbstractServerController {
$servers[$x]['ip'] = '<a href="'.$servers[$x]['ip'].'" target="_blank">'.$ip.'</a>';
$servers[$x]['ip_short'] = $ip;
} else {
$servers[$x]['type_icon'] = 'icon-cog';
$servers[$x]['ip_short'] = $servers[$x]['ip'] . ' : ' . $servers[$x]['port'];
}
if(($servers[$x]['active'] == 'yes')) {
@ -142,10 +146,10 @@ class ServerController extends AbstractServerController {
$tpl_data = $this->getLabels();
$tpl_data['edit_server_id'] = $this->server_id;
$tpl_data['url_save'] = psm_build_url(array(
'mod' => 'server',
'action' => 'save',
'id' => $this->server_id,
'back_to' => $back_to,
'mod' => 'server',
'action' => 'save',
'id' => $this->server_id,
'back_to' => $back_to,
));
// depending on where the user came from, add the go back url:
@ -207,18 +211,31 @@ class ServerController extends AbstractServerController {
));
}
$notifications = array('email', 'sms', 'pushover');
foreach($notifications as $notification) {
if(psm_get_conf($notification . '_status') == 0) {
$tpl_data['warning_' . $notification] = true;
$tpl_data['control_class_' . $notification] = 'warning';
$tpl_data['label_warning_' . $notification] = psm_get_lang(
'servers', 'warning_notifications_disabled_' . $notification
);
} else {
$tpl_data['warning_' . $notification] = false;
}
}
// generate language array
$updater = new \psm\Util\Server\Updater\StatusUpdater($this->db);
$types = array();
foreach($updater->GetHandlers() as $key => $handler) {
$types[] = array(
'value' => $key,
'label' => $key,
'selected' => ($key == $edit_server['type']) ? 'selected="selected"' : '',
);
}
$tpl_data = array_merge($tpl_data, array(
'types' => $types,
'edit_value_label' => $edit_server['label'],
'edit_value_ip' => $edit_server['ip'],
'edit_value_port' => $edit_server['port'],
'edit_value_pattern' => $edit_server['pattern'],
'edit_value_warning_threshold' => $edit_server['warning_threshold'],
'edit_active_selected_' . $edit_server['active'] => 'selected="selected"',
'edit_email_selected_' . $edit_server['email'] => 'selected="selected"',
'edit_sms_selected_' . $edit_server['sms'] => 'selected="selected"',
));
return $this->twig->render('module/server/server/update.tpl.html', $tpl_data);
}
@ -244,10 +261,8 @@ class ServerController extends AbstractServerController {
'sms' => in_array($_POST['sms'], array('yes', 'no')) ? $_POST['sms'] : 'no',
'pushover' => in_array($_POST['pushover'], array('yes', 'no')) ? $_POST['pushover'] : 'no',
);
// make sure websites start with http://
if($clean['type'] == 'website' && substr($clean['ip'], 0, 4) != 'http') {
$clean['ip'] = 'http://' . $clean['ip'];
}
$statusUpdater = new \psm\Util\Updater\StatusUpdater($this->db);
$clean['ip'] = $statusUpdater->GetHandler($clean['type'])->PrepareIP($clean['ip']);
// validate the lot
$server_validator = new \psm\Util\Server\ServerValidator($this->db);

View File

@ -213,7 +213,7 @@ class Installer {
`ip` varchar(500) NOT NULL,
`port` int(5) unsigned NOT NULL,
`label` varchar(255) NOT NULL,
`type` enum('service','website') NOT NULL default 'service',
`type` varchar(255) NOT NULL default 'service',
`pattern` varchar(255) NOT NULL,
`status` enum('on','off') NOT NULL default 'on',
`error` varchar(255) NULL,
@ -283,6 +283,9 @@ class Installer {
if(version_compare($version_from, '3.2.0', '<')) {
$this->upgrade320();
}
if(version_compare($version_from, '3.2.1', '<')) {
$this->upgrade321();
}
psm_update_conf('version', $version_to);
}
@ -430,4 +433,12 @@ class Installer {
$this->execSQL($queries);
}
protected function upgrade321(){
$queries = array();
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` CHANGE `type` `type` CHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT 'service'";
$this->execSQL($queries);
}
}

View File

@ -27,6 +27,7 @@
**/
namespace psm\Util\Server;
use psm\Util\Updater\StatusUpdater;
/**
* The ServerValidator helps you to check input data for servers.
@ -39,9 +40,13 @@ class ServerValidator {
*/
protected $db;
public function __construct(\psm\Service\Database $db) {
protected $statusUpdater ;
public function __construct(\psm\Service\Database $db) {
$this->db = $db;
}
$this->statusUpdater = new \psm\Util\Server\Updater\StatusUpdater($this->db);
}
/**
* Check if the server id exists
@ -86,22 +91,8 @@ class ServerValidator {
throw new \InvalidArgumentException('server_ip_bad_length');
}
switch($type) {
case 'website':
if(!filter_var($value, FILTER_VALIDATE_URL)) {
throw new \InvalidArgumentException('server_ip_bad_website');
}
break;
case 'service':
if(
!filter_var($value, FILTER_VALIDATE_IP)
// domain regex as per http://stackoverflow.com/questions/106179/regular-expression-to-match-hostname-or-ip-address :
&& !preg_match("/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])/", $value)
) {
throw new \InvalidArgumentException('server_ip_bad_service');
}
break;
}
$this->statusUpdater->GetHandler($type)->ValidateIP($value);
return true;
}
@ -113,7 +104,7 @@ class ServerValidator {
* @throws \InvalidArgumentException
*/
public function type($type) {
if(!in_array($type, array('service', 'website'))) {
if( $this->statusUpdater->GetHandler($type) == null) {
throw new \InvalidArgumentException('server_type_invalid');
}
return true;

View File

@ -63,7 +63,7 @@ class UpdateManager extends ContainerAware {
$servers = $this->container->get('db')->query($sql);
$updater = new Updater\StatusUpdater($this->container->get('db'));
$updater = new \psm\Util\Server\Updater\StatusUpdater($this->container->get('db'));
$notifier = new Updater\StatusNotifier($this->container->get('db'));
foreach($servers as $server) {

View File

@ -18,8 +18,8 @@
* along with PHP Server Monitor. If not, see <http://www.gnu.org/licenses/>.
*
* @package phpservermon
* @author Pepijn Over <pep@peplab.net>
* @copyright Copyright (c) 2008-2015 Pepijn Over <pep@peplab.net>
* @author Pepijn Over <pep@neanderthal-technology.com>
* @copyright Copyright (c) 2008-2014 Pepijn Over <pep@neanderthal-technology.com>
* @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3
* @version Release: @package_version@
* @link http://www.phpservermonitor.org/
@ -28,18 +28,17 @@
/**
* The status class is for checking the status of a server.
*
* @see \psm\Util\Server\Updater\StatusNotifier
* @see \psm\Util\Server\Updater\Autorun
* @see \psm\Util\Updater\StatusNotifier
* @see \psm\Util\Updater\Autorun
*/
namespace psm\Util\Server\Updater;
use psm\Service\Database;
use psm\Util\Updater\Types;
class StatusUpdater {
public $error = '';
public $rtime = 0;
public $status_new = false;
class StatusUpdater
{
/**
* Database service
@ -59,8 +58,58 @@ class StatusUpdater {
*/
protected $server;
function __construct(Database $db) {
protected $handlers = array ();
function __construct(Database $db)
{
$this->db = $db;
$this->LoadHandlers();
}
private function LoadHandlers()
{
foreach (glob(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'types' . DIRECTORY_SEPARATOR . '*.Updater.php') as $path)
{
$filename = basename($path);
if ( !preg_match('/(?P<name>[a-zA-Z0-9]+).Updater.php$/', $filename, $matches))
continue;
if ($matches === null || empty( $matches['name'] ))
continue;
$name = $matches['name'];
if (array_key_exists($name, $this->handlers))
continue;
include_once $path;
$class_name = 'psm\\Util\\Updater\\Types\\' . $name . 'Updater';
if ( !class_exists($class_name))
continue;
$this->handlers[strtolower($name)] = new $class_name($this->db);
}
}
public function GetHandlers()
{
return $this->handlers;
}
public function GetHandler($name)
{
if ( !array_key_exists($name, $this->handlers))
throw new \InvalidArgumentException('server_type_invalid');
return $this->handlers[strtolower($name)];
}
/**
@ -69,175 +118,86 @@ class StatusUpdater {
*
* Please note: if the server is down but has not met the warning threshold, this will return true
* to avoid any "we are down" events.
*
* @param int $server_id
* @param int $max_runs how many times should the script recheck the server if unavailable. default is 2
*
* @return boolean TRUE if server is up, FALSE otherwise
*/
public function update($server_id, $max_runs = 2) {
public function update($server_id, $max_runs = 2)
{
$this->server_id = $server_id;
$this->error = '';
$this->rtime = '';
$this->error = '';
$this->rtime = '';
// get server info from db
$this->server = $this->db->selectRow(PSM_DB_PREFIX . 'servers', array(
$this->server = $this->db->selectRow(PSM_DB_PREFIX . 'servers', array (
'server_id' => $server_id,
), array(
'server_id', 'ip', 'port', 'label', 'type', 'pattern', 'status', 'active', 'warning_threshold', 'warning_threshold_counter', 'timeout',
));
if(empty($this->server)) {
), array (
'server_id', 'ip', 'port', 'label', 'type', 'pattern', 'status', 'active', 'warning_threshold', 'warning_threshold_counter',
));
if (empty( $this->server ))
{
return false;
}
switch($this->server['type']) {
case 'service':
$this->status_new = $this->updateService($max_runs);
break;
case 'website':
$this->status_new = $this->updateWebsite($max_runs);
break;
}
$cur_run = 1;
$handler = $this->GetHandler($this->server['type']);
$status_new = true;
do
{
$status_new = $handler->Update($this->server);
} while ($status_new == false && $cur_run++ <= $max_runs);
// update server status
$save = array(
$save = array (
'last_check' => date('Y-m-d H:i:s'),
'error' => $this->error,
'rtime' => $this->rtime,
'error' => $handler->GetError(),
'rtime' => $handler->GetRunTime(),
);
// log the uptime before checking the warning threshold,
// so that the warnings can still be reviewed in the server history.
psm_log_uptime($this->server_id, (int) $this->status_new, $this->rtime);
psm_log_uptime($this->server_id, (int)$status_new, $handler->GetRunTime());
if($this->status_new == true) {
if ($status_new == true)
{
// if the server is on, add the last_online value and reset the error threshold counter
$save['status'] = 'on';
$save['last_online'] = date('Y-m-d H:i:s');
$save['status'] = 'on';
$save['last_online'] = date('Y-m-d H:i:s');
$save['warning_threshold_counter'] = 0;
} else {
}
else
{
// server is offline, increase the error counter
$save['warning_threshold_counter'] = $this->server['warning_threshold_counter'] + 1;
if($save['warning_threshold_counter'] < $this->server['warning_threshold']) {
if ($save['warning_threshold_counter'] < $this->server['warning_threshold'])
{
// the server is offline but the error threshold has not been met yet.
// so we are going to leave the status "on" for now while we are in a sort of warning state..
$save['status'] = 'on';
$this->status_new = true;
} else {
$status_new = true;
}
else
{
$save['status'] = 'off';
}
}
$this->db->save(PSM_DB_PREFIX . 'servers', $save, array('server_id' => $this->server_id));
$this->db->save(PSM_DB_PREFIX . 'servers', $save, array ( 'server_id' => $this->server_id ));
return $this->status_new;
return $status_new;
}
/**
* Check the current server as a service
* @param int $max_runs
* @param int $run
* @return boolean
*/
protected function updateService($max_runs, $run = 1) {
$errno = 0;
// save response time
$starttime = microtime(true);
$fp = fsockopen ($this->server['ip'], $this->server['port'], $errno, $this->error, 10);
$status = ($fp === false) ? false : true;
$this->rtime = (microtime(true) - $starttime);
if(is_resource($fp)) {
fclose($fp);
}
// check if server is available and rerun if asked.
if(!$status && $run < $max_runs) {
return $this->updateService($max_runs, $run + 1);
}
return $status;
}
/**
* Check the current server as a website
* @param int $max_runs
* @param int $run
* @return boolean
*/
protected function updateWebsite($max_runs, $run = 1) {
$starttime = microtime(true);
// We're only interested in the header, because that should tell us plenty!
// unless we have a pattern to search for!
$curl_result = psm_curl_get(
$this->server['ip'],
true,
($this->server['pattern'] == '' ? false : true),
$this->server['timeout']
);
$this->rtime = (microtime(true) - $starttime);
// the first line would be the status code..
$status_code = strtok($curl_result, "\r\n");
// keep it general
// $code[1][0] = status code
// $code[2][0] = name of status code
$code_matches = array();
preg_match_all("/[A-Z]{2,5}\/\d\.\d\s(\d{3})\s(.*)/", $status_code, $code_matches);
if(empty($code_matches[0])) {
// somehow we dont have a proper response.
$this->error = 'TIMEOUT ERROR: no response from server';
$result = false;
} else {
$code = $code_matches[1][0];
$msg = $code_matches[2][0];
// All status codes starting with a 4 or higher mean trouble!
if(substr($code, 0, 1) >= '4') {
$this->error = "HTTP STATUS ERROR: ".$code . ' ' . $msg;
$result = false;
} else {
$result = true;
//Okay, the HTTP status is good : 2xx or 3xx. Now we have to test the pattern if it's set up
if($this->server['pattern'] != '') {
// Check to see if the pattern was found.
if(!preg_match("/{$this->server['pattern']}/i", $curl_result)) {
$this->error = 'TEXT ERROR : Pattern not found.';
$result = false;
}
}
}
}
// check if server is available and rerun if asked.
if(!$result && $run < $max_runs) {
return $this->updateWebsite($max_runs, $run + 1);
}
return $result;
}
/**
* Get the error returned by the update function
*
* @return string
*/
public function getError() {
return $this->error;
}
/**
* Get the response time of the server
*
* @return string
*/
public function getRtime() {
return $this->rtime;
}
}
}

View File

@ -0,0 +1,64 @@
<?php
namespace psm\Util\Updater\Types;
use psm\Service\Database;
abstract class AbstractUpdater
{
private $run_time;
private $run_start = 0;
private $error = '';
public function GetIcon(){
return 'icon-cog';
}
protected function StartRun(){
$this->run_start = microtime(true);
}
protected function StopRun(){
$this->run_time = (microtime(true) - $this->run_start);
}
protected function SetRunTime($time_microsec){
$this->run_time = $time_microsec;
}
public function GetRunTime(){
return $this->run_time;
}
public function GetError(){
return $this->error;
}
protected function SetError($error){
$this->error = $error;
}
public function PrepareIP($ip) {
return $ip;
}
public function ValidateIP($ip){
}
abstract public function Update($server);
}

View File

@ -0,0 +1,94 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
*
* This file is part of PHP Server Monitor.
* PHP Server Monitor is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* PHP Server Monitor 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with PHP Server Monitor. If not, see <http://www.gnu.org/licenses/>.
*
* @package phpservermon
* @author Samuel Denis-D'Ortun <sam@sddproductions.com>
* @copyright Copyright (c) 2014 Samuel Denis-D'Ortun <sam@sddproductions.com>
* @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3
* @version Release: @package_version@
* @link http://www.phpservermonitor.org/
**/
namespace psm\Util\Updater\Types;
require_once 'AbstractUpdater.php';
use psm\Service\Database;
use psm\Util\Updater;
class ImapUpdater extends AbstractUpdater
{
public function GetIcon(){
return 'icon-globe';
}
public function ValidateIP($ip)
{
// make sure websites start with http://
if(substr($ip, 0, 7) != 'imap://') {
throw new \InvalidArgumentException('server_ip_bad_imap');
}
if(!filter_var($ip, FILTER_VALIDATE_URL)) {
throw new \InvalidArgumentException('server_ip_bad_imap');
}
}
/**
* Check the current server as a IMAP Server
*
* Allow to open connections to IMAP server.
*
* IP must be provided in a URL encoded string (See PHP imap_open())
* - imap://user:pass@domain.com/OPTIONS
*
* When host require full email address, replace the @ with %40 in the user field.
* - imap://mailbox%40domain.com:mypassword@domain.com/novalidate-cert
*
* @param array $server
* @return boolean
*/
public function Update($server) {
$this->StartRun();
$url = parse_url($server['ip']);
imap_errors(); // clean error list
$stream = @imap_open( '{' . $url['host'] . $url['path'] . '}' ,urldecode( $url['user'] ) ,urldecode($url['pass']) , OP_HALFOPEN );
if($stream === false)
{
$errors = @imap_errors() ;
$this->SetError( implode(" ; " , $errors));
}
else
imap_close($stream);
$result = ($stream !== false) ? true: false;
$this->StopRun();
return $result;
}
}

View File

@ -0,0 +1,92 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
*
* This file is part of PHP Server Monitor.
* PHP Server Monitor is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* PHP Server Monitor 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with PHP Server Monitor. If not, see <http://www.gnu.org/licenses/>.
*
* @package phpservermon
* @author Samuel Denis-D'Ortun <sam@sddproductions.com>
* @copyright Copyright (c) 2014 Samuel Denis-D'Ortun <sam@sddproductions.com>
* @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3
* @version Release: @package_version@
* @link http://www.phpservermonitor.org/
**/
namespace psm\Util\Updater\Types;
require_once 'AbstractUpdater.php';
use psm\Service\Database;
use psm\Util\Updater;
class PingUpdater extends AbstractUpdater
{
/**
* Check the current server as a ping
* @param array $server
* @return boolean
*/
public function Update($server) {
/**
* Only run if is cron
* socket_create() need to run as root :(
* ugly cli hack i know
* might be a better way still have not found a solution when updating true website
*/
if(psm_is_cli()) {
$this->StartRun();
// if ipv6 we have to use AF_INET6
if (psm_validate_ipv6($server['ip'])) {
// Need to remove [] on ipv6 address
$server['ip'] = trim($server['ip'], '[]');
$socket = socket_create(AF_INET6, SOCK_RAW, 1);
} else {
$socket = socket_create(AF_INET, SOCK_RAW, 1);
}
$timeout = 1;
$package = "\x08\x00\x7d\x4b\x00\x00\x00\x00PingHost"; /* ICMP ping packet with a pre-calculated checksum */
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $timeout, 'usec' => 0));
socket_connect($socket, $server['ip'], null);
socket_send($socket, $package, strLen($package), 0);
// if ping fails it returns false
$status = (socket_read($socket, 255)) ? true : false;
$this->StopRun();
socket_close($socket);
return $status;
// If state on last update was 'on' and the update request is comming from the website
} elseif ($server['status'] == 'on') {
// need to set rtime to the value from last update, if not the latency will be 0
$this->rtime = $server['rtime'];
$this->SetError( 'Update skipped, status will be updated on next cron script run.');
return true;
} else {
return false;
}
}
}

View File

@ -0,0 +1,140 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
*
* This file is part of PHP Server Monitor.
* PHP Server Monitor is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* PHP Server Monitor 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with PHP Server Monitor. If not, see <http://www.gnu.org/licenses/>.
*
* @package phpservermon
* @author Samuel Denis-D'Ortun <sam@sddproductions.com>
* @copyright Copyright (c) 2014 Samuel Denis-D'Ortun <sam@sddproductions.com>
* @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3
* @version Release: @package_version@
* @link http://www.phpservermonitor.org/
**/
namespace psm\Util\Updater\Types;
require_once 'AbstractUpdater.php';
use psm\Service\Database;
use psm\Util\Updater;
class WebsiteUpdater extends AbstractUpdater
{
public function GetIcon()
{
return 'icon-globe';
}
public function PrepareIP($ip)
{
// make sure websites start with http://
if (substr($ip, 0, 4) != 'http')
{
$ip = 'http://' . $ip;
}
return $ip;
}
public function ValidateIP($ip)
{
if ( !filter_var($ip, FILTER_VALIDATE_URL))
{
throw new \InvalidArgumentException('server_ip_bad_website');
}
}
/**
* Check the current server as a website
*
* @param array $server
*
* @return boolean
*/
public function Update($server)
{
$this->StartRun();
// We're only interested in the header, because that should tell us plenty!
// unless we have a pattern to search for!
$curl_result = psm_curl_get(
$server['ip'],
true,
( $server['pattern'] == '' ? false : true )
);
$this->StopRun();
$result = $this->CheckResponseCode($curl_result);
//Okay, the HTTP status is good : 2xx or 3xx. Now we have to test the pattern if it's set up
if ($result != false && $server['pattern'] != '')
{
// Check to see if the pattern was found.
if ( !preg_match("/{$server['pattern']}/i", $curl_result))
{
$this->SetError('TEXT ERROR : Pattern not found.');
$result = false;
}
}
return $result;
}
private function CheckResponseCode($curl_result)
{
// the first line would be the status code..
$status_code = strtok($curl_result, "\r\n");
// keep it general
// $code[1][0] = status code
// $code[2][0] = name of status code
$code_matches = array ();
preg_match_all("/[A-Z]{2,5}\/\d\.\d\s(\d{3})\s(.*)/", $status_code, $code_matches);
if (empty( $code_matches[0] ))
{
// somehow we dont have a proper response.
$this->SetError('TIMEOUT ERROR: no response from server');
return false;
}
else
{
$code = $code_matches[1][0];
$msg = $code_matches[2][0];
// All status codes starting with a 4 or higher mean trouble!
if (substr($code, 0, 1) >= '4')
{
$this->SetError("HTTP STATUS ERROR: " . $code . ' ' . $msg);
return false;
}
else
{
return true;
}
}
}
}

View File

@ -19,8 +19,9 @@
<label class="control-label" for="type">{{ label_type }}</label>
<div class="controls">
<select id="type" name="type">
<option value="service" {{ edit_type_selected_service|raw }}>{{ label_service }}</option>
<option value="website" {{ edit_type_selected_website|raw }}>{{ label_website }}</option>
{% for type in types %}
<option value="{{type.value}}" {{type.selected}}>{{type.label}}</option>
{% endfor %}
</select>
</div>
</div>