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,6 +26,7 @@
* @link http://www.phpservermonitor.org/
**/
namespace {
// include main configuration and functionality
require_once __DIR__ . '/../src/bootstrap.php';
@ -41,7 +43,15 @@ 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";
}
@ -88,3 +98,4 @@ $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.

View File

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

View File

@ -1,4 +1,5 @@
<?php
/**
* PHP Server Monitor
* Monitor your servers and websites.
@ -26,6 +27,7 @@
* @since phpservermon 2.1.0
**/
namespace {
// Include paths
define('PSM_PATH_SRC', __DIR__ . DIRECTORY_SEPARATOR);
define('PSM_PATH_CONFIG', PSM_PATH_SRC . 'config' . DIRECTORY_SEPARATOR);
@ -62,14 +64,20 @@ if (!defined('PSM_CRON_ALLOW')) {
define('PSM_CRON_ALLOW', serialize(array()));
}
$vendor_autoload = PSM_PATH_SRC.'..'.DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'autoload.php';
$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);
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:
// this may seem insignificant, but right now lots of functions
// depend on the following global var definition:
$db = $router->getService('db');
// sanity check!
@ -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);
}

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)) {
@ -75,21 +79,27 @@ 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';
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);
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);
}
}
@ -99,7 +109,8 @@ 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);
$langs = array();
@ -127,7 +138,8 @@ function psm_get_langs() {
*
* @return array
*/
function psm_get_sms_gateways() {
function psm_get_sms_gateways()
{
$sms_gateway_files = glob(PSM_PATH_SMS_GATEWAY . '*.php');
$sms_gateways = array();
@ -151,7 +163,8 @@ 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();
}
@ -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();
@ -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
@ -238,7 +253,8 @@ 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(
@ -257,7 +273,8 @@ 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(
@ -276,7 +293,8 @@ 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(
@ -296,15 +314,34 @@ 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;
}
@ -314,11 +351,13 @@ function psm_log_uptime($server_id, $status, $latency) {
*
* @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) {
function psm_parse_msg($status, $type, $vars, $combi = false)
{
if (is_bool($status)) {
$status = ($status === true) ? 'on_' : 'off_';
}
@ -353,7 +392,17 @@ 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();
@ -378,7 +427,12 @@ 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)) {
if (
$website_username !== false &&
$website_password !== false &&
!empty($website_username) &&
!empty($website_password)
) {
curl_setopt($ch, CURLOPT_USERPWD, $website_username . ":" . $website_password);
}
@ -397,16 +451,19 @@ function psm_curl_get($href, $header = false, $body = true, $timeout = null, $ad
}
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;
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;
@ -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,14 +496,25 @@ 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');
}
@ -452,7 +524,8 @@ function psm_timespan($time) {
* @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');
}
@ -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;
@ -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';
@ -543,7 +618,8 @@ function psm_build_mail($from_name = null, $from_email = null) {
*
* @return \Pushover
*/
function psm_build_pushover() {
function psm_build_pushover()
{
$pushover = new \Pushover();
$pushover->setToken(psm_get_conf('pushover_api_token'));
@ -554,7 +630,8 @@ function psm_build_pushover() {
*
* @return \Telegram
*/
function psm_build_telegram() {
function psm_build_telegram()
{
$telegram = new \Telegram();
$telegram->setToken(psm_get_conf('telegram_api_token'));
@ -566,7 +643,8 @@ function psm_build_telegram() {
*
* @return \psm\Txtmsg\TxtmsgInterface
*/
function psm_build_sms() {
function psm_build_sms()
{
$sms = null;
// open the right class
@ -650,11 +728,13 @@ 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']);
@ -687,7 +767,8 @@ 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 {
@ -701,7 +782,8 @@ 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 {
@ -715,7 +797,8 @@ 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,7 +813,8 @@ function psm_is_cli() {
*
* @param mixed $arr
*/
function pre($arr = null) {
function pre($arr = null)
{
echo "<pre>";
if ($arr === null) {
debug_print_backtrace();
@ -742,7 +826,8 @@ function pre($arr = null) {
/**
* 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("Cache-Control: no-cache, must-revalidate");
@ -814,7 +899,8 @@ function psm_password_decrypt($key, $encryptedString)
$cipher,
hash('sha256', $key, true),
OPENSSL_ZERO_PADDING,
$iv),
$iv
),
"\0"
);
@ -827,30 +913,34 @@ function psm_password_decrypt($key, $encryptedString)
* @return string
* @author Tim Zandbergen <tim@xervion.nl>
*/
class telegram
class Telegram
{
private $_token;
private $_user;
private $_message;
private $_url;
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) {
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;
$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));
@ -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.

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,7 +184,8 @@ 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..
@ -205,7 +210,8 @@ 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(
@ -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,7 +371,8 @@ 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);
}
@ -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',
);
}
}

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,7 +94,8 @@ 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();
@ -150,12 +155,18 @@ 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'] =
@ -171,7 +182,11 @@ class ConfigController extends AbstractController {
$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));
@ -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(
@ -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');
@ -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',
);
}
}

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,7 +47,8 @@ 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);
@ -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');
}
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();
@ -114,8 +138,9 @@ class InstallController extends AbstractController {
$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');
'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();
}
@ -246,7 +278,6 @@ class InstallController extends AbstractController {
} else {
$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,7 +286,7 @@ 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) {
@ -290,7 +321,8 @@ 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) {
protected function writeConfigFile($array_config)
{
$config = "<?php" . PHP_EOL;
foreach ($array_config as $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,7 +371,8 @@ class InstallController extends AbstractController {
/**
* Is it an upgrade or install?
*/
protected function isUpgrade() {
protected function isUpgrade()
{
if (!$this->db->status()) {
return false;
}
@ -349,7 +383,8 @@ class InstallController extends AbstractController {
* 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;
}
@ -370,7 +405,8 @@ 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();

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',
);
}
}

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,7 +45,8 @@ 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 = '';
@ -109,7 +114,8 @@ 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']);

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'),
@ -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,7 +154,8 @@ 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
@ -183,7 +190,8 @@ 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`,

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,7 +144,9 @@ 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'));
}
@ -197,7 +206,8 @@ class ServerController extends AbstractServerController {
'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_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'],
@ -212,7 +222,8 @@ class ServerController extends AbstractServerController {
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
'servers',
'warning_notifications_disabled_' . $notification
);
} else {
$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,7 +288,11 @@ 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') {
if (
$clean['type'] == 'website' &&
substr($clean['ip'], 0, 4) != 'http' &&
substr($clean['ip'], 0, 3) != 'rdp'
) {
$clean['ip'] = 'http://' . $clean['ip'];
}
@ -371,7 +390,8 @@ 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
@ -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,7 +584,8 @@ 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',
array('server_id' => $server_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'));
@ -87,7 +92,9 @@ class StatusController extends AbstractServerController {
if ($server['last_offline_nice'] != psm_get_lang('system', 'never')) {
$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,18 +29,22 @@
**/
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();
@ -48,5 +53,4 @@ class UpdateController extends AbstractController {
), 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',
);
}
}

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(
@ -58,8 +63,7 @@ class LoginController extends AbstractController {
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);
@ -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
@ -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;
}
@ -308,7 +345,8 @@ 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 {
@ -334,7 +372,8 @@ class UserController extends AbstractController {
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,7 +410,8 @@ 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',
array('user_id' => $user_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',
);
}
}

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,7 +119,8 @@ 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;
@ -123,7 +129,8 @@ class Router {
$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')) {

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,7 +193,8 @@ 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';
@ -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,7 +253,8 @@ 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) {
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 ";
@ -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;
}
@ -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 = '';
@ -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) {
@ -459,7 +479,10 @@ class Database {
}
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) {
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,7 +555,8 @@ class Database {
/**
* Is called after connection failure
*/
protected function onConnectFailure(\PDOException $e) {
protected function onConnectFailure(\PDOException $e)
{
trigger_error('MySQL connection failed: ' . $e->getMessage(), E_USER_WARNING);
return false;
}
@ -532,7 +564,8 @@ class Database {
/**
* 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) {
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,7 +183,8 @@ 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']);
@ -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,7 +225,8 @@ 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;
@ -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,10 +276,12 @@ 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
@ -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,7 +516,8 @@ 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) {
@ -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;
}

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;
@ -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;
@ -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,7 +47,8 @@ class FreeMobileSMS extends Core {
* @return bool|string
*/
public function sendSMS($message) {
public function sendSMS($message)
{
$success = 1;
$error = "";
@ -57,8 +60,7 @@ class FreeMobileSMS extends Core {
"pass" => $this->password,
"msg" => urlencode($message),
)
)
);
));
$result = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

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,14 +50,14 @@ 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(
array(
@ -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;

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;
@ -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,10 +61,13 @@ 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,
curl_setopt(
$ch,
CURLOPT_POSTFIELDS,
"originator=" . urlencode($this->originator == '' ? 'PSM' : $this->originator) .
"&body=" . urlencode($message) .
"&recipients=".implode(",", $recipients));
"&recipients=" . implode(",", $recipients)
);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$headers = array();

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,14 +50,14 @@ 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(
array(
@ -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);
@ -79,7 +80,6 @@ class Mosms extends Core {
$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,12 +52,12 @@ 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(
@ -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,7 +55,8 @@ 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
@ -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;
@ -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;
@ -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,12 +51,12 @@ 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(
@ -64,8 +66,7 @@ class Smsit extends Core {
"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;
@ -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";

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,15 +49,26 @@ 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);

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,12 +126,19 @@ 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 . "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'),
@ -172,7 +185,8 @@ 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` (
`key` varchar(255) NOT NULL,
@ -196,7 +210,8 @@ 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,
@ -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,7 +347,8 @@ 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` );";
@ -339,7 +356,8 @@ class Installer {
$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 `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;";
@ -353,40 +371,60 @@ 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
('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` 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` 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 `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;";
@ -447,18 +485,24 @@ class Installer {
/**
* 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;";
@ -477,12 +521,14 @@ 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[] = "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', ''),
@ -519,20 +565,27 @@ class Installer {
/**
* 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[] = "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'),
@ -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,7 +649,8 @@ 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;";
$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;

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();
}
@ -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,7 +110,8 @@ 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) {

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,11 +53,13 @@ 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 '
@ -71,7 +76,8 @@ class LogsArchiver implements ArchiverInterface {
/**
* Empty tables log and log_users
*/
public function cleanupall() {
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
@ -80,7 +85,8 @@ class UptimeArchiver implements ArchiverInterface {
"SELECT `server_id`,`date`,`status`,`latency`
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
@ -120,7 +126,8 @@ 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",
@ -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,7 +170,8 @@ 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 '

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,7 +201,8 @@ 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();
}
@ -181,7 +215,8 @@ class HistoryGraph {
'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();
@ -231,22 +273,21 @@ class HistoryGraph {
$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}'
// Previous datapoint was offline
: '{ x: ' . ($time * 1000) . ', y:0.1}';
$lines['online'][] = '{ x: '.($time*1000).', y: '.round((float) $record[$key], 4).'}';
$lines['online'][] = '{ x: ' . ($time * 1000) . ', y: ' .
round((float) $record[$key], 4) . '}';
$prev_downtime == 0 ?: $downtime += ($time - $prev_downtime);
$prev_downtime = 0;
}
}
else {
} else {
$lines[$key][] = '{ x: \'' . $record['date'] . '\', y: ' . $record[$key] . '}';
}
$prev = $record;
@ -263,7 +304,6 @@ class HistoryGraph {
$lines_merged = array();
foreach ($lines as $line_key => $line_value) {
if (empty($line_value)) {
continue;
}

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,7 +52,8 @@ class ServerValidator {
* @return boolean
* @throws \InvalidArgumentException
*/
public function serverId($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)) {
@ -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,7 +50,8 @@ 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 = '';
@ -59,7 +63,8 @@ class UpdateManager implements ContainerAwareInterface {
)";
}
$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`
$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' ";

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 &&
@ -155,7 +159,18 @@ class StatusNotifier {
$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;
@ -242,7 +257,8 @@ 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)) {
@ -267,7 +283,8 @@ class StatusNotifier {
*
* @return void
*/
public function notifyCombined() {
public function notifyCombined()
{
if (empty($this->combiNotification['userNotifications'])) {
return;
}
@ -300,8 +317,10 @@ class StatusNotifier {
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,7 +334,8 @@ class StatusNotifier {
* @param array $notification Notification
* @return string
*/
protected function createCombiMessage($method, $notification){
protected function createCombiMessage($method, $notification)
{
if (empty($notification['off'])) {
$notification['off'] = "<ul><li>" . psm_get_lang('system', 'none') . "</li></ul>";
}
@ -333,8 +353,12 @@ 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']);
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;
@ -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,10 +556,12 @@ 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`
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`

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,7 +81,8 @@ 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 = '';
@ -88,9 +92,12 @@ class StatusUpdater {
$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;
@ -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.
@ -155,7 +163,6 @@ class StatusUpdater {
$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
@ -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']
);
@ -278,7 +290,13 @@ 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)) {
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.';
@ -289,10 +307,18 @@ class StatusUpdater {
// Check if the website redirects to another domain
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);
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;
}
}