Implementing the PSR12 standard

Using PHPCS and PHPSBF.
This commit is contained in:
TimZ99 2019-12-11 20:19:38 +01:00
parent 0c91d27a70
commit 2c51ad12f7
No known key found for this signature in database
GPG Key ID: 4D8268DC68E8339D
70 changed files with 8944 additions and 8129 deletions

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -25,10 +26,11 @@
* @link http://www.phpservermonitor.org/
**/
namespace {
// include main configuration and functionality
require_once __DIR__.'/../src/bootstrap.php';
require_once __DIR__ . '/../src/bootstrap.php';
if (!psm_is_cli()) {
if (!psm_is_cli()) {
// check if it's an allowed host
if (!isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
$_SERVER["HTTP_X_FORWARDED_FOR"] = "";
@ -41,14 +43,22 @@ if (!psm_is_cli()) {
if (!in_array($_SERVER['REMOTE_ADDR'], $allow) && !in_array($_SERVER["HTTP_X_FORWARDED_FOR"], $allow)) {
header('HTTP/1.0 403 Forbidden');
die('<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><html><head><title>403 Forbidden</title></head><body><h1>Forbidden</h1><p>IP address not allowed. See the <a href="http://docs.phpservermonitor.org/en/latest/install.html#cronjob-over-web">documentation</a> for more info.</p></body></html>');
die('
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><html>
<head><title>403 Forbidden</title></head>
<body>
<h1>Forbidden</h1><p>IP address not allowed. See the
<a href="http://docs.phpservermonitor.org/en/latest/install.html#cronjob-over-web">documentation</a>
for more info.</p>
</body>
</html>');
}
echo "OK";
}
}
$cron_timeout = PSM_CRON_TIMEOUT;
$cron_timeout = PSM_CRON_TIMEOUT;
// parse a couple of arguments
if (!empty($_SERVER['argv'])) {
if (!empty($_SERVER['argv'])) {
foreach ($_SERVER['argv'] as $argv) {
$argi = explode('=', ltrim($argv, '--'));
if (count($argi) !== 2) {
@ -65,26 +75,27 @@ if (!empty($_SERVER['argv'])) {
break;
}
}
}
}
// prevent cron from running twice at the same time
// however if the cron has been running for X mins, we'll assume it died and run anyway
// if you want to change PSM_CRON_TIMEOUT, have a look in src/includes/psmconfig.inc.php.
// or you can provide the --timeout=x argument
$time = time();
if (
$time = time();
if (
psm_get_conf('cron_running') == 1
&& $cron_timeout > 0
&& ($time - psm_get_conf('cron_running_time') < $cron_timeout)
) {
) {
die('Cron is already running. Exiting.');
}
if (!defined('PSM_DEBUG') || !PSM_DEBUG) {
}
if (!defined('PSM_DEBUG') || !PSM_DEBUG) {
psm_update_conf('cron_running', 1);
}
psm_update_conf('cron_running_time', $time);
$autorun = $router->getService('util.server.updatemanager');
$autorun->run(true);
psm_update_conf('cron_running', 0);
}
psm_update_conf('cron_running_time', $time);
$autorun = $router->getService('util.server.updatemanager');
$autorun->run(true);
psm_update_conf('cron_running', 0);

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -25,14 +26,14 @@
* @link http://www.phpservermonitor.org/
**/
require __DIR__.'/src/bootstrap.php';
require __DIR__ . '/src/bootstrap.php';
psm_no_cache();
if (isset($_GET["logout"])) {
$router->getService('user')->doLogout();
// logged out, redirect to login
header('Location: '.psm_build_url());
header('Location: ' . psm_build_url());
die();
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -25,8 +26,10 @@
* @link http://www.phpservermonitor.org/
**/
define('PSM_INSTALL', true);
namespace {
define('PSM_INSTALL', true);
require __DIR__.'/src/bootstrap.php';
require __DIR__ . '/src/bootstrap.php';
$router->run('install');
$router->run('install');
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -26,54 +27,61 @@
* @since phpservermon 2.1.0
**/
// Include paths
define('PSM_PATH_SRC', __DIR__.DIRECTORY_SEPARATOR);
define('PSM_PATH_CONFIG', PSM_PATH_SRC.'config'.DIRECTORY_SEPARATOR);
define('PSM_PATH_LANG', PSM_PATH_SRC.'lang'.DIRECTORY_SEPARATOR);
define('PSM_PATH_SMS_GATEWAY', PSM_PATH_SRC.'psm'.DIRECTORY_SEPARATOR.'Txtmsg'.DIRECTORY_SEPARATOR);
namespace {
// Include paths
define('PSM_PATH_SRC', __DIR__ . DIRECTORY_SEPARATOR);
define('PSM_PATH_CONFIG', PSM_PATH_SRC . 'config' . DIRECTORY_SEPARATOR);
define('PSM_PATH_LANG', PSM_PATH_SRC . 'lang' . DIRECTORY_SEPARATOR);
define('PSM_PATH_SMS_GATEWAY', PSM_PATH_SRC . 'psm' . DIRECTORY_SEPARATOR . 'Txtmsg' . DIRECTORY_SEPARATOR);
// user levels
define('PSM_USER_ADMIN', 10);
define('PSM_USER_USER', 20);
define('PSM_USER_ANONYMOUS', 30);
// user levels
define('PSM_USER_ADMIN', 10);
define('PSM_USER_USER', 20);
define('PSM_USER_ANONYMOUS', 30);
if (function_exists('date_default_timezone_set') && function_exists('date_default_timezone_get')) {
if (function_exists('date_default_timezone_set') && function_exists('date_default_timezone_get')) {
date_default_timezone_set(@date_default_timezone_get());
}
}
// find config file
$path_conf = PSM_PATH_SRC.'../config.php';
if (file_exists($path_conf)) {
// find config file
$path_conf = PSM_PATH_SRC . '../config.php';
if (file_exists($path_conf)) {
include_once $path_conf;
}
// check for a debug var
if (!defined('PSM_DEBUG')) {
}
// check for a debug var
if (!defined('PSM_DEBUG')) {
define('PSM_DEBUG', false);
}
}
// Debug enabled: report everything
// Debug disabled: report error only if created manually
ini_set('display_errors', 1);
PSM_DEBUG ? error_reporting(E_ALL) : error_reporting(E_USER_ERROR);
// Debug enabled: report everything
// Debug disabled: report error only if created manually
ini_set('display_errors', 1);
PSM_DEBUG ? error_reporting(E_ALL) : error_reporting(E_USER_ERROR);
// check for a cron allowed ip array
if (!defined('PSM_CRON_ALLOW')) {
// check for a cron allowed ip array
if (!defined('PSM_CRON_ALLOW')) {
//serialize for php version lower than 7.0.0
define('PSM_CRON_ALLOW', serialize(array()));
}
}
$vendor_autoload = PSM_PATH_SRC.'..'.DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'autoload.php';
if (!file_exists($vendor_autoload)) {
trigger_error("No dependencies found in vendor dir. Did you install the dependencies? Please run \"php composer.phar install\".", E_USER_ERROR);
}
require_once $vendor_autoload;
$vendor_autoload = PSM_PATH_SRC . '..' . DIRECTORY_SEPARATOR . 'vendor' .
DIRECTORY_SEPARATOR . 'autoload.php';
if (!file_exists($vendor_autoload)) {
trigger_error(
"No dependencies found in vendor dir. Did you install the dependencies?
Please run \"php composer.phar install\".",
E_USER_ERROR
);
}
require_once $vendor_autoload;
$router = new psm\Router();
// this may seem insignificant, but right now lots of functions depend on the following global var definition:
$db = $router->getService('db');
$router = new psm\Router();
// this may seem insignificant, but right now lots of functions
// depend on the following global var definition:
$db = $router->getService('db');
// sanity check!
if (!defined('PSM_INSTALL') || !PSM_INSTALL) {
// sanity check!
if (!defined('PSM_INSTALL') || !PSM_INSTALL) {
if ($db->getDbHost() === null) {
// no config file has been loaded, redirect the user to the install
header('Location: install.php');
@ -92,9 +100,14 @@ if (!defined('PSM_INSTALL') || !PSM_INSTALL) {
// config load OK, make sure database version is up to date
$installer = new \psm\Util\Install\Installer($db);
if ($installer->isUpgradeRequired()) {
trigger_error("Your database is for an older version and requires an upgrade, <a href=\"install.php\">please click here</a> to update your database to the latest version.", E_USER_ERROR);
trigger_error(
"Your database is for an older version and requires an upgrade,
<a href=\"install.php\">please click here</a> to update your database to the latest version.",
E_USER_ERROR
);
}
}
}
$lang = psm_get_conf('language', 'en_US');
psm_load_lang($lang);
$lang = psm_get_conf('language', 'en_US');
psm_load_lang($lang);
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -25,6 +26,8 @@
* @link http://www.phpservermonitor.org/
**/
namespace {
###############################################
#
# Language functions
@ -38,7 +41,8 @@
* @return string|bool
* @see psm_load_lang()
*/
function psm_get_lang() {
function psm_get_lang()
{
$args = func_get_args();
if (empty($args)) {
@ -66,7 +70,7 @@ function psm_get_lang() {
$lang = $lang[$translation];
}
return $lang;
}
}
/**
* Load default language from the English (en_US) language file to the $GLOBALS['sm_lang_default'] variable
@ -75,23 +79,29 @@ function psm_get_lang() {
* @param string $lang language
* @see psm_get_lang()
*/
function psm_load_lang($lang) {
function psm_load_lang($lang)
{
// load default language - English (en_US)
// this will also fill in every part that is not translated in other translation files
$default_lang_file = PSM_PATH_LANG.'en_US.lang.php';
$default_lang_file = PSM_PATH_LANG . 'en_US.lang.php';
file_exists($default_lang_file) ? require $default_lang_file : trigger_error("English translation needs to be installed at all time!", E_USER_ERROR);
isset($sm_lang) ? $GLOBALS['sm_lang_default'] = $sm_lang : trigger_error("\$sm_lang not found in English translation!", E_USER_ERROR);
file_exists($default_lang_file) ? require $default_lang_file :
trigger_error("English translation needs to be installed at all time!", E_USER_ERROR);
isset($sm_lang) ? $GLOBALS['sm_lang_default'] = $sm_lang :
trigger_error("\$sm_lang not found in English translation!", E_USER_ERROR);
unset($sm_lang);
// load translation is the selected language is not English (en_US)
if ($lang != "en_US") {
$lang_file = PSM_PATH_LANG.$lang.'.lang.php';
file_exists($lang_file) ? require $lang_file : trigger_error("Translation file could not be found! Default language will be used.", E_USER_WARNING);
$lang_file = PSM_PATH_LANG . $lang . '.lang.php';
file_exists($lang_file) ? require $lang_file :
trigger_error("Translation file could not be found! Default language will be used.", E_USER_WARNING);
isset($sm_lang) ? $GLOBALS['sm_lang'] = $sm_lang : trigger_error("\$sm_lang not found in translation file! Default language will be used.", E_USER_WARNING);
isset($sm_lang['locale']) ? setlocale(LC_TIME, $sm_lang['locale']) : trigger_error("locale could not ben found in translation file.", E_USER_WARNING);
isset($sm_lang) ? $GLOBALS['sm_lang'] = $sm_lang :
trigger_error("\$sm_lang not found in translation file! Default language will be used.", E_USER_WARNING);
isset($sm_lang['locale']) ? setlocale(LC_TIME, $sm_lang['locale']) :
trigger_error("locale could not ben found in translation file.", E_USER_WARNING);
}
}
}
/**
* Retrieve a list with keys of the available languages
@ -99,9 +109,10 @@ function psm_load_lang($lang) {
* @return array
* @see psm_load_lang()
*/
function psm_get_langs() {
function psm_get_langs()
{
$fn_ext = '.lang.php';
$lang_files = glob(PSM_PATH_LANG.'*'.$fn_ext);
$lang_files = glob(PSM_PATH_LANG . '*' . $fn_ext);
$langs = array();
foreach ($lang_files as $file) {
@ -120,15 +131,16 @@ function psm_get_langs() {
}
ksort($langs);
return $langs;
}
}
/**
* Retrieve a list with available sms gateways
*
* @return array
*/
function psm_get_sms_gateways() {
$sms_gateway_files = glob(PSM_PATH_SMS_GATEWAY.'*.php');
function psm_get_sms_gateways()
{
$sms_gateway_files = glob(PSM_PATH_SMS_GATEWAY . '*.php');
$sms_gateways = array();
foreach ($sms_gateway_files as $file) {
@ -141,7 +153,7 @@ function psm_get_sms_gateways() {
ksort($sms_gateways);
return $sms_gateways;
}
}
/**
* Get a setting from the config.
@ -151,14 +163,15 @@ function psm_get_sms_gateways() {
* @return string
* @see psm_load_conf()
*/
function psm_get_conf($key, $alt = null) {
function psm_get_conf($key, $alt = null)
{
if (!isset($GLOBALS['sm_config'])) {
psm_load_conf();
}
$result = (isset($GLOBALS['sm_config'][$key])) ? $GLOBALS['sm_config'][$key] : $alt;
return $result;
}
}
/**
* Load config from the database to the $GLOBALS['sm_config'] variable
@ -167,7 +180,8 @@ function psm_get_conf($key, $alt = null) {
* @return boolean
* @see psm_get_conf()
*/
function psm_load_conf() {
function psm_load_conf()
{
global $db;
$GLOBALS['sm_config'] = array();
@ -175,10 +189,10 @@ function psm_load_conf() {
if (!defined('PSM_DB_PREFIX') || !$db->status()) {
return false;
}
if (!$db->ifTableExists(PSM_DB_PREFIX.'config')) {
if (!$db->ifTableExists(PSM_DB_PREFIX . 'config')) {
return false;
}
$config_db = $db->select(PSM_DB_PREFIX.'config', null, array('key', 'value'));
$config_db = $db->select(PSM_DB_PREFIX . 'config', null, array('key', 'value'));
if (is_array($config_db) && !empty($config_db)) {
foreach ($config_db as $setting) {
@ -188,7 +202,7 @@ function psm_load_conf() {
} else {
return false;
}
}
}
/**
* Update a config setting.
@ -198,7 +212,8 @@ function psm_load_conf() {
* @param string $key
* @param string $value
*/
function psm_update_conf($key, $value) {
function psm_update_conf($key, $value)
{
global $db;
// check if key exists
@ -206,7 +221,7 @@ function psm_update_conf($key, $value) {
if ($exists === false) {
// add new config record
$db->save(
PSM_DB_PREFIX.'config',
PSM_DB_PREFIX . 'config',
array(
'key' => $key,
'value' => $value,
@ -214,13 +229,13 @@ function psm_update_conf($key, $value) {
);
} else {
$db->save(
PSM_DB_PREFIX.'config',
PSM_DB_PREFIX . 'config',
array('value' => $value),
array('key' => $key)
);
}
$GLOBALS['sm_config'][$key] = $value;
}
}
###############################################
#
@ -238,18 +253,19 @@ function psm_update_conf($key, $value) {
*
* @return int log_id
*/
function psm_add_log($server_id, $type, $message) {
function psm_add_log($server_id, $type, $message)
{
global $db;
return $db->save(
PSM_DB_PREFIX.'log',
PSM_DB_PREFIX . 'log',
array(
'server_id' => $server_id,
'type' => $type,
'message' => $message,
)
);
}
}
/**
* This function just adds a user to the log_users table.
@ -257,17 +273,18 @@ function psm_add_log($server_id, $type, $message) {
* @param $log_id
* @param $user_id
*/
function psm_add_log_user($log_id, $user_id) {
function psm_add_log_user($log_id, $user_id)
{
global $db;
$db->save(
PSM_DB_PREFIX.'log_users',
PSM_DB_PREFIX . 'log_users',
array(
'log_id' => $log_id,
'user_id' => $user_id,
)
);
}
}
/**
* This function adds the result of a check to the uptime table for logging purposes.
@ -276,11 +293,12 @@ function psm_add_log_user($log_id, $user_id) {
* @param int $status
* @param string $latency
*/
function psm_log_uptime($server_id, $status, $latency) {
function psm_log_uptime($server_id, $status, $latency)
{
global $db;
$db->save(
PSM_DB_PREFIX.'servers_uptime',
PSM_DB_PREFIX . 'servers_uptime',
array(
'server_id' => $server_id,
'date' => date('Y-m-d H:i:s'),
@ -288,7 +306,7 @@ function psm_log_uptime($server_id, $status, $latency) {
'latency' => $latency,
)
);
}
}
/**
* Converts an interval into a string
@ -296,36 +314,57 @@ function psm_log_uptime($server_id, $status, $latency) {
* @param DateInterval $interval
* @return string
*/
function psm_format_interval(DateInterval $interval) {
function psm_format_interval(DateInterval $interval)
{
$result = "";
if ($interval->y) { $result .= $interval->format("%y ").(($interval->y == 1) ? psm_get_lang('system', 'year') : psm_get_lang('system', 'years'))." "; }
if ($interval->m) { $result .= $interval->format("%m ").(($interval->m == 1) ? psm_get_lang('system', 'month') : psm_get_lang('system', 'months'))." "; }
if ($interval->d) { $result .= $interval->format("%d ").(($interval->d == 1) ? psm_get_lang('system', 'day') : psm_get_lang('system', 'days'))." "; }
if ($interval->h) { $result .= $interval->format("%h ").(($interval->h == 1) ? psm_get_lang('system', 'hour') : psm_get_lang('system', 'hours'))." "; }
if ($interval->i) { $result .= $interval->format("%i ").(($interval->i == 1) ? psm_get_lang('system', 'minute') : psm_get_lang('system', 'minutes'))." "; }
if ($interval->s) { $result .= $interval->format("%s ").(($interval->s == 1) ? psm_get_lang('system', 'second') : psm_get_lang('system', 'seconds'))." "; }
if ($interval->y) {
$result .= $interval->format("%y ") . (($interval->y == 1) ?
psm_get_lang('system', 'year') : psm_get_lang('system', 'years')) . " ";
}
if ($interval->m) {
$result .= $interval->format("%m ") . (($interval->m == 1) ?
psm_get_lang('system', 'month') : psm_get_lang('system', 'months')) . " ";
}
if ($interval->d) {
$result .= $interval->format("%d ") . (($interval->d == 1) ?
psm_get_lang('system', 'day') : psm_get_lang('system', 'days')) . " ";
}
if ($interval->h) {
$result .= $interval->format("%h ") . (($interval->h == 1) ?
psm_get_lang('system', 'hour') : psm_get_lang('system', 'hours')) . " ";
}
if ($interval->i) {
$result .= $interval->format("%i ") . (($interval->i == 1) ?
psm_get_lang('system', 'minute') : psm_get_lang('system', 'minutes')) . " ";
}
if ($interval->s) {
$result .= $interval->format("%s ") . (($interval->s == 1) ?
psm_get_lang('system', 'second') : psm_get_lang('system', 'seconds')) . " ";
}
return $result;
}
}
/**
* Parses a string from the language file with the correct variables replaced in the message
*
* @param boolean|null $status
* @param string $type is either 'sms', 'email', 'pushover_title', 'pushover_message' or 'telegram_message'
* @param array $vars server information about the server which may be placed in a message: %KEY% will be replaced by your value
* @param array $vars server information about the server which may be placed in a message:
* %KEY% will be replaced by your value
* @param boolean $combi parse other message if notifications need to be send combined
* @return string parsed message
*/
function psm_parse_msg($status, $type, $vars, $combi = false) {
if(is_bool($status)) {
function psm_parse_msg($status, $type, $vars, $combi = false)
{
if (is_bool($status)) {
$status = ($status === true) ? 'on_' : 'off_';
}
$combi = ($combi === true) ? 'combi_' : '';
$message = psm_get_lang('notifications', $combi.$status.$type);
$message = psm_get_lang('notifications', $combi . $status . $type);
if (!$message) {
return $message;
@ -333,11 +372,11 @@ function psm_parse_msg($status, $type, $vars, $combi = false) {
$vars['date'] = date('Y-m-d H:i:s');
foreach ($vars as $k => $v) {
$message = str_replace('%'.strtoupper($k).'%', $v, $message);
$message = str_replace('%' . strtoupper($k) . '%', $v, $message);
}
return $message;
}
}
/**
* Shortcut to curl_init(), curl_exec and curl_close()
@ -353,11 +392,21 @@ function psm_parse_msg($status, $type, $vars, $combi = false) {
* @param string|null $post_field POST data
* @return string cURL result
*/
function psm_curl_get($href, $header = false, $body = true, $timeout = null, $add_agent = true, $website_username = false, $website_password = false, $request_method = null, $post_field = null) {
function psm_curl_get(
$href,
$header = false,
$body = true,
$timeout = null,
$add_agent = true,
$website_username = false,
$website_password = false,
$request_method = null,
$post_field = null
) {
($timeout === null || $timeout > 0) ? PSM_CURL_TIMEOUT : intval($timeout);
$ch = curl_init();
if(defined('PSM_DEBUG') && PSM_DEBUG === true && psm_is_cli()) {
if (defined('PSM_DEBUG') && PSM_DEBUG === true && psm_is_cli()) {
curl_setopt($ch, CURLOPT_VERBOSE, true);
}
curl_setopt($ch, CURLOPT_HEADER, $header);
@ -378,11 +427,16 @@ function psm_curl_get($href, $header = false, $body = true, $timeout = null, $ad
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_field);
}
if ($website_username !== false && $website_password !== false && !empty($website_username) && !empty($website_password)) {
curl_setopt($ch, CURLOPT_USERPWD, $website_username.":".$website_password);
if (
$website_username !== false &&
$website_password !== false &&
!empty($website_username) &&
!empty($website_password)
) {
curl_setopt($ch, CURLOPT_USERPWD, $website_username . ":" . $website_password);
}
$href = preg_replace('/(.*)(%cachebuster%)/', '$0'.time(), $href);
$href = preg_replace('/(.*)(%cachebuster%)/', '$0' . time(), $href);
curl_setopt($ch, CURLOPT_URL, $href);
@ -392,25 +446,28 @@ function psm_curl_get($href, $header = false, $body = true, $timeout = null, $ad
$proxy_user = psm_get_conf('proxy_user', '');
$proxy_password = psm_get_conf('proxy_password', '');
if (!empty($proxy_user) && !empty($proxy_password)) {
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxy_user.':'.$proxy_password);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxy_user . ':' . $proxy_password);
}
}
if ($add_agent) {
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; phpservermon/'.PSM_VERSION.'; +https://github.com/phpservermon/phpservermon)');
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; phpservermon/' .
PSM_VERSION . '; +https://github.com/phpservermon/phpservermon)');
}
$result = curl_exec($ch);
curl_close($ch);
if(defined('PSM_DEBUG') && PSM_DEBUG === true && psm_is_cli()) {
echo PHP_EOL.'==============cURL Result for: '.$href.'==========================================='.PHP_EOL;
if (defined('PSM_DEBUG') && PSM_DEBUG === true && psm_is_cli()) {
echo PHP_EOL .
'==============cURL Result for: ' . $href . '===========================================' . PHP_EOL;
print_r($result);
echo PHP_EOL.'==============END cURL Resul for: '.$href.'==========================================='.PHP_EOL;
echo PHP_EOL .
'==============END cURL Resul for: ' . $href . '===========================================' . PHP_EOL;
}
return $result;
}
}
/**
* Get a "nice" timespan message
@ -419,13 +476,17 @@ function psm_curl_get($href, $header = false, $body = true, $timeout = null, $ad
* @param string $time
* @return string
*/
function psm_timespan($time) {
function psm_timespan($time)
{
if (empty($time) || $time == '0000-00-00 00:00:00') {
return psm_get_lang('system', 'never');
}
if ($time !== intval($time)) { $time = strtotime($time); }
if ($time !== intval($time)) {
$time = strtotime($time);
}
if ($time < strtotime(date('Y-m-d 00:00:00')) - 60 * 60 * 24 * 3) {
$format = psm_get_lang('system', (date('Y') !== date('Y', $time)) ? 'long_day_format' : 'short_day_format');
$format = psm_get_lang('system', (date('Y') !== date('Y', $time)) ?
'long_day_format' : 'short_day_format');
// Check for Windows to find and replace the %e
// modifier correctly
if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
@ -435,29 +496,41 @@ function psm_timespan($time) {
}
$d = time() - $time;
if ($d >= 60 * 60 * 24) {
$format = psm_get_lang('system', (date('l', time() - 60 * 60 * 24) == date('l', $time)) ? 'yesterday_format' : 'other_day_format');
$format = psm_get_lang('system', (date('l', time() - 60 * 60 * 24) == date('l', $time)) ?
'yesterday_format' : 'other_day_format');
return strftime($format, $time);
}
if ($d >= 60 * 60 * 2) { return sprintf(psm_get_lang('system', 'hours_ago'), intval($d / (60 * 60))); }
if ($d >= 60 * 60) { return psm_get_lang('system', 'an_hour_ago'); }
if ($d >= 60 * 2) { return sprintf(psm_get_lang('system', 'minutes_ago'), intval($d / 60)); }
if ($d >= 60) { return psm_get_lang('system', 'a_minute_ago'); }
if ($d >= 2) { return sprintf(psm_get_lang('system', 'seconds_ago'), intval($d)); }
if ($d >= 60 * 60 * 2) {
return sprintf(psm_get_lang('system', 'hours_ago'), intval($d / (60 * 60)));
}
if ($d >= 60 * 60) {
return psm_get_lang('system', 'an_hour_ago');
}
if ($d >= 60 * 2) {
return sprintf(psm_get_lang('system', 'minutes_ago'), intval($d / 60));
}
if ($d >= 60) {
return psm_get_lang('system', 'a_minute_ago');
}
if ($d >= 2) {
return sprintf(psm_get_lang('system', 'seconds_ago'), intval($d));
}
return psm_get_lang('system', 'a_second_ago');
}
}
/**
* Get a localised date from MySQL date format
* @param string $time
* @return string
*/
function psm_date($time) {
function psm_date($time)
{
if (empty($time) || $time == '0000-00-00 00:00:00') {
return psm_get_lang('system', 'never');
}
return strftime('%x %X', strtotime($time));
}
}
/**
* Check if an update is available for PHP Server Monitor.
@ -465,7 +538,8 @@ function psm_date($time) {
* Will only check for new version if user turned updates on in config.
* @return boolean
*/
function psm_update_available() {
function psm_update_available()
{
if (!psm_get_conf('show_update')) {
// user does not want updates, fair enough.
return false;
@ -494,7 +568,7 @@ function psm_update_available() {
} else {
return false;
}
}
}
/**
* Prepare a new phpmailer instance.
@ -504,7 +578,8 @@ function psm_update_available() {
* @param string $from_email
* @return \PHPMailer\PHPMailer\PHPMailer
*/
function psm_build_mail($from_name = null, $from_email = null) {
function psm_build_mail($from_name = null, $from_email = null)
{
$phpmailer = new \PHPMailer\PHPMailer\PHPMailer();
$phpmailer->Encoding = "base64";
$phpmailer->CharSet = 'UTF-8';
@ -536,37 +611,40 @@ function psm_build_mail($from_name = null, $from_email = null) {
$phpmailer->SetFrom($from_email, $from_name);
return $phpmailer;
}
}
/**
* Prepare a new Pushover util.
*
* @return \Pushover
*/
function psm_build_pushover() {
function psm_build_pushover()
{
$pushover = new \Pushover();
$pushover->setToken(psm_get_conf('pushover_api_token'));
return $pushover;
}
}
/**
*
* @return \Telegram
*/
function psm_build_telegram() {
function psm_build_telegram()
{
$telegram = new \Telegram();
$telegram->setToken(psm_get_conf('telegram_api_token'));
return $telegram;
}
}
/**
* Prepare a new SMS util.
*
* @return \psm\Txtmsg\TxtmsgInterface
*/
function psm_build_sms() {
function psm_build_sms()
{
$sms = null;
// open the right class
@ -641,7 +719,7 @@ function psm_build_sms() {
}
return $sms;
}
}
/**
* Generate a new link to the current monitor
@ -650,17 +728,19 @@ function psm_build_sms() {
* @param boolean $htmlentities use entities in url?
* @return string
*/
function psm_build_url($params = array(), $urlencode = true, $htmlentities = true) {
function psm_build_url($params = array(), $urlencode = true, $htmlentities = true)
{
if (defined('PSM_BASE_URL') && PSM_BASE_URL !== null) {
$url = PSM_BASE_URL;
} else {
$url = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443 ? 'https' : 'http').'://'.$_SERVER['HTTP_HOST'];
$url = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') ||
$_SERVER['SERVER_PORT'] == 443 ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'];
// on Windows, dirname() adds both back- and forward slashes (http://php.net/dirname).
// for urls, we only want the forward slashes.
$url .= dirname($_SERVER['SCRIPT_NAME']);
$url = str_replace('\\', '', $url);
}
$url = rtrim($url, '/').'/';
$url = rtrim($url, '/') . '/';
if ($params != null) {
$url .= '?';
@ -671,7 +751,7 @@ function psm_build_url($params = array(), $urlencode = true, $htmlentities = tru
if ($urlencode) {
$v = urlencode($v);
}
$url .= $delim.$k.'='.$v;
$url .= $delim . $k . '=' . $v;
}
} else {
$url .= $params;
@ -679,7 +759,7 @@ function psm_build_url($params = array(), $urlencode = true, $htmlentities = tru
}
return $url;
}
}
/**
* Try existence of a GET var, if not return the alternative
@ -687,13 +767,14 @@ function psm_build_url($params = array(), $urlencode = true, $htmlentities = tru
* @param string $alt
* @return mixed
*/
function psm_GET($key, $alt = null) {
function psm_GET($key, $alt = null)
{
if (isset($_GET[$key])) {
return $_GET[$key];
} else {
return $alt;
}
}
}
/**
* Try existence of a POST var, if not return the alternative
@ -701,13 +782,14 @@ function psm_GET($key, $alt = null) {
* @param string|array|bool $alt
* @return mixed
*/
function psm_POST($key, $alt = null) {
function psm_POST($key, $alt = null)
{
if (isset($_POST[$key])) {
return $_POST[$key];
} else {
return $alt;
}
}
}
/**
* Check if we are in CLI mode
@ -715,9 +797,10 @@ function psm_POST($key, $alt = null) {
* Note, php_sapi cannot be used because cgi-fcgi returns both for web and cli.
* @return boolean
*/
function psm_is_cli() {
function psm_is_cli()
{
return (!isset($_SERVER['SERVER_SOFTWARE']) || php_sapi_name() == 'cli');
}
}
###############################################
#
@ -730,24 +813,26 @@ function psm_is_cli() {
*
* @param mixed $arr
*/
function pre($arr = null) {
function pre($arr = null)
{
echo "<pre>";
if ($arr === null) {
debug_print_backtrace();
}
print_r($arr);
echo "</pre>";
}
}
/**
* Send headers to the browser to avoid caching
*/
function psm_no_cache() {
function psm_no_cache()
{
header("Expires: Mon, 20 Dec 1998 01:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
}
}
/**
* Encrypts the password for storage in the database
@ -757,8 +842,8 @@ function psm_no_cache() {
* @return string
* @author Pavel Laupe Dvorak <pavel@pavel-dvorak.cz>
*/
function psm_password_encrypt($key, $password)
{
function psm_password_encrypt($key, $password)
{
if (empty($password)) {
return '';
}
@ -768,9 +853,9 @@ function psm_password_encrypt($key, $password)
}
// using open ssl
$cipher="AES-256-CBC";
$cipher = "AES-256-CBC";
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes( $ivlen );
$iv = openssl_random_pseudo_bytes($ivlen);
$encrypted = base64_encode(
$iv .
openssl_encrypt(
@ -783,7 +868,7 @@ function psm_password_encrypt($key, $password)
);
return $encrypted;
}
}
/**
* Decrypts password stored in the database for future use
@ -793,8 +878,8 @@ function psm_password_encrypt($key, $password)
* @return string
* @author Pavel Laupe Dvorak <pavel@pavel-dvorak.cz>
*/
function psm_password_decrypt($key, $encryptedString)
{
function psm_password_decrypt($key, $encryptedString)
{
if (empty($encryptedString)) {
return '';
}
@ -805,7 +890,7 @@ function psm_password_decrypt($key, $encryptedString)
// using open ssl
$data = base64_decode($encryptedString);
$cipher="AES-256-CBC";
$cipher = "AES-256-CBC";
$ivlen = openssl_cipher_iv_length($cipher);
$iv = substr($data, 0, $ivlen);
$decrypted = rtrim(
@ -814,12 +899,13 @@ function psm_password_decrypt($key, $encryptedString)
$cipher,
hash('sha256', $key, true),
OPENSSL_ZERO_PADDING,
$iv),
$iv
),
"\0"
);
return $decrypted;
}
}
/**
* Send notification to Telegram
@ -827,30 +913,34 @@ function psm_password_decrypt($key, $encryptedString)
* @return string
* @author Tim Zandbergen <tim@xervion.nl>
*/
class telegram
{
private $_token;
private $_user;
private $_message;
private $_url;
class Telegram
{
private $token;
private $user;
private $message;
private $url;
public function setToken($token) {
$this->_token = (string) $token;
public function setToken($token)
{
$this->token = (string) $token;
}
public function setUser($user) {
$this->_user = (string) $user;
public function setUser($user)
{
$this->user = (string) $user;
}
public function setMessage($message) {
$message = str_replace("<ul>","",$message);
$message = str_replace("</ul>","\n",$message);
$message = str_replace("<li>","- ",$message);
$message = str_replace("</li>","\n",$message);
$message = str_replace("<br>","\n",$message);
$message = str_replace("<br/>","\n",$message);
$this->_message = (string) $message;
public function setMessage($message)
{
$message = str_replace("<ul>", "", $message);
$message = str_replace("</ul>", "\n", $message);
$message = str_replace("<li>", "- ", $message);
$message = str_replace("</li>", "\n", $message);
$message = str_replace("<br>", "\n", $message);
$message = str_replace("<br/>", "\n", $message);
$this->message = (string) $message;
}
public function sendurl() {
$con = curl_init($this->_url);
public function sendurl()
{
$con = curl_init($this->url);
curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
curl_setopt($con, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($con, CURLOPT_TIMEOUT, 60);
@ -858,19 +948,22 @@ class telegram
$response = json_decode($response, true);
return $response;
}
public function send() {
if (!Empty($this->_token) && !Empty($this->_user) && !Empty($this->_message)) {
$this->_url = 'https://api.telegram.org/bot'.urlencode($this->_token).
'/sendMessage?chat_id='.urlencode($this->_user).'&text='.
urlencode($this->_message).'&parse_mode=HTML';
public function send()
{
if (!empty($this->token) && !empty($this->user) && !empty($this->message)) {
$this->url = 'https://api.telegram.org/bot' . urlencode($this->token) .
'/sendMessage?chat_id=' . urlencode($this->user) . '&text=' .
urlencode($this->message) . '&parse_mode=HTML';
}
return $this->sendurl();
}
// Get the bots username
public function getBotUsername() {
if (!Empty($this->_token)) {
$this->_url = 'https://api.telegram.org/bot'.urlencode($this->_token).'/getMe';
public function getBotUsername()
{
if (!empty($this->token)) {
$this->url = 'https://api.telegram.org/bot' . urlencode($this->token) . '/getMe';
}
return $this->sendurl();
}
}
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -35,7 +36,6 @@
*/
if (!defined('PASSWORD_DEFAULT')) {
define('PASSWORD_BCRYPT', 1);
define('PASSWORD_DEFAULT', PASSWORD_BCRYPT);
@ -48,7 +48,8 @@ if (!defined('PASSWORD_DEFAULT')) {
*
* @return string|false The hashed password, or false on error.
*/
function password_hash($password, $algo, array $options = array()) {
function password_hash($password, $algo, array $options = array())
{
if (!function_exists('crypt')) {
trigger_error("Crypt must be loaded for password_hash to function", E_USER_WARNING);
return null;
@ -58,7 +59,8 @@ if (!defined('PASSWORD_DEFAULT')) {
return null;
}
if (!is_int($algo)) {
trigger_error("password_hash() expects parameter 2 to be long, ".gettype($algo)." given", E_USER_WARNING);
trigger_error("password_hash() expects parameter 2 to be long, " . gettype($algo) .
" given", E_USER_WARNING);
return null;
}
switch ($algo) {
@ -68,7 +70,10 @@ if (!defined('PASSWORD_DEFAULT')) {
if (isset($options['cost'])) {
$cost = $options['cost'];
if ($cost < 4 || $cost > 31) {
trigger_error(sprintf("password_hash(): Invalid bcrypt cost parameter specified: %d", $cost), E_USER_WARNING);
trigger_error(
sprintf("password_hash(): Invalid bcrypt cost parameter specified: %d", $cost),
E_USER_WARNING
);
return null;
}
}
@ -79,7 +84,10 @@ if (!defined('PASSWORD_DEFAULT')) {
$hash_format = sprintf("$2y$%02d$", $cost);
break;
default:
trigger_error(sprintf("password_hash(): Unknown password hashing algorithm: %s", $algo), E_USER_WARNING);
trigger_error(
sprintf("password_hash(): Unknown password hashing algorithm: %s", $algo),
E_USER_WARNING
);
return null;
}
if (isset($options['salt'])) {
@ -96,6 +104,7 @@ if (!defined('PASSWORD_DEFAULT')) {
$salt = (string) $options['salt'];
break;
}
// no break
case 'array':
case 'resource':
default:
@ -103,7 +112,14 @@ if (!defined('PASSWORD_DEFAULT')) {
return null;
}
if (strlen($salt) < $required_salt_len) {
trigger_error(sprintf("password_hash(): Provided salt is too short: %d expecting %d", strlen($salt), $required_salt_len), E_USER_WARNING);
trigger_error(
sprintf(
"password_hash(): Provided salt is too short: %d expecting %d",
strlen($salt),
$required_salt_len
),
E_USER_WARNING
);
return null;
} elseif (0 == preg_match('#^[a-zA-Z0-9./]+$#D', $salt)) {
$salt = str_replace('+', '.', base64_encode($salt));
@ -149,7 +165,7 @@ if (!defined('PASSWORD_DEFAULT')) {
}
$salt = substr($salt, 0, $required_salt_len);
$hash = $hash_format.$salt;
$hash = $hash_format . $salt;
$ret = crypt($password, $hash);
@ -176,7 +192,8 @@ if (!defined('PASSWORD_DEFAULT')) {
*
* @return array The array of information about the hash.
*/
function password_get_info($hash) {
function password_get_info($hash)
{
$return = array(
'algo' => 0,
'algoName' => 'unknown',
@ -202,7 +219,8 @@ if (!defined('PASSWORD_DEFAULT')) {
*
* @return boolean True if the password needs to be rehashed.
*/
function password_needs_rehash($hash, $algo, array $options = array()) {
function password_needs_rehash($hash, $algo, array $options = array())
{
$info = password_get_info($hash);
if ($info['algo'] != $algo) {
return true;
@ -226,7 +244,8 @@ if (!defined('PASSWORD_DEFAULT')) {
*
* @return boolean If the password matches the hash
*/
function password_verify($password, $hash) {
function password_verify($password, $hash)
{
if (!function_exists('crypt')) {
trigger_error("Crypt must be loaded for password_verify to function", E_USER_WARNING);
return false;

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -212,13 +213,13 @@ $sm_lang = array(
'pushover_api_token' => 'Pushover App API Token',
'pushover_api_token_description' => 'Før du kan benytte Pushover, skal du <a href="%1$s" target="_blank" rel="noopener">registrere en app</a> på deres website og indtaste en App API Token her.',
'alert_type' => 'Vælg hvornår du vil modtage beskeden',
'alert_type_description' => '<b>Status ændring:</b> '.
'Du vil modtage en notifkation når en server har en ændring i status. Fra online -> offline eller offline -> online.<br>'.
'<br /><b>Offline:</b> '.
'Du vil modtage en meddelelse, når en server går offline for første gang. Eksempelvis '.
'hvis dit cronjob kører hvert kvarter, og din server går ned kl 01 og kommer først op kl 06, '.
' vil du kun modtage en mail kl 01.<br>'.
'<br><b>Altid:</b> '.
'alert_type_description' => '<b>Status ændring:</b> ' .
'Du vil modtage en notifkation når en server har en ændring i status. Fra online -> offline eller offline -> online.<br>' .
'<br /><b>Offline:</b> ' .
'Du vil modtage en meddelelse, når en server går offline for første gang. Eksempelvis ' .
'hvis dit cronjob kører hvert kvarter, og din server går ned kl 01 og kommer først op kl 06, ' .
' vil du kun modtage en mail kl 01.<br>' .
'<br><b>Altid:</b> ' .
'Du vil modtage en besked, hver gang scriptet kører og et websted er nede, selvom site har været offline i flere timer.',
'alert_type_status' => 'Status ændret',
'alert_type_offline' => 'Offline',
@ -239,9 +240,9 @@ $sm_lang = array(
'settings_log' => 'Log indstillinger',
'auto_refresh' => 'Genopfrisk automatisk',
'auto_refresh_description' =>
'Genopfrisk automatisk serversider.<br>'.
'<span class="small">'.
'Tid i sekunder. Hvis 0 vil siden ikke genopfriske automatisk'.
'Genopfrisk automatisk serversider.<br>' .
'<span class="small">' .
'Tid i sekunder. Hvis 0 vil siden ikke genopfriske automatisk' .
'</span>',
'seconds' => 'sekunder',
'test' => 'Test',

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -26,12 +27,13 @@
**/
namespace psm\Module;
use psm\Service\Database;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
abstract class AbstractController implements ControllerInterface {
abstract class AbstractController implements ControllerInterface
{
use ContainerAwareTrait;
/**
@ -144,7 +146,8 @@ abstract class AbstractController implements ControllerInterface {
*/
protected $xhr = false;
function __construct(Database $db, \Twig_Environment $twig) {
public function __construct(Database $db, \Twig_Environment $twig)
{
$this->db = $db;
$this->twig = $twig;
}
@ -155,7 +158,8 @@ abstract class AbstractController implements ControllerInterface {
* @param string $action if NULL, the action will be retrieved from user input (GET/POST)
* @return \Symfony\Component\HttpFoundation\Response
*/
public function run($action = null) {
public function run($action = null)
{
if ($action === null) {
$action = psm_GET('action', psm_POST('action', $this->action_default));
}
@ -180,14 +184,15 @@ abstract class AbstractController implements ControllerInterface {
* @param string $action
* @return mixed FALSE when action couldnt be initialized, response otherwise
*/
protected function runAction($action) {
protected function runAction($action)
{
if (isset($this->user_level_required_actions[$action])) {
if ($this->getUser()->getUserLevel() > $this->user_level_required_actions[$action]) {
// user is not allowed to access this action..
return false;
}
}
$method = 'execute'.ucfirst($action);
$method = 'execute' . ucfirst($action);
if (method_exists($this, $method)) {
$this->action = $action;
$result = $this->$method();
@ -205,14 +210,15 @@ abstract class AbstractController implements ControllerInterface {
* @param string $html HTML code to add to the main body
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function createHTML($html = null) {
protected function createHTML($html = null)
{
if (!$this->xhr) {
// in XHR mode, we will not add the main template
$tpl_data = array(
'title' => strtoupper(psm_get_lang('system', 'title')),
'label_back_to_top' => psm_get_lang('system', 'back_to_top'),
'add_footer' => $this->add_footer,
'version' => 'v'.PSM_VERSION,
'version' => 'v' . PSM_VERSION,
'messages' => $this->getMessages(),
'html_content' => $html,
);
@ -239,7 +245,12 @@ abstract class AbstractController implements ControllerInterface {
}
if (psm_update_available()) {
$tpl_data['update_available'] = str_replace('{version}', 'v'.psm_get_conf('version_update_check'), psm_get_lang('system', 'update_available'));
$tpl_data['update_available'] = str_replace(
'{version}',
'v' .
psm_get_conf('version_update_check'),
psm_get_lang('system', 'update_available')
);
}
if ($this->black_background) {
@ -257,7 +268,8 @@ abstract class AbstractController implements ControllerInterface {
* Create HTML code for the menu
* @return string
*/
protected function createHTMLMenu() {
protected function createHTMLMenu()
{
$ulvl = $this->getUser()->getUserLevel();
$tpl_data = array(
@ -304,7 +316,8 @@ abstract class AbstractController implements ControllerInterface {
* Hide or show the footer of the page
* @param boolean $value
*/
protected function addFooter($value) {
protected function addFooter($value)
{
$this->add_footer = $value;
}
@ -312,7 +325,8 @@ abstract class AbstractController implements ControllerInterface {
* Hide or show the menu of the page
* @param boolean $value
*/
protected function addMenu($value) {
protected function addMenu($value)
{
$this->add_menu = $value;
}
@ -324,7 +338,8 @@ abstract class AbstractController implements ControllerInterface {
* @return psm\Module\AbstractModule
* @see getAction()
*/
protected function setActions($actions, $default = null, $append = true) {
protected function setActions($actions, $default = null, $append = true)
{
if (!is_array($actions)) {
$actions = array($actions);
}
@ -344,7 +359,8 @@ abstract class AbstractController implements ControllerInterface {
* @return string
* @see setActions()
*/
public function getAction() {
public function getAction()
{
return $this->action;
}
@ -355,15 +371,16 @@ abstract class AbstractController implements ControllerInterface {
* @return \psm\Module\ControllerInterface
* @see getMessages()
*/
public function addMessage($msg, $shortcode = 'primary') {
public function addMessage($msg, $shortcode = 'primary')
{
if (!is_array($msg)) {
$msg = array($msg);
}
$class= $shortcode;
$class = $shortcode;
switch ($shortcode) {
case 'error':
$icon = 'exclamation-circle';
$class= 'danger';
$class = 'danger';
break;
case 'success':
$icon = 'check-circle';
@ -395,7 +412,8 @@ abstract class AbstractController implements ControllerInterface {
* @return array
* @see addMessage()
*/
public function getMessages($clear = true) {
public function getMessages($clear = true)
{
$msgs = $this->messages;
if ($clear) {
$this->messages = array();
@ -408,7 +426,8 @@ abstract class AbstractController implements ControllerInterface {
* @param int $level
* @return \psm\Module\AbstractController
*/
public function setMinUserLevelRequired($level) {
public function setMinUserLevelRequired($level)
{
$this->user_level_required = intval($level);
return $this;
}
@ -417,7 +436,8 @@ abstract class AbstractController implements ControllerInterface {
* Get the minimum required user level for this controller
* @return int
*/
public function getMinUserLevelRequired() {
public function getMinUserLevelRequired()
{
return $this->user_level_required;
}
@ -430,7 +450,8 @@ abstract class AbstractController implements ControllerInterface {
* @return \psm\Module\AbstractController
* @see setMinUserLevelRequired()
*/
public function setMinUserLevelRequiredForAction($level, $actions) {
public function setMinUserLevelRequiredForAction($level, $actions)
{
if (!is_array($actions)) {
$actions = array($actions);
}
@ -445,7 +466,8 @@ abstract class AbstractController implements ControllerInterface {
* @param \psm\Util\Module\SidebarInterface $sidebar
* @return \psm\Module\ControllerInterface
*/
public function setSidebar(\psm\Util\Module\SidebarInterface $sidebar) {
public function setSidebar(\psm\Util\Module\SidebarInterface $sidebar)
{
$this->sidebar = $sidebar;
return $this;
}
@ -455,7 +477,8 @@ abstract class AbstractController implements ControllerInterface {
* @param \psm\Util\Module\ModalInterface $modal
* @return \psm\Module\ControllerInterface
*/
public function addModal(\psm\Util\Module\ModalInterface $modal) {
public function addModal(\psm\Util\Module\ModalInterface $modal)
{
$this->modal[$modal->getModalID()] = $modal;
return $this;
}
@ -464,7 +487,8 @@ abstract class AbstractController implements ControllerInterface {
* Set the html code of the header accessories
* @param string $html
*/
public function setHeaderAccessories($html) {
public function setHeaderAccessories($html)
{
$this->header_accessories = $html;
}
@ -472,7 +496,8 @@ abstract class AbstractController implements ControllerInterface {
* Check if XHR is on
* @return boolean
*/
public function isXHR() {
public function isXHR()
{
return $this->xhr;
}
@ -480,7 +505,8 @@ abstract class AbstractController implements ControllerInterface {
* Get user service
* @return \psm\Service\User
*/
public function getUser() {
public function getUser()
{
return $this->container->get('user');
}
@ -488,7 +514,8 @@ abstract class AbstractController implements ControllerInterface {
* Get custom key for CSRF validation
* @return string
*/
public function getCSRFKey() {
public function getCSRFKey()
{
return $this->csrf_key;
}
@ -497,7 +524,8 @@ abstract class AbstractController implements ControllerInterface {
* @param string $key
* @return \psm\Module\ControllerInterface
*/
protected function setCSRFKey($key) {
protected function setCSRFKey($key)
{
$this->csrf_key = $key;
$this->twig->addGlobal('csrf_key', $key);
return $this;

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -31,16 +32,17 @@ namespace psm\Module\Config;
use psm\Module\ModuleInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class ConfigModule implements ModuleInterface {
public function load(ContainerBuilder $container) {
class ConfigModule implements ModuleInterface
{
public function load(ContainerBuilder $container)
{
}
public function getControllers() {
public function getControllers()
{
return array(
'config' => __NAMESPACE__.'\Controller\ConfigController',
'config' => __NAMESPACE__ . '\Controller\ConfigController',
);
}
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -26,10 +27,12 @@
**/
namespace psm\Module\Config\Controller;
use psm\Module\AbstractController;
use psm\Service\Database;
class ConfigController extends AbstractController {
class ConfigController extends AbstractController
{
/**
* Checkboxes
@ -74,7 +77,8 @@ class ConfigController extends AbstractController {
private $default_tab = 'general';
function __construct(Database $db, \Twig_Environment $twig) {
public function __construct(Database $db, \Twig_Environment $twig)
{
parent::__construct($db, $twig);
$this->setMinUserLevelRequired(PSM_USER_ADMIN);
@ -90,12 +94,13 @@ class ConfigController extends AbstractController {
*
* @return string
*/
protected function executeIndex() {
protected function executeIndex()
{
$this->twig->addGlobal('subtitle', psm_get_lang('menu', 'config'));
$tpl_data = $this->getLabels();
$config_db = $this->db->select(
PSM_DB_PREFIX.'config',
PSM_DB_PREFIX . 'config',
null,
array('key', 'value')
);
@ -131,7 +136,7 @@ class ConfigController extends AbstractController {
foreach (array("status", "offline", "always") as $alert_type) {
$tpl_data['alert_type'][] = array(
'value' => $alert_type,
'label' => psm_get_lang('config', 'alert_type_'.$alert_type),
'label' => psm_get_lang('config', 'alert_type_' . $alert_type),
);
}
@ -150,15 +155,21 @@ class ConfigController extends AbstractController {
)
);
$tpl_data['sms_gateway_selected'] = isset($config['sms_gateway']) ? $config['sms_gateway'] : current($sms_gateways);
$tpl_data['alert_type_selected'] = isset($config['alert_type']) ? $config['alert_type'] : '';
$tpl_data['email_smtp_security_selected'] = isset($config['email_smtp_security']) ? $config['email_smtp_security'] : '';
$tpl_data['auto_refresh_servers'] = isset($config['auto_refresh_servers']) ? $config['auto_refresh_servers'] : '0';
$tpl_data['log_retention_period'] = isset($config['log_retention_period']) ? $config['log_retention_period'] : '365';
$tpl_data['password_encrypt_key'] = isset($config['password_encrypt_key']) ? $config['password_encrypt_key'] : sha1(microtime());
$tpl_data['sms_gateway_selected'] = isset($config['sms_gateway']) ?
$config['sms_gateway'] : current($sms_gateways);
$tpl_data['alert_type_selected'] = isset($config['alert_type']) ?
$config['alert_type'] : '';
$tpl_data['email_smtp_security_selected'] = isset($config['email_smtp_security']) ?
$config['email_smtp_security'] : '';
$tpl_data['auto_refresh_servers'] = isset($config['auto_refresh_servers']) ?
$config['auto_refresh_servers'] : '0';
$tpl_data['log_retention_period'] = isset($config['log_retention_period']) ?
$config['log_retention_period'] : '365';
$tpl_data['password_encrypt_key'] = isset($config['password_encrypt_key']) ?
$config['password_encrypt_key'] : sha1(microtime());
foreach ($this->checkboxes as $input_key) {
$tpl_data[$input_key.'_checked'] =
$tpl_data[$input_key . '_checked'] =
(isset($config[$input_key]) && (int) $config[$input_key] == 1)
? 'checked="checked"'
: '';
@ -167,14 +178,18 @@ class ConfigController extends AbstractController {
$tpl_data[$input_key] = (isset($config[$input_key])) ? $config[$input_key] : '';
}
$tpl_data[$this->default_tab.'_active'] = 'active';
$tpl_data[$this->default_tab . '_active'] = 'active';
$testmodals = array('email', 'sms', 'pushover', 'telegram');
foreach ($testmodals as $modal_id) {
$modal = new \psm\Util\Module\Modal($this->twig, 'test'.ucfirst($modal_id), \psm\Util\Module\Modal::MODAL_TYPE_OKCANCEL);
$modal = new \psm\Util\Module\Modal(
$this->twig,
'test' . ucfirst($modal_id),
\psm\Util\Module\Modal::MODAL_TYPE_OKCANCEL
);
$this->addModal($modal);
$modal->setTitle(psm_get_lang('servers', 'send_'.$modal_id));
$modal->setMessage(psm_get_lang('config', 'test_'.$modal_id));
$modal->setTitle(psm_get_lang('servers', 'send_' . $modal_id));
$modal->setMessage(psm_get_lang('config', 'test_' . $modal_id));
$modal->setOKButtonLabel(psm_get_lang('config', 'send'));
}
@ -185,7 +200,8 @@ class ConfigController extends AbstractController {
* If a post has been done, gather all the posted data
* and save it to the database
*/
protected function executeSave() {
protected function executeSave()
{
if (!empty($_POST)) {
// save new config
$clean = array(
@ -225,7 +241,7 @@ class ConfigController extends AbstractController {
}
if ($language_refresh) {
header('Location: '.psm_build_url(array('mod' => 'config'), true, false));
header('Location: ' . psm_build_url(array('mod' => 'config'), true, false));
die();
}
@ -249,7 +265,8 @@ class ConfigController extends AbstractController {
*
* @todo move test to separate class
*/
protected function testEmail() {
protected function testEmail()
{
$mail = psm_build_mail();
$message = psm_get_lang('config', 'test_message');
$mail->Subject = psm_get_lang('config', 'test_subject');
@ -261,7 +278,7 @@ class ConfigController extends AbstractController {
if ($mail->Send()) {
$this->addMessage(psm_get_lang('config', 'email_sent'), 'success');
} else {
$this->addMessage(psm_get_lang('config', 'email_error').': '.$mail->ErrorInfo, 'error');
$this->addMessage(psm_get_lang('config', 'email_error') . ': ' . $mail->ErrorInfo, 'error');
}
}
@ -270,7 +287,8 @@ class ConfigController extends AbstractController {
*
* @todo move test to separate class
*/
protected function testSMS() {
protected function testSMS()
{
$sms = psm_build_sms();
if ($sms) {
$user = $this->getUser()->getUser();
@ -293,7 +311,8 @@ class ConfigController extends AbstractController {
*
* @todo move test to separate class
*/
protected function testPushover() {
protected function testPushover()
{
$pushover = psm_build_pushover();
$pushover->setDebug(true);
$user = $this->getUser()->getUser();
@ -331,7 +350,8 @@ class ConfigController extends AbstractController {
*
* @todo move test to separate class
*/
protected function testTelegram() {
protected function testTelegram()
{
$telegram = psm_build_telegram();
$user = $this->getUser()->getUser();
$apiToken = psm_get_conf('telegram_api_token');
@ -359,7 +379,8 @@ class ConfigController extends AbstractController {
}
}
protected function getLabels() {
protected function getLabels()
{
return array(
'label_tab_email' => psm_get_lang('config', 'tab_email'),
'label_tab_sms' => psm_get_lang('config', 'tab_sms'),

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -27,10 +28,12 @@
**/
namespace psm\Module;
use psm\Service\Database;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
interface ControllerInterface extends ContainerAwareInterface {
interface ControllerInterface extends ContainerAwareInterface
{
public function __construct(Database $db, \Twig_Environment $twig);

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -27,12 +28,15 @@
**/
namespace psm\Module\Error\Controller;
use psm\Module\AbstractController;
use psm\Service\Database;
class ErrorController extends AbstractController {
class ErrorController extends AbstractController
{
function __construct(Database $db, \Twig_Environment $twig) {
public function __construct(Database $db, \Twig_Environment $twig)
{
parent::__construct($db, $twig);
$this->setMinUserLevelRequired(PSM_USER_ANONYMOUS);
@ -47,7 +51,8 @@ class ErrorController extends AbstractController {
*
* @return string
*/
protected function execute401() {
protected function execute401()
{
return $this->twig->render('module/error/401.tpl.html', array(
'label_title' => psm_get_lang('error', '401_unauthorized'),
'label_description' => psm_get_lang('error', '401_unauthorized_description'),

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -31,16 +32,17 @@ namespace psm\Module\Error;
use psm\Module\ModuleInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class ErrorModule implements ModuleInterface {
public function load(ContainerBuilder $container) {
class ErrorModule implements ModuleInterface
{
public function load(ContainerBuilder $container)
{
}
public function getControllers() {
public function getControllers()
{
return array(
'error' => __NAMESPACE__.'\Controller\ErrorController',
'error' => __NAMESPACE__ . '\Controller\ErrorController',
);
}
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -27,10 +28,12 @@
**/
namespace psm\Module\Install\Controller;
use psm\Module\AbstractController;
use psm\Service\Database;
class InstallController extends AbstractController {
class InstallController extends AbstractController
{
/**
* Full path to config file
@ -44,15 +47,16 @@ class InstallController extends AbstractController {
*/
protected $path_config_old;
function __construct(Database $db, \Twig_Environment $twig) {
public function __construct(Database $db, \Twig_Environment $twig)
{
parent::__construct($db, $twig);
$this->setMinUserLevelRequired(PSM_USER_ANONYMOUS);
$this->setCSRFKey('install');
$this->addMenu(false);
$this->path_config = PSM_PATH_SRC.'../config.php';
$this->path_config_old = PSM_PATH_SRC.'../config.inc.php';
$this->path_config = PSM_PATH_SRC . '../config.php';
$this->path_config_old = PSM_PATH_SRC . '../config.inc.php';
$this->setActions(array(
'index', 'config', 'install'
@ -64,19 +68,30 @@ class InstallController extends AbstractController {
/**
* Say hi to our new user
*/
protected function executeIndex() {
protected function executeIndex()
{
// build prerequisites
$errors = 0;
$phpv = phpversion();
if (version_compare($phpv, '5.5.9', '<') || (version_compare($phpv, '7.0.8', '<') && version_compare($phpv, '7.0.0', '>='))) {
if (
version_compare($phpv, '5.5.9', '<') ||
(version_compare($phpv, '7.0.8', '<') && version_compare($phpv, '7.0.0', '>='))
) {
$errors++;
$this->addMessage('PHP 5.5.9+ or 7.0.8+ is required to run PHP Server Monitor. You\'re using '.$phpv.'.', 'error');
$this->addMessage('PHP 5.5.9+ or 7.0.8+ is required to run PHP Server Monitor. You\'re using ' .
$phpv . '.', 'error');
} else {
$this->addMessage('PHP version: '.$phpv, 'success');
$this->addMessage('PHP version: ' . $phpv, 'success');
}
if (version_compare(PHP_RELEASE_VERSION, '7', '<')) {
$this->addMessage('PHP 5 reaches the end of life (January 1, 2019), please update to PHP 7. PHP supported versions can be found <a href="https://secure.php.net/supported-versions.php" target="_blank" rel="noopener">here</a>.', 'warning');
$this->addMessage(
'PHP 5 reaches the end of life (January 1, 2019), please update to PHP 7.
PHP supported versions can be found
<a href="https://secure.php.net/supported-versions.php" target="_blank"
rel="noopener">here</a>.',
'warning'
);
}
if (!function_exists('curl_init')) {
$this->addMessage('PHP is installed without the cURL module. Please install cURL.', 'warning');
@ -88,11 +103,19 @@ class InstallController extends AbstractController {
$this->addMessage('The PDO MySQL driver needs to be installed.', 'error');
}
if (!ini_get('date.timezone')) {
$this->addMessage('You should set a timezone in your php.ini file (e.g. \'date.timezone = UTC\'). See <a href="http://www.php.net/manual/en/timezones.php" target="_blank" rel="noopener">this page</a> for more info.', 'warning');
$this->addMessage(
'You should set a timezone in your php.ini file (e.g. \'date.timezone = UTC\').
See <a href="http://www.php.net/manual/en/timezones.php" target="_blank" rel="noopener">this page</a>
for more info.',
'warning'
);
}
if ($errors > 0) {
$this->addMessage($errors.' error(s) have been encountered. Please fix them and refresh this page.', 'error');
$this->addMessage(
$errors . ' error(s) have been encountered. Please fix them and refresh this page.',
'error'
);
}
return $this->twig->render('module/install/index.tpl.html', array(
@ -103,7 +126,8 @@ class InstallController extends AbstractController {
/**
* Help the user create a new config file
*/
protected function executeConfig() {
protected function executeConfig()
{
$tpl_name = 'module/install/config_new.tpl.html';
$tpl_data = array();
@ -113,9 +137,10 @@ class InstallController extends AbstractController {
// oldtimer huh
$this->addMessage('Configuration file for v2.0 found.', 'success');
$this->addMessage(
'The location of the config file has been changed since v2.0.<br/>'.
'We will attempt to create a new config file for you.'
, 'warning');
'The location of the config file has been changed since v2.0.<br/>' .
'We will attempt to create a new config file for you.',
'warning'
);
$values = $this->parseConfig20();
} else {
// fresh install
@ -175,14 +200,17 @@ class InstallController extends AbstractController {
$version_from = $this->getPreviousVersion();
if (version_compare($version_from, '3.0.0', '<')) {
// upgrade from before 3.0, does not have passwords yet.. create new user first
$this->addMessage('Your current version does not have an authentication system, but since v3.0 access to the monitor is restricted by user accounts. Please set up a new account to be able to login after the upgrade, and which you can use to change the passwords for your other accounts.');
$this->addMessage(
'Your current version does not have an authentication system,
but since v3.0 access to the monitor is restricted by user accounts.
Please set up a new account to be able to login after the upgrade,
and which you can use to change the passwords for your other accounts.'
);
$tpl_name = 'module/install/config_new_user.tpl.html';
}
elseif (version_compare($version_from, PSM_VERSION, '=')) {
} elseif (version_compare($version_from, PSM_VERSION, '=')) {
$this->addMessage('Your installation is already at the latest version.', 'success');
$tpl_name = 'module/install/success.tpl.html';
}
else {
} else {
$this->addMessage('We have discovered a previous version.');
$tpl_name = 'module/install/config_upgrade.tpl.html';
$tpl_data['version'] = PSM_VERSION;
@ -195,7 +223,10 @@ class InstallController extends AbstractController {
$tpl_data['email'] = (isset($_POST['email'])) ? $_POST['email'] : '';
}
} else {
$this->addMessage('Configuration file found, but unable to connect to MySQL. Please check your information.', 'error');
$this->addMessage(
'Configuration file found, but unable to connect to MySQL. Please check your information.',
'error'
);
}
}
$tpl_data['messages'] = $this->getMessages();
@ -205,7 +236,8 @@ class InstallController extends AbstractController {
/**
* Execute the install and upgrade process to a newer version
*/
protected function executeInstall() {
protected function executeInstall()
{
if (!defined('PSM_DB_PREFIX') || !$this->db->status()) {
return $this->executeConfig();
}
@ -244,9 +276,8 @@ class InstallController extends AbstractController {
} elseif (version_compare($version_from, PSM_VERSION, '>')) {
$this->addMessage('This installer does not support downgrading, sorry.', 'error');
} else {
$this->addMessage('Upgrading from '.$version_from.' to '.PSM_VERSION);
$this->addMessage('Upgrading from ' . $version_from . ' to ' . PSM_VERSION);
$installer->upgrade($version_from, PSM_VERSION);
}
if (version_compare($version_from, '3.0.0', '<')) {
$add_user = true;
@ -255,11 +286,11 @@ class InstallController extends AbstractController {
} else {
// validate the lot
try {
$validator->username_new($new_user['user_name']);
$validator->usernameNew($new_user['user_name']);
$validator->email($new_user['email']);
$validator->password($new_user['password'], $new_user['password_repeat']);
} catch (\InvalidArgumentException $e) {
$this->addMessage(psm_get_lang('users', 'error_'.$e->getMessage()), 'error');
$this->addMessage(psm_get_lang('users', 'error_' . $e->getMessage()), 'error');
return $this->executeConfig();
}
@ -271,7 +302,7 @@ class InstallController extends AbstractController {
if ($add_user) {
unset($new_user['password_repeat']);
$user_id = $this->db->save(PSM_DB_PREFIX.'users', $new_user);
$user_id = $this->db->save(PSM_DB_PREFIX . 'users', $new_user);
if (intval($user_id) > 0) {
$this->getUser()->changePassword($user_id, $new_user['password']);
$this->addMessage('User account has been created successfully.', 'success');
@ -290,11 +321,12 @@ class InstallController extends AbstractController {
* @param array $array_config prefix,user,pass,name,host
* @return boolean|string TRUE on success, string with config otherwise
*/
protected function writeConfigFile($array_config) {
$config = "<?php".PHP_EOL;
protected function writeConfigFile($array_config)
{
$config = "<?php" . PHP_EOL;
foreach ($array_config as $key => $value) {
$line = "define('PSM_{key}', '{value}');".PHP_EOL;
$line = "define('PSM_{key}', '{value}');" . PHP_EOL;
$line = str_replace(
array('{key}', '{value}'),
array(strtoupper($key), $value),
@ -314,7 +346,8 @@ class InstallController extends AbstractController {
* Parse the 2.0 config file for prefilling
* @return array
*/
protected function parseConfig20() {
protected function parseConfig20()
{
$config_old = file_get_contents($this->path_config_old);
$vars = array(
'prefix' => '',
@ -338,22 +371,24 @@ class InstallController extends AbstractController {
/**
* Is it an upgrade or install?
*/
protected function isUpgrade() {
protected function isUpgrade()
{
if (!$this->db->status()) {
return false;
}
return $this->db->ifTableExists(PSM_DB_PREFIX.'config');
return $this->db->ifTableExists(PSM_DB_PREFIX . 'config');
}
/**
* Get the previous version from the config table
* @return boolean|string FALSE on failure, string otherwise
*/
protected function getPreviousVersion() {
protected function getPreviousVersion()
{
if (!$this->isUpgrade()) {
return false;
}
$version_conf = $this->db->selectRow(PSM_DB_PREFIX.'config', array('key' => 'version'), array('value'));
$version_conf = $this->db->selectRow(PSM_DB_PREFIX . 'config', array('key' => 'version'), array('value'));
if (empty($version_conf)) {
return false;
} else {
@ -370,9 +405,10 @@ class InstallController extends AbstractController {
* Get base url of the current application
* @return string
*/
protected function getBaseUrl() {
protected function getBaseUrl()
{
$sym_request = \Symfony\Component\HttpFoundation\Request::createFromGlobals();
return $sym_request->getSchemeAndHttpHost().$sym_request->getBasePath();
return $sym_request->getSchemeAndHttpHost() . $sym_request->getBasePath();
}
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -31,16 +32,17 @@ namespace psm\Module\Install;
use psm\Module\ModuleInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class InstallModule implements ModuleInterface {
public function load(ContainerBuilder $container) {
class InstallModule implements ModuleInterface
{
public function load(ContainerBuilder $container)
{
}
public function getControllers() {
public function getControllers()
{
return array(
'install' => __NAMESPACE__.'\Controller\InstallController',
'install' => __NAMESPACE__ . '\Controller\InstallController',
);
}
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -27,9 +28,11 @@
**/
namespace psm\Module;
use Symfony\Component\DependencyInjection\ContainerBuilder;
interface ModuleInterface {
interface ModuleInterface
{
public function load(ContainerBuilder $container);

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -27,12 +28,15 @@
**/
namespace psm\Module\Server\Controller;
use psm\Module\AbstractController;
use psm\Service\Database;
abstract class AbstractServerController extends AbstractController {
abstract class AbstractServerController extends AbstractController
{
function __construct(Database $db, \Twig_Environment $twig) {
public function __construct(Database $db, \Twig_Environment $twig)
{
parent::__construct($db, $twig);
}
@ -41,13 +45,14 @@ abstract class AbstractServerController extends AbstractController {
* @param Countable|array|\PDOStatement $server_id (int) if true only that server will be retrieved.
* @return array
*/
public function getServers($server_id = null) {
public function getServers($server_id = null)
{
$sql_join = '';
$sql_where = '';
if ($this->getUser()->getUserLevel() > PSM_USER_ADMIN) {
// restrict by user_id
$sql_join = "JOIN `".PSM_DB_PREFIX."users_servers` AS `us` ON (
$sql_join = "JOIN `" . PSM_DB_PREFIX . "users_servers` AS `us` ON (
`us`.`user_id`={$this->getUser()->getUserId()}
AND `us`.`server_id`=`s`.`server_id`
)";
@ -91,7 +96,7 @@ abstract class AbstractServerController extends AbstractController {
`s`.`last_error`,
`s`.`last_error_output`,
`s`.`last_output`
FROM `".PSM_DB_PREFIX."servers` AS `s`
FROM `" . PSM_DB_PREFIX . "servers` AS `s`
{$sql_join}
{$sql_where}
ORDER BY `active` ASC, `status` DESC, `label` ASC";
@ -109,13 +114,14 @@ abstract class AbstractServerController extends AbstractController {
* @param array $server
* @return array
*/
protected function formatServer($server) {
protected function formatServer($server)
{
$server['rtime'] = round((float) $server['rtime'], 4);
$server['last_online'] = psm_timespan($server['last_online']);
$server['last_offline'] = psm_timespan($server['last_offline']);
if ($server['last_offline'] != psm_get_lang('system', 'never')) {
$server['last_offline_duration'] = is_null($server['last_offline_duration']) ?
null : "(".$server['last_offline_duration'].")";
null : "(" . $server['last_offline_duration'] . ")";
}
$server['last_check'] = psm_timespan($server['last_check']);
@ -124,7 +130,7 @@ abstract class AbstractServerController extends AbstractController {
}
$server['error'] = htmlentities($server['error']);
$server['type'] = psm_get_lang('servers', 'type_'.$server['type']);
$server['type'] = psm_get_lang('servers', 'type_' . $server['type']);
$server['timeout'] = ($server['timeout'] > 0) ? $server['timeout'] : PSM_CURL_TIMEOUT;
$server['last_error'] = htmlentities($server['last_error']);
@ -133,7 +139,7 @@ abstract class AbstractServerController extends AbstractController {
$url_actions = array('delete', 'edit', 'view');
foreach ($url_actions as $action) {
$server['url_'.$action] = psm_build_url(array(
$server['url_' . $action] = psm_build_url(array(
'mod' => 'server',
'action' => $action,
'id' => $server['server_id'],

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -26,14 +27,17 @@
**/
namespace psm\Module\Server\Controller;
use psm\Service\Database;
/**
* Log module. Create the page to view previous log messages
*/
class LogController extends AbstractServerController {
class LogController extends AbstractServerController
{
function __construct(Database $db, \Twig_Environment $twig) {
public function __construct(Database $db, \Twig_Environment $twig)
{
parent::__construct($db, $twig);
$this->setActions(array(
@ -44,7 +48,8 @@ class LogController extends AbstractServerController {
/**
* Prepare the template with a list of all log entries
*/
protected function executeIndex() {
protected function executeIndex()
{
$this->twig->addGlobal('subtitle', psm_get_lang('menu', 'server_log'));
$tpl_data = array(
'label_status' => psm_get_lang('log', 'status'),
@ -100,13 +105,13 @@ class LogController extends AbstractServerController {
for ($x = 0; $x < $log_count; $x++) {
$record = &$records[$x];
$record['users'] = '';
if($key == 'status'){
if ($key == 'status') {
$record['server'] = $record['label'];
$record['type_icon'] = ($record['server_type'] == 'website') ? 'globe-americas' : 'cogs';
$record['type_title'] = psm_get_lang('servers', 'type_'.$record['server_type']);
$ip = '('.$record['ip'];
$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))) {
$ip .= ':'.$record['port'];
$ip .= ':' . $record['port'];
}
$ip .= ')';
$record['ip'] = $ip;
@ -130,7 +135,8 @@ class LogController extends AbstractServerController {
return $this->twig->render('module/server/log.tpl.html', $tpl_data);
}
protected function executeDelete() {
protected function executeDelete()
{
/**
* Empty table log and log_users.
* Only when user is admin.
@ -148,30 +154,31 @@ class LogController extends AbstractServerController {
* @param string $type status/email/sms
* @return \PDOStatement array
*/
public function getEntries($type) {
public function getEntries($type)
{
$sql_join = '';
if ($this->getUser()->getUserLevel() > PSM_USER_ADMIN) {
// restrict by user_id
$sql_join = "JOIN `".PSM_DB_PREFIX."users_servers` AS `us` ON (
$sql_join = "JOIN `" . PSM_DB_PREFIX . "users_servers` AS `us` ON (
`us`.`user_id`={$this->getUser()->getUserId()}
AND `us`.`server_id`=`servers`.`server_id`
)";
}
$entries = $this->db->query(
'SELECT '.
'`servers`.`label`, '.
'`servers`.`ip`, '.
'`servers`.`port`, '.
'`servers`.`type` AS server_type, '.
'`log`.`log_id`, '.
'`log`.`type`, '.
'`log`.`message`, '.
'`log`.`datetime` '.
'FROM `'.PSM_DB_PREFIX.'log` AS `log` '.
'JOIN `'.PSM_DB_PREFIX.'servers` AS `servers` ON (`servers`.`server_id`=`log`.`server_id`) '.
$sql_join.
'WHERE `log`.`type`=\''.$type.'\' '.
'ORDER BY `datetime` DESC '.
'SELECT ' .
'`servers`.`label`, ' .
'`servers`.`ip`, ' .
'`servers`.`port`, ' .
'`servers`.`type` AS server_type, ' .
'`log`.`log_id`, ' .
'`log`.`type`, ' .
'`log`.`message`, ' .
'`log`.`datetime` ' .
'FROM `' . PSM_DB_PREFIX . 'log` AS `log` ' .
'JOIN `' . PSM_DB_PREFIX . 'servers` AS `servers` ON (`servers`.`server_id`=`log`.`server_id`) ' .
$sql_join .
'WHERE `log`.`type`=\'' . $type . '\' ' .
'ORDER BY `datetime` DESC ' .
'LIMIT 0,20'
);
return $entries;
@ -183,14 +190,15 @@ class LogController extends AbstractServerController {
* @param $log_id
* @return \PDOStatement array
*/
protected function getLogUsers($log_id) {
protected function getLogUsers($log_id)
{
return $this->db->query(
"SELECT
u.`user_id`,
u.`name`
FROM `".PSM_DB_PREFIX."log_users` AS lu
LEFT JOIN `".PSM_DB_PREFIX."users` AS u ON lu.`user_id` = u.`user_id`
WHERE lu.`log_id` = ".(int) $log_id."
FROM `" . PSM_DB_PREFIX . "log_users` AS lu
LEFT JOIN `" . PSM_DB_PREFIX . "users` AS u ON lu.`user_id` = u.`user_id`
WHERE lu.`log_id` = " . (int) $log_id . "
ORDER BY u.`name` ASC"
);
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -26,12 +27,14 @@
**/
namespace psm\Module\Server\Controller;
use psm\Service\Database;
/**
* Server module. Add/edit/delete servers, show a list of all servers etc.
*/
class ServerController extends AbstractServerController {
class ServerController extends AbstractServerController
{
/**
* Current server id
@ -39,7 +42,8 @@ class ServerController extends AbstractServerController {
*/
protected $server_id;
function __construct(Database $db, \Twig_Environment $twig) {
public function __construct(Database $db, \Twig_Environment $twig)
{
parent::__construct($db, $twig);
$this->server_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
@ -59,7 +63,8 @@ class ServerController extends AbstractServerController {
/**
* Prepare the template to show a list of all servers
*/
protected function executeIndex() {
protected function executeIndex()
{
$tpl_data = $this->getLabels();
$tpl_data['user_level'] = $this->getUser()->getUserLevel();
$sidebar = new \psm\Util\Module\Sidebar($this->twig);
@ -106,7 +111,8 @@ class ServerController extends AbstractServerController {
if ($servers[$x]['type'] == 'website') {
// add link to label
$ip = $servers[$x]['ip'];
$servers[$x]['ip'] = '<a href="'.$servers[$x]['ip'].'" target="_blank" rel="noopener">'.$ip.'</a>';
$servers[$x]['ip'] = '<a href="' . $servers[$x]['ip'] .
'" target="_blank" rel="noopener">' . $ip . '</a>';
}
if (($servers[$x]['active'] == 'yes')) {
$servers[$x]['active_title'] = psm_get_lang('servers', 'monitoring');
@ -123,7 +129,8 @@ class ServerController extends AbstractServerController {
/**
* Prepare the template to show the update screen for a single server
*/
protected function executeEdit() {
protected function executeEdit()
{
$back_to = isset($_GET['back_to']) ? $_GET['back_to'] : '';
$tpl_data = $this->getLabels();
@ -137,12 +144,14 @@ class ServerController extends AbstractServerController {
// depending on where the user came from, add the go back url:
if ($back_to == 'view' && $this->server_id > 0) {
$tpl_data['url_go_back'] = psm_build_url(array('mod' => 'server', 'action' => 'view', 'id' => $this->server_id));
$tpl_data['url_go_back'] = psm_build_url(
array('mod' => 'server', 'action' => 'view', 'id' => $this->server_id)
);
} else {
$tpl_data['url_go_back'] = psm_build_url(array('mod' => 'server'));
}
$tpl_data['users'] = $this->db->select(PSM_DB_PREFIX.'users', null, array('user_id', 'name'), '', 'name');
$tpl_data['users'] = $this->db->select(PSM_DB_PREFIX . 'users', null, array('user_id', 'name'), '', 'name');
switch ($this->server_id) {
case 0:
@ -160,7 +169,7 @@ class ServerController extends AbstractServerController {
$this->addMessage(psm_get_lang('servers', 'error_server_no_match'), 'error');
return $this->runAction('index');
}
$tpl_data['titlemode'] = psm_get_lang('system', 'edit').' '.$edit_server['label'];
$tpl_data['titlemode'] = psm_get_lang('system', 'edit') . ' ' . $edit_server['label'];
$user_idc_selected = $this->getServerUsers($this->server_id);
foreach ($tpl_data['users'] as &$user) {
@ -190,15 +199,16 @@ class ServerController extends AbstractServerController {
'edit_value_post_field' => $edit_server['post_field'],
'edit_value_timeout' => $edit_server['timeout'],
'edit_value_pattern' => $edit_server['pattern'],
'edit_pattern_selected_'.$edit_server['pattern_online'] => 'selected="selected"',
'edit_redirect_check_selected_'.$edit_server['redirect_check'] => 'selected="selected"',
'edit_pattern_selected_' . $edit_server['pattern_online'] => 'selected="selected"',
'edit_redirect_check_selected_' . $edit_server['redirect_check'] => 'selected="selected"',
'edit_value_allow_http_status' => $edit_server['allow_http_status'],
'edit_value_header_name' => $edit_server['header_name'],
'edit_value_header_value' => $edit_server['header_value'],
'edit_value_warning_threshold' => $edit_server['warning_threshold'],
'edit_value_website_username' => $edit_server['website_username'],
'edit_value_website_password' => empty($edit_server['website_password']) ? '' : sha1($edit_server['website_password']),
'edit_type_selected_'.$edit_server['type'] => 'selected="selected"',
'edit_value_website_password' => empty($edit_server['website_password']) ? '' :
sha1($edit_server['website_password']),
'edit_type_selected_' . $edit_server['type'] => 'selected="selected"',
'edit_active_selected' => $edit_server['active'],
'edit_email_selected' => $edit_server['email'],
'edit_sms_selected' => $edit_server['sms'],
@ -209,13 +219,14 @@ class ServerController extends AbstractServerController {
$notifications = array('email', 'sms', 'pushover', 'telegram');
foreach ($notifications as $notification) {
if (psm_get_conf($notification.'_status') == 0) {
$tpl_data['warning_'.$notification] = true;
$tpl_data['label_warning_'.$notification] = psm_get_lang(
'servers', 'warning_notifications_disabled_'.$notification
if (psm_get_conf($notification . '_status') == 0) {
$tpl_data['warning_' . $notification] = true;
$tpl_data['label_warning_' . $notification] = psm_get_lang(
'servers',
'warning_notifications_disabled_' . $notification
);
} else {
$tpl_data['warning_'.$notification] = false;
$tpl_data['warning_' . $notification] = false;
}
}
@ -225,7 +236,8 @@ class ServerController extends AbstractServerController {
/**
* Executes the saving of one of the servers
*/
protected function executeSave() {
protected function executeSave()
{
if (empty($_POST)) {
// dont process anything if no data has been posted
return $this->executeIndex();
@ -244,7 +256,8 @@ class ServerController extends AbstractServerController {
if ($new_password == $hash) {
$encrypted_password = $edit_server['website_password'];
} else {
$encrypted_password = psm_password_encrypt(strval($this->server_id).psm_get_conf('password_encrypt_key'), $new_password);
$encrypted_password = psm_password_encrypt(strval($this->server_id) .
psm_get_conf('password_encrypt_key'), $new_password);
}
}
}
@ -260,8 +273,10 @@ class ServerController extends AbstractServerController {
'post_field' => empty(psm_POST('post_field')) ? null : psm_POST('post_field'),
'type' => psm_POST('type', ''),
'pattern' => psm_POST('pattern', ''),
'pattern_online' => in_array($_POST['pattern_online'], array('yes', 'no')) ? $_POST['pattern_online'] : 'yes',
'redirect_check' => in_array($_POST['redirect_check'], array('ok', 'bad')) ? $_POST['redirect_check'] : 'bad',
'pattern_online' => in_array($_POST['pattern_online'], array('yes', 'no')) ?
$_POST['pattern_online'] : 'yes',
'redirect_check' => in_array($_POST['redirect_check'], array('ok', 'bad')) ?
$_POST['redirect_check'] : 'bad',
'allow_http_status' => psm_POST('allow_http_status', ''),
'header_name' => psm_POST('header_name', ''),
'header_value' => psm_POST('header_value', ''),
@ -273,11 +288,15 @@ class ServerController extends AbstractServerController {
'telegram' => in_array($_POST['telegram'], array('yes', 'no')) ? $_POST['telegram'] : 'no',
);
// make sure websites start with http://
if ($clean['type'] == 'website' && substr($clean['ip'], 0, 4) != 'http' && substr($clean['ip'], 0, 3) != 'rdp') {
$clean['ip'] = 'http://'.$clean['ip'];
if (
$clean['type'] == 'website' &&
substr($clean['ip'], 0, 4) != 'http' &&
substr($clean['ip'], 0, 3) != 'rdp'
) {
$clean['ip'] = 'http://' . $clean['ip'];
}
if($clean['request_method'] == null) {
if ($clean['request_method'] == null) {
$clean['post_field'] = null;
}
@ -307,7 +326,7 @@ class ServerController extends AbstractServerController {
$server_validator->ip($clean['ip'], $clean['type']);
$server_validator->warningThreshold($clean['warning_threshold']);
} catch (\InvalidArgumentException $ex) {
$this->addMessage(psm_get_lang('servers', 'error_'.$ex->getMessage()), 'error');
$this->addMessage(psm_get_lang('servers', 'error_' . $ex->getMessage()), 'error');
return $this->executeEdit();
}
@ -315,7 +334,7 @@ class ServerController extends AbstractServerController {
if ($this->server_id > 0) {
// edit
$this->db->save(
PSM_DB_PREFIX.'servers',
PSM_DB_PREFIX . 'servers',
$clean,
array('server_id' => $this->server_id)
);
@ -323,19 +342,19 @@ class ServerController extends AbstractServerController {
} else {
// add
$clean['status'] = 'on';
$this->server_id = $this->db->save(PSM_DB_PREFIX.'servers', $clean);
$this->server_id = $this->db->save(PSM_DB_PREFIX . 'servers', $clean);
// server has been added, re-encrypt
if (!empty($_POST['website_password'])) {
$cleanWebsitePassword = array(
'website_password' => psm_password_encrypt(
strval($this->server_id).psm_get_conf('password_encrypt_key'),
strval($this->server_id) . psm_get_conf('password_encrypt_key'),
psm_POST('website_password')
),
);
$this->db->save(
PSM_DB_PREFIX.'servers',
PSM_DB_PREFIX . 'servers',
$cleanWebsitePassword,
array('server_id' => $this->server_id)
);
@ -354,10 +373,10 @@ class ServerController extends AbstractServerController {
'server_id' => intval($this->server_id),
);
}
$this->db->delete(PSM_DB_PREFIX.'users_servers', array('server_id' => $this->server_id));
$this->db->delete(PSM_DB_PREFIX . 'users_servers', array('server_id' => $this->server_id));
if (!empty($user_idc_save)) {
// add all new users
$this->db->insertMultiple(PSM_DB_PREFIX.'users_servers', $user_idc_save);
$this->db->insertMultiple(PSM_DB_PREFIX . 'users_servers', $user_idc_save);
}
$back_to = isset($_GET['back_to']) ? $_GET['back_to'] : 'index';
@ -371,17 +390,18 @@ class ServerController extends AbstractServerController {
/**
* Executes the deletion of one of the servers
*/
protected function executeDelete() {
protected function executeDelete()
{
if (isset($_GET['id'])) {
$id = intval($_GET['id']);
// do delete
$res = $this->db->delete(PSM_DB_PREFIX.'servers', array('server_id' => $id));
$res = $this->db->delete(PSM_DB_PREFIX . 'servers', array('server_id' => $id));
if ($res === 1) {
$this->db->delete(PSM_DB_PREFIX.'log', array('server_id' => $id));
$this->db->delete(PSM_DB_PREFIX.'users_servers', array('server_id' => $id));
$this->db->delete(PSM_DB_PREFIX.'servers_uptime', array('server_id' => $id));
$this->db->delete(PSM_DB_PREFIX.'servers_history', array('server_id' => $id));
$this->db->delete(PSM_DB_PREFIX . 'log', array('server_id' => $id));
$this->db->delete(PSM_DB_PREFIX . 'users_servers', array('server_id' => $id));
$this->db->delete(PSM_DB_PREFIX . 'servers_uptime', array('server_id' => $id));
$this->db->delete(PSM_DB_PREFIX . 'servers_history', array('server_id' => $id));
}
$this->addMessage(psm_get_lang('servers', 'deleted'), 'success');
}
@ -391,7 +411,8 @@ class ServerController extends AbstractServerController {
/**
* Prepare the view template
*/
protected function executeView() {
protected function executeView()
{
if ($this->server_id == 0) {
return $this->runAction('index');
}
@ -412,7 +433,8 @@ class ServerController extends AbstractServerController {
$this->setSidebar($sidebar);
// check which module the user came from, and add a link accordingly
$back_to = isset($_GET['back_to']) && ($_GET['back_to'] == 'server_status' || $_GET['back_to'] == 'user') ? $_GET['back_to'] : 'server';
$back_to = isset($_GET['back_to']) && ($_GET['back_to'] == 'server_status' || $_GET['back_to'] == 'user') ?
$_GET['back_to'] : 'server';
$sidebar->addButton(
'go_back',
psm_get_lang('system', 'go_back'),
@ -425,7 +447,9 @@ class ServerController extends AbstractServerController {
// add edit/delete buttons for admins
if ($this->getUser()->getUserLevel() == PSM_USER_ADMIN) {
$tpl_data['has_admin_actions'] = true;
$tpl_data['url_edit'] = psm_build_url(array('mod' => 'server', 'action' => 'edit', 'id' => $this->server_id, 'back_to' => 'view'));
$tpl_data['url_edit'] = psm_build_url(
array('mod' => 'server', 'action' => 'edit', 'id' => $this->server_id, 'back_to' => 'view')
);
$modal = new \psm\Util\Module\Modal($this->twig, 'delete', \psm\Util\Module\Modal::MODAL_TYPE_DANGER);
$this->addModal($modal);
@ -436,7 +460,9 @@ class ServerController extends AbstractServerController {
$sidebar->addButton(
'edit',
psm_get_lang('system', 'edit'),
psm_build_url(array('mod' => 'server', 'action' => 'edit', 'id' => $this->server_id, 'back_to' => 'view')),
psm_build_url(
array('mod' => 'server', 'action' => 'edit', 'id' => $this->server_id, 'back_to' => 'view')
),
'edit',
'primary',
psm_get_lang('system', 'edit')
@ -449,7 +475,9 @@ class ServerController extends AbstractServerController {
foreach ($servers as $i => $server_available) {
$tpl_data['options'][] = array(
'class_active' => ($server_available['server_id'] == $this->server_id) ? 'active' : '',
'url' => psm_build_url(array('mod' => 'server', 'action' => 'view', 'id' => $server_available['server_id'])),
'url' => psm_build_url(
array('mod' => 'server', 'action' => 'view', 'id' => $server_available['server_id'])
),
'label' => $server_available['label'],
);
}
@ -468,7 +496,8 @@ class ServerController extends AbstractServerController {
return $this->twig->render('module/server/server/view.tpl.html', $tpl_data);
}
protected function getLabels() {
protected function getLabels()
{
return array(
'label_label' => psm_get_lang('servers', 'label'),
'label_status' => psm_get_lang('servers', 'status'),
@ -555,9 +584,10 @@ class ServerController extends AbstractServerController {
* @param int $server_id
* @return array with ids only
*/
protected function getServerUsers($server_id) {
protected function getServerUsers($server_id)
{
$users = $this->db->select(
PSM_DB_PREFIX.'users_servers',
PSM_DB_PREFIX . 'users_servers',
array('server_id' => $server_id),
array('user_id')
);

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -27,14 +28,17 @@
**/
namespace psm\Module\Server\Controller;
use psm\Service\Database;
/**
* Status module
*/
class StatusController extends AbstractServerController {
class StatusController extends AbstractServerController
{
function __construct(Database $db, \Twig_Environment $twig) {
public function __construct(Database $db, \Twig_Environment $twig)
{
parent::__construct($db, $twig);
$this->setCSRFKey('status');
@ -44,7 +48,8 @@ class StatusController extends AbstractServerController {
/**
* Prepare the template to show a list of all servers
*/
protected function executeIndex() {
protected function executeIndex()
{
// set background color to black
$this->black_background = true;
$this->twig->addGlobal('subtitle', psm_get_lang('menu', 'server_status'));
@ -85,9 +90,11 @@ class StatusController extends AbstractServerController {
$server['last_offline_nice'] = psm_timespan($server['last_offline']);
$server['last_offline_duration_nice'] = "";
if ($server['last_offline_nice'] != psm_get_lang('system', 'never')) {
$server['last_offline_duration_nice'] = "(".$server['last_offline_duration'].")";
$server['last_offline_duration_nice'] = "(" . $server['last_offline_duration'] . ")";
}
$server['url_view'] = psm_build_url(array('mod' => 'server', 'action' => 'view', 'id' => $server['server_id'], 'back_to' => 'server_status'));
$server['url_view'] = psm_build_url(
array('mod' => 'server', 'action' => 'view', 'id' => $server['server_id'], 'back_to' => 'server_status')
);
if ($server['status'] == "off") {
$layout_data['servers_offline'][] = $server;
@ -113,7 +120,8 @@ class StatusController extends AbstractServerController {
return $this->twig->render('module/server/status/index.tpl.html', $layout_data);
}
protected function executeSaveLayout() {
protected function executeSaveLayout()
{
if ($this->isXHR()) {
$layout = psm_POST('layout', 0);
$this->getUser()->setUserPref('status_layout', $layout);

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -28,25 +29,28 @@
**/
namespace psm\Module\Server\Controller;
use psm\Module\AbstractController;
use psm\Service\Database;
class UpdateController extends AbstractController {
class UpdateController extends AbstractController
{
function __construct(Database $db, \Twig_Environment $twig) {
public function __construct(Database $db, \Twig_Environment $twig)
{
parent::__construct($db, $twig);
$this->setActions('index', 'index');
}
protected function executeIndex() {
protected function executeIndex()
{
$autorun = $this->container->get('util.server.updatemanager');
$autorun->run();
header('Location: '.psm_build_url(array(
header('Location: ' . psm_build_url(array(
'mod' => 'server_status'
), true, false));
die();
}
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -31,19 +32,20 @@ namespace psm\Module\Server;
use psm\Module\ModuleInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class ServerModule implements ModuleInterface {
public function load(ContainerBuilder $container) {
class ServerModule implements ModuleInterface
{
public function load(ContainerBuilder $container)
{
}
public function getControllers() {
public function getControllers()
{
return array(
'server' => __NAMESPACE__.'\Controller\ServerController',
'log' => __NAMESPACE__.'\Controller\LogController',
'status' => __NAMESPACE__.'\Controller\StatusController',
'update' => __NAMESPACE__.'\Controller\UpdateController',
'server' => __NAMESPACE__ . '\Controller\ServerController',
'log' => __NAMESPACE__ . '\Controller\LogController',
'status' => __NAMESPACE__ . '\Controller\StatusController',
'update' => __NAMESPACE__ . '\Controller\UpdateController',
);
}
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -27,12 +28,15 @@
**/
namespace psm\Module\User\Controller;
use psm\Module\AbstractController;
use psm\Service\Database;
class LoginController extends AbstractController {
class LoginController extends AbstractController
{
function __construct(Database $db, \Twig_Environment $twig) {
public function __construct(Database $db, \Twig_Environment $twig)
{
parent::__construct($db, $twig);
$this->setMinUserLevelRequired(PSM_USER_ANONYMOUS);
@ -44,7 +48,8 @@ class LoginController extends AbstractController {
$this->addMenu(false);
}
protected function executeLogin() {
protected function executeLogin()
{
if (isset($_POST['user_name']) && isset($_POST['user_password'])) {
$rememberme = (isset($_POST['user_rememberme'])) ? true : false;
$result = $this->getUser()->loginWithPostData(
@ -55,11 +60,10 @@ class LoginController extends AbstractController {
if ($result) {
// success login, redirect
header('Location: '.
header('Location: ' .
psm_build_url(
empty($_SERVER["QUERY_STRING"]) ? null : $_SERVER["QUERY_STRING"]
)
);
));
die();
} else {
$this->addMessage(psm_get_lang('login', 'error_login_incorrect'), 'error');
@ -85,7 +89,8 @@ class LoginController extends AbstractController {
*
* @return string
*/
protected function executeForgot() {
protected function executeForgot()
{
if (isset($_POST['user_name'])) {
$user = $this->getUser()->getUserByUsername($_POST['user_name']);
@ -117,7 +122,8 @@ class LoginController extends AbstractController {
/**
* Show/process the password reset form (after the mail)
*/
protected function executeReset() {
protected function executeReset()
{
$service_user = $this->getUser();
$user_id = (isset($_GET['user_id'])) ? intval($_GET['user_id']) : 0;
$token = (isset($_GET['token'])) ? $_GET['token'] : '';
@ -161,7 +167,8 @@ class LoginController extends AbstractController {
* @param string $user_email
* @param string $user_password_reset_hash
*/
protected function sendPasswordForgotMail($user_id, $user_email, $user_password_reset_hash) {
protected function sendPasswordForgotMail($user_id, $user_email, $user_password_reset_hash)
{
$mail = psm_build_mail();
$mail->Subject = psm_get_lang('login', 'password_reset_email_subject');

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -26,18 +27,22 @@
**/
namespace psm\Module\User\Controller;
use psm\Module\AbstractController;
use psm\Service\Database;
class ProfileController extends AbstractController {
class ProfileController extends AbstractController
{
/**
* Editable fields for the profile
* @var array $profile_fields
*/
protected $profile_fields = array('name', 'user_name', 'email', 'mobile', 'pushover_key', 'pushover_device', 'telegram_id');
protected $profile_fields =
array('name', 'user_name', 'email', 'mobile', 'pushover_key', 'pushover_device', 'telegram_id');
function __construct(Database $db, \Twig_Environment $twig) {
public function __construct(Database $db, \Twig_Environment $twig)
{
parent::__construct($db, $twig);
$this->setActions(array(
@ -50,11 +55,16 @@ class ProfileController extends AbstractController {
* Show the profile page
* @return string
*/
protected function executeIndex() {
protected function executeIndex()
{
$this->twig->addGlobal('subtitle', psm_get_lang('users', 'profile'));
$user = $this->getUser()->getUser(null, true);
$modal = new \psm\Util\Module\Modal($this->twig, 'activate' . ucfirst('telegram'), \psm\Util\Module\Modal::MODAL_TYPE_OKCANCEL);
$modal = new \psm\Util\Module\Modal(
$this->twig,
'activate' . ucfirst('telegram'),
\psm\Util\Module\Modal::MODAL_TYPE_OKCANCEL
);
$this->addModal($modal);
$modal->setTitle(psm_get_lang('users', 'activate_telegram'));
$modal->setMessage(psm_get_lang('users', 'activate_telegram_description'));
@ -98,7 +108,8 @@ class ProfileController extends AbstractController {
/**
* Save the profile
*/
protected function executeSave() {
protected function executeSave()
{
if (empty($_POST)) {
// dont process anything if no data has been posted
return $this->executeIndex();
@ -156,7 +167,8 @@ class ProfileController extends AbstractController {
* Allow the bot to send notifications to chat_id
*
*/
protected function activateTelegram() {
protected function activateTelegram()
{
$telegram = psm_build_telegram();
$apiToken = psm_get_conf('telegram_api_token');

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -26,6 +27,7 @@
**/
namespace psm\Module\User\Controller;
use psm\Module\AbstractController;
use psm\Service\Database;
@ -33,10 +35,12 @@ use psm\Service\Database;
* User module. Add, edit and delete users, or assign
* servers to users.
*/
class UserController extends AbstractController {
class UserController extends AbstractController
{
public $servers = array();
function __construct(Database $db, \Twig_Environment $twig) {
public function __construct(Database $db, \Twig_Environment $twig)
{
parent::__construct($db, $twig);
$this->setMinUserLevelRequired(PSM_USER_ADMIN);
@ -48,8 +52,15 @@ class UserController extends AbstractController {
$this->twig->addGlobal('subtitle', psm_get_lang('menu', 'user'));
}
public function run($action = NULL) {
$servers = $this->db->select(PSM_DB_PREFIX.'servers', null, array('server_id', 'label'), '', "ORDER BY `label` ASC");
public function run($action = null)
{
$servers = $this->db->select(
PSM_DB_PREFIX . 'servers',
null,
array('server_id', 'label'),
'',
"ORDER BY `label` ASC"
);
// change the indexes to reflect their server ids
foreach ($servers as $server) {
$this->servers[$server['server_id']] = $server;
@ -63,7 +74,8 @@ class UserController extends AbstractController {
*
* @return string
*/
protected function executeIndex() {
protected function executeIndex()
{
$sidebar = new \psm\Util\Module\Sidebar($this->twig);
$this->setSidebar($sidebar);
@ -89,7 +101,7 @@ class UserController extends AbstractController {
}
$users = $this->db->select(
PSM_DB_PREFIX.'users',
PSM_DB_PREFIX . 'users',
null,
array('user_id', 'user_name', 'level', 'name', 'mobile', 'email'),
null,
@ -99,7 +111,7 @@ class UserController extends AbstractController {
foreach ($users as $x => &$user) {
$user_servers = $this->getUserServers($user['user_id']);
$user['class'] = ($x & 1) ? 'odd' : 'even';
$user['level_text'] = psm_get_lang('users', 'level_'.$user['level']);
$user['level_text'] = psm_get_lang('users', 'level_' . $user['level']);
$user['emp_servers'] = array();
@ -110,7 +122,9 @@ class UserController extends AbstractController {
}
$user['emp_servers'][] = array(
'label' => $servers_labels[$server_id],
'url' => psm_build_url(array('mod' => 'server', 'action' => 'view', 'id' => $server_id, 'back_to' => 'user'))
'url' => psm_build_url(
array('mod' => 'server', 'action' => 'view', 'id' => $server_id, 'back_to' => 'user')
)
);
}
sort($user['emp_servers']);
@ -137,9 +151,18 @@ class UserController extends AbstractController {
*
* @return string
*/
protected function executeEdit() {
protected function executeEdit()
{
$user_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$fields_prefill = array('name', 'user_name', 'mobile', 'pushover_key', 'pushover_device', 'telegram_id', 'email');
$fields_prefill = array(
'name',
'user_name',
'mobile',
'pushover_key',
'pushover_device',
'telegram_id',
'email'
);
if ($user_id == 0) {
// insert mode
@ -162,11 +185,11 @@ class UserController extends AbstractController {
try {
$this->container->get('util.user.validator')->userId($user_id);
} catch (\InvalidArgumentException $e) {
$this->addMessage(psm_get_lang('users', 'error_'.$e->getMessage()), 'error');
$this->addMessage(psm_get_lang('users', 'error_' . $e->getMessage()), 'error');
return $this->executeIndex();
}
$edit_user = $this->getUser()->getUser($user_id);
$title = psm_get_lang('system', 'edit').' '.$edit_user->name;
$title = psm_get_lang('system', 'edit') . ' ' . $edit_user->name;
$placeholder_password = psm_get_lang('users', 'password_leave_blank');
$lvl_selected = $edit_user->level;
@ -196,7 +219,7 @@ class UserController extends AbstractController {
);
foreach ($fields_prefill as $field) {
if (isset($edit_user->$field)) {
$tpl_data['edit_value_'.$field] = $edit_user->$field;
$tpl_data['edit_value_' . $field] = $edit_user->$field;
}
}
@ -204,7 +227,7 @@ class UserController extends AbstractController {
foreach ($this->container->get('util.user.validator')->getUserLevels() as $lvl) {
$tpl_data['levels'][] = array(
'value' => $lvl,
'label' => psm_get_lang('users', 'level_'.$lvl),
'label' => psm_get_lang('users', 'level_' . $lvl),
);
}
@ -216,14 +239,26 @@ class UserController extends AbstractController {
/**
* Executes the saving of a user
*/
protected function executeSave() {
protected function executeSave()
{
if (empty($_POST)) {
// dont process anything if no data has been posted
return $this->executeIndex();
}
$user_id = (isset($_GET['id'])) ? intval($_GET['id']) : 0;
$fields = array('name', 'user_name', 'password', 'password_repeat', 'level', 'mobile', 'pushover_key', 'pushover_device', 'telegram_id', 'email');
$fields = array(
'name',
'user_name',
'password',
'password_repeat',
'level',
'mobile',
'pushover_key',
'pushover_device',
'telegram_id',
'email'
);
$clean = array();
foreach ($fields as $field) {
if (isset($_POST[$field])) {
@ -239,8 +274,10 @@ class UserController extends AbstractController {
$user_validator->username($clean['user_name'], $user_id);
$user_validator->email($clean['email']);
$user_validator->level($clean['level']);
if(count($this->db->select(PSM_DB_PREFIX.'users', array('level' => PSM_USER_ADMIN))) == 1 &&
$this->getUser()->getUserLevel() == PSM_USER_ADMIN) {
if (
count($this->db->select(PSM_DB_PREFIX . 'users', array('level' => PSM_USER_ADMIN))) == 1 &&
$this->getUser()->getUserLevel() == PSM_USER_ADMIN
) {
$this->addMessage(psm_get_lang('users', 'error_user_admin_cant_be_deleted'), 'warning');
$clean['level'] = PSM_USER_ADMIN;
}
@ -254,7 +291,7 @@ class UserController extends AbstractController {
$user_validator->userId($user_id);
}
} catch (\InvalidArgumentException $e) {
$this->addMessage(psm_get_lang('users', 'error_'.$e->getMessage()), 'error');
$this->addMessage(psm_get_lang('users', 'error_' . $e->getMessage()), 'error');
return $this->executeEdit();
}
if (!empty($clean['password'])) {
@ -265,14 +302,14 @@ class UserController extends AbstractController {
if ($user_id > 0) {
// edit user
unset($clean['password']); // password update is executed separately
$this->db->save(PSM_DB_PREFIX.'users', $clean, array('user_id' => $user_id));
$this->db->save(PSM_DB_PREFIX . 'users', $clean, array('user_id' => $user_id));
$this->addMessage(psm_get_lang('users', 'updated'), 'success');
$event = \psm\Module\User\UserEvents::USER_EDIT;
} else {
// add user
$clean['password'] = ''; // password update is executed separately
$user_id = $this->db->save(PSM_DB_PREFIX.'users', $clean);
$user_id = $this->db->save(PSM_DB_PREFIX . 'users', $clean);
$this->addMessage(psm_get_lang('users', 'inserted'), 'success');
$event = \psm\Module\User\UserEvents::USER_ADD;
@ -296,10 +333,10 @@ class UserController extends AbstractController {
);
}
// delete all existing records
$this->db->delete(PSM_DB_PREFIX.'users_servers', array('user_id' => $user_id));
$this->db->delete(PSM_DB_PREFIX . 'users_servers', array('user_id' => $user_id));
if (!empty($server_idc_save)) {
// add all new servers
$this->db->insertMultiple(PSM_DB_PREFIX.'users_servers', $server_idc_save);
$this->db->insertMultiple(PSM_DB_PREFIX . 'users_servers', $server_idc_save);
}
return $this->executeIndex();
@ -308,17 +345,18 @@ class UserController extends AbstractController {
/**
* Executes the deletion of a user
*/
protected function executeDelete() {
protected function executeDelete()
{
$id = (isset($_GET['id'])) ? intval($_GET['id']) : 0;
try {
$this->container->get('util.user.validator')->userId($id);
if(count($this->db->select(PSM_DB_PREFIX.'users', array('level' => PSM_USER_ADMIN))) == 1) {
if (count($this->db->select(PSM_DB_PREFIX . 'users', array('level' => PSM_USER_ADMIN))) == 1) {
$this->addMessage(psm_get_lang('users', 'error_user_admin_cant_be_deleted'), 'error');
} else {
$this->db->delete(PSM_DB_PREFIX.'users', array('user_id' => $id,));
$this->db->delete(PSM_DB_PREFIX.'users_servers', array('user_id' => $id));
$this->db->delete(PSM_DB_PREFIX . 'users', array('user_id' => $id,));
$this->db->delete(PSM_DB_PREFIX . 'users_servers', array('user_id' => $id));
$this->container->get('event')->dispatch(
\psm\Module\User\UserEvents::USER_DELETE,
@ -328,13 +366,14 @@ class UserController extends AbstractController {
$this->addMessage(psm_get_lang('users', 'deleted'), 'success');
}
} catch (\InvalidArgumentException $e) {
$this->addMessage(psm_get_lang('users', 'error_'.$e->getMessage()), 'error');
$this->addMessage(psm_get_lang('users', 'error_' . $e->getMessage()), 'error');
}
return $this->executeIndex();
}
protected function getLabels() {
protected function getLabels()
{
return array(
'label_users' => psm_get_lang('menu', 'user'),
'label_user' => psm_get_lang('users', 'user'),
@ -371,9 +410,10 @@ class UserController extends AbstractController {
* @return array with ids only
* @todo we should probably find a central place for this kind of stuff
*/
protected function getUserServers($user_id) {
protected function getUserServers($user_id)
{
$servers = $this->db->select(
PSM_DB_PREFIX.'users_servers',
PSM_DB_PREFIX . 'users_servers',
array('user_id' => $user_id),
array('server_id')
);

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -30,22 +31,26 @@ namespace psm\Module\User\Event;
use Symfony\Component\EventDispatcher\Event;
class UserEvent extends Event {
class UserEvent extends Event
{
protected $user_id;
protected $user_id_by;
public function __construct($user_id, $user_id_by = null) {
public function __construct($user_id, $user_id_by = null)
{
$this->user_id = $user_id;
$this->user_id_by = $user_id_by;
}
public function getUserId() {
public function getUserId()
{
return $this->user_id;
}
public function getUserIdBy() {
public function getUserIdBy()
{
return $this->user_id_by;
}
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -32,9 +33,11 @@ use psm\Module\User\UserEvents;
use psm\Module\User\Event\UserEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class UserSubscriber implements EventSubscriberInterface {
class UserSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents() {
public static function getSubscribedEvents()
{
return array(
UserEvents::USER_ADD => array('onUserAdd', 0),
UserEvents::USER_EDIT => array('onUserEdit', 0),
@ -42,12 +45,15 @@ class UserSubscriber implements EventSubscriberInterface {
);
}
public function onUserAdd(UserEvent $event) {
public function onUserAdd(UserEvent $event)
{
}
public function onUserEdit(UserEvent $event) {
public function onUserEdit(UserEvent $event)
{
}
public function onUserDelete(UserEvent $event) {
public function onUserDelete(UserEvent $event)
{
}
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -28,21 +29,21 @@
namespace psm\Module\User;
final class UserEvents {
final class UserEvents
{
/**
* @var string
*/
const USER_ADD = 'user.add';
public const USER_ADD = 'user.add';
/**
* @var string
*/
const USER_EDIT = 'user.edit';
public const USER_EDIT = 'user.edit';
/**
* @var string
*/
const USER_DELETE = 'user.delete';
public const USER_DELETE = 'user.delete';
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -31,19 +32,21 @@ namespace psm\Module\User;
use psm\Module\ModuleInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class UserModule implements ModuleInterface {
class UserModule implements ModuleInterface
{
public function load(ContainerBuilder $container) {
public function load(ContainerBuilder $container)
{
$event = $container->get('event');
$event->addSubscriber(new EventListener\UserSubscriber);
$event->addSubscriber(new EventListener\UserSubscriber());
}
public function getControllers() {
public function getControllers()
{
return array(
'user' => __NAMESPACE__.'\Controller\UserController',
'login' => __NAMESPACE__.'\Controller\LoginController',
'profile' => __NAMESPACE__.'\Controller\ProfileController',
'user' => __NAMESPACE__ . '\Controller\UserController',
'login' => __NAMESPACE__ . '\Controller\LoginController',
'profile' => __NAMESPACE__ . '\Controller\ProfileController',
);
}
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -27,6 +28,7 @@
**/
namespace psm;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Config\FileLocator;
@ -42,7 +44,8 @@ use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
* the module config. If the controller part is absent, it will always try to load
* the controller with the same name as the module.
*/
class Router {
class Router
{
/**
* Service container
@ -50,7 +53,8 @@ class Router {
*/
protected $container;
public function __construct() {
public function __construct()
{
$this->container = $this->buildServiceContainer();
$mods = $this->container->getParameter('modules');
@ -72,7 +76,8 @@ class Router {
* @throws \InvalidArgumentException
* @throws \LogicException
*/
public function run($mod) {
public function run($mod)
{
if (strpos($mod, '_') !== false) {
list($mod, $controller) = explode('_', $mod);
} else {
@ -114,16 +119,18 @@ class Router {
* @return \psm\Module\ControllerInterface
* @throws \InvalidArgumentException
*/
public function getController($module_id, $controller_id = null) {
public function getController($module_id, $controller_id = null)
{
if ($controller_id === null) {
// by default, we use the controller with the same id as the module.
$controller_id = $module_id;
}
$module = $this->container->get('module.'.$module_id);
$module = $this->container->get('module.' . $module_id);
$controllers = $module->getControllers();
if (!isset($controllers[$controller_id]) || !class_exists($controllers[$controller_id])) {
throw new \InvalidArgumentException('Controller "'.$controller_id.'" is not registered or does not exist.');
throw new \InvalidArgumentException('Controller "' . $controller_id . '"
is not registered or does not exist.');
}
$controller = new $controllers[$controller_id](
$this->container->get('db'),
@ -144,7 +151,8 @@ class Router {
* @return mixed FALSE on failure, service otherwise
* @throws \InvalidArgumentException
*/
public function getService($id) {
public function getService($id)
{
return $this->container->get($id);
}
@ -153,7 +161,8 @@ class Router {
* @param \psm\Module\ControllerInterface $controller
* @throws \InvalidArgumentException
*/
protected function validateRequest(\psm\Module\ControllerInterface $controller) {
protected function validateRequest(\psm\Module\ControllerInterface $controller)
{
$request = Request::createFromGlobals();
if ($request->getMethod() == 'POST') {
@ -167,10 +176,12 @@ class Router {
throw new \InvalidArgumentException('invalid_csrf_token');
}
} else {
if (!hash_equals(
if (
!hash_equals(
hash_hmac('sha256', $csrf_key, $session->get('csrf_token2')),
$token_in
)) {
)
) {
throw new \InvalidArgumentException('invalid_csrf_token');
}
}
@ -195,7 +206,8 @@ class Router {
* @return \Symfony\Component\DependencyInjection\ContainerBuilder
* @throws \InvalidArgumentException
*/
protected function buildServiceContainer() {
protected function buildServiceContainer()
{
$builder = new ContainerBuilder();
$loader = new XmlFileLoader($builder, new FileLocator(PSM_PATH_CONFIG));
$loader->load('services.xml');
@ -207,7 +219,8 @@ class Router {
* Prepare twig environment
* @return \Twig_Environment
*/
protected function buildTwigEnvironment() {
protected function buildTwigEnvironment()
{
$twig = $this->container->get('twig');
$session = $this->container->get('user')->getSession();
if (!$session->has('csrf_token')) {
@ -220,7 +233,7 @@ class Router {
$twig->addFunction(
new \Twig_SimpleFunction(
'csrf_token',
function($lock_to = null) use ($session) {
function ($lock_to = null) use ($session) {
if (empty($lock_to)) {
return $session->get('csrf_token');
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -27,7 +28,8 @@
namespace psm\Service;
class Database {
class Database
{
/**
* DB hostname
@ -88,7 +90,8 @@ class Database {
* @param string $db
* @param string|integer $port
*/
function __construct($host = null, $user = null, $pass = null, $db = null, $port = '') {
public function __construct($host = null, $user = null, $pass = null, $db = null, $port = '')
{
if ($host != null && $user != null && $pass !== null && $db != null) {
$this->db_host = $host;
$this->db_port = $port;
@ -107,7 +110,8 @@ class Database {
* @param boolean $fetch automatically fetch results, or return PDOStatement?
* @return \PDOStatement|int|bool|array object
*/
public function query($query, $fetch = true) {
public function query($query, $fetch = true)
{
// Execute query and process results
try {
$this->last = $this->pdo()->query($query);
@ -143,7 +147,8 @@ class Database {
* @param string $query
* @return int
*/
public function exec($query) {
public function exec($query)
{
try {
$this->last = $this->pdo()->exec($query);
} catch (\PDOException $e) {
@ -156,11 +161,13 @@ class Database {
/**
* Prepare and execute SQL statement with parameters
* @param string $query SQL statement
* @param array $parameters An array of values with as many elements as there are bound parameters in the SQL statement
* @param array $parameters An array of values with as many elements as there are
* bound parameters in the SQL statement
* @param boolean $fetch automatically fetch results, or return PDOStatement?
* @return array|\PDOStatement if $fetch = true, array, otherwise \PDOStatement
*/
public function execute($query, $parameters, $fetch = true) {
public function execute($query, $parameters, $fetch = true)
{
try {
$this->last = $this->pdo()->prepare($query);
$this->last->execute($parameters);
@ -186,14 +193,15 @@ class Database {
* @param string $direction ASC or DESC. Defaults to ASC
* @return \PDOStatement array multi dimensional array with results
*/
public function select($table, $where = null, $fields = null, $limit = '', $orderby = null, $direction = 'ASC') {
public function select($table, $where = null, $fields = null, $limit = '', $orderby = null, $direction = 'ASC')
{
// build query
$query_parts = array();
$query_parts[] = 'SELECT SQL_CALC_FOUND_ROWS';
// Fields
if ($fields !== null && !empty($fields)) {
$query_parts[] = "`".implode('`,`', $fields)."`";
$query_parts[] = "`" . implode('`,`', $fields) . "`";
} else {
$query_parts[] = ' * ';
}
@ -211,7 +219,7 @@ class Database {
// Limit
if ($limit != '') {
$query_parts[] = 'LIMIT '.$limit;
$query_parts[] = 'LIMIT ' . $limit;
}
$query = implode(' ', $query_parts);
@ -228,7 +236,8 @@ class Database {
* @param string $direction ASC or DESC. Defaults to ASC
* @return array
*/
public function selectRow($table, $where = null, $fields = null, $orderby = null, $direction = 'ASC') {
public function selectRow($table, $where = null, $fields = null, $orderby = null, $direction = 'ASC')
{
$result = $this->select($table, $where, $fields, '1', $orderby, $direction);
if (isset($result[0])) {
@ -244,8 +253,9 @@ class Database {
* @param mixed $where Where clause array or primary Id (string) or where clause (string)
* @return int number of affected rows
*/
public function delete($table, $where = null) {
$sql = 'DELETE FROM `'.$table.'` '.$this->buildSQLClauseWhere($table, $where);
public function delete($table, $where = null)
{
$sql = 'DELETE FROM `' . $table . '` ' . $this->buildSQLClauseWhere($table, $where);
return $this->exec($sql);
}
@ -254,10 +264,12 @@ class Database {
* Insert or update data to the database
* @param string $table table name
* @param array $data data to save or insert
* @param string|array $where either string ('user_id=2' or just '2' (works only with primary field)) or array with where clause (only when updating)
* @param string|array $where either string ('user_id=2' or just '2' (works only with primary field)) or
* array with where clause (only when updating)
* @return int|array|\PDOStatement
*/
public function save($table, array $data, $where = null) {
public function save($table, array $data, $where = null)
{
if ($where === null) {
// insert mode
$query = "INSERT INTO ";
@ -278,7 +290,7 @@ class Database {
$query .= "`{$table}`.`{$field}`={$value}, ";
}
$query = substr($query, 0, -2).' '.$this->buildSQLClauseWhere($table, $where);
$query = substr($query, 0, -2) . ' ' . $this->buildSQLClauseWhere($table, $where);
if ($exec) {
return $this->exec($query);
@ -300,7 +312,8 @@ class Database {
* @return \PDOStatement
* @see insert()
*/
public function insertMultiple($table, array $data) {
public function insertMultiple($table, array $data)
{
if (empty($data)) {
return false;
}
@ -308,11 +321,11 @@ class Database {
// prepare first part
$query = "INSERT INTO `{$table}` ";
$fields = array_keys($data[0]);
$query .= "(`".implode('`,`', $fields)."`) VALUES ";
$query .= "(`" . implode('`,`', $fields) . "`) VALUES ";
// prepare all rows to be inserted with placeholders for vars (\?)
$q_part = array_fill(0, count($fields), '?');
$q_part = "(".implode(',', $q_part).")";
$q_part = "(" . implode(',', $q_part) . ")";
$q_part = array_fill(0, count($data), $q_part);
$query .= implode(',', $q_part);
@ -345,7 +358,8 @@ class Database {
* @param string $table
* @return boolean
*/
public function ifTableExists($table) {
public function ifTableExists($table)
{
$table = $this->quote($table);
$db = $this->quote($this->getDbName());
@ -368,7 +382,8 @@ class Database {
* @param string $value
* @return string
*/
public function quote($value) {
public function quote($value)
{
return $this->pdo()->quote($value);
}
@ -376,7 +391,8 @@ class Database {
* Get the PDO object
* @return \PDO
*/
public function pdo() {
public function pdo()
{
return $this->pdo;
}
@ -384,7 +400,8 @@ class Database {
* Get number of rows of last statement
* @return int number of rows
*/
public function getNumRows() {
public function getNumRows()
{
return $this->last->rowCount();
}
@ -392,7 +409,8 @@ class Database {
* Get the last inserted id after an insert
* @return int
*/
public function getLastInsertedId() {
public function getLastInsertedId()
{
return $this->pdo()->lastInsertId();
}
@ -403,7 +421,8 @@ class Database {
* @return string sql where clause
* @see buildSQLClauseOrderBy()
*/
public function buildSQLClauseWhere($table, $where = null) {
public function buildSQLClauseWhere($table, $where = null)
{
$query = '';
@ -423,7 +442,7 @@ class Database {
} elseif (strpos(strtolower(trim($where)), 'where') === false) {
$query .= " WHERE {$where}";
} else {
$query .= ' '.$where;
$query .= ' ' . $where;
}
}
}
@ -437,7 +456,8 @@ class Database {
* @return string sql order by clause
* @see buildSQLClauseWhere()
*/
public function buildSQLClauseOrderBy($order_by, $direction) {
public function buildSQLClauseOrderBy($order_by, $direction)
{
$query = '';
if ($order_by !== null) {
@ -453,14 +473,17 @@ class Database {
if (strpos(strtolower(trim($order_by)), 'order by') === false) {
$query .= " ORDER BY {$order_by}";
} else {
$query .= ' '.$order_by;
$query .= ' ' . $order_by;
}
}
}
if (strlen($query) > 0) {
// check if "ASC" or "DESC" is already in the order by clause
if (strpos(strtolower(trim($query)), 'asc') === false && strpos(strtolower(trim($query)), 'desc') === false) {
$query .= ' '.$direction;
if (
strpos(strtolower(trim($query)), 'asc') === false &&
strpos(strtolower(trim($query)), 'desc') === false
) {
$query .= ' ' . $direction;
}
}
@ -471,7 +494,8 @@ class Database {
* Get the host of the current connection
* @return string
*/
public function getDbHost() {
public function getDbHost()
{
return $this->db_host;
}
@ -479,7 +503,8 @@ class Database {
* Get the db name of the current connection
* @return string
*/
public function getDbName() {
public function getDbName()
{
return $this->db_name;
}
@ -487,7 +512,8 @@ class Database {
* Get the db user of the current connection
* @return string
*/
public function getDbUser() {
public function getDbUser()
{
return $this->db_user;
}
@ -495,7 +521,8 @@ class Database {
* Get status of the connection
* @return boolean
*/
public function status() {
public function status()
{
return $this->status;
}
@ -504,11 +531,15 @@ class Database {
*
* @return resource mysql resource
*/
protected function connect() {
protected function connect()
{
// Initizale connection
try {
$this->pdo = new \PDO(
'mysql:host='.$this->db_host.';port='.$this->db_port.';dbname='.$this->db_name.';charset=utf8',
'mysql:host=' . $this->db_host .
';port=' . $this->db_port .
';dbname=' . $this->db_name .
';charset=utf8',
$this->db_user,
$this->db_pass
);
@ -524,15 +555,17 @@ class Database {
/**
* Is called after connection failure
*/
protected function onConnectFailure(\PDOException $e) {
trigger_error('MySQL connection failed: '.$e->getMessage(), E_USER_WARNING);
protected function onConnectFailure(\PDOException $e)
{
trigger_error('MySQL connection failed: ' . $e->getMessage(), E_USER_WARNING);
return false;
}
/**
* Disconnect from current link
*/
protected function disconnect() {
protected function disconnect()
{
$this->pdo = null;
}
@ -540,7 +573,8 @@ class Database {
* Handle a PDOException
* @param \PDOException $e
*/
protected function error(\PDOException $e) {
trigger_error('SQL error: '.$e->getMessage(), E_USER_WARNING);
protected function error(\PDOException $e)
{
trigger_error('SQL error: ' . $e->getMessage(), E_USER_WARNING);
}
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -28,6 +29,7 @@
**/
namespace psm\Service;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
@ -42,7 +44,8 @@ use Symfony\Component\HttpFoundation\Session\SessionInterface;
* @link https://github.com/panique/php-login-advanced/
* @license http://opensource.org/licenses/MIT MIT License
*/
class User {
class User
{
/**
* The database connection
@ -86,7 +89,8 @@ class User {
* @param \psm\Service\Database $db
* @param \Symfony\Component\HttpFoundation\Session\SessionInterface $session if NULL, one will be created
*/
public function __construct(Database $db, SessionInterface $session = null) {
public function __construct(Database $db, SessionInterface $session = null)
{
$this->db_connection = $db->pdo();
if (!psm_is_cli()) {
@ -98,7 +102,8 @@ class User {
if ((!defined('PSM_INSTALL') || !PSM_INSTALL)) {
// check the possible login actions:
// 1. login via session data (happens each time user opens a page on your php project AFTER he has successfully logged in via the login form)
// 1. login via session data (happens each time user opens a page on your php project AFTER
// he has successfully logged in via the login form)
// 2. login via cookie
// if user has an active session on the server
@ -115,7 +120,8 @@ class User {
* @param boolean $flush if TRUE it will query db regardless of whether we already have the data
* @return object|boolean FALSE if user not found, object otherwise
*/
public function getUser($user_id = null, $flush = false) {
public function getUser($user_id = null, $flush = false)
{
if ($user_id == null) {
if (!$this->isUserLoggedIn()) {
return false;
@ -125,7 +131,8 @@ class User {
}
if (!isset($this->user_data[$user_id]) || $flush) {
$query_user = $this->db_connection->prepare('SELECT * FROM '.PSM_DB_PREFIX.'users WHERE user_id = :user_id');
$query_user = $this->db_connection->prepare('SELECT * FROM ' .
PSM_DB_PREFIX . 'users WHERE user_id = :user_id');
$query_user->bindValue(':user_id', $user_id, \PDO::PARAM_INT);
$query_user->execute();
// get result row (as an object)
@ -138,9 +145,11 @@ class User {
* Search into database for the user data of user_name specified as parameter
* @return object|boolean user data as an object if existing user
*/
public function getUserByUsername($user_name) {
public function getUserByUsername($user_name)
{
// database query, getting all the info of the selected user
$query_user = $this->db_connection->prepare('SELECT * FROM '.PSM_DB_PREFIX.'users WHERE user_name = :user_name');
$query_user = $this->db_connection->prepare('SELECT * FROM ' .
PSM_DB_PREFIX . 'users WHERE user_name = :user_name');
$query_user->bindValue(':user_name', $user_name, \PDO::PARAM_STR);
$query_user->execute();
// get result row (as an object)
@ -152,7 +161,8 @@ class User {
*
* @return boolean
*/
protected function loginWithSessionData() {
protected function loginWithSessionData()
{
if (!$this->session->has('user_id')) {
return false;
}
@ -173,12 +183,13 @@ class User {
* Logs in via the Cookie
* @return bool success state of cookie login
*/
private function loginWithCookieData() {
private function loginWithCookieData()
{
if (isset($_COOKIE['rememberme'])) {
// extract data from the cookie
list ($user_id, $token, $hash) = explode(':', $_COOKIE['rememberme']);
// check cookie hash validity
if ($hash == hash('sha256', $user_id.':'.$token.PSM_LOGIN_COOKIE_SECRET_KEY) && !empty($token)) {
if ($hash == hash('sha256', $user_id . ':' . $token . PSM_LOGIN_COOKIE_SECRET_KEY) && !empty($token)) {
// cookie looks good, try to select corresponding user
// get real token from database (and all other data)
$user = $this->getUser($user_id);
@ -204,7 +215,8 @@ class User {
* @param boolean $user_rememberme
* @return boolean
*/
public function loginWithPostData($user_name, $user_password, $user_rememberme = false) {
public function loginWithPostData($user_name, $user_password, $user_rememberme = false)
{
$user_name = trim($user_name);
$user_password = trim($user_password);
@ -213,11 +225,12 @@ class User {
}
$user = $this->getUserByUsername($user_name);
// using PHP 5.5's password_verify() function to check if the provided passwords fits to the hash of that user's password
// using PHP 5.5's password_verify() function to check if the provided passwords
// fits to the hash of that user's password
if (!isset($user->user_id)) {
password_verify($user_password, 'dummy_call_against_timing');
return false;
} else if (!password_verify($user_password, $user->password)) {
} elseif (!password_verify($user_password, $user->password)) {
return false;
}
@ -229,7 +242,8 @@ class User {
}
// recalculate the user's password hash
// DELETE this if-block if you like, it only exists to recalculate users's hashes when you provide a cost factor,
// DELETE this if-block if you like, it only exists to recalculate
// users's hashes when you provide a cost factor,
// by default the script will use a cost factor of 10 and never change it.
// check if the have defined a cost factor in config/hashing.php
if (defined('PSM_LOGIN_HASH_COST_FACTOR')) {
@ -246,7 +260,8 @@ class User {
* @param int $user_id
* @param boolean $regenerate regenerate session id against session fixation?
*/
protected function setUserLoggedIn($user_id, $regenerate = false) {
protected function setUserLoggedIn($user_id, $regenerate = false)
{
if ($regenerate) {
$this->session->invalidate();
}
@ -261,16 +276,18 @@ class User {
/**
* Create all data needed for remember me cookie connection on client and server side
*/
protected function newRememberMeCookie() {
protected function newRememberMeCookie()
{
// generate 64 char random string and store it in current user data
$random_token_string = hash('sha256', mt_rand());
$sth = $this->db_connection->prepare('UPDATE '.PSM_DB_PREFIX.'users SET rememberme_token = :user_rememberme_token WHERE user_id = :user_id');
$sth = $this->db_connection->prepare('UPDATE ' .
PSM_DB_PREFIX . 'users SET rememberme_token = :user_rememberme_token WHERE user_id = :user_id');
$sth->execute(array(':user_rememberme_token' => $random_token_string, ':user_id' => $this->getUserId()));
// generate cookie string that consists of userid, randomstring and combined hash of both
$cookie_string_first_part = $this->getUserId().':'.$random_token_string;
$cookie_string_hash = hash('sha256', $cookie_string_first_part.PSM_LOGIN_COOKIE_SECRET_KEY);
$cookie_string = $cookie_string_first_part.':'.$cookie_string_hash;
$cookie_string_first_part = $this->getUserId() . ':' . $random_token_string;
$cookie_string_hash = hash('sha256', $cookie_string_first_part . PSM_LOGIN_COOKIE_SECRET_KEY);
$cookie_string = $cookie_string_first_part . ':' . $cookie_string_hash;
// set cookie
setcookie('rememberme', $cookie_string, time() + PSM_LOGIN_COOKIE_RUNTIME, "/", PSM_LOGIN_COOKIE_DOMAIN);
@ -279,10 +296,12 @@ class User {
/**
* Delete all data needed for remember me cookie connection on client and server side
*/
protected function deleteRememberMeCookie() {
protected function deleteRememberMeCookie()
{
// Reset rememberme token
if ($this->session->has('user_id')) {
$sth = $this->db_connection->prepare('UPDATE '.PSM_DB_PREFIX.'users SET rememberme_token = NULL WHERE user_id = :user_id');
$sth = $this->db_connection->prepare('UPDATE ' .
PSM_DB_PREFIX . 'users SET rememberme_token = NULL WHERE user_id = :user_id');
$sth->execute(array(':user_id' => $this->session->get('user_id')));
}
@ -295,7 +314,8 @@ class User {
/**
* Perform the logout, resetting the session
*/
public function doLogout() {
public function doLogout()
{
$this->deleteRememberMeCookie();
$this->session->clear();
@ -308,7 +328,8 @@ class User {
* Simply return the current state of the user's login
* @return bool user's login status
*/
public function isUserLoggedIn() {
public function isUserLoggedIn()
{
return $this->user_is_logged_in;
}
@ -318,7 +339,8 @@ class User {
* @param int $user_id
* @return string|boolean FALSE on error, string otherwise
*/
public function generatePasswordResetToken($user_id) {
public function generatePasswordResetToken($user_id)
{
$user_id = intval($user_id);
if ($user_id == 0) {
@ -329,7 +351,8 @@ class User {
// generate random hash for email password reset verification (40 char string)
$user_password_reset_hash = sha1(uniqid(mt_rand(), true));
$query_update = $this->db_connection->prepare('UPDATE '.PSM_DB_PREFIX.'users SET password_reset_hash = :user_password_reset_hash,
$query_update = $this->db_connection->prepare('UPDATE ' .
PSM_DB_PREFIX . 'users SET password_reset_hash = :user_password_reset_hash,
password_reset_timestamp = :user_password_reset_timestamp
WHERE user_id = :user_id');
$query_update->bindValue(':user_password_reset_hash', $user_password_reset_hash, \PDO::PARAM_STR);
@ -353,7 +376,8 @@ class User {
* @param string $token
* @return boolean
*/
public function verifyPasswordResetToken($user_id, $token) {
public function verifyPasswordResetToken($user_id, $token)
{
$user_id = intval($user_id);
if (empty($user_id) || empty($token)) {
@ -378,24 +402,28 @@ class User {
* @param string $password
* @return boolean TRUE on success, FALSE on failure
*/
public function changePassword($user_id, $password) {
public function changePassword($user_id, $password)
{
$user_id = intval($user_id);
if (empty($user_id) || empty($password)) {
return false;
}
// now it gets a little bit crazy: check if we have a constant PSM_LOGIN_HASH_COST_FACTOR defined (in src/includes/psmconfig.inc.php),
// now it gets a little bit crazy: check if we have a constant
// PSM_LOGIN_HASH_COST_FACTOR defined (in src/includes/psmconfig.inc.php),
// if so: put the value into $hash_cost_factor, if not, make $hash_cost_factor = null
$hash_cost_factor = (defined('PSM_LOGIN_HASH_COST_FACTOR') ? PSM_LOGIN_HASH_COST_FACTOR : null);
// crypt the user's password with the PHP 5.5's password_hash() function, results in a 60 character hash string
// the PASSWORD_DEFAULT constant is defined by the PHP 5.5, or if you are using PHP 5.3/5.4, by the password hashing
// the PASSWORD_DEFAULT constant is defined by the PHP 5.5,
// or if you are using PHP 5.3/5.4, by the password hashing
// compatibility library. the third parameter looks a little bit shitty, but that's how those PHP 5.5 functions
// want the parameter: as an array with, currently only used with 'cost' => XX.
$user_password_hash = password_hash($password, PASSWORD_DEFAULT, array('cost' => $hash_cost_factor));
// write users new hash into database
$query_update = $this->db_connection->prepare('UPDATE '.PSM_DB_PREFIX.'users SET password = :user_password_hash,
$query_update = $this->db_connection->prepare('UPDATE ' .
PSM_DB_PREFIX . 'users SET password = :user_password_hash,
password_reset_hash = NULL, password_reset_timestamp = NULL
WHERE user_id = :user_id');
$query_update->bindValue(':user_password_hash', $user_password_hash, \PDO::PARAM_STR);
@ -414,7 +442,8 @@ class User {
* Gets the user id
* @return int
*/
public function getUserId() {
public function getUserId()
{
return $this->user_id;
}
@ -422,7 +451,8 @@ class User {
* Gets the username
* @return string
*/
public function getUsername() {
public function getUsername()
{
$user = $this->getUser();
return (isset($user->user_name) ? $user->user_name : null);
}
@ -431,7 +461,8 @@ class User {
* Gets the user level
* @return int
*/
public function getUserLevel() {
public function getUserLevel()
{
$user = $this->getUser();
if (isset($user->level)) {
@ -445,14 +476,18 @@ class User {
* read current user preferences from the database
* @return boolean return false is user not connected
*/
protected function loadPreferences() {
protected function loadPreferences()
{
if ($this->user_preferences === null) {
if (!$this->getUser()) {
return false;
}
$this->user_preferences = array();
foreach ($this->db_connection->query('SELECT `key`,`value` FROM `'.PSM_DB_PREFIX.'users_preferences` WHERE `user_id` = '.$this->user_id) as $row) {
foreach (
$this->db_connection->query('SELECT `key`,`value` FROM `' .
PSM_DB_PREFIX . 'users_preferences` WHERE `user_id` = ' . $this->user_id) as $row
) {
$this->user_preferences[$row['key']] = $row['value'];
}
}
@ -465,7 +500,8 @@ class User {
* @param mixed $default
* @return mixed
*/
public function getUserPref($key, $default = '') {
public function getUserPref($key, $default = '')
{
if (!$this->loadPreferences() || !isset($this->user_preferences[$key])) {
return $default;
}
@ -480,15 +516,16 @@ class User {
* @param string $key
* @param mixed $value
*/
public function setUserPref($key, $value) {
public function setUserPref($key, $value)
{
if ($this->loadPreferences()) {
if (isset($this->user_preferences[$key])) {
if ($this->user_preferences[$key] == $value) {
return; // no change
}
$sql = 'UPDATE `'.PSM_DB_PREFIX.'users_preferences` SET `key` = ?, `value` = ? WHERE `user_id` = ?';
$sql = 'UPDATE `' . PSM_DB_PREFIX . 'users_preferences` SET `key` = ?, `value` = ? WHERE `user_id` = ?';
} else {
$sql = 'INSERT INTO `'.PSM_DB_PREFIX.'users_preferences` SET `key` = ?, `value` = ?, `user_id` = ?';
$sql = 'INSERT INTO `' . PSM_DB_PREFIX . 'users_preferences` SET `key` = ?, `value` = ?, `user_id` = ?';
}
$sth = $this->db_connection->prepare($sql);
$sth->execute(array($key, $value, $this->user_id));
@ -500,7 +537,8 @@ class User {
* Get session object
* @return \Symfony\Component\HttpFoundation\Session\SessionInterface
*/
public function getSession() {
public function getSession()
{
return $this->session;
}
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -36,7 +37,8 @@ namespace psm\Txtmsg;
*
* Requirements: cURL v7.18.1+ and OpenSSL 0.9.8j+
*/
class CMBulkSMS extends Core {
class CMBulkSMS extends Core
{
/** @var bool True when cURL request succeeded */
public $result = true;
@ -65,10 +67,10 @@ class CMBulkSMS extends Core {
protected $messageBody;
/** @var string JSON Gateway API URL */
const GATEWAY_URL_JSON = "https://gw.cmtelecom.com/v1.0/message";
public const GATEWAY_URL_JSON = "https://gw.cmtelecom.com/v1.0/message";
/** @var string XML Gateway API URL */
const GATEWAY_URL_XML = "https://sgw01.cm.nl/gateway.ashx";
public const GATEWAY_URL_XML = "https://sgw01.cm.nl/gateway.ashx";
/**
* Build the message and send cURL request to the sms gateway
@ -77,7 +79,8 @@ class CMBulkSMS extends Core {
* @param string $message Your text message
* @return bool|string true when cURL request was successful, otherwise string with error message
*/
public function sendSMS($message) {
public function sendSMS($message)
{
// Check if recipient and text message are available
if (count($this->recipients) < 1 || empty($message)) {
return false;
@ -112,7 +115,8 @@ class CMBulkSMS extends Core {
* @see https://docs.cmtelecom.com/bulk-sms/v1.0#/send_a_message%7Cmultipart
* @return string JSON message object
*/
protected function buildMessageJson() {
protected function buildMessageJson()
{
// Prepare recipient array for batch message
$recipients = array();
foreach ($this->recipients as $recipient) {
@ -155,7 +159,8 @@ class CMBulkSMS extends Core {
* @see https://docs.cmtelecom.com/bulk-sms/v1.0#/send_a_message%7Cmultipart
* @return string XML message
*/
protected function buildMessageXml() {
protected function buildMessageXml()
{
// Create XML string
$xml = new \SimpleXMLElement('<MESSAGES/>');
@ -192,7 +197,8 @@ class CMBulkSMS extends Core {
* @return boolean|string boolean if message is sent, else string
*/
protected function executeCurlRequest() {
protected function executeCurlRequest()
{
$cr = curl_init();
curl_setopt_array($cr, array(
CURLOPT_URL => $this->apiUrl,
@ -201,8 +207,7 @@ class CMBulkSMS extends Core {
CURLOPT_POSTFIELDS => $this->request,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FAILONERROR => true
)
);
));
// execute curl request and fetch the response/error
$cResponse = curl_exec($cr);
@ -212,7 +217,8 @@ class CMBulkSMS extends Core {
// set result and log error if needed
if ($cError) {
$this->error = 'Response: CM SMS API:'.$cResponse.' cURL Error Code: '.$cErrorCode.'"'.$cError.'"';
$this->error = 'Response: CM SMS API:' . $cResponse . ' cURL Error Code: ' .
$cErrorCode . '"' . $cError . '"';
error_log($this->error, E_USER_ERROR);
$this->result = false;
}
@ -220,7 +226,7 @@ class CMBulkSMS extends Core {
// Debug output
// Note: CM's XML gateway gives no response when message is sent successfully :/
if ($this->debug || PSM_DEBUG) {
$debug = '<pre>Request: '.$this->request.'<br>Response: '.$cResponse.'</pre>';
$debug = '<pre>Request: ' . $this->request . '<br>Response: ' . $cResponse . '</pre>';
error_log("Request: $this->request\r\nResponse: $cResponse", E_USER_NOTICE);
echo $debug;
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -29,7 +30,8 @@
namespace psm\Txtmsg;
class Callr extends Core {
class Callr extends Core
{
/**
* Send sms using the Callr API
@ -52,7 +54,8 @@ class Callr extends Core {
* @return bool|string
*/
public function sendSMS($message) {
public function sendSMS($message)
{
$error = "";
$success = 1;
@ -74,7 +77,7 @@ class Callr extends Core {
)
),
CURLOPT_HTTPHEADER => array(
"authorization: Basic ".base64_encode($this->username.":".$this->password),
"authorization: Basic " . base64_encode($this->username . ":" . $this->password),
"content-type: application/json"
),
));
@ -85,7 +88,8 @@ class Callr extends Core {
if ($err != 0 || $httpcode != 200 || $result['status'] == "error") {
$success = 0;
$error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". Result: ".$result['data']['code']." - ".$result['data']['message'];
$error = "HTTP_code: " . $httpcode . ".\ncURL error (" . $err . "): " . curl_strerror($err) .
". Result: " . $result['data']['code'] . " - " . $result['data']['message'];
}
curl_close($curl);
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -28,7 +29,8 @@
namespace psm\Txtmsg;
class ClickSend extends Core {
class ClickSend extends Core
{
/**
* Send sms using the SMSgw.NET API
@ -49,7 +51,8 @@ class ClickSend extends Core {
* @return bool|string
*/
public function sendSMS($message) {
public function sendSMS($message)
{
$error = "";
$success = 1;
@ -78,7 +81,7 @@ class ClickSend extends Core {
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => array(
"authorization: Basic ".base64_encode($this->username.":".$this->password),
"authorization: Basic " . base64_encode($this->username . ":" . $this->password),
"content-type: application/json"
),
));
@ -87,9 +90,13 @@ class ClickSend extends Core {
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$err = curl_errno($curl);
if ($err != 0 || ($httpcode != '200' && $httpcode != '201' && $httpcode != '202' && $result['response_code'] != "SUCCESS")) {
if (
$err != 0 ||
($httpcode != '200' && $httpcode != '201' && $httpcode != '202' && $result['response_code'] != "SUCCESS")
) {
$success = 0;
$error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". Result: ".$result."";
$error = "HTTP_code: " . $httpcode . ".\ncURL error (" . $err . "): " .
curl_strerror($err) . ". Result: " . $result . "";
}
curl_close($curl);

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -28,7 +29,8 @@
namespace psm\Txtmsg;
class Clickatell extends Core {
class Clickatell extends Core
{
/**
* Send sms using the Clickatell API
@ -44,12 +46,14 @@ class Clickatell extends Core {
* @return bool|string
*/
public function sendSMS($message) {
public function sendSMS($message)
{
$success = 1;
$error = '';
foreach ($this->recipients as $recipient) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://platform.clickatell.com/messages/http/send?apiKey=".urlencode($this->password)."&to=".urlencode($recipient)."&content=".urlencode($message));
curl_setopt($ch, CURLOPT_URL, "https://platform.clickatell.com/messages/http/send?apiKey=" .
urlencode($this->password) . "&to=" . urlencode($recipient) . "&content=" . urlencode($message));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$headers = array();
$headers[] = "Content-Type: application/x-www-form-urlencoded";
@ -58,7 +62,7 @@ class Clickatell extends Core {
curl_close($ch);
// Check on error
if (strpos($result, ",\"errorCode\":null,\"error\":null,\"errorDescription\":null") === False) {
if (strpos($result, ",\"errorCode\":null,\"error\":null,\"errorDescription\":null") === false) {
$error = $result;
$success = 0;
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -27,7 +28,8 @@
namespace psm\Txtmsg;
abstract class Core implements TxtmsgInterface {
abstract class Core implements TxtmsgInterface
{
protected $originator;
protected $password;
protected $recipients = array();
@ -39,7 +41,8 @@ abstract class Core implements TxtmsgInterface {
* @param string $username
* @param string $password
*/
public function setLogin($username, $password) {
public function setLogin($username, $password)
{
$this->username = $username;
$this->password = $password;
}
@ -49,7 +52,8 @@ abstract class Core implements TxtmsgInterface {
*
* @param string $originator
*/
public function setOriginator($originator) {
public function setOriginator($originator)
{
$this->originator = $originator;
}
@ -58,7 +62,8 @@ abstract class Core implements TxtmsgInterface {
*
* @param string|int $recipient
*/
public function addRecipients($recipient) {
public function addRecipients($recipient)
{
array_push($this->recipients, $recipient);
}
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -27,7 +28,8 @@
namespace psm\Txtmsg;
class FreeMobileSMS extends Core {
class FreeMobileSMS extends Core
{
/**
* Send sms using the FreeMobileSMS API
@ -45,20 +47,20 @@ class FreeMobileSMS extends Core {
* @return bool|string
*/
public function sendSMS($message) {
public function sendSMS($message)
{
$success = 1;
$error = "";
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, "https://smsapi.free-mobile.fr/sendmsg?".http_build_query(
curl_setopt($curl, CURLOPT_URL, "https://smsapi.free-mobile.fr/sendmsg?" . http_build_query(
array(
"user" => $this->username,
"pass" => $this->password,
"msg" => urlencode($message),
)
)
);
));
$result = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
@ -66,7 +68,7 @@ class FreeMobileSMS extends Core {
if ($err != 0 || $httpcode != 200) {
$success = 0;
$error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err);
$error = "HTTP_code: " . $httpcode . ".\ncURL error (" . $err . "): " . curl_strerror($err);
}
curl_close($curl);

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -28,7 +29,8 @@
namespace psm\Txtmsg;
class FreeVoipDeal extends Core {
class FreeVoipDeal extends Core
{
/**
* Send sms using the FreeVoipDeal API
@ -48,16 +50,16 @@ class FreeVoipDeal extends Core {
* @return bool|string
*/
public function sendSMS($message) {
public function sendSMS($message)
{
$error = "";
$success = 1;
$message = rawurlencode($message);
foreach ($this->recipients as $recipient) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://www.freevoipdeal.com/myaccount/sendsms.php?".http_build_query(
curl_setopt($curl, CURLOPT_URL, "https://www.freevoipdeal.com/myaccount/sendsms.php?" . http_build_query(
array(
"username" => $this->username,
"password" => $this->password,
@ -65,8 +67,7 @@ class FreeVoipDeal extends Core {
"to" => $recipient,
"text" => $message,
)
)
);
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -29,7 +30,8 @@
namespace psm\Txtmsg;
class GatewayAPI extends Core {
class GatewayAPI extends Core
{
/**
* Send sms using the GatewayAPI API
@ -49,7 +51,8 @@ class GatewayAPI extends Core {
* @return bool|string
*/
public function sendSMS($message) {
public function sendSMS($message)
{
$error = "";
$success = 1;
@ -70,7 +73,7 @@ class GatewayAPI extends Core {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://gatewayapi.com/rest/mtsms");
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
curl_setopt($curl, CURLOPT_USERPWD, $this->password.":");
curl_setopt($curl, CURLOPT_USERPWD, $this->password . ":");
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($json));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
@ -81,7 +84,7 @@ class GatewayAPI extends Core {
if ($err != 0 || $httpcode != 200) {
$success = 0;
$error = $result['code']." - ".$result['message'];
$error = $result['code'] . " - " . $result['message'];
}
if ($success) {

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -28,7 +29,8 @@
namespace psm\Txtmsg;
class Inetworx extends Core {
class Inetworx extends Core
{
/**
* Send sms using the Inetworx API
@ -49,7 +51,8 @@ class Inetworx extends Core {
* @return bool|string
*/
public function sendSMS($message) {
public function sendSMS($message)
{
$error = "";
$success = 1;
@ -74,7 +77,7 @@ class Inetworx extends Core {
)
),
CURLOPT_HTTPHEADER => array(
"authorization: Basic ".base64_encode("inetworxag:conn2smsapp"),
"authorization: Basic " . base64_encode("inetworxag:conn2smsapp"),
"content-type: application/x-www-form-urlencoded"
),
));
@ -85,7 +88,8 @@ class Inetworx extends Core {
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($err != 0 || $httpcode != 200 || strpos($result, "200") === false) {
$success = 0;
$error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". \nResult: ".$result;
$error = "HTTP_code: " . $httpcode . ".\ncURL error (" . $err . "): " .
curl_strerror($err) . ". \nResult: " . $result;
}
curl_close($curl);
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -29,7 +30,8 @@
namespace psm\Txtmsg;
class Messagebird extends Core {
class Messagebird extends Core
{
/**
* Send sms using the Messagebird API
@ -48,7 +50,8 @@ class Messagebird extends Core {
* @return bool|string
*/
public function sendSMS($message) {
public function sendSMS($message)
{
$success = 1;
$error = '';
@ -58,14 +61,17 @@ class Messagebird extends Core {
foreach ($recipients_chunk as $recipients) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://rest.messagebird.com/messages");
curl_setopt($ch, CURLOPT_POSTFIELDS,
"originator=".urlencode($this->originator == '' ? 'PSM' : $this->originator).
"&body=".urlencode($message).
"&recipients=".implode(",", $recipients));
curl_setopt(
$ch,
CURLOPT_POSTFIELDS,
"originator=" . urlencode($this->originator == '' ? 'PSM' : $this->originator) .
"&body=" . urlencode($message) .
"&recipients=" . implode(",", $recipients)
);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$headers = array();
$headers[] = "Authorization: AccessKey ".$this->password;
$headers[] = "Authorization: AccessKey " . $this->password;
$headers[] = "Content-Type: application/x-www-form-urlencoded";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -28,7 +29,8 @@
namespace psm\Txtmsg;
class Mosms extends Core {
class Mosms extends Core
{
/**
* Send sms using the Mosms API
@ -48,16 +50,16 @@ class Mosms extends Core {
* @return bool|string
*/
public function sendSMS($message) {
public function sendSMS($message)
{
$error = "";
$success = 1;
$message = rawurlencode($message);
foreach ($this->recipients as $recipient) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://www.mosms.com/se/sms-send.php?".http_build_query(
curl_setopt($curl, CURLOPT_URL, "https://www.mosms.com/se/sms-send.php?" . http_build_query(
array(
"username" => $this->username,
"password" => $this->password,
@ -66,8 +68,7 @@ class Mosms extends Core {
"type" => "text",
"data" => $message,
)
)
);
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
@ -76,10 +77,9 @@ class Mosms extends Core {
if ($err != 0 || $httpcode != 200 || $result == 2 || $result == 5) {
$success = 0;
$error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".$err.". \nResult: ".$result;
$error = "HTTP_code: " . $httpcode . ".\ncURL error (" . $err . "): " . $err . ". \nResult: " . $result;
}
curl_close($curl);
}
if ($success) {

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -28,7 +29,8 @@
namespace psm\Txtmsg;
class Nexmo extends Core {
class Nexmo extends Core
{
/**
@ -50,15 +52,15 @@ class Nexmo extends Core {
* @return bool|string
*/
public function sendSMS($message) {
public function sendSMS($message)
{
$success = 1;
$error = "";
foreach ($this->recipients as $recipient) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, "https://rest.nexmo.com/sms/json?".http_build_query(
curl_setopt($curl, CURLOPT_URL, "https://rest.nexmo.com/sms/json?" . http_build_query(
array(
"api_key" => $this->username,
"api_secret" => $this->password,
@ -66,8 +68,7 @@ class Nexmo extends Core {
"to" => $recipient,
"text" => $message,
)
)
);
));
$result = json_decode(curl_exec($curl), true);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
@ -75,10 +76,10 @@ class Nexmo extends Core {
if ($err != 0 || $httpcode != 200 || $result['messages'][0]['status'] != "0") {
$success = 0;
$error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". \nResult: ".$result['messages'][0]['error-text'];
$error = "HTTP_code: " . $httpcode . ".\ncURL error (" . $err . "): " . curl_strerror($err) .
". \nResult: " . $result['messages'][0]['error-text'];
}
curl_close($curl);
}
if ($success) {

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -30,7 +31,8 @@
namespace psm\Txtmsg;
class Octopush extends Core {
class Octopush extends Core
{
/**
* Send sms using the Octopush API
@ -53,17 +55,18 @@ class Octopush extends Core {
* @return bool|string
*/
public function sendSMS($message) {
public function sendSMS($message)
{
$error = "";
$success = 1;
$smsType = "XXX"; //FR = premium, WWW = world, XXX = Low cost
$recipients = join(',', $this->recipients);
$message = ($smsType == "FR") ? urlencode($message." STOP au XXXX") : urlencode($message);
$message = ($smsType == "FR") ? urlencode($message . " STOP au XXXX") : urlencode($message);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "http://www.octopush-dm.com/api/sms/?".http_build_query(
curl_setopt($curl, CURLOPT_URL, "http://www.octopush-dm.com/api/sms/?" . http_build_query(
array(
"user_login" => $this->username,
"api_key" => $this->password,
@ -72,8 +75,7 @@ class Octopush extends Core {
"sms_sender" => substr($this->originator, 0, 11),
"sms_text" => $message,
)
)
);
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
@ -83,7 +85,9 @@ class Octopush extends Core {
if ($err != 0 || $httpcode != 200 || $xmlResults === false || $xmlResults->error_code != '000') {
$success = 0;
$error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". \nResult: ".$xmlResults->error_code.". Look at http://www.octopush-dm.com/en/errors for the error description.";
$error = "HTTP_code: " . $httpcode . ".\ncURL error (" . $err . "): " . curl_strerror($err) .
". \nResult: " . $xmlResults->error_code .
". Look at http://www.octopush-dm.com/en/errors for the error description.";
}
curl_close($curl);

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -29,7 +30,8 @@
namespace psm\Txtmsg;
class Plivo extends Core {
class Plivo extends Core
{
/**
* Send sms using the Plivo API
@ -48,7 +50,8 @@ class Plivo extends Core {
* @return bool|string
*/
public function sendSMS($message) {
public function sendSMS($message)
{
$error = "";
$success = 1;
@ -60,7 +63,7 @@ class Plivo extends Core {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.plivo.com/v1/Account/".$this->username."/Message/",
CURLOPT_URL => "https://api.plivo.com/v1/Account/" . $this->username . "/Message/",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
@ -75,7 +78,7 @@ class Plivo extends Core {
)
),
CURLOPT_HTTPHEADER => array(
"authorization: Basic ".base64_encode($this->username.":".$this->password),
"authorization: Basic " . base64_encode($this->username . ":" . $this->password),
"content-type: application/json"
),
));
@ -86,7 +89,8 @@ class Plivo extends Core {
if ($err != 0 || ($httpcode != '200' && $httpcode != '201' && $httpcode != '202')) {
$success = 0;
$error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". Result: ".$result."";
$error = "HTTP_code: " . $httpcode . ".\ncURL error (" . $err . "): " .
curl_strerror($err) . ". Result: " . $result . "";
}
curl_close($curl);

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -28,7 +29,8 @@
namespace psm\Txtmsg;
class Smsglobal extends Core {
class Smsglobal extends Core
{
/**
* Send sms using the Smsglobal API
@ -49,7 +51,8 @@ class Smsglobal extends Core {
* @return bool|string
*/
public function sendSMS($message) {
public function sendSMS($message)
{
$error = "";
$success = 1;
@ -61,7 +64,7 @@ class Smsglobal extends Core {
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_URL, "https://www.smsglobal.com/http-api.php?".http_build_query(
curl_setopt($curl, CURLOPT_URL, "https://www.smsglobal.com/http-api.php?" . http_build_query(
array(
"action" => "sendsms",
"user" => $this->username,
@ -81,7 +84,8 @@ class Smsglobal extends Core {
if ($err != 0 || substr($result, 0, 5) != "OK: 0") {
$success = 0;
$result = ($result == '') ? 'Wrong input, please check if all values are correct!' : $result;
$error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". \nResult: ".$result;
$error = "HTTP_code: " . $httpcode . ".\ncURL error (" . $err . "): " .
curl_strerror($err) . ". \nResult: " . $result;
}
curl_close($curl);

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -29,7 +30,8 @@
namespace psm\Txtmsg;
class Smsgw extends Core {
class Smsgw extends Core
{
/**
* Send sms using the SMSgw.NET API
@ -48,7 +50,8 @@ class Smsgw extends Core {
* @return bool|string
*/
public function sendSMS($message) {
public function sendSMS($message)
{
$error = "";
$success = 1;
@ -78,7 +81,8 @@ class Smsgw extends Core {
if ($err != 0 || ($httpcode != '200' && $httpcode != '201' && $httpcode != '202' && $result != "1")) {
$success = 0;
$error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". Result: ".$result."";
$error = "HTTP_code: " . $httpcode . ".\ncURL error (" . $err . "): " .
curl_strerror($err) . ". Result: " . $result . "";
}
curl_close($curl);

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -28,7 +29,8 @@
namespace psm\Txtmsg;
class Smsit extends Core {
class Smsit extends Core
{
/**
* Send sms using the Smsit API
@ -49,23 +51,22 @@ class Smsit extends Core {
* @return bool|string
*/
public function sendSMS($message) {
public function sendSMS($message)
{
$success = 1;
$error = "";
foreach ($this->recipients as $recipient) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, "https://www.smsit.dk/api/v2?".http_build_query(
curl_setopt($curl, CURLOPT_URL, "https://www.smsit.dk/api/v2?" . http_build_query(
array(
"apiKey" => $this->password,
"mobile" => $recipient,
"message" => urlencode($message),
"senderId" => substr($this->originator, 0, 11),
)
)
);
));
$result = curl_exec($curl);
$err = curl_errno($curl);

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -29,7 +30,8 @@
namespace psm\Txtmsg;
class SolutionsInfini extends Core {
class SolutionsInfini extends Core
{
/**
* Send sms using the SolutionsInfini API
@ -49,7 +51,8 @@ class SolutionsInfini extends Core {
* @return bool|string
*/
public function sendSMS($message) {
public function sendSMS($message)
{
$error = "";
$success = 1;
@ -58,7 +61,7 @@ class SolutionsInfini extends Core {
$recipients = join(',', $this->recipients);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://api-alerts.solutionsinfini.com/v4/?".http_build_query(
curl_setopt($curl, CURLOPT_URL, "https://api-alerts.solutionsinfini.com/v4/?" . http_build_query(
array(
"api_key" => $this->password,
"method" => "sms",
@ -66,8 +69,7 @@ class SolutionsInfini extends Core {
"sender" => substr($this->originator, 0, 11),
"message" => $message,
)
)
);
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
@ -77,7 +79,8 @@ class SolutionsInfini extends Core {
if ($err != 0 || $httpcode != 200 || $result['status'] != "OK") {
$success = 0;
$error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". Result: ".$result['status']." - ".$result['message'].".";
$error = "HTTP_code: " . $httpcode . ".\ncURL error (" . $err . "): " .
curl_strerror($err) . ". Result: " . $result['status'] . " - " . $result['message'] . ".";
}
curl_close($curl);
if ($success) {

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -27,7 +28,8 @@
namespace psm\Txtmsg;
class Spryng extends Core {
class Spryng extends Core
{
/**
* Send sms using the Spryngsms API
@ -45,11 +47,21 @@ class Spryng extends Core {
* @return bool|string
*/
public function sendSMS($message) {
public function sendSMS($message)
{
$recipients = implode(",", $this->recipients);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.spryngsms.com/api/send.php?OPERATION=send&USERNAME=".urlencode($this->username)."&PASSWORD=".urlencode($this->password)."&DESTINATION=".urlencode($recipients)."&SENDER=".urlencode($this->originator)."&BODY=".urlencode($message)."&SMSTYPE=BUSINESS");
curl_setopt(
$ch,
CURLOPT_URL,
"https://api.spryngsms.com/api/send.php?OPERATION=send&USERNAME=" .
urlencode($this->username) .
"&PASSWORD=" . urlencode($this->password) .
"&DESTINATION=" . urlencode($recipients) .
"&SENDER=" . urlencode($this->originator) .
"&BODY=" . urlencode($message) . "&SMSTYPE=BUSINESS"
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$headers = array();
$headers[] = "Content-Type: application/x-www-form-urlencoded";
@ -59,7 +71,7 @@ class Spryng extends Core {
// Check on error
if ($result != 1) {
return "Error ".$result.": see http://www.spryng.nl/en/developers/http-api/ for the description.";
return "Error " . $result . ": see http://www.spryng.nl/en/developers/http-api/ for the description.";
}
return 1;
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -29,7 +30,8 @@
namespace psm\Txtmsg;
class Textmarketer extends Core {
class Textmarketer extends Core
{
/**
* Send sms using the Textmarketer API
@ -47,13 +49,21 @@ class Textmarketer extends Core {
* @return bool|string
*/
public function sendSMS($message) {
public function sendSMS($message)
{
$success = 1;
$error = '';
foreach ($this->recipients as $recipient) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.textmarketer.co.uk/gateway/?username=".$this->username."&password=".$this->password."&to=".$recipient."&message=".urlencode($message)."&orig=SERVERALERT");
curl_setopt(
$ch,
CURLOPT_URL,
"https://api.textmarketer.co.uk/gateway/?username=" . $this->username .
"&password=" . $this->password .
"&to=" . $recipient .
"&message=" . urlencode($message) .
"&orig=SERVERALERT"
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$headers = array();
$headers[] = "Content-Type: application/x-www-form-urlencoded";

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -27,7 +28,8 @@
namespace psm\Txtmsg;
class Twilio extends Core {
class Twilio extends Core
{
/**
* Send sms using the Twilio API
@ -47,17 +49,28 @@ class Twilio extends Core {
* @return bool|string
*/
public function sendSMS($message) {
public function sendSMS($message)
{
$success = 1;
$error = '';
foreach ($this->recipients as $recipient) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.twilio.com/2010-04-01/Accounts/".$this->username."/Messages.json");
curl_setopt(
$ch,
CURLOPT_URL,
"https://api.twilio.com/2010-04-01/Accounts/" . $this->username . "/Messages.json"
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "From=".urlencode($this->originator)."&Body=".urlencode($message)."&To=".urlencode($recipient));
curl_setopt(
$ch,
CURLOPT_POSTFIELDS,
"From=" . urlencode($this->originator) .
"&Body=" . urlencode($message) .
"&To=" . urlencode($recipient)
);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, $this->username.":".$this->password);
curl_setopt($ch, CURLOPT_USERPWD, $this->username . ":" . $this->password);
$headers = array();
$headers[] = "Content-Type: application/x-www-form-urlencoded";

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -27,11 +28,11 @@
namespace psm\Txtmsg;
interface TxtmsgInterface {
interface TxtmsgInterface
{
public function setLogin($username, $password);
public function setOriginator($originator);
public function addRecipients($recipient);
public function sendSMS($message);
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -33,7 +34,8 @@ namespace psm\Util\Install;
*
* Executes the queries to install/upgrade phpservermon.
*/
class Installer {
class Installer
{
/**
* Database service
@ -58,7 +60,8 @@ class Installer {
* @param \psm\Service\Database $db
* @param callable $logger
*/
function __construct(\psm\Service\Database $db, $logger = null) {
public function __construct(\psm\Service\Database $db, $logger = null)
{
$this->db = $db;
$this->logger = $logger;
}
@ -68,7 +71,8 @@ class Installer {
* @return boolean
* @see upgrade()
*/
public function isUpgradeRequired() {
public function isUpgradeRequired()
{
$version_db = psm_get_conf('version');
if (version_compare(PSM_VERSION, $version_db, '==')) {
@ -91,7 +95,8 @@ class Installer {
* @param string|array $msg
* @return \psm\Util\Install\Installer
*/
protected function log($msg) {
protected function log($msg)
{
if (is_callable($this->logger)) {
$msg = (!is_array($msg)) ? array($msg) : $msg;
@ -107,7 +112,8 @@ class Installer {
* @param string|array $query
* @return \psm\Util\Install\Installer
*/
protected function execSQL($query) {
protected function execSQL($query)
{
$query = (!is_array($query)) ? array($query) : $query;
foreach ($query as $q) {
@ -120,14 +126,21 @@ class Installer {
/**
* Retrieve table queries for install
*/
public function install() {
public function install()
{
$this->installTables();
$this->log('Populating database...');
$queries = array();
$queries[] = "INSERT INTO `".PSM_DB_PREFIX."servers` (`ip`, `port`, `label`, `type`, `pattern`, `pattern_online`, `redirect_check`, `status`, `rtime`, `active`, `email`, `sms`, `pushover`, `telegram`) VALUES ('http://sourceforge.net/index.php', 80, 'SourceForge', 'website', '', 'yes', 'bad', 'on', '0.0000000', 'yes', 'yes', 'yes', 'yes', 'yes'), ('smtp.gmail.com', 465, 'Gmail SMTP', 'service', '', 'yes', 'bad','on', '0.0000000', 'yes', 'yes', 'yes', 'yes', 'yes')";
$queries[] = "INSERT INTO `".PSM_DB_PREFIX."users_servers` (`user_id`,`server_id`) VALUES (1, 1), (1, 2);";
$queries[] = "INSERT INTO `".PSM_DB_PREFIX."config` (`key`, `value`) VALUE
$queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "servers` (
`ip`, `port`, `label`, `type`, `pattern`, `pattern_online`, `redirect_check`,
`status`, `rtime`, `active`, `email`, `sms`, `pushover`, `telegram`)
VALUES ('http://sourceforge.net/index.php', 80, 'SourceForge', 'website', '',
'yes', 'bad', 'on', '0.0000000', 'yes', 'yes', 'yes', 'yes', 'yes'),
('smtp.gmail.com', 465, 'Gmail SMTP', 'service', '',
'yes', 'bad','on', '0.0000000', 'yes', 'yes', 'yes', 'yes', 'yes')";
$queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "users_servers` (`user_id`,`server_id`) VALUES (1, 1), (1, 2);";
$queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`) VALUE
('language', 'en_US'),
('proxy', '0'),
('proxy_url', ''),
@ -151,7 +164,7 @@ class Installer {
('pushover_api_token', ''),
('telegram_status', '0'),
('telegram_api_token', ''),
('password_encrypt_key', '".sha1(microtime())."'),
('password_encrypt_key', '" . sha1(microtime()) . "'),
('alert_type', 'status'),
('log_status', '1'),
('log_email', '1'),
@ -159,8 +172,8 @@ class Installer {
('log_pushover', '1'),
('log_telegram', '1'),
('log_retention_period', '365'),
('version', '".PSM_VERSION."'),
('version_update_check', '".PSM_VERSION."'),
('version', '" . PSM_VERSION . "'),
('version_update_check', '" . PSM_VERSION . "'),
('auto_refresh_servers', '0'),
('show_update', '1'),
('last_update_check', '0'),
@ -172,14 +185,15 @@ class Installer {
/**
* Install the tables for the monitor
*/
protected function installTables() {
protected function installTables()
{
$tables = array(
PSM_DB_PREFIX.'config' => "CREATE TABLE `".PSM_DB_PREFIX."config` (
PSM_DB_PREFIX . 'config' => "CREATE TABLE `" . PSM_DB_PREFIX . "config` (
`key` varchar(255) NOT NULL,
`value` varchar(255) NOT NULL,
PRIMARY KEY (`key`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;",
PSM_DB_PREFIX.'users' => "CREATE TABLE IF NOT EXISTS `".PSM_DB_PREFIX."users` (
PSM_DB_PREFIX . 'users' => "CREATE TABLE IF NOT EXISTS `" . PSM_DB_PREFIX . "users` (
`user_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`user_name` varchar(64) NOT NULL COMMENT 'user''s name, unique',
`password` varchar(255) NOT NULL COMMENT 'user''s password in salted and hashed format',
@ -196,18 +210,19 @@ class Installer {
PRIMARY KEY (`user_id`),
UNIQUE KEY `unique_username` (`user_name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;",
PSM_DB_PREFIX.'users_preferences' => "CREATE TABLE IF NOT EXISTS `".PSM_DB_PREFIX."users_preferences` (
PSM_DB_PREFIX .
'users_preferences' => "CREATE TABLE IF NOT EXISTS `" . PSM_DB_PREFIX . "users_preferences` (
`user_id` int(11) unsigned NOT NULL,
`key` varchar(255) NOT NULL,
`value` varchar(255) NOT NULL,
PRIMARY KEY (`user_id`, `key`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;",
PSM_DB_PREFIX.'users_servers' => "CREATE TABLE `".PSM_DB_PREFIX."users_servers` (
PSM_DB_PREFIX . 'users_servers' => "CREATE TABLE `" . PSM_DB_PREFIX . "users_servers` (
`user_id` INT( 11 ) UNSIGNED NOT NULL ,
`server_id` INT( 11 ) UNSIGNED NOT NULL ,
PRIMARY KEY ( `user_id` , `server_id` )
) ENGINE = MyISAM DEFAULT CHARSET=utf8;",
PSM_DB_PREFIX.'log' => "CREATE TABLE `".PSM_DB_PREFIX."log` (
PSM_DB_PREFIX . 'log' => "CREATE TABLE `" . PSM_DB_PREFIX . "log` (
`log_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`server_id` int(11) unsigned NOT NULL,
`type` enum('status','email','sms','pushover','telegram') NOT NULL,
@ -215,12 +230,12 @@ class Installer {
`datetime` timestamp NOT NULL default CURRENT_TIMESTAMP,
PRIMARY KEY (`log_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;",
PSM_DB_PREFIX.'log_users' => "CREATE TABLE `".PSM_DB_PREFIX."log_users` (
PSM_DB_PREFIX . 'log_users' => "CREATE TABLE `" . PSM_DB_PREFIX . "log_users` (
`log_id` int(11) UNSIGNED NOT NULL ,
`user_id` int(11) UNSIGNED NOT NULL ,
PRIMARY KEY (`log_id`, `user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;",
PSM_DB_PREFIX.'servers' => "CREATE TABLE `".PSM_DB_PREFIX."servers` (
PSM_DB_PREFIX . 'servers' => "CREATE TABLE `" . PSM_DB_PREFIX . "servers` (
`server_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`ip` varchar(500) NOT NULL,
`port` int(5) NOT NULL,
@ -256,7 +271,7 @@ class Installer {
`last_output` TEXT,
PRIMARY KEY (`server_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;",
PSM_DB_PREFIX.'servers_uptime' => "CREATE TABLE IF NOT EXISTS `".PSM_DB_PREFIX."servers_uptime` (
PSM_DB_PREFIX . 'servers_uptime' => "CREATE TABLE IF NOT EXISTS `" . PSM_DB_PREFIX . "servers_uptime` (
`servers_uptime_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`server_id` int(11) unsigned NOT NULL,
`date` datetime NOT NULL,
@ -265,7 +280,7 @@ class Installer {
PRIMARY KEY (`servers_uptime_id`),
KEY `server_id` (`server_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;",
PSM_DB_PREFIX.'servers_history' => "CREATE TABLE IF NOT EXISTS `".PSM_DB_PREFIX."servers_history` (
PSM_DB_PREFIX . 'servers_history' => "CREATE TABLE IF NOT EXISTS `" . PSM_DB_PREFIX . "servers_history` (
`servers_history_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`server_id` int(11) unsigned NOT NULL,
`date` date NOT NULL,
@ -283,10 +298,10 @@ class Installer {
$if_table_exists = $this->db->query("SHOW TABLES LIKE '{$name}'");
if (!empty($if_table_exists)) {
$this->log('Table '.$name.' already exists in your database!');
$this->log('Table ' . $name . ' already exists in your database!');
} else {
$this->execSQL($sql);
$this->log('Table '.$name.' added.');
$this->log('Table ' . $name . ' added.');
}
}
}
@ -297,7 +312,8 @@ class Installer {
* @param string $version_to
* @see isUpgradeRequired()
*/
public function upgrade($version_from, $version_to) {
public function upgrade($version_from, $version_to)
{
if (version_compare($version_from, '2.1.0', '<')) {
$this->upgrade210();
}
@ -331,21 +347,23 @@ class Installer {
/**
* Upgrade for v2.1.0 release
*/
protected function upgrade210() {
protected function upgrade210()
{
$queries = array();
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."config` DROP `config_id`;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."config` ADD PRIMARY KEY ( `key` );";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."config` DROP INDEX `key`;";
$queries[] = "INSERT INTO `".PSM_DB_PREFIX."config` (`key`, `value`) VALUES ('cron_running', '0');";
$queries[] = "INSERT INTO `".PSM_DB_PREFIX."config` (`key`, `value`) VALUES ('cron_running_time', '0');";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "config` DROP `config_id`;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "config` ADD PRIMARY KEY ( `key` );";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "config` DROP INDEX `key`;";
$queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`) VALUES ('cron_running', '0');";
$queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`) VALUES ('cron_running_time', '0');";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` CHANGE `error` `error` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` CHANGE `rtime` `rtime` FLOAT( 9, 7 ) NULL;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` CHANGE `last_online` `last_online` DATETIME NULL;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` CHANGE `last_check` `last_check` DATETIME NULL;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `pattern` VARCHAR( 255 ) NOT NULL AFTER `type`;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `last_offline` DATETIME NULL;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `last_offline_duration` varchar(255) NULL;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` CHANGE `error` `error` VARCHAR( 255 )
CHARACTER SET utf8 COLLATE utf8_general_ci NULL;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` CHANGE `rtime` `rtime` FLOAT( 9, 7 ) NULL;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` CHANGE `last_online` `last_online` DATETIME NULL;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` CHANGE `last_check` `last_check` DATETIME NULL;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `pattern` VARCHAR( 255 ) NOT NULL AFTER `type`;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `last_offline` DATETIME NULL;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `last_offline_duration` varchar(255) NULL;";
$this->execSQL($queries);
}
@ -353,46 +371,66 @@ class Installer {
/**
* Upgrade for v3.0.0 release
*/
protected function upgrade300() {
protected function upgrade300()
{
$queries = array();
// language is now stored as language code (ISO 639-1) + country code (ISO 3166-1)
$queries[] = "UPDATE `".PSM_DB_PREFIX."config` SET `value`='bg_BG' WHERE `key`='language' AND `value`='bg';";
$queries[] = "UPDATE `".PSM_DB_PREFIX."config` SET `value`='de_DE' WHERE `key`='language' AND `value`='de';";
$queries[] = "UPDATE `".PSM_DB_PREFIX."config` SET `value`='en_US' WHERE `key`='language' AND `value`='en';";
$queries[] = "UPDATE `".PSM_DB_PREFIX."config` SET `value`='fr_FR' WHERE `key`='language' AND `value`='fr';";
$queries[] = "UPDATE `".PSM_DB_PREFIX."config` SET `value`='ko_KR' WHERE `key`='language' AND `value`='kr';";
$queries[] = "UPDATE `".PSM_DB_PREFIX."config` SET `value`='nl_NL' WHERE `key`='language' AND `value`='nl';";
$queries[] = "UPDATE `".PSM_DB_PREFIX."config` SET `value`='pt_BR' WHERE `key`='language' AND `value`='br';";
$queries[] = "UPDATE `" . PSM_DB_PREFIX . "config` SET `value`='bg_BG'
WHERE `key`='language' AND `value`='bg';";
$queries[] = "UPDATE `" . PSM_DB_PREFIX . "config` SET `value`='de_DE'
WHERE `key`='language' AND `value`='de';";
$queries[] = "UPDATE `" . PSM_DB_PREFIX . "config` SET `value`='en_US'
WHERE `key`='language' AND `value`='en';";
$queries[] = "UPDATE `" . PSM_DB_PREFIX . "config` SET `value`='fr_FR'
WHERE `key`='language' AND `value`='fr';";
$queries[] = "UPDATE `" . PSM_DB_PREFIX . "config` SET `value`='ko_KR'
WHERE `key`='language' AND `value`='kr';";
$queries[] = "UPDATE `" . PSM_DB_PREFIX . "config` SET `value`='nl_NL'
WHERE `key`='language' AND `value`='nl';";
$queries[] = "UPDATE `" . PSM_DB_PREFIX . "config` SET `value`='pt_BR'
WHERE `key`='language' AND `value`='br';";
$queries[] = "INSERT INTO `".PSM_DB_PREFIX."config` (`key`, `value`) VALUES ('version_update_check', '".PSM_VERSION."');";
$queries[] = "INSERT INTO `".PSM_DB_PREFIX."config` (`key`, `value`) VALUES ('email_smtp', '');";
$queries[] = "INSERT INTO `".PSM_DB_PREFIX."config` (`key`, `value`) VALUES ('email_smtp_host', '');";
$queries[] = "INSERT INTO `".PSM_DB_PREFIX."config` (`key`, `value`) VALUES ('email_smtp_port', '');";
$queries[] = "INSERT INTO `".PSM_DB_PREFIX."config` (`key`, `value`) VALUES ('email_smtp_username', '');";
$queries[] = "INSERT INTO `".PSM_DB_PREFIX."config` (`key`, `value`) VALUES ('email_smtp_password', '');";
$queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`) VALUES
('version_update_check', '" . PSM_VERSION . "');";
$queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`) VALUES ('email_smtp', '');";
$queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`) VALUES ('email_smtp_host', '');";
$queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`) VALUES ('email_smtp_port', '');";
$queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`) VALUES ('email_smtp_username', '');";
$queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`) VALUES ('email_smtp_password', '');";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."log` CHANGE `log_id` `log_id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."log` CHANGE `server_id` `server_id` INT( 11 ) UNSIGNED NOT NULL;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "log` CHANGE `log_id` `log_id` INT( 11 )
UNSIGNED NOT NULL AUTO_INCREMENT;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "log` CHANGE `server_id` `server_id` INT( 11 )
UNSIGNED NOT NULL;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` CHANGE `server_id` `server_id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `warning_threshold` MEDIUMINT( 1 ) UNSIGNED NOT NULL DEFAULT '1';";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `warning_threshold_counter` MEDIUMINT( 1 ) UNSIGNED NOT NULL DEFAULT '0';";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `last_offline` DATETIME NULL;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `last_offline_duration` varchar(255) NULL;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` CHANGE `server_id` `server_id` INT( 11 )
UNSIGNED NOT NULL AUTO_INCREMENT;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `warning_threshold` MEDIUMINT( 1 )
UNSIGNED NOT NULL DEFAULT '1';";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `warning_threshold_counter` MEDIUMINT( 1 )
UNSIGNED NOT NULL DEFAULT '0';";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `last_offline` DATETIME NULL;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `last_offline_duration` varchar(255) NULL;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."users` CHANGE `user_id` `user_id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."users`
ADD `user_name` varchar(64) COLLATE utf8_general_ci NOT NULL COMMENT 'user\'s name, unique' AFTER `user_id`,
ADD `password` varchar(255) COLLATE utf8_general_ci NOT NULL COMMENT 'user\'s password in salted and hashed format' AFTER `user_name`,
ADD `password_reset_hash` char(40) COLLATE utf8_general_ci DEFAULT NULL COMMENT 'user\'s password reset code' AFTER `password`,
ADD `password_reset_timestamp` bigint(20) DEFAULT NULL COMMENT 'timestamp of the password reset request' AFTER `password_reset_hash`,
ADD `rememberme_token` varchar(64) COLLATE utf8_general_ci DEFAULT NULL COMMENT 'user\'s remember-me cookie token' AFTER `password_reset_timestamp`,
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "users` CHANGE `user_id` `user_id` INT( 11 )
UNSIGNED NOT NULL AUTO_INCREMENT;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "users`
ADD `user_name` varchar(64) COLLATE utf8_general_ci NOT NULL
COMMENT 'user\'s name, unique' AFTER `user_id`,
ADD `password` varchar(255) COLLATE utf8_general_ci NOT NULL
COMMENT 'user\'s password in salted and hashed format' AFTER `user_name`,
ADD `password_reset_hash` char(40) COLLATE utf8_general_ci DEFAULT NULL
COMMENT 'user\'s password reset code' AFTER `password`,
ADD `password_reset_timestamp` bigint(20) DEFAULT NULL
COMMENT 'timestamp of the password reset request' AFTER `password_reset_hash`,
ADD `rememberme_token` varchar(64) COLLATE utf8_general_ci DEFAULT NULL
COMMENT 'user\'s remember-me cookie token' AFTER `password_reset_timestamp`,
ADD `level` TINYINT( 2 ) UNSIGNED NOT NULL DEFAULT '20' AFTER `rememberme_token`;";
// make sure all current users are admins (previously we didnt have non-admins):
$queries[] = "UPDATE `".PSM_DB_PREFIX."users` SET `user_name`=`email`, `level`=10;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."users` ADD UNIQUE `unique_username` ( `user_name` );";
$queries[] = "UPDATE `" . PSM_DB_PREFIX . "users` SET `user_name`=`email`, `level`=10;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "users` ADD UNIQUE `unique_username` ( `user_name` );";
$queries[] = "CREATE TABLE IF NOT EXISTS `".PSM_DB_PREFIX."servers_uptime` (
$queries[] = "CREATE TABLE IF NOT EXISTS `" . PSM_DB_PREFIX . "servers_uptime` (
`servers_uptime_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`server_id` int(11) unsigned NOT NULL,
`date` datetime NOT NULL,
@ -402,7 +440,7 @@ class Installer {
KEY `server_id` (`server_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
$queries[] = "CREATE TABLE IF NOT EXISTS `".PSM_DB_PREFIX."servers_history` (
$queries[] = "CREATE TABLE IF NOT EXISTS `" . PSM_DB_PREFIX . "servers_history` (
`servers_history_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`server_id` int(11) unsigned NOT NULL,
`date` date NOT NULL,
@ -415,7 +453,7 @@ class Installer {
UNIQUE KEY `server_id_date` (`server_id`,`date`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
$queries[] = "CREATE TABLE `".PSM_DB_PREFIX."users_servers` (
$queries[] = "CREATE TABLE `" . PSM_DB_PREFIX . "users_servers` (
`user_id` INT( 11 ) UNSIGNED NOT NULL ,
`server_id` INT( 11 ) UNSIGNED NOT NULL ,
PRIMARY KEY ( `user_id` , `server_id` )
@ -423,7 +461,7 @@ class Installer {
$this->execSQL($queries);
// from 3.0 all user-server relations are in a separate table
$users = $this->db->select(PSM_DB_PREFIX.'users', null, array('user_id', 'server_id'));
$users = $this->db->select(PSM_DB_PREFIX . 'users', null, array('user_id', 'server_id'));
foreach ($users as $user) {
$idc = array();
if ($user['server_id'] == '') {
@ -435,36 +473,42 @@ class Installer {
$idc = explode(',', $user['server_id']);
}
foreach ($idc as $id) {
$this->db->save(PSM_DB_PREFIX.'users_servers', array(
$this->db->save(PSM_DB_PREFIX . 'users_servers', array(
'user_id' => $user['user_id'],
'server_id' => $id,
));
}
}
$this->execSQL("ALTER TABLE `".PSM_DB_PREFIX."users` DROP `server_id`;");
$this->execSQL("ALTER TABLE `" . PSM_DB_PREFIX . "users` DROP `server_id`;");
}
/**
* Upgrade for v3.1.0 release
*/
protected function upgrade310() {
protected function upgrade310()
{
$queries = array();
psm_update_conf('log_retention_period', '365');
psm_update_conf('pushover_status', 0);
psm_update_conf('log_pushover', 1);
psm_update_conf('pushover_api_token', '');
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."users` ADD `pushover_key` VARCHAR( 255 ) NOT NULL AFTER `mobile`;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."users` ADD `pushover_device` VARCHAR( 255 ) NOT NULL AFTER `pushover_key`;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "users` ADD `pushover_key` VARCHAR( 255 )
NOT NULL AFTER `mobile`;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "users` ADD `pushover_device` VARCHAR( 255 )
NOT NULL AFTER `pushover_key`;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `pushover` ENUM( 'yes','no' ) NOT NULL DEFAULT 'yes' AFTER `sms`;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."log` CHANGE `type` `type` ENUM( 'status', 'email', 'sms', 'pushover' ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `pushover` ENUM( 'yes','no' )
NOT NULL DEFAULT 'yes' AFTER `sms`;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX .
"log` CHANGE `type` `type` ENUM( 'status', 'email', 'sms', 'pushover' )
CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `timeout` smallint(1) unsigned NULL DEFAULT NULL;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `last_offline` DATETIME NULL;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `last_offline_duration` varchar(255) NULL;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `timeout` smallint(1) unsigned NULL DEFAULT NULL;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `last_offline` DATETIME NULL;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `last_offline_duration` varchar(255) NULL;";
$queries[] = "CREATE TABLE IF NOT EXISTS `".PSM_DB_PREFIX."users_preferences` (
$queries[] = "CREATE TABLE IF NOT EXISTS `" . PSM_DB_PREFIX . "users_preferences` (
`user_id` int(11) unsigned NOT NULL,
`key` varchar(255) NOT NULL,
`value` varchar(255) NOT NULL,
@ -477,13 +521,15 @@ class Installer {
/**
* Upgrade for v3.2.0 release
*/
protected function upgrade320() {
protected function upgrade320()
{
$queries = array();
psm_update_conf('password_encrypt_key', sha1(microtime()));
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` CHANGE `ip` `ip` VARCHAR(500) NOT NULL;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `website_username` varchar(255) NULL, ADD `website_password` varchar(255) NULL AFTER `website_username`;";
$queries[] = "INSERT INTO `".PSM_DB_PREFIX."config` (`key`, `value`) VALUE
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` CHANGE `ip` `ip` VARCHAR(500) NOT NULL;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `website_username` varchar(255) NULL,
ADD `website_password` varchar(255) NULL AFTER `website_username`;";
$queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`) VALUE
('proxy', '0'),
('proxy_url', ''),
('proxy_user', ''),
@ -492,14 +538,14 @@ class Installer {
$this->execSQL($queries);
// Create log_users table
$this->execSQL("CREATE TABLE `".PSM_DB_PREFIX."log_users` (
$this->execSQL("CREATE TABLE `" . PSM_DB_PREFIX . "log_users` (
`log_id` int(11) UNSIGNED NOT NULL ,
`user_id` int(11) UNSIGNED NOT NULL ,
PRIMARY KEY (`log_id`, `user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;");
// Migrate the data
$logs = $this->db->select(PSM_DB_PREFIX.'log', null, array('log_id', 'user_id'));
$logs = $this->db->select(PSM_DB_PREFIX . 'log', null, array('log_id', 'user_id'));
foreach ($logs as $log) {
// Validation
if (empty($log['user_id']) || trim($log['user_id']) == '') {
@ -513,27 +559,34 @@ class Installer {
}
// Drop old user_id('s) column
$this->execSQL("ALTER TABLE `".PSM_DB_PREFIX."log` DROP COLUMN `user_id`;");
$this->execSQL("ALTER TABLE `" . PSM_DB_PREFIX . "log` DROP COLUMN `user_id`;");
}
/**
* Upgrade for v3.2.1 release
*/
protected function upgrade321() {
protected function upgrade321()
{
$queries = array();
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD COLUMN `header_name` VARCHAR(255) AFTER `pattern`, ADD COLUMN `header_value` VARCHAR(255) AFTER `header_name`";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD COLUMN `header_name` VARCHAR(255) AFTER `pattern`,
ADD COLUMN `header_value` VARCHAR(255) AFTER `header_name`";
$this->execSQL($queries);
}
/**
* Upgrade for v3.2.2 release
*/
protected function upgrade322() {
protected function upgrade322()
{
$queries = array();
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."users` ADD `telegram_id` VARCHAR( 255 ) NOT NULL AFTER `pushover_device`;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `telegram` ENUM( 'yes','no' ) NOT NULL DEFAULT 'yes' AFTER `pushover`;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."log` CHANGE `type` `type` ENUM( 'status', 'email', 'sms', 'pushover', 'telegram' ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;";
$queries[] = "INSERT INTO `".PSM_DB_PREFIX."config` (`key`, `value`) VALUE
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "users` ADD `telegram_id` VARCHAR( 255 )
NOT NULL AFTER `pushover_device`;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `telegram` ENUM( 'yes','no' )
NOT NULL DEFAULT 'yes' AFTER `pushover`;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX .
"log` CHANGE `type` `type` ENUM( 'status', 'email', 'sms', 'pushover', 'telegram' )
CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;";
$queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`) VALUE
('telegram_status', '0'),
('log_telegram', '1'),
('telegram_api_token', '');";
@ -543,10 +596,13 @@ class Installer {
/**
* Upgrade for v3.3.0 release
*/
protected function upgrade330() {
protected function upgrade330()
{
$queries = array();
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD COLUMN `last_offline` DATETIME NULL AFTER `last_online`, ADD COLUMN `last_offline_duration` varchar(255) NULL AFTER `last_offline`;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `pattern_online` ENUM( 'yes','no' ) NOT NULL DEFAULT 'yes' AFTER `pattern`;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD COLUMN `last_offline` DATETIME
NULL AFTER `last_online`, ADD COLUMN `last_offline_duration` varchar(255) NULL AFTER `last_offline`;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `pattern_online` ENUM( 'yes','no' )
NOT NULL DEFAULT 'yes' AFTER `pattern`;";
$this->execSQL($queries);
if (psm_get_conf('sms_gateway') == 'mollie') {
psm_update_conf('sms_gateway', 'messagebird');
@ -556,23 +612,34 @@ class Installer {
/**
* Upgrade for v3.4.0 release
*/
protected function upgrade340() {
protected function upgrade340()
{
$queries = array();
/**
* Redirect_check is first set to default ok.
* If you have a lot of server that are redirecting,
* this will make sure you're servers stay online.
*/
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD COLUMN `allow_http_status` VARCHAR(255) NOT NULL DEFAULT '' AFTER `pattern_online`;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `redirect_check` ENUM( 'ok','bad' ) NOT NULL DEFAULT 'ok' AFTER `allow_http_status`;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` CHANGE `redirect_check` `redirect_check` ENUM('ok','bad') NOT NULL DEFAULT 'bad';";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD COLUMN `last_error` VARCHAR(255) NULL AFTER `website_password`;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD COLUMN `last_error_output` TEXT AFTER `last_error`;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD COLUMN `last_output` TEXT AFTER `last_error_output`;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD COLUMN `request_method` varchar(50) NULL AFTER `port`;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD COLUMN `post_field` varchar(255) NULL AFTER `pattern_online`;";
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."log` CHANGE `message` `message` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;";
$queries[] = "INSERT INTO `".PSM_DB_PREFIX."config` (`key`, `value`) VALUES ('combine_notifications', '1');";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers`
ADD COLUMN `allow_http_status` VARCHAR(255) NOT NULL DEFAULT '' AFTER `pattern_online`;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers`
ADD `redirect_check` ENUM( 'ok','bad' ) NOT NULL DEFAULT 'ok' AFTER `allow_http_status`;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers`
CHANGE `redirect_check` `redirect_check` ENUM('ok','bad') NOT NULL DEFAULT 'bad';";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers`
ADD COLUMN `last_error` VARCHAR(255) NULL AFTER `website_password`;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers`
ADD COLUMN `last_error_output` TEXT AFTER `last_error`;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers`
ADD COLUMN `last_output` TEXT AFTER `last_error_output`;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers`
ADD COLUMN `request_method` varchar(50) NULL AFTER `port`;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers`
ADD COLUMN `post_field` varchar(255) NULL AFTER `pattern_online`;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "log`
CHANGE `message` `message` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;";
$queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`)
VALUES ('combine_notifications', '1');";
$this->execSQL($queries);
$this->log('Combined notifications enabled. Check out the config page for more info.');
}
@ -582,9 +649,10 @@ class Installer {
* Version_compare was forgotten in v3.4.1 and query failed.
* Fixed in v3.4.2, 3.4.1 has been removed.
*/
protected function upgrade342() {
protected function upgrade342()
{
$queries = array();
$queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` CHANGE `last_output` `last_output` TEXT;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` CHANGE `last_output` `last_output` TEXT;";
$this->execSQL($queries);
}
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -28,11 +29,12 @@
namespace psm\Util\Module;
class Modal implements ModalInterface {
class Modal implements ModalInterface
{
const MODAL_TYPE_OK = 0;
const MODAL_TYPE_OKCANCEL = 1;
const MODAL_TYPE_DANGER = 2;
public const MODAL_TYPE_OK = 0;
public const MODAL_TYPE_OKCANCEL = 1;
public const MODAL_TYPE_DANGER = 2;
/**
* prefix used for modal dialog box elements
@ -69,7 +71,8 @@ class Modal implements ModalInterface {
*/
protected $twig;
public function __construct(\Twig_Environment $twig, $modal_id = 'main', $type = self::MODAL_TYPE_OK) {
public function __construct(\Twig_Environment $twig, $modal_id = 'main', $type = self::MODAL_TYPE_OK)
{
$this->modal_id = $modal_id;
$this->twig = $twig;
$this->type = $type;
@ -79,7 +82,8 @@ class Modal implements ModalInterface {
* get the modal dialog box element prefix
* @return string
*/
public function getModalID() {
public function getModalID()
{
return $this->modal_id;
}
@ -88,7 +92,8 @@ class Modal implements ModalInterface {
* @param int $type
* @return \psm\Util\Module\Modal
*/
public function setType($type) {
public function setType($type)
{
if (in_array($type, array(self::MODAL_TYPE_OK, self::MODAL_TYPE_OKCANCEL, self::MODAL_TYPE_DANGER))) {
$this->type = $type;
}
@ -100,7 +105,8 @@ class Modal implements ModalInterface {
* @param string $title
* @return \psm\Util\Module\Modal
*/
public function setTitle($title) {
public function setTitle($title)
{
$this->title = $title;
return $this;
}
@ -110,17 +116,20 @@ class Modal implements ModalInterface {
* @param string $message
* @return \psm\Util\Module\Modal
*/
public function setMessage($message) {
public function setMessage($message)
{
$this->message = $message;
return $this;
}
public function setOKButtonLabel($label) {
public function setOKButtonLabel($label)
{
$this->ok_label = $label;
return $this;
}
public function createHTML() {
public function createHTML()
{
$has_cancel = ($this->type == self::MODAL_TYPE_OK) ? false : true;
$button_type = ($this->type == self::MODAL_TYPE_DANGER) ? 'danger' : 'primary';
$button_label = empty($this->ok_label) ? psm_get_lang('system', 'ok') : $this->ok_label;
@ -129,7 +138,7 @@ class Modal implements ModalInterface {
$matches = array();
if (preg_match_all('/%(\d)/', $message, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
$message = str_replace($match[0], '<span class="modalP'.$match[1].'"></span>', $message);
$message = str_replace($match[0], '<span class="modalP' . $match[1] . '"></span>', $message);
}
}
@ -141,7 +150,7 @@ class Modal implements ModalInterface {
'has_cancel' => $has_cancel,
'label_cancel' => psm_get_lang('system', 'cancel'),
'modal_button_type' => $button_type,
'modal_button_label'=> $button_label,
'modal_button_label' => $button_label,
));
return $html;

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -28,7 +29,8 @@
namespace psm\Util\Module;
interface ModalInterface {
interface ModalInterface
{
public function __construct(\Twig_Environment $twig);

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -27,7 +28,8 @@
namespace psm\Util\Module;
class Sidebar implements SidebarInterface {
class Sidebar implements SidebarInterface
{
/**
* ID of active item
@ -55,7 +57,8 @@ class Sidebar implements SidebarInterface {
*/
protected $twig;
public function __construct(\Twig_Environment $twig) {
public function __construct(\Twig_Environment $twig)
{
$this->twig = $twig;
}
@ -64,7 +67,8 @@ class Sidebar implements SidebarInterface {
* @param string $id
* @return \psm\Util\Module\Sidebar
*/
public function setActiveItem($id) {
public function setActiveItem($id)
{
$this->active_id = $id;
return $this;
}
@ -74,7 +78,8 @@ class Sidebar implements SidebarInterface {
* @param string $title
* @return \psm\Util\Module\Sidebar
*/
public function setSubtitle($title) {
public function setSubtitle($title)
{
$this->subtitle = $title;
return $this;
}
@ -87,7 +92,8 @@ class Sidebar implements SidebarInterface {
* @param string $icon
* @return \psm\Util\Module\Sidebar
*/
public function addLink($id, $label, $url, $icon = null) {
public function addLink($id, $label, $url, $icon = null)
{
if (!isset($this->items['link'])) {
$this->items['link'] = array();
}
@ -111,7 +117,8 @@ class Sidebar implements SidebarInterface {
* @param boolean $url_is_onclick if you want onclick rather than url, change this to true
* @return \psm\Util\Module\Sidebar
*/
public function addButton($id, $label, $url, $icon = null, $btn_class = 'link', $title = '', $modal_id = null) {
public function addButton($id, $label, $url, $icon = null, $btn_class = 'link', $title = '', $modal_id = null)
{
if (!isset($this->items['button'])) {
$this->items['button'] = array();
}
@ -121,9 +128,9 @@ class Sidebar implements SidebarInterface {
'label' => $label,
'url' => str_replace('"', '\"', $url),
'icon' => $icon,
'btn_class'=> $btn_class,
'title'=> $title,
'modal_id'=> $modal_id
'btn_class' => $btn_class,
'title' => $title,
'modal_id' => $modal_id
);
return $this;
}
@ -137,7 +144,8 @@ class Sidebar implements SidebarInterface {
* @param string $btn_class
* @return \psm\Util\Module\Sidebar
*/
public function addDropdown($id, $label, $options, $icon = null, $btn_class = null) {
public function addDropdown($id, $label, $options, $icon = null, $btn_class = null)
{
if (!isset($this->items['dropdown'])) {
$this->items['dropdown'] = array();
}
@ -151,7 +159,8 @@ class Sidebar implements SidebarInterface {
return $this;
}
public function createHTML() {
public function createHTML()
{
$tpl_data = array(
'subtitle' => $this->subtitle,
);

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -27,10 +28,10 @@
namespace psm\Util\Module;
interface SidebarInterface {
interface SidebarInterface
{
public function __construct(\Twig_Environment $twig);
public function createHTML();
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -31,7 +32,8 @@ namespace psm\Util\Server;
/**
* Makes sure all data of servers is being archived properly or removed if necessary.
*/
class ArchiveManager {
class ArchiveManager
{
/**
* Available archiver utils.
@ -52,7 +54,8 @@ class ArchiveManager {
*/
protected $retention_period;
public function __construct(\psm\Service\Database $db) {
public function __construct(\psm\Service\Database $db)
{
$this->db = $db;
$this->setRetentionPeriod(psm_get_conf('log_retention_period', 365));
@ -66,7 +69,8 @@ class ArchiveManager {
* @param int $server_id
* @return boolean
*/
public function archive($server_id = null) {
public function archive($server_id = null)
{
$result = true;
foreach ($this->archivers as $archiver) {
if (!$archiver->archive($server_id)) {
@ -81,7 +85,8 @@ class ArchiveManager {
* @param int $server_id
* @return boolean
*/
public function cleanup($server_id = null) {
public function cleanup($server_id = null)
{
$result = true;
if (!$this->retention_period) {
// cleanup is disabled
@ -105,14 +110,15 @@ class ArchiveManager {
* @param \DateInterval|int $period \DateInterval object or number of days (int)
* @return \psm\Util\Server\ArchiveManager
*/
public function setRetentionPeriod($period) {
public function setRetentionPeriod($period)
{
if (is_object($period) && $period instanceof \DateInterval) {
$this->retention_period = $period;
} elseif (intval($period) == 0) {
// cleanup disabled
$this->retention_period = false;
} else {
$this->retention_period = new \DateInterval('P'.intval($period).'D');
$this->retention_period = new \DateInterval('P' . intval($period) . 'D');
}
return $this;
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -28,7 +29,8 @@
namespace psm\Util\Server\Archiver;
interface ArchiverInterface {
interface ArchiverInterface
{
/**
* Archive for one or all servers.

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -32,7 +33,8 @@
namespace psm\Util\Server\Archiver;
use psm\Service\Database;
class LogsArchiver implements ArchiverInterface {
class LogsArchiver implements ArchiverInterface
{
/**
* Database service
@ -40,7 +42,8 @@ class LogsArchiver implements ArchiverInterface {
*/
protected $db;
function __construct(Database $db) {
public function __construct(Database $db)
{
$this->db = $db;
}
@ -50,18 +53,20 @@ class LogsArchiver implements ArchiverInterface {
* It stays in the log table until cleaned up.
* @param int $server_id
*/
public function archive($server_id = null) {
public function archive($server_id = null)
{
return true;
}
public function cleanup(\DateTime $retention_date, $server_id = null) {
public function cleanup(\DateTime $retention_date, $server_id = null)
{
$sql_where_server = ($server_id !== null)
// this is obviously not the cleanest way to implement this when using paramter binding.. sorry.
? ' `server_id` = '.intval($server_id).' AND '
? ' `server_id` = ' . intval($server_id) . ' AND '
: '';
$this->db->execute(
"DELETE FROM `".PSM_DB_PREFIX."log` WHERE {$sql_where_server} `datetime` < :latest_date",
"DELETE FROM `" . PSM_DB_PREFIX . "log` WHERE {$sql_where_server} `datetime` < :latest_date",
array('latest_date' => $retention_date->format('Y-m-d 00:00:00')),
false
);
@ -71,9 +76,10 @@ class LogsArchiver implements ArchiverInterface {
/**
* Empty tables log and log_users
*/
public function cleanupall() {
$this->db->delete(PSM_DB_PREFIX."log");
$this->db->delete(PSM_DB_PREFIX."log_users");
public function cleanupall()
{
$this->db->delete(PSM_DB_PREFIX . "log");
$this->db->delete(PSM_DB_PREFIX . "log_users");
return true;
}
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -40,7 +41,8 @@
namespace psm\Util\Server\Archiver;
use psm\Service\Database;
class UptimeArchiver implements ArchiverInterface {
class UptimeArchiver implements ArchiverInterface
{
/**
* Database service
@ -48,7 +50,8 @@ class UptimeArchiver implements ArchiverInterface {
*/
protected $db;
function __construct(Database $db) {
public function __construct(Database $db)
{
$this->db = $db;
}
@ -60,12 +63,14 @@ class UptimeArchiver implements ArchiverInterface {
*
* @param int $server_id
*/
public function archive($server_id = null) {
public function archive($server_id = null)
{
$latest_date = new \DateTime('-1 week 0:0:0');
// Lock tables to prevent simultaneous archiving (by other sessions or the cron job)
try {
$this->db->pdo()->exec('LOCK TABLES '.PSM_DB_PREFIX.'servers_uptime WRITE, '.PSM_DB_PREFIX.'servers_history WRITE');
$this->db->pdo()->exec('LOCK TABLES ' . PSM_DB_PREFIX .
'servers_uptime WRITE, ' . PSM_DB_PREFIX . 'servers_history WRITE');
$locked = true;
} catch (\PDOException $e) {
// user does not have lock rights, ignore
@ -78,9 +83,10 @@ class UptimeArchiver implements ArchiverInterface {
$records = $this->db->execute(
"SELECT `server_id`,`date`,`status`,`latency`
FROM `".PSM_DB_PREFIX."servers_uptime`
FROM `" . PSM_DB_PREFIX . "servers_uptime`
WHERE {$sql_where_server} `date` < :latest_date",
array('latest_date' => $latest_date_str));
array('latest_date' => $latest_date_str)
);
if (!empty($records)) {
// first group all records by day and server_id
@ -103,11 +109,11 @@ class UptimeArchiver implements ArchiverInterface {
}
// Save all
$this->db->insertMultiple(PSM_DB_PREFIX.'servers_history', $histories);
$this->db->insertMultiple(PSM_DB_PREFIX . 'servers_history', $histories);
// now remove all records from the uptime table
$this->db->execute(
"DELETE FROM `".PSM_DB_PREFIX."servers_uptime` WHERE {$sql_where_server} `date` < :latest_date",
"DELETE FROM `" . PSM_DB_PREFIX . "servers_uptime` WHERE {$sql_where_server} `date` < :latest_date",
array('latest_date' => $latest_date_str),
false
);
@ -120,10 +126,11 @@ class UptimeArchiver implements ArchiverInterface {
return true;
}
public function cleanup(\DateTime $retention_date, $server_id = null) {
public function cleanup(\DateTime $retention_date, $server_id = null)
{
$sql_where_server = $this->createSQLWhereServer($server_id);
$this->db->execute(
"DELETE FROM `".PSM_DB_PREFIX."servers_history` WHERE {$sql_where_server} `date` < :latest_date",
"DELETE FROM `" . PSM_DB_PREFIX . "servers_history` WHERE {$sql_where_server} `date` < :latest_date",
array('latest_date' => $retention_date->format('Y-m-d 00:00:00')),
false
);
@ -137,7 +144,8 @@ class UptimeArchiver implements ArchiverInterface {
* @param array $day_records
* @return array
*/
protected function getHistoryForDay($day, $server_id, $day_records) {
protected function getHistoryForDay($day, $server_id, $day_records)
{
$latencies = array();
$checks_failed = 0;
@ -162,10 +170,11 @@ class UptimeArchiver implements ArchiverInterface {
return $history;
}
protected function createSQLWhereServer($server_id) {
protected function createSQLWhereServer($server_id)
{
$sql_where_server = ($server_id !== null)
// this is obviously not the cleanest way to implement this when using paramter binding.. sorry.
? ' `server_id` = '.intval($server_id).' AND '
? ' `server_id` = ' . intval($server_id) . ' AND '
: '';
return $sql_where_server;

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -27,12 +28,14 @@
**/
namespace psm\Util\Server;
use psm\Service\Database;
/**
* History util, create HTML for server graphs
*/
class HistoryGraph {
class HistoryGraph
{
/**
* Database service
@ -46,7 +49,8 @@ class HistoryGraph {
*/
protected $twig;
function __construct(Database $db, \Twig_Environment $twig) {
public function __construct(Database $db, \Twig_Environment $twig)
{
$this->db = $db;
$this->twig = $twig;
}
@ -55,7 +59,8 @@ class HistoryGraph {
* Prepare the HTML for the graph
* @return string
*/
public function createHTML($server_id) {
public function createHTML($server_id)
{
// Archive all records for this server to make sure we have up-to-date stats
$archive = new ArchiveManager($this->db);
$archive->archive($server_id);
@ -100,7 +105,8 @@ class HistoryGraph {
* @param \DateTime $end_time Highest DateTime of the graph
* @return array
*/
public function generateGraphUptime($server_id, $start_time, $end_time) {
public function generateGraphUptime($server_id, $start_time, $end_time)
{
$lines = array(
'latency' => array(),
@ -119,9 +125,22 @@ class HistoryGraph {
$data['unit'] = 'minute';
$data['buttons'] = array();
$data['button_name'] = 'timeframe_short';
$data['buttons'][] = array('unit' => 'minute', 'time' => $hour->getTimestamp()*1000, 'label' => psm_get_lang('servers', 'hour'), 'class_active' => 'active');
$data['buttons'][] = array('unit' => 'hour', 'time' => $day->getTimestamp()*1000, 'label' => psm_get_lang('servers', 'day'));
$data['buttons'][] = array('unit' => 'day', 'time' => $week->getTimestamp()*1000, 'label' => psm_get_lang('servers', 'week'));
$data['buttons'][] = array(
'unit' => 'minute',
'time' => $hour->getTimestamp() * 1000,
'label' => psm_get_lang('servers', 'hour'),
'class_active' => 'active'
);
$data['buttons'][] = array(
'unit' => 'hour',
'time' => $day->getTimestamp() * 1000,
'label' => psm_get_lang('servers', 'day')
);
$data['buttons'][] = array(
'unit' => 'day',
'time' => $week->getTimestamp() * 1000,
'label' => psm_get_lang('servers', 'week')
);
return $data;
}
@ -133,7 +152,8 @@ class HistoryGraph {
* @param \DateTime $end_time Highest DateTime of the graph
* @return array
*/
public function generateGraphHistory($server_id, $start_time, $end_time) {
public function generateGraphHistory($server_id, $start_time, $end_time)
{
$lines = array(
'latency_min' => array(),
'latency_avg' => array(),
@ -153,9 +173,22 @@ class HistoryGraph {
$data['unit'] = 'week';
$data['buttons'] = array();
$data['button_name'] = 'timeframe_long';
$data['buttons'][] = array('unit' => 'day', 'time' => $week->getTimestamp()*1000, 'label' => psm_get_lang('servers', 'week'));
$data['buttons'][] = array('unit' => 'week', 'time' => $month->getTimestamp()*1000, 'label' => psm_get_lang('servers', 'month'), 'class_active' => 'active');
$data['buttons'][] = array('unit' => 'month', 'time' => $year->getTimestamp()*1000, 'label' => psm_get_lang('servers', 'year'));
$data['buttons'][] = array(
'unit' => 'day',
'time' => $week->getTimestamp() * 1000,
'label' => psm_get_lang('servers', 'week')
);
$data['buttons'][] = array(
'unit' => 'week',
'time' => $month->getTimestamp() * 1000,
'label' => psm_get_lang('servers', 'month'),
'class_active' => 'active'
);
$data['buttons'][] = array(
'unit' => 'month',
'time' => $year->getTimestamp() * 1000,
'label' => psm_get_lang('servers', 'year')
);
return $data;
}
@ -168,20 +201,22 @@ class HistoryGraph {
* @param \DateTime $end_time Highest DateTime of the graph
* @return array
*/
protected function getRecords($type, $server_id, $start_time, $end_time) {
protected function getRecords($type, $server_id, $start_time, $end_time)
{
if (!in_array($type, array('history', 'uptime'))) {
return array();
}
$records = $this->db->execute(
"SELECT *
FROM `".PSM_DB_PREFIX."servers_$type`
FROM `" . PSM_DB_PREFIX . "servers_$type`
WHERE `server_id` = :server_id AND `date` BETWEEN :start_time AND :end_time ORDER BY `date` ASC",
array(
'server_id' => $server_id,
'start_time' => $start_time->format('Y-m-d H:i:s'),
'end_time' => $end_time->format('Y-m-d H:i:s'),
));
)
);
return $records;
}
@ -198,7 +233,14 @@ class HistoryGraph {
* @param int $prev_downtime Timestamp from last offline record. 0 when last record is uptime
* @return array
*/
protected function generateGraphLines($records, $lines, $latency_avg_key, $start_time, $end_time, $add_uptime = false) {
protected function generateGraphLines(
$records,
$lines,
$latency_avg_key,
$start_time,
$end_time,
$add_uptime = false
) {
$now = new \DateTime();
$data = array();
@ -219,35 +261,34 @@ class HistoryGraph {
foreach ($lines as $key => $value) {
// add the value for each of the different lines
if (isset($record[$key])) {
if (isset($record['status'])){
if (isset($record['status'])) {
// down
if ($record['status'] == 0){
if ($record['status'] == 0) {
$lines['online'][] = $prev['status']
// Previous datapoint was online
? '{ x: '.($time*1000).', y: '.$prev['latency'].'}'
? '{ x: ' . ($time * 1000) . ', y: ' . $prev['latency'] . '}'
// Previous datapoint was offline
: '{ x: '.($time*1000).', y: null}';
: '{ x: ' . ($time * 1000) . ', y: null}';
// new outage start
$lines['offline'][] = '{ x: '.($time*1000).', y:0.1}';
$lines['offline'][] = '{ x: ' . ($time * 1000) . ', y:0.1}';
$prev_downtime != 0 ?: $prev_downtime = $time;
}
} else {
// up
else {
// outage ends
$lines['offline'][] = $prev['status']
// Previous datapoint was online
? '{ x: '.($time*1000).', y:null}'
? '{ x: ' . ($time * 1000) . ', y:null}'
// Previous datapoint was offline
: '{ x: '.($time*1000).', y:0.1}';
$lines['online'][] = '{ x: '.($time*1000).', y: '.round((float) $record[$key], 4).'}';
: '{ x: ' . ($time * 1000) . ', y:0.1}';
$lines['online'][] = '{ x: ' . ($time * 1000) . ', y: ' .
round((float) $record[$key], 4) . '}';
$prev_downtime == 0 ?: $downtime += ($time - $prev_downtime);
$prev_downtime = 0;
}
}
else {
$lines[$key][] = '{ x: \''.$record['date'].'\', y: '.$record[$key].'}';
} else {
$lines[$key][] = '{ x: \'' . $record['date'] . '\', y: ' . $record[$key] . '}';
}
$prev = $record;
}
@ -255,15 +296,14 @@ class HistoryGraph {
}
// Was down before.
// Record the first and last date as a string in the down array
$prev_downtime == 0 ?: $downtime += ($now->getTimestamp()-$prev_downtime);
$prev_downtime == 0 ?: $downtime += ($now->getTimestamp() - $prev_downtime);
if ($add_uptime) {
$prev['status'] ?: $lines['offline'][] = '{ x: '.($now->getTimestamp()*1000).', y:0.1}';
$prev['status'] ?: $lines['offline'][] = '{ x: ' . ($now->getTimestamp() * 1000) . ', y:0.1}';
$data['uptime'] = 100 - ($downtime / ($end_time->getTimestamp() - $start_time->getTimestamp()));
}
$lines_merged = array();
foreach ($lines as $line_key => $line_value) {
if (empty($line_value)) {
continue;
}
@ -273,8 +313,8 @@ class HistoryGraph {
$data['latency_avg'] = count($records) > 0 ? ($latency_avg / count($records)) : 0;
$data['lines'] = sizeof($lines_merged) ? $lines_merged : '';
$data['end_timestamp'] = number_format($end_time->getTimestamp(), 0, '', '')*1000;
$data['start_timestamp'] = number_format($start_time->getTimestamp(), 0, '', '')*1000;
$data['end_timestamp'] = number_format($end_time->getTimestamp(), 0, '', '') * 1000;
$data['start_timestamp'] = number_format($start_time->getTimestamp(), 0, '', '') * 1000;
return $data;
}
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -31,7 +32,8 @@ namespace psm\Util\Server;
/**
* The ServerValidator helps you to check input data for servers.
*/
class ServerValidator {
class ServerValidator
{
/**
* Database service
@ -39,7 +41,8 @@ class ServerValidator {
*/
protected $db;
public function __construct(\psm\Service\Database $db) {
public function __construct(\psm\Service\Database $db)
{
$this->db = $db;
}
@ -49,8 +52,9 @@ class ServerValidator {
* @return boolean
* @throws \InvalidArgumentException
*/
public function serverId($server_id) {
$server = $this->db->selectRow(PSM_DB_PREFIX.'servers', array('server_id' => $server_id), array('server_id'));
public function serverId($server_id)
{
$server = $this->db->selectRow(PSM_DB_PREFIX . 'servers', array('server_id' => $server_id), array('server_id'));
if (empty($server)) {
throw new \InvalidArgumentException('server_no_match');
@ -64,7 +68,8 @@ class ServerValidator {
* @return boolean
* @throws \InvalidArgumentException
*/
public function label($label) {
public function label($label)
{
$label = trim($label);
if (empty($label) || strlen($label) > 255) {
throw new \InvalidArgumentException('server_label_bad_length');
@ -79,7 +84,8 @@ class ServerValidator {
* @return boolean
* @throws \InvalidArgumentException
*/
public function ip($value, $type = null) {
public function ip($value, $type = null)
{
$value = trim($value);
if (empty($value) || strlen($value) > 255) {
@ -89,16 +95,32 @@ class ServerValidator {
switch ($type) {
case 'website':
// url regex as per https://stackoverflow.com/a/3809435
if (!preg_match_all("/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,12}\b([-a-zA-Z0-9@:%_\+.~#?&\/\/=]*)/", $value)) {
// Regex looks a bit weird, but otherwise it's more then 120 characters
if (
!preg_match_all(
"/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\." .
"[a-z]{2,12}\b([-a-zA-Z0-9@:%_\+.~#?&\/\/=]*)/",
$value
)
) {
throw new \InvalidArgumentException('server_ip_bad_website');
}
break;
case 'service':
case 'ping':
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'); }
if (
!filter_var($value, FILTER_VALIDATE_IP)
// domain regex as per
// http://stackoverflow.com/questions/106179/regular-expression-to-match-hostname-or-ip-address
// Regex looks a bit weird, but otherwise it's more then 120 characters
&& !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;
}
@ -111,7 +133,8 @@ class ServerValidator {
* @return boolean
* @throws \InvalidArgumentException
*/
public function type($type) {
public function type($type)
{
if (!in_array($type, array('ping', 'service', 'website'))) {
throw new \InvalidArgumentException('server_type_invalid');
}
@ -124,7 +147,8 @@ class ServerValidator {
* @return boolean
* @throws \InvalidArgumentException
*/
public function warningThreshold($value) {
public function warningThreshold($value)
{
if (!is_numeric($value) || intval($value) == 0) {
throw new \InvalidArgumentException('server_warning_threshold_invalid');
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -27,6 +28,7 @@
**/
namespace psm\Util\Server;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
@ -34,11 +36,12 @@ use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Run an update on all servers.
*/
class UpdateManager implements ContainerAwareInterface {
class UpdateManager implements ContainerAwareInterface
{
use ContainerAwareTrait;
function __construct(ContainerInterface $container) {
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
@ -47,20 +50,22 @@ class UpdateManager implements ContainerAwareInterface {
*
* @param boolean $skip_perms if TRUE, no user permissions will be taken in account and all servers will be updated
*/
public function run($skip_perms = false) {
public function run($skip_perms = false)
{
// check if we need to restrict the servers to a certain user
$sql_join = '';
if (!$skip_perms && $this->container->get('user')->getUserLevel() > PSM_USER_ADMIN) {
// restrict by user_id
$sql_join = "JOIN `".PSM_DB_PREFIX."users_servers` AS `us` ON (
$sql_join = "JOIN `" . PSM_DB_PREFIX . "users_servers` AS `us` ON (
`us`.`user_id`={$this->container->get('user')->getUserId()}
AND `us`.`server_id`=`s`.`server_id`
)";
}
$sql = "SELECT `s`.`server_id`,`s`.`ip`,`s`.`port`,`s`.`label`,`s`.`type`,`s`.`pattern`,`s`.`header_name`,`s`.`header_value`,`s`.`status`,`s`.`active`,`s`.`email`,`s`.`sms`,`s`.`pushover`,`s`.`telegram`
FROM `".PSM_DB_PREFIX."servers` AS `s`
$sql = "SELECT `s`.`server_id`,`s`.`ip`,`s`.`port`,`s`.`label`,`s`.`type`,`s`.`pattern`,`s`.`header_name`,
`s`.`header_value`,`s`.`status`,`s`.`active`,`s`.`email`,`s`.`sms`,`s`.`pushover`,`s`.`telegram`
FROM `" . PSM_DB_PREFIX . "servers` AS `s`
{$sql_join}
WHERE `active`='yes' ";
@ -79,7 +84,7 @@ class UpdateManager implements ContainerAwareInterface {
$archive->archive($server['server_id']);
$archive->cleanup($server['server_id']);
}
if($notifier->combine){
if ($notifier->combine) {
$notifier->notifyCombined();
}
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -34,7 +35,8 @@
namespace psm\Util\Server\Updater;
use psm\Service\Database;
class StatusNotifier {
class StatusNotifier
{
/**
* Database service
@ -113,7 +115,8 @@ class StatusNotifier {
*/
protected $status_new;
function __construct(Database $db) {
public function __construct(Database $db)
{
$this->db = $db;
$this->send_emails = psm_get_conf('email_status');
@ -133,7 +136,8 @@ class StatusNotifier {
* @return boolean
* @throws \PHPMailer\PHPMailer\Exception
*/
public function notify($server_id, $status_old, $status_new) {
public function notify($server_id, $status_old, $status_new)
{
if (
!$this->send_emails &&
!$this->send_sms &&
@ -152,10 +156,21 @@ class StatusNotifier {
// get server info from db
// only get info that will be put into the notification
// or is needed to check if a notification need to be send
$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', 'error', 'email', 'sms', 'pushover', 'telegram', 'last_online', 'last_offline', 'last_offline_duration',
'server_id',
'ip',
'port',
'label',
'error',
'email',
'sms',
'pushover',
'telegram',
'last_online',
'last_offline',
'last_offline_duration',
));
if (empty($this->server)) {
return false;
@ -204,7 +219,7 @@ class StatusNotifier {
return $notify;
}
if($this->combine){
if ($this->combine) {
$this->setCombi('init', $users);
}
@ -242,12 +257,13 @@ class StatusNotifier {
* @param array $users Users
* @return void
*/
public function setCombi($method, $users = array()) {
public function setCombi($method, $users = array())
{
$status = $this->status_new ? 'on' : 'off';
if ($method == 'init' && !empty($users)){
foreach($users as $user) {
if(!isset($this->combiNotification['count'][$user['user_id']])){
if ($method == 'init' && !empty($users)) {
foreach ($users as $user) {
if (!isset($this->combiNotification['count'][$user['user_id']])) {
$this->combiNotification['count'][$user['user_id']] = array('on' => 0, 'off' => 0);
}
$this->combiNotification['userNotifications'][$user['user_id']][] = $this->server_id;
@ -258,7 +274,7 @@ class StatusNotifier {
}
$this->combiNotification['notifications'][$method][$status][$this->server_id] =
psm_parse_msg($this->status_new, $method.'_message', $this->server, true);
psm_parse_msg($this->status_new, $method . '_message', $this->server, true);
return;
}
@ -267,8 +283,9 @@ class StatusNotifier {
*
* @return void
*/
public function notifyCombined() {
if(empty($this->combiNotification['userNotifications'])){
public function notifyCombined()
{
if (empty($this->combiNotification['userNotifications'])) {
return;
}
// Get the servers the user will get notified of
@ -277,31 +294,33 @@ class StatusNotifier {
$notifications = array();
// Combine all of the messages belonging to the server the user will get notification of
foreach ($servers as $server) {
foreach ($this->combiNotification['notifications'] as $method => $status){
foreach ($this->combiNotification['notifications'] as $method => $status) {
foreach ($status as $the_status => $value) {
if(!key_exists($method, $notifications)){
if (!key_exists($method, $notifications)) {
$notifications[$method] = array('on' => '', 'off' => '');
}
if(key_exists($server, $status[$the_status])){
if (key_exists($server, $status[$the_status])) {
$notifications[$method][$the_status] .= $status[$the_status][$server];
}
// Set $this->status_new to false if a server is down.
// This is used by Pushover to determine the priority.
if(!empty($notifications[$method]['off'])){
if (!empty($notifications[$method]['off'])) {
$this->status_new = false;
}
}
}
}
// Send combined notification per user
foreach ($notifications as $method => $notification){
foreach ($notifications as $method => $notification) {
$finalNotification['message'] = $this->createCombiMessage($method, $notification);
$subject = $this->createCombiSubject($method, $user);
if(!is_null($subject)){
if (!is_null($subject)) {
$finalNotification['subject'] = $subject;
}
$this->{'notifyBy' . ucwords($method)}
(array($this->combiNotification['users'][$user]), $finalNotification);
$this->{'notifyBy' . ucwords($method)}(
array($this->combiNotification['users'][$user]),
$finalNotification
);
}
}
unset($notifications);
@ -315,15 +334,16 @@ class StatusNotifier {
* @param array $notification Notification
* @return string
*/
protected function createCombiMessage($method, $notification){
if(empty($notification['off'])){
$notification['off'] = "<ul><li>".psm_get_lang('system', 'none')."</li></ul>";
protected function createCombiMessage($method, $notification)
{
if (empty($notification['off'])) {
$notification['off'] = "<ul><li>" . psm_get_lang('system', 'none') . "</li></ul>";
}
if(empty($notification['on'])){
$notification['on'] = "<ul><li>".psm_get_lang('system', 'none')."</li></ul>";
if (empty($notification['on'])) {
$notification['on'] = "<ul><li>" . psm_get_lang('system', 'none') . "</li></ul>";
}
$vars = array('DOWN_SERVERS' => $notification['off'], 'UP_SERVERS' => $notification['on']);
return psm_parse_msg(null, $method.'_message', $vars, true);
return psm_parse_msg(null, $method . '_message', $vars, true);
}
/**
@ -333,10 +353,14 @@ class StatusNotifier {
* @param integer $user_id User id
* @return string|null
*/
protected function createCombiSubject($method, $user_id){
$vars = array('DOWN' => $this->combiNotification['count'][$user_id]['off'], 'UP' => $this->combiNotification['count'][$user_id]['on']);
$translation = isset($GLOBALS['sm_lang_default']['notifications']['combi_'.$method.'_subject']) ?
psm_parse_msg(null, $method.'_subject', $vars, true) :
protected function createCombiSubject($method, $user_id)
{
$vars = array(
'DOWN' => $this->combiNotification['count'][$user_id]['off'],
'UP' => $this->combiNotification['count'][$user_id]['on']
);
$translation = isset($GLOBALS['sm_lang_default']['notifications']['combi_' . $method . '_subject']) ?
psm_parse_msg(null, $method . '_subject', $vars, true) :
null;
return $translation;
}
@ -349,7 +373,8 @@ class StatusNotifier {
* @return void
* @throws \PHPMailer\PHPMailer\Exception
*/
protected function notifyByEmail($users, $combi = array()) {
protected function notifyByEmail($users, $combi = array())
{
// build mail object with some default values
$mail = psm_build_mail();
$mail->Subject = key_exists('subject', $combi) ?
@ -388,7 +413,8 @@ class StatusNotifier {
* @param array $combi contains message and subject (optional)
* @return void
*/
protected function notifyByPushover($users, $combi = array()) {
protected function notifyByPushover($users, $combi = array())
{
// Remove users that have no pushover_key
foreach ($users as $k => $user) {
if (trim($user['pushover_key']) == '') {
@ -411,8 +437,11 @@ class StatusNotifier {
$pushover->setPriority(0);
} else {
$pushover->setPriority(2);
$pushover->setRetry(300); //Used with Priority = 2; Pushover will resend the notification every 60 seconds until the user accepts.
$pushover->setExpire(3600); //Used with Priority = 2; Pushover will resend the notification every 60 seconds for 3600 seconds. After that point, it stops sending notifications.
//Used with Priority = 2; Pushover will resend the notification every 60 seconds until the user accepts.
$pushover->setRetry(300);
// Used with Priority = 2; Pushover will resend the notification every 60 seconds for 3600 seconds.
// After that point, it stops sending notifications.
$pushover->setExpire(3600);
}
$title = key_exists('subject', $combi) ?
$combi['subject'] :
@ -449,7 +478,8 @@ class StatusNotifier {
* @param \PDOStatement $users
* @return boolean
*/
protected function notifyByTxtMsg($users) {
protected function notifyByTxtMsg($users)
{
$sms = psm_build_sms();
if (!$sms) {
return false;
@ -485,7 +515,8 @@ class StatusNotifier {
* @param array $combi contains message and subject (optional)
* @return void
*/
protected function notifyByTelegram($users, $combi = array()) {
protected function notifyByTelegram($users, $combi = array())
{
// Remove users that have no telegram_id
foreach ($users as $k => $user) {
if (trim($user['telegram_id']) == '') {
@ -525,12 +556,14 @@ class StatusNotifier {
* @param int $server_id
* @return \PDOStatement array
*/
public function getUsers($server_id) {
public function getUsers($server_id)
{
// find all the users with this server listed
$users = $this->db->query("
SELECT `u`.`user_id`, `u`.`name`,`u`.`email`, `u`.`mobile`, `u`.`pushover_key`, `u`.`pushover_device`, `u`.`telegram_id`
FROM `".PSM_DB_PREFIX."users` AS `u`
JOIN `".PSM_DB_PREFIX."users_servers` AS `us` ON (
SELECT `u`.`user_id`, `u`.`name`,`u`.`email`, `u`.`mobile`, `u`.`pushover_key`,
`u`.`pushover_device`, `u`.`telegram_id`
FROM `" . PSM_DB_PREFIX . "users` AS `u`
JOIN `" . PSM_DB_PREFIX . "users_servers` AS `us` ON (
`us`.`user_id`=`u`.`user_id`
AND `us`.`server_id` = {$server_id}
)

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -34,7 +35,8 @@
namespace psm\Util\Server\Updater;
use psm\Service\Database;
class StatusUpdater {
class StatusUpdater
{
public $error = '';
public $header = '';
@ -61,7 +63,8 @@ class StatusUpdater {
*/
protected $server;
function __construct(Database $db) {
public function __construct(Database $db)
{
$this->db = $db;
}
@ -78,19 +81,23 @@ class StatusUpdater {
* @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->header = '';
$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', 'request_method', 'label', 'type', 'pattern', 'pattern_online', 'post_field',
'allow_http_status', 'redirect_check', 'header_name', 'header_value', 'status', 'active', 'warning_threshold',
'warning_threshold_counter', 'timeout', 'website_username', 'website_password', 'last_offline'
'server_id', 'ip', 'port', 'request_method', 'label',
'type', 'pattern', 'pattern_online', 'post_field',
'allow_http_status', 'redirect_check', 'header_name',
'header_value', 'status', 'active', 'warning_threshold',
'warning_threshold_counter', 'timeout', 'website_username',
'website_password', 'last_offline'
));
if (empty($this->server)) {
return false;
@ -114,7 +121,7 @@ class StatusUpdater {
'error' => $this->error,
'rtime' => $this->rtime
);
if(!empty($this->error)){
if (!empty($this->error)) {
$save['last_error'] = $this->error;
}
@ -126,7 +133,7 @@ class StatusUpdater {
// 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['last_output'] = substr($this->header,0,5000);
$save['last_output'] = substr($this->header, 0, 5000);
$save['warning_threshold_counter'] = 0;
if ($this->server['status'] == 'off') {
$online_date = new \DateTime($save['last_online']);
@ -138,7 +145,8 @@ class StatusUpdater {
// server is offline, increase the error counter and set last offline
$save['warning_threshold_counter'] = $this->server['warning_threshold_counter'] + 1;
$save['last_offline'] = date('Y-m-d H:i:s');
$save['last_error_output'] = empty($this->header) ? "Could not get headers. probably HTTP 50x error." : $this->header;
$save['last_error_output'] = empty($this->header) ?
"Could not get headers. probably HTTP 50x error." : $this->header;
if ($save['warning_threshold_counter'] < $this->server['warning_threshold']) {
// the server is offline but the error threshold has not been met yet.
@ -152,10 +160,9 @@ class StatusUpdater {
}
}
}
$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;
}
/**
@ -164,7 +171,8 @@ class StatusUpdater {
* @param int $run
* @return boolean
*/
protected function updatePing($max_runs, $run = 1) {
protected function updatePing($max_runs, $run = 1)
{
// save response time
$starttime = microtime(true);
// set ping payload
@ -182,7 +190,7 @@ class StatusUpdater {
// set error message
$errorcode = socket_last_error();
$this->error = "Couldn't create socket [".$errorcode."]: ".socket_strerror($errorcode);
$this->error = "Couldn't create socket [" . $errorcode . "]: " . socket_strerror($errorcode);
}
$this->rtime = microtime(true) - $starttime;
socket_close($socket);
@ -201,8 +209,10 @@ class StatusUpdater {
* @param int $run
* @return boolean
*/
protected function updateService($max_runs, $run = 1) {
$timeout = ($this->server['timeout'] === null || $this->server['timeout'] > 0) ? PSM_CURL_TIMEOUT : intval($this->server['timeout']);
protected function updateService($max_runs, $run = 1)
{
$timeout = ($this->server['timeout'] === null || $this->server['timeout'] > 0) ?
PSM_CURL_TIMEOUT : intval($this->server['timeout']);
$errno = 0;
// save response time
$starttime = microtime(true);
@ -230,7 +240,8 @@ class StatusUpdater {
* @param int $run
* @return boolean
*/
protected function updateWebsite($max_runs, $run = 1) {
protected function updateWebsite($max_runs, $run = 1)
{
$starttime = microtime(true);
// We're only interested in the header, because that should tell us plenty!
@ -242,7 +253,8 @@ class StatusUpdater {
$this->server['timeout'],
true,
$this->server['website_username'],
psm_password_decrypt($this->server['server_id'].psm_get_conf('password_encrypt_key'), $this->server['website_password']),
psm_password_decrypt($this->server['server_id'] .
psm_get_conf('password_encrypt_key'), $this->server['website_password']),
$this->server['request_method'],
$this->server['post_field']
);
@ -258,7 +270,7 @@ class StatusUpdater {
$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])) {
if (empty($code_matches[0])) {
// somehow we dont have a proper response.
$this->error = 'TIMEOUT ERROR: no response from server';
$result = false;
@ -268,8 +280,8 @@ class StatusUpdater {
$allow_http_status = explode("|", $this->server['allow_http_status']);
// All status codes starting with a 4 or higher mean trouble!
if (substr($code, 0, 1) >= '4' && !in_array($code ,$allow_http_status)) {
$this->error = "HTTP STATUS ERROR: ".$code.' '.$msg;
if (substr($code, 0, 1) >= '4' && !in_array($code, $allow_http_status)) {
$this->error = "HTTP STATUS ERROR: " . $code . ' ' . $msg;
$result = false;
} else {
$result = true;
@ -278,21 +290,35 @@ class StatusUpdater {
if ($this->server['pattern'] != '') {
// Check to see if the body should not contain specified pattern
// Check to see if the pattern was [not] found.
if (($this->server['pattern_online'] == 'yes') == !preg_match("/{$this->server['pattern']}/i", $curl_result)) {
$this->error = "TEXT ERROR : Pattern '{$this->server['pattern']}' ".
($this->server['pattern_online'] == 'yes' ? 'not' : 'was').
if (
($this->server['pattern_online'] == 'yes') ==
!preg_match(
"/{$this->server['pattern']}/i",
$curl_result
)
) {
$this->error = "TEXT ERROR : Pattern '{$this->server['pattern']}' " .
($this->server['pattern_online'] == 'yes' ? 'not' : 'was') .
' found.';
$result = false;
}
}
// Check if the website redirects to another domain
if ($this->server['redirect_check'] == 'bad'){
if ($this->server['redirect_check'] == 'bad') {
$location_matches = array();
preg_match('/([Ll]ocation: )(https*:\/\/)(www.)?([a-zA-Z.:0-9]*)([\/][[:alnum:][:punct:]]*)/', $curl_result, $location_matches);
if(!empty($location_matches)) {
preg_match(
'/([Ll]ocation: )(https*:\/\/)(www.)?([a-zA-Z.:0-9]*)([\/][[:alnum:][:punct:]]*)/',
$curl_result,
$location_matches
);
if (!empty($location_matches)) {
$ip_matches = array();
preg_match('/(https*:\/\/)(www.)?([a-zA-Z.:0-9]*)([\/][[:alnum:][:punct:]]*)?/', $this->server['ip'], $ip_matches);
preg_match(
'/(https*:\/\/)(www.)?([a-zA-Z.:0-9]*)([\/][[:alnum:][:punct:]]*)?/',
$this->server['ip'],
$ip_matches
);
if (strtolower($location_matches[4]) !== strtolower($ip_matches[3])) {
$this->error = "The IP/URL redirects to another domain.";
$result = false;
@ -303,14 +329,17 @@ class StatusUpdater {
// Should we check a header ?
if ($this->server['header_name'] != '' && $this->server['header_value'] != '') {
$header_flag = false;
$header_text = substr($curl_result, 0, strpos($curl_result, "\r\n\r\n")); // Only get the header text if the result also includes the body
// Only get the header text if the result also includes the body
$header_text = substr($curl_result, 0, strpos($curl_result, "\r\n\r\n"));
foreach (explode("\r\n", $header_text) as $i => $line) {
if ($i === 0 || strpos($line, ':') == false) {
continue; // We skip the status code & other non-header lines. Needed for proxy or redirects
} else {
list ($key, $value) = explode(': ', $line);
if (strcasecmp($key, $this->server['header_name']) == 0) { // Header found (case-insensitive)
if (!preg_match("/{$this->server['header_value']}/i", $value)) { // The value doesn't match what we needed
// Header found (case-insensitive)
if (strcasecmp($key, $this->server['header_name']) == 0) {
// The value doesn't match what we needed
if (!preg_match("/{$this->server['header_value']}/i", $value)) {
$result = false;
} else {
$header_flag = true;
@ -341,7 +370,8 @@ class StatusUpdater {
*
* @return string
*/
public function getError() {
public function getError()
{
return $this->error;
}
@ -350,7 +380,8 @@ class StatusUpdater {
*
* @return string
*/
public function getRtime() {
public function getRtime()
{
return $this->rtime;
}
}

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -31,7 +32,8 @@ namespace psm\Util\User;
/**
* The UserValidator helps you to check input data for user accounts.
*/
class UserValidator {
class UserValidator
{
/**
* Available editable user levels
@ -45,7 +47,8 @@ class UserValidator {
*/
protected $user;
public function __construct(\psm\Service\User $user) {
public function __construct(\psm\Service\User $user)
{
$this->user = $user;
}
@ -55,7 +58,8 @@ class UserValidator {
* @return boolean
* @throws \InvalidArgumentException
*/
public function userId($user_id) {
public function userId($user_id)
{
$user = $this->user->getUser($user_id);
if (empty($user)) {
throw new \InvalidArgumentException('user_no_match');
@ -74,7 +78,8 @@ class UserValidator {
* @return boolean
* @throws \InvalidArgumentException
*/
public function username($username, $user_id = 0) {
public function username($username, $user_id = 0)
{
if (strlen($username) > 64 || strlen($username) < 2) {
throw new \InvalidArgumentException('user_name_bad_length');
}
@ -96,7 +101,8 @@ class UserValidator {
* @return boolean
* @throws \InvalidArgumentException
*/
public function password($password, $password_repeat) {
public function password($password, $password_repeat)
{
if (empty($password) || empty($password_repeat)) {
throw new \InvalidArgumentException('user_password_invalid');
}
@ -115,7 +121,8 @@ class UserValidator {
* @return boolean
* @throws \InvalidArgumentException
*/
public function username_new($username) {
public function usernameNew($username)
{
if (strlen($username) > 64 || strlen($username) < 2) {
throw new \InvalidArgumentException('user_name_bad_length');
}
@ -131,7 +138,8 @@ class UserValidator {
* @return boolean
* @throws \InvalidArgumentException
*/
public function email($email) {
public function email($email)
{
if (strlen($email) > 255 || strlen($email) < 5) {
throw new \InvalidArgumentException('user_email_bad_length');
}
@ -147,7 +155,8 @@ class UserValidator {
* @return boolean
* @throws \InvalidArgumentException
*/
public function level($level) {
public function level($level)
{
if (!in_array($level, $this->user_levels)) {
throw new \InvalidArgumentException('user_level_invalid');
}
@ -158,7 +167,8 @@ class UserValidator {
* Get list of all available user levels
* @return array
*/
public function getUserLevels() {
public function getUserLevels()
{
return $this->user_levels;
}
}