Spacing, indentation and braces

Co-Authored-By: Scrutinizer Auto-Fixer <auto-fixes@scrutinizer-ci.com>
pull/612/merge
TimZ99 2018-07-05 19:59:57 +02:00
parent a05d36d5f6
commit e2c424e167
No known key found for this signature in database
GPG Key ID: 4D8268DC68E8339D
79 changed files with 2555 additions and 2508 deletions

View File

@ -26,11 +26,11 @@
**/ **/
// include main configuration and functionality // include main configuration and functionality
require_once __DIR__ . '/../src/bootstrap.php'; require_once __DIR__.'/../src/bootstrap.php';
if(!psm_is_cli()) { if (!psm_is_cli()) {
// check if it's an allowed host // check if it's an allowed host
if(!isset($_SERVER["HTTP_X_FORWARDED_FOR"])){ if (!isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
$_SERVER["HTTP_X_FORWARDED_FOR"] = ""; $_SERVER["HTTP_X_FORWARDED_FOR"] = "";
} }
@ -39,7 +39,7 @@ if(!psm_is_cli()) {
$data = @unserialize(PSM_CRON_ALLOW); $data = @unserialize(PSM_CRON_ALLOW);
$allow = $data === false ? PSM_CRON_ALLOW : $data; $allow = $data === false ? PSM_CRON_ALLOW : $data;
if(!in_array($_SERVER['REMOTE_ADDR'], $allow) && !in_array($_SERVER["HTTP_X_FORWARDED_FOR"], $allow)) { if (!in_array($_SERVER['REMOTE_ADDR'], $allow) && !in_array($_SERVER["HTTP_X_FORWARDED_FOR"], $allow)) {
header('HTTP/1.0 403 Forbidden'); 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>');
} }
@ -48,15 +48,15 @@ if(!psm_is_cli()) {
$cron_timeout = PSM_CRON_TIMEOUT; $cron_timeout = PSM_CRON_TIMEOUT;
// parse a couple of arguments // parse a couple of arguments
if(!empty($_SERVER['argv'])) { if (!empty($_SERVER['argv'])) {
foreach ($_SERVER['argv'] as $argv) { foreach ($_SERVER['argv'] as $argv) {
$argi = explode('=', ltrim($argv, '--')); $argi = explode('=', ltrim($argv, '--'));
if(count($argi) !== 2) { if (count($argi) !== 2) {
continue; continue;
} }
switch($argi[0]) { switch ($argi[0]) {
case 'uri': case 'uri':
if(!defined('PSM_BASE_URL')){ if (!defined('PSM_BASE_URL')) {
define('PSM_BASE_URL', $argi[1]); define('PSM_BASE_URL', $argi[1]);
} }
break; break;
@ -72,14 +72,14 @@ if(!empty($_SERVER['argv'])) {
// if you want to change PSM_CRON_TIMEOUT, have a look in src/includes/psmconfig.inc.php. // if you want to change PSM_CRON_TIMEOUT, have a look in src/includes/psmconfig.inc.php.
// or you can provide the --timeout=x argument // or you can provide the --timeout=x argument
$time = time(); $time = time();
if( if (
psm_get_conf('cron_running') == 1 psm_get_conf('cron_running') == 1
&& $cron_timeout > 0 && $cron_timeout > 0
&& ($time - psm_get_conf('cron_running_time') < $cron_timeout) && ($time - psm_get_conf('cron_running_time') < $cron_timeout)
) { ) {
die('Cron is already running. Exiting.'); die('Cron is already running. Exiting.');
} }
if(!defined('PSM_DEBUG') || !PSM_DEBUG) { if (!defined('PSM_DEBUG') || !PSM_DEBUG) {
psm_update_conf('cron_running', 1); psm_update_conf('cron_running', 1);
} }
psm_update_conf('cron_running_time', $time); psm_update_conf('cron_running_time', $time);

View File

@ -25,14 +25,14 @@
* @link http://www.phpservermonitor.org/ * @link http://www.phpservermonitor.org/
**/ **/
require __DIR__ . '/src/bootstrap.php'; require __DIR__.'/src/bootstrap.php';
psm_no_cache(); psm_no_cache();
if(isset($_GET["logout"])) { if (isset($_GET["logout"])) {
$router->getService('user')->doLogout(); $router->getService('user')->doLogout();
// logged out, redirect to login // logged out, redirect to login
header('Location: ' . psm_build_url()); header('Location: '.psm_build_url());
die(); die();
} }
@ -40,7 +40,7 @@ $mod = psm_GET('mod', PSM_MODULE_DEFAULT);
try { try {
$router->run($mod); $router->run($mod);
} catch(\InvalidArgumentException $e) { } catch (\InvalidArgumentException $e) {
// invalid module, try the default one // invalid module, try the default one
// it that somehow also doesnt exist, we have a bit of an issue // it that somehow also doesnt exist, we have a bit of an issue
// and we really have no reason catch it // and we really have no reason catch it

View File

@ -27,6 +27,6 @@
define('PSM_INSTALL', true); define('PSM_INSTALL', true);
require __DIR__ . '/src/bootstrap.php'; require __DIR__.'/src/bootstrap.php';
$router->run('install'); $router->run('install');

View File

@ -27,27 +27,27 @@
**/ **/
// Include paths // Include paths
define('PSM_PATH_SRC', __DIR__ . DIRECTORY_SEPARATOR); define('PSM_PATH_SRC', __DIR__.DIRECTORY_SEPARATOR);
define('PSM_PATH_CONFIG', PSM_PATH_SRC . 'config' . DIRECTORY_SEPARATOR); define('PSM_PATH_CONFIG', PSM_PATH_SRC.'config'.DIRECTORY_SEPARATOR);
define('PSM_PATH_LANG', PSM_PATH_SRC . 'lang' . DIRECTORY_SEPARATOR); define('PSM_PATH_LANG', PSM_PATH_SRC.'lang'.DIRECTORY_SEPARATOR);
define('PSM_PATH_SMS_GATEWAY', PSM_PATH_SRC . 'psm' . DIRECTORY_SEPARATOR . 'Txtmsg' . DIRECTORY_SEPARATOR); define('PSM_PATH_SMS_GATEWAY', PSM_PATH_SRC.'psm'.DIRECTORY_SEPARATOR.'Txtmsg'.DIRECTORY_SEPARATOR);
// user levels // user levels
define('PSM_USER_ADMIN', 10); define('PSM_USER_ADMIN', 10);
define('PSM_USER_USER', 20); define('PSM_USER_USER', 20);
define('PSM_USER_ANONYMOUS', 30); define('PSM_USER_ANONYMOUS', 30);
if(function_exists('date_default_timezone_set') && function_exists('date_default_timezone_get')) { if (function_exists('date_default_timezone_set') && function_exists('date_default_timezone_get')) {
date_default_timezone_set(@date_default_timezone_get()); date_default_timezone_set(@date_default_timezone_get());
} }
// find config file // find config file
$path_conf = PSM_PATH_SRC . '../config.php'; $path_conf = PSM_PATH_SRC.'../config.php';
if(file_exists($path_conf)) { if (file_exists($path_conf)) {
include_once $path_conf; include_once $path_conf;
} }
// check for a debug var // check for a debug var
if(!defined('PSM_DEBUG')) { if (!defined('PSM_DEBUG')) {
define('PSM_DEBUG', false); define('PSM_DEBUG', false);
} }
@ -57,13 +57,13 @@ ini_set('display_errors', 1);
PSM_DEBUG ? error_reporting(E_ALL) : error_reporting(E_USER_ERROR); PSM_DEBUG ? error_reporting(E_ALL) : error_reporting(E_USER_ERROR);
// check for a cron allowed ip array // check for a cron allowed ip array
if(!defined('PSM_CRON_ALLOW')) { if (!defined('PSM_CRON_ALLOW')) {
//serialize for php version lower than 7.0.0 //serialize for php version lower than 7.0.0
define('PSM_CRON_ALLOW', serialize(array())); 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)) { 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; require_once $vendor_autoload;
@ -73,25 +73,25 @@ $router = new psm\Router();
$db = $router->getService('db'); $db = $router->getService('db');
// sanity check! // sanity check!
if(!defined('PSM_INSTALL') || !PSM_INSTALL) { if (!defined('PSM_INSTALL') || !PSM_INSTALL) {
if($db->getDbHost() === null) { if ($db->getDbHost() === null) {
// no config file has been loaded, redirect the user to the install // no config file has been loaded, redirect the user to the install
header('Location: install.php'); header('Location: install.php');
trigger_error("Could not load config file. Redirect to install failed, <a href=\"install.php\">click here</a>.", E_USER_ERROR); trigger_error("Could not load config file. Redirect to install failed, <a href=\"install.php\">click here</a>.", E_USER_ERROR);
} }
// config file has been loaded, check if we have a connection // config file has been loaded, check if we have a connection
if(!$db->status()) { if (!$db->status()) {
trigger_error("Unable to establish database connection...", E_USER_ERROR); trigger_error("Unable to establish database connection...", E_USER_ERROR);
} }
// attempt to load configuration from database // attempt to load configuration from database
if(!psm_load_conf()) { if (!psm_load_conf()) {
// unable to load from config table // unable to load from config table
header('Location: install.php'); header('Location: install.php');
trigger_error("Could not load config table. Redirect to install failed, <a href=\"install.php\">click here</a>.", E_USER_ERROR); trigger_error("Could not load config table. Redirect to install failed, <a href=\"install.php\">click here</a>.", E_USER_ERROR);
} }
// config load OK, make sure database version is up to date // config load OK, make sure database version is up to date
$installer = new \psm\Util\Install\Installer($db); $installer = new \psm\Util\Install\Installer($db);
if($installer->isUpgradeRequired()) { 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);
} }
} }

View File

@ -40,25 +40,28 @@
function psm_get_lang() { function psm_get_lang() {
$args = func_get_args(); $args = func_get_args();
if (empty($args)) if (empty($args)) {
return isset($GLOBALS['sm_lang']) ? $GLOBALS['sm_lang'] : $GLOBALS['sm_lang_default']; return isset($GLOBALS['sm_lang']) ? $GLOBALS['sm_lang'] : $GLOBALS['sm_lang_default'];
}
if(isset($GLOBALS['sm_lang'])) { if (isset($GLOBALS['sm_lang'])) {
$lang = $GLOBALS['sm_lang']; $lang = $GLOBALS['sm_lang'];
$not_found = false; $not_found = false;
foreach($args as $translation) { foreach ($args as $translation) {
// if translation does not exist, use default translation // if translation does not exist, use default translation
if(!isset($lang[$translation])) { if (!isset($lang[$translation])) {
$not_found = true; $not_found = true;
break; break;
} }
$lang = $lang[$translation]; $lang = $lang[$translation];
} }
if(!$not_found) return $lang; if (!$not_found) {
return $lang;
}
} }
$lang = $GLOBALS['sm_lang_default']; $lang = $GLOBALS['sm_lang_default'];
foreach($args as $translation) { foreach ($args as $translation) {
$lang = $lang[$translation]; $lang = $lang[$translation];
} }
return $lang; return $lang;
@ -74,14 +77,14 @@ function psm_get_lang() {
function psm_load_lang($lang) { function psm_load_lang($lang) {
// load default language - English (en_US) // load default language - English (en_US)
// this will also fill in every part that is not translated in other translation files // this will also fill in every part that is not translated in other translation files
$default_lang_file = PSM_PATH_LANG . 'en_US.lang.php'; $default_lang_file = PSM_PATH_LANG.'en_US.lang.php';
file_exists($default_lang_file) ? require $default_lang_file : trigger_error("English translation needs to be installed at all time!", E_USER_ERROR); 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); isset($sm_lang) ? $GLOBALS['sm_lang_default'] = $sm_lang : trigger_error("\$sm_lang not found in English translation!", E_USER_ERROR);
unset($sm_lang); unset($sm_lang);
// load translation is the selected language is not English (en_US) // load translation is the selected language is not English (en_US)
if($lang != "en_US"){ if ($lang != "en_US") {
$lang_file = PSM_PATH_LANG . $lang . '.lang.php'; $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) ? $GLOBALS['sm_lang'] = $sm_lang : trigger_error("\$sm_lang not found in translation file! Default language will be used.", E_USER_WARNING);
@ -97,16 +100,16 @@ function psm_load_lang($lang) {
*/ */
function psm_get_langs() { function psm_get_langs() {
$fn_ext = '.lang.php'; $fn_ext = '.lang.php';
$lang_files = glob(PSM_PATH_LANG . '*' . $fn_ext); $lang_files = glob(PSM_PATH_LANG.'*'.$fn_ext);
$langs = array(); $langs = array();
foreach($lang_files as $file) { foreach ($lang_files as $file) {
$key = str_replace($fn_ext, '', basename($file)); $key = str_replace($fn_ext, '', basename($file));
$sm_lang = array(); $sm_lang = array();
if(file_exists($file)) { if (file_exists($file)) {
require $file; require $file;
} }
if(isset($sm_lang['name'])) { if (isset($sm_lang['name'])) {
$name = $sm_lang['name']; $name = $sm_lang['name'];
} else { } else {
$name = $key; $name = $key;
@ -124,13 +127,13 @@ function psm_get_langs() {
* @return array * @return array
*/ */
function psm_get_sms_gateways() { function psm_get_sms_gateways() {
$sms_gateway_files = glob(PSM_PATH_SMS_GATEWAY . '*.php'); $sms_gateway_files = glob(PSM_PATH_SMS_GATEWAY.'*.php');
$sms_gateways = array(); $sms_gateways = array();
foreach($sms_gateway_files as $file) { foreach ($sms_gateway_files as $file) {
$name = basename($file, ".php"); $name = basename($file, ".php");
// filter system files out // filter system files out
if($name != "Core" && $name != "TxtmsgInterface"){ if ($name != "Core" && $name != "TxtmsgInterface") {
$sms_gateways[strtolower($name)] = $name; $sms_gateways[strtolower($name)] = $name;
} }
} }
@ -148,7 +151,7 @@ function psm_get_sms_gateways() {
* @see psm_load_conf() * @see psm_load_conf()
*/ */
function psm_get_conf($key, $alt = null) { function psm_get_conf($key, $alt = null) {
if(!isset($GLOBALS['sm_config'])) { if (!isset($GLOBALS['sm_config'])) {
psm_load_conf(); psm_load_conf();
} }
$result = (isset($GLOBALS['sm_config'][$key])) ? $GLOBALS['sm_config'][$key] : $alt; $result = (isset($GLOBALS['sm_config'][$key])) ? $GLOBALS['sm_config'][$key] : $alt;
@ -168,16 +171,16 @@ function psm_load_conf() {
$GLOBALS['sm_config'] = array(); $GLOBALS['sm_config'] = array();
if(!defined('PSM_DB_PREFIX') || !$db->status()) { if (!defined('PSM_DB_PREFIX') || !$db->status()) {
return false; return false;
} }
if(!$db->ifTableExists(PSM_DB_PREFIX.'config')) { if (!$db->ifTableExists(PSM_DB_PREFIX.'config')) {
return false; return false;
} }
$config_db = $db->select(PSM_DB_PREFIX . 'config', null, array('key', 'value')); $config_db = $db->select(PSM_DB_PREFIX.'config', null, array('key', 'value'));
if(is_array($config_db) && !empty($config_db)) { if (is_array($config_db) && !empty($config_db)) {
foreach($config_db as $setting) { foreach ($config_db as $setting) {
$GLOBALS['sm_config'][$setting['key']] = $setting['value']; $GLOBALS['sm_config'][$setting['key']] = $setting['value'];
} }
return true; return true;
@ -199,10 +202,10 @@ function psm_update_conf($key, $value) {
// check if key exists // check if key exists
$exists = psm_get_conf($key, false); $exists = psm_get_conf($key, false);
if($exists === false) { if ($exists === false) {
// add new config record // add new config record
$db->save( $db->save(
PSM_DB_PREFIX . 'config', PSM_DB_PREFIX.'config',
array( array(
'key' => $key, 'key' => $key,
'value' => $value, 'value' => $value,
@ -257,7 +260,7 @@ function psm_add_log_user($log_id, $user_id) {
global $db; global $db;
$db->save( $db->save(
PSM_DB_PREFIX . 'log_users', PSM_DB_PREFIX.'log_users',
array( array(
'log_id' => $log_id, 'log_id' => $log_id,
'user_id' => $user_id, 'user_id' => $user_id,
@ -295,12 +298,12 @@ function psm_log_uptime($server_id, $status, $latency) {
function psm_format_interval(DateInterval $interval) { function psm_format_interval(DateInterval $interval) {
$result = ""; $result = "";
if ($interval->y) { $result .= $interval->format("%y ") . ( ($interval->y == 1) ? psm_get_lang('system', 'year') : psm_get_lang('system', 'years') ) . " "; } 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->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->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->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->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->s) { $result .= $interval->format("%s ").(($interval->s == 1) ? psm_get_lang('system', 'second') : psm_get_lang('system', 'seconds'))." "; }
return $result; return $result;
} }
@ -316,15 +319,15 @@ function psm_log_uptime($server_id, $status, $latency) {
function psm_parse_msg($status, $type, $vars) { function psm_parse_msg($status, $type, $vars) {
$status = ($status == true) ? 'on' : 'off'; $status = ($status == true) ? 'on' : 'off';
$message = psm_get_lang('notifications', $status . '_' . $type); $message = psm_get_lang('notifications', $status.'_'.$type);
if(!$message) { if (!$message) {
return $message; return $message;
} }
$vars['date'] = date('Y-m-d H:i:s'); $vars['date'] = date('Y-m-d H:i:s');
foreach($vars as $k => $v) { foreach ($vars as $k => $v) {
$message = str_replace('%' . strtoupper($k) . '%', $v, $message); $message = str_replace('%'.strtoupper($k).'%', $v, $message);
} }
return $message; return $message;
@ -356,24 +359,24 @@ function psm_curl_get($href, $header = false, $body = true, $timeout = null, $ad
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_ENCODING, ''); curl_setopt($ch, CURLOPT_ENCODING, '');
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); curl_setopt($ch, CURLOPT_USERPWD, $website_username.":".$website_password);
} }
curl_setopt($ch, CURLOPT_URL, $href); curl_setopt($ch, CURLOPT_URL, $href);
$proxy_url = psm_get_conf('proxy_url',''); $proxy_url = psm_get_conf('proxy_url', '');
if (psm_get_conf('proxy','0') === '1') { if (psm_get_conf('proxy', '0') === '1') {
curl_setopt($ch, CURLOPT_PROXY, $proxy_url); curl_setopt($ch, CURLOPT_PROXY, $proxy_url);
$proxy_user = psm_get_conf('proxy_user',''); $proxy_user = psm_get_conf('proxy_user', '');
$proxy_password = psm_get_conf('proxy_password',''); $proxy_password = psm_get_conf('proxy_password', '');
if (!empty($proxy_user) && !empty($proxy_password)) { if (!empty($proxy_user) && !empty($proxy_password)) {
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxy_user . ':' . $proxy_password); curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxy_user.':'.$proxy_password);
} }
} }
if($add_agent) { if ($add_agent) {
curl_setopt ($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; phpservermon/'.PSM_VERSION.'; +http://www.phpservermonitor.org)'); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; phpservermon/'.PSM_VERSION.'; +http://www.phpservermonitor.org)');
} }
$result = curl_exec($ch); $result = curl_exec($ch);
@ -390,11 +393,11 @@ function psm_curl_get($href, $header = false, $body = true, $timeout = null, $ad
* @return string * @return string
*/ */
function psm_timespan($time) { function psm_timespan($time) {
if(empty($time) || $time == '0000-00-00 00:00:00') { if (empty($time) || $time == '0000-00-00 00:00:00') {
return psm_get_lang('system', 'never'); 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) { 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 // Check for Windows to find and replace the %e
// modifier correctly // modifier correctly
@ -404,13 +407,13 @@ function psm_timespan($time) {
return strftime($format, $time); return strftime($format, $time);
} }
$d = time() - $time; $d = time() - $time;
if ($d >= 60*60*24) { 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); 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 * 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 * 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 * 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 >= 60) { return psm_get_lang('system', 'a_minute_ago'); }
if ($d >= 2) { return sprintf(psm_get_lang('system', 'seconds_ago'), intval($d)); } if ($d >= 2) { return sprintf(psm_get_lang('system', 'seconds_ago'), intval($d)); }
@ -423,7 +426,7 @@ function psm_timespan($time) {
* @return string * @return string
*/ */
function psm_date($time) { function psm_date($time) {
if(empty($time) || $time == '0000-00-00 00:00:00') { if (empty($time) || $time == '0000-00-00 00:00:00') {
return psm_get_lang('system', 'never'); return psm_get_lang('system', 'never');
} }
return strftime('%x %X', strtotime($time)); return strftime('%x %X', strtotime($time));
@ -436,27 +439,27 @@ function psm_date($time) {
* @return boolean * @return boolean
*/ */
function psm_update_available() { function psm_update_available() {
if(!psm_get_conf('show_update')) { if (!psm_get_conf('show_update')) {
// user does not want updates, fair enough. // user does not want updates, fair enough.
return false; return false;
} }
$last_update = psm_get_conf('last_update_check'); $last_update = psm_get_conf('last_update_check');
if((time() - PSM_UPDATE_INTERVAL) > $last_update) { if ((time() - PSM_UPDATE_INTERVAL) > $last_update) {
// been more than a week since update, lets go // been more than a week since update, lets go
// update last check date // update last check date
psm_update_conf('last_update_check', time()); psm_update_conf('last_update_check', time());
$latest = psm_curl_get(PSM_UPDATE_URL); $latest = psm_curl_get(PSM_UPDATE_URL);
// add latest version to database // add latest version to database
if($latest !== false && strlen($latest) < 15) { if ($latest !== false && strlen($latest) < 15) {
psm_update_conf('version_update_check', $latest); psm_update_conf('version_update_check', $latest);
} }
} else { } else {
$latest = psm_get_conf('version_update_check'); $latest = psm_get_conf('version_update_check');
} }
if($latest != false) { if ($latest != false) {
$current = psm_get_conf('version'); $current = psm_get_conf('version');
return version_compare($latest, $current, '>'); return version_compare($latest, $current, '>');
} else { } else {
@ -478,7 +481,7 @@ function psm_build_mail($from_name = null, $from_email = null) {
$phpmailer->CharSet = 'UTF-8'; $phpmailer->CharSet = 'UTF-8';
$phpmailer->SMTPDebug = false; $phpmailer->SMTPDebug = false;
if(psm_get_conf('email_smtp') == '1') { if (psm_get_conf('email_smtp') == '1') {
$phpmailer->IsSMTP(); $phpmailer->IsSMTP();
$phpmailer->Host = psm_get_conf('email_smtp_host'); $phpmailer->Host = psm_get_conf('email_smtp_host');
$phpmailer->Port = psm_get_conf('email_smtp_port'); $phpmailer->Port = psm_get_conf('email_smtp_port');
@ -487,7 +490,7 @@ function psm_build_mail($from_name = null, $from_email = null) {
$smtp_user = psm_get_conf('email_smtp_username'); $smtp_user = psm_get_conf('email_smtp_username');
$smtp_pass = psm_get_conf('email_smtp_password'); $smtp_pass = psm_get_conf('email_smtp_password');
if($smtp_user != '' && $smtp_pass != '') { if ($smtp_user != '' && $smtp_pass != '') {
$phpmailer->SMTPAuth = true; $phpmailer->SMTPAuth = true;
$phpmailer->Username = $smtp_user; $phpmailer->Username = $smtp_user;
$phpmailer->Password = $smtp_pass; $phpmailer->Password = $smtp_pass;
@ -495,10 +498,10 @@ function psm_build_mail($from_name = null, $from_email = null) {
} else { } else {
$phpmailer->IsMail(); $phpmailer->IsMail();
} }
if($from_name == null) { if ($from_name == null) {
$from_name = psm_get_conf('email_from_name'); $from_name = psm_get_conf('email_from_name');
} }
if($from_email == null) { if ($from_email == null) {
$from_email = psm_get_conf('email_from_email'); $from_email = psm_get_conf('email_from_email');
} }
$phpmailer->SetFrom($from_email, $from_name); $phpmailer->SetFrom($from_email, $from_name);
@ -539,7 +542,7 @@ function psm_build_sms() {
// open the right class // open the right class
// not making this any more dynamic, because perhaps some gateways need custom settings // not making this any more dynamic, because perhaps some gateways need custom settings
switch(strtolower(psm_get_conf('sms_gateway'))) { switch (strtolower(psm_get_conf('sms_gateway'))) {
case 'mosms': case 'mosms':
$sms = new \psm\Txtmsg\Mosms(); $sms = new \psm\Txtmsg\Mosms();
break; break;
@ -603,7 +606,7 @@ function psm_build_sms() {
} }
// copy login information from the config file // copy login information from the config file
if($sms) { if ($sms) {
$sms->setLogin(psm_get_conf('sms_gateway_username'), psm_get_conf('sms_gateway_password')); $sms->setLogin(psm_get_conf('sms_gateway_username'), psm_get_conf('sms_gateway_password'));
$sms->setOriginator(psm_get_conf('sms_from')); $sms->setOriginator(psm_get_conf('sms_from'));
} }
@ -619,27 +622,27 @@ function psm_build_sms() {
* @return string * @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) { if (defined('PSM_BASE_URL') && PSM_BASE_URL !== null) {
$url = PSM_BASE_URL; $url = PSM_BASE_URL;
} else { } 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). // on Windows, dirname() adds both back- and forward slashes (http://php.net/dirname).
// for urls, we only want the forward slashes. // for urls, we only want the forward slashes.
$url .= dirname($_SERVER['SCRIPT_NAME']); $url .= dirname($_SERVER['SCRIPT_NAME']);
$url = str_replace('\\', '', $url); $url = str_replace('\\', '', $url);
} }
$url = rtrim($url, '/') . '/'; $url = rtrim($url, '/').'/';
if($params != null) { if ($params != null) {
$url .= '?'; $url .= '?';
if(is_array($params)) { if (is_array($params)) {
$delim = ($htmlentities) ? '&amp;' : '&'; $delim = ($htmlentities) ? '&amp;' : '&';
foreach($params as $k => $v) { foreach ($params as $k => $v) {
if($urlencode) { if ($urlencode) {
$v = urlencode($v); $v = urlencode($v);
} }
$url .= $delim . $k . '=' . $v; $url .= $delim.$k.'='.$v;
} }
} else { } else {
$url .= $params; $url .= $params;
@ -656,7 +659,7 @@ function psm_build_url($params = array(), $urlencode = true, $htmlentities = tru
* @return mixed * @return mixed
*/ */
function psm_GET($key, $alt = null) { function psm_GET($key, $alt = null) {
if(isset($_GET[$key])) { if (isset($_GET[$key])) {
return $_GET[$key]; return $_GET[$key];
} else { } else {
return $alt; return $alt;
@ -670,7 +673,7 @@ function psm_GET($key, $alt = null) {
* @return mixed * @return mixed
*/ */
function psm_POST($key, $alt = null) { function psm_POST($key, $alt = null) {
if(isset($_POST[$key])) { if (isset($_POST[$key])) {
return $_POST[$key]; return $_POST[$key];
} else { } else {
return $alt; return $alt;
@ -712,7 +715,7 @@ function pre($arr = null) {
*/ */
function psm_no_cache() { function psm_no_cache() {
header("Expires: Mon, 20 Dec 1998 01:00:00 GMT"); header("Expires: Mon, 20 Dec 1998 01:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: no-cache, must-revalidate"); header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache"); header("Pragma: no-cache");
} }
@ -727,11 +730,13 @@ function psm_no_cache() {
*/ */
function psm_password_encrypt($key, $password) function psm_password_encrypt($key, $password)
{ {
if(empty($password)) if (empty($password)) {
return ''; return '';
}
if (empty($key)) if (empty($key)) {
throw new \InvalidArgumentException('invalid_encryption_key'); throw new \InvalidArgumentException('invalid_encryption_key');
}
$iv = mcrypt_create_iv( $iv = mcrypt_create_iv(
mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC),
@ -739,7 +744,7 @@ function psm_password_encrypt($key, $password)
); );
$encrypted = base64_encode( $encrypted = base64_encode(
$iv . $iv.
mcrypt_encrypt( mcrypt_encrypt(
MCRYPT_RIJNDAEL_128, MCRYPT_RIJNDAEL_128,
hash('sha256', $key, true), hash('sha256', $key, true),
@ -762,11 +767,13 @@ function psm_password_encrypt($key, $password)
*/ */
function psm_password_decrypt($key, $encryptedString) function psm_password_decrypt($key, $encryptedString)
{ {
if(empty($encryptedString)) if (empty($encryptedString)) {
return ''; return '';
}
if (empty($key)) if (empty($key)) {
throw new \InvalidArgumentException('invalid_encryption_key'); throw new \InvalidArgumentException('invalid_encryption_key');
}
$data = base64_decode($encryptedString); $data = base64_decode($encryptedString);
$iv = substr($data, 0, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC)); $iv = substr($data, 0, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));
@ -798,16 +805,16 @@ class telegram
private $_message; private $_message;
private $_url; private $_url;
public function setToken ($token) { public function setToken($token) {
$this->_token = (string)$token; $this->_token = (string) $token;
} }
public function setUser ($user) { public function setUser($user) {
$this->_user = (string)$user; $this->_user = (string) $user;
} }
public function setMessage ($message) { public function setMessage($message) {
$this->_message = (string)$message; $this->_message = (string) $message;
} }
public function sendurl () { public function sendurl() {
$con = curl_init($this->_url); $con = curl_init($this->_url);
curl_setopt($con, CURLOPT_RETURNTRANSFER, true); curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
curl_setopt($con, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($con, CURLOPT_CONNECTTIMEOUT, 5);
@ -816,16 +823,16 @@ class telegram
$response = json_decode($response, true); $response = json_decode($response, true);
return $response; return $response;
} }
public function send () { public function send() {
if(!Empty($this->_token) && !Empty($this->_user) && !Empty($this->_message)) { 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); $this->_url = 'https://api.telegram.org/bot'.urlencode($this->_token).'/sendMessage?chat_id='.urlencode($this->_user).'&text='.urlencode($this->_message);
} }
return $this->sendurl(); return $this->sendurl();
} }
// Get the bots username // Get the bots username
public function getBotUsername () { public function getBotUsername() {
if(!Empty($this->_token)) { if (!Empty($this->_token)) {
$this->_url = 'https://api.telegram.org/bot' . urlencode($this->_token) . '/getMe'; $this->_url = 'https://api.telegram.org/bot'.urlencode($this->_token).'/getMe';
} }
return $this->sendurl(); return $this->sendurl();
} }

View File

@ -58,7 +58,7 @@ if (!defined('PASSWORD_DEFAULT')) {
return null; return null;
} }
if (!is_int($algo)) { 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; return null;
} }
switch ($algo) { switch ($algo) {
@ -149,7 +149,7 @@ if (!defined('PASSWORD_DEFAULT')) {
} }
$salt = substr($salt, 0, $required_salt_len); $salt = substr($salt, 0, $required_salt_len);
$hash = $hash_format . $salt; $hash = $hash_format.$salt;
$ret = crypt($password, $hash); $ret = crypt($password, $hash);

View File

@ -118,7 +118,7 @@ define('PSM_TELEGRAM_GET_ID_URL', 'https://telegram.me/cid_bot');
*/ */
//define('PSM_BASE_URL', null); //define('PSM_BASE_URL', null);
if(!defined('PSM_MODULE_DEFAULT')) { if (!defined('PSM_MODULE_DEFAULT')) {
/** /**
* Default theme * Default theme
*/ */

View File

@ -218,7 +218,7 @@ $sm_lang = array(
'서버 상태가 변경이되면 알림을 받습니다. online -> offline -> online.<br/>'. '서버 상태가 변경이되면 알림을 받습니다. online -> offline -> online.<br/>'.
'<br/><b>오프라인: </b><br/>'. '<br/><b>오프라인: </b><br/>'.
'서버가 첫번째로 오프라인이 되었을 때 알림을 받습니다. 예를들어, '. '서버가 첫번째로 오프라인이 되었을 때 알림을 받습니다. 예를들어, '.
'cron이 매 15분이고 오전1시 부터 오전6시까지 다운되었을때 오전1시에 한번 알림을 받습니다.<br />' . 'cron이 매 15분이고 오전1시 부터 오전6시까지 다운되었을때 오전1시에 한번 알림을 받습니다.<br />'.
'<br/><b>항상: </b><br/>'. '<br/><b>항상: </b><br/>'.
'사이트가 다운되었을 때 매시간 알림을 받습니다.', '사이트가 다운되었을 때 매시간 알림을 받습니다.',

View File

@ -199,13 +199,13 @@ $sm_lang = array(
'pushover_api_token' => 'Pushover API žeton', 'pushover_api_token' => 'Pushover API žeton',
'pushover_api_token_description' => 'Pred uporabo storitve Pushover, morate na njihovi spletni strani <a href="%1$s" target="_blank">registrirati aplikacijo</a>, tukaj pa vnesti API žeton.', 'pushover_api_token_description' => 'Pred uporabo storitve Pushover, morate na njihovi spletni strani <a href="%1$s" target="_blank">registrirati aplikacijo</a>, tukaj pa vnesti API žeton.',
'alert_type' => 'Izberite kdaj naj se vam pošljejo obvestila.', 'alert_type' => 'Izberite kdaj naj se vam pošljejo obvestila.',
'alert_type_description' => '<b>Sprememba statusa:</b> ' . 'alert_type_description' => '<b>Sprememba statusa:</b> '.
'Obvestilo boste dobili ob vsaki spremembi statusa, torej iz delujoč -> nedelujoč ter nedelujoč -> delujoč.<br/>' . 'Obvestilo boste dobili ob vsaki spremembi statusa, torej iz delujoč -> nedelujoč ter nedelujoč -> delujoč.<br/>'.
'<br /><b>Nedelujoč:</b> ' . '<br /><b>Nedelujoč:</b> '.
'Obvestilo boste dobili samo, ko se bo strežnik PRVIKRAT prenehal odzivati. Na primer:' . 'Obvestilo boste dobili samo, ko se bo strežnik PRVIKRAT prenehal odzivati. Na primer:'.
'nastavljeno imate preverjanje strežnikov vsakih 15 minut. Strežnik preneha delovati ob 13h in ostane nedelujoč do 18h. ' . 'nastavljeno imate preverjanje strežnikov vsakih 15 minut. Strežnik preneha delovati ob 13h in ostane nedelujoč do 18h. '.
'Dobili boste obvestilo samo ob 13h.<br/>' . 'Dobili boste obvestilo samo ob 13h.<br/>'.
'<br><b>Vedno:</b> ' . '<br><b>Vedno:</b> '.
'Obvestilo boste dobili vedno, ko se izvede skripta za preverjanje in strežnik ne deluje, pa čeprav bo strežnik nedelujoč več ur.', 'Obvestilo boste dobili vedno, ko se izvede skripta za preverjanje in strežnik ne deluje, pa čeprav bo strežnik nedelujoč več ur.',
'alert_type_status' => 'Sprememba statusa', 'alert_type_status' => 'Sprememba statusa',
'alert_type_offline' => 'Nedelujoč', 'alert_type_offline' => 'Nedelujoč',
@ -226,9 +226,9 @@ $sm_lang = array(
'settings_log' => 'Hramba dnevniških zapisov', 'settings_log' => 'Hramba dnevniških zapisov',
'auto_refresh' => 'Samodejno posodabljanje', 'auto_refresh' => 'Samodejno posodabljanje',
'auto_refresh_servers' => 'auto_refresh_servers' =>
'Samodejno posodabljanje pregleda statusa strežnikov.<br/>' . 'Samodejno posodabljanje pregleda statusa strežnikov.<br/>'.
'<span class="small">' . '<span class="small">'.
'Čas v sekundah. Če je vrednost 0 se stran ne bo samodejno posodabljala.' . 'Čas v sekundah. Če je vrednost 0 se stran ne bo samodejno posodabljala.'.
'</span>', '</span>',
'seconds' => 'sekund', 'seconds' => 'sekund',
'test' => 'Test', 'test' => 'Test',

View File

@ -156,16 +156,16 @@ abstract class AbstractController implements ControllerInterface {
* @return \Symfony\Component\HttpFoundation\Response * @return \Symfony\Component\HttpFoundation\Response
*/ */
public function run($action = null) { public function run($action = null) {
if($action === null) { if ($action === null) {
$action = psm_GET('action', psm_POST('action', $this->action_default)); $action = psm_GET('action', psm_POST('action', $this->action_default));
} }
$this->xhr = (bool) psm_GET('xhr', psm_POST('xhr', false)); $this->xhr = (bool) psm_GET('xhr', psm_POST('xhr', false));
if(!in_array($action, $this->actions) || !($result = $this->runAction($action))) { if (!in_array($action, $this->actions) || !($result = $this->runAction($action))) {
$result = $this->runAction($this->action_default); $result = $this->runAction($this->action_default);
} }
if($result instanceof Response) { if ($result instanceof Response) {
return $result; return $result;
} }
@ -181,14 +181,14 @@ abstract class AbstractController implements ControllerInterface {
* @return mixed FALSE when action couldnt be initialized, response otherwise * @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 (isset($this->user_level_required_actions[$action])) {
if($this->getUser()->getUserLevel() > $this->user_level_required_actions[$action]) { if ($this->getUser()->getUserLevel() > $this->user_level_required_actions[$action]) {
// user is not allowed to access this action.. // user is not allowed to access this action..
return false; return false;
} }
} }
$method = 'execute' . ucfirst($action); $method = 'execute'.ucfirst($action);
if(method_exists($this, $method)) { if (method_exists($this, $method)) {
$this->action = $action; $this->action = $action;
$result = $this->$method(); $result = $this->$method();
// if result from execute is null, no return value given so return true to indicate a successful execute // if result from execute is null, no return value given so return true to indicate a successful execute
@ -206,43 +206,43 @@ abstract class AbstractController implements ControllerInterface {
* @return \Symfony\Component\HttpFoundation\Response * @return \Symfony\Component\HttpFoundation\Response
*/ */
protected function createHTML($html = null) { protected function createHTML($html = null) {
if(!$this->xhr) { if (!$this->xhr) {
// in XHR mode, we will not add the main template // in XHR mode, we will not add the main template
$tpl_data = array( $tpl_data = array(
'title' => strtoupper(psm_get_lang('system', 'title')), 'title' => strtoupper(psm_get_lang('system', 'title')),
'label_back_to_top' => psm_get_lang('system', 'back_to_top'), 'label_back_to_top' => psm_get_lang('system', 'back_to_top'),
'add_footer' => $this->add_footer, 'add_footer' => $this->add_footer,
'version' => 'v' . PSM_VERSION, 'version' => 'v'.PSM_VERSION,
'messages' => $this->getMessages(), 'messages' => $this->getMessages(),
'html_content' => $html, 'html_content' => $html,
); );
// add menu to page? // add menu to page?
if($this->add_menu) { if ($this->add_menu) {
$tpl_data['html_menu'] = $this->createHTMLMenu(); $tpl_data['html_menu'] = $this->createHTMLMenu();
} }
// add header accessories to page ? // add header accessories to page ?
if($this->header_accessories) { if ($this->header_accessories) {
$tpl_data['header_accessories'] = $this->header_accessories; $tpl_data['header_accessories'] = $this->header_accessories;
} }
// add modal dialog to page ? // add modal dialog to page ?
if(sizeof($this->modal)) { if (sizeof($this->modal)) {
$html_modal = ''; $html_modal = '';
foreach($this->modal as $modal) { foreach ($this->modal as $modal) {
$html_modal .= $modal->createHTML(); $html_modal .= $modal->createHTML();
} }
$tpl_data['html_modal'] = $html_modal; $tpl_data['html_modal'] = $html_modal;
} }
// add sidebar to page? // add sidebar to page?
if($this->sidebar !== null) { if ($this->sidebar !== null) {
$tpl_data['html_sidebar'] = $this->sidebar->createHTML(); $tpl_data['html_sidebar'] = $this->sidebar->createHTML();
} }
if(psm_update_available()) { 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) { if ($this->black_background) {
$tpl_data['body_class'] = 'black_background'; $tpl_data['body_class'] = 'black_background';
} }
$html = $this->twig->render('main/body.tpl.html', $tpl_data); $html = $this->twig->render('main/body.tpl.html', $tpl_data);
@ -268,7 +268,7 @@ abstract class AbstractController implements ControllerInterface {
'url_logout' => psm_build_url(array('logout' => 1)), 'url_logout' => psm_build_url(array('logout' => 1)),
); );
switch($ulvl) { switch ($ulvl) {
case PSM_USER_ADMIN: case PSM_USER_ADMIN:
$items = array('server_status', 'server', 'server_log', 'user', 'config', 'server_update'); $items = array('server_status', 'server', 'server_log', 'user', 'config', 'server_update');
break; break;
@ -280,7 +280,7 @@ abstract class AbstractController implements ControllerInterface {
break; break;
} }
$tpl_data['menu'] = array(); $tpl_data['menu'] = array();
foreach($items as $key) { foreach ($items as $key) {
$tpl_data['menu'][] = array( $tpl_data['menu'][] = array(
'active' => ($key == psm_GET('mod')) ? 'active' : '', 'active' => ($key == psm_GET('mod')) ? 'active' : '',
'url' => psm_build_url(array('mod' => $key)), 'url' => psm_build_url(array('mod' => $key)),
@ -288,7 +288,7 @@ abstract class AbstractController implements ControllerInterface {
); );
} }
if($ulvl != PSM_USER_ANONYMOUS) { if ($ulvl != PSM_USER_ANONYMOUS) {
$user = $this->getUser()->getUser(); $user = $this->getUser()->getUser();
$tpl_data['label_usermenu'] = str_replace( $tpl_data['label_usermenu'] = str_replace(
'%user_name%', '%user_name%',
@ -324,15 +324,15 @@ abstract class AbstractController implements ControllerInterface {
* @see getAction() * @see getAction()
*/ */
protected function setActions($actions, $default = null, $append = true) { protected function setActions($actions, $default = null, $append = true) {
if(!is_array($actions)) { if (!is_array($actions)) {
$actions = array($actions); $actions = array($actions);
} }
if($append) { if ($append) {
$this->actions = array_merge($actions); $this->actions = array_merge($actions);
} else { } else {
$this->actions = $actions; $this->actions = $actions;
} }
if($default !== null) { if ($default !== null) {
$this->action_default = $default; $this->action_default = $default;
} }
return $this; return $this;
@ -355,10 +355,10 @@ abstract class AbstractController implements ControllerInterface {
* @see getMessages() * @see getMessages()
*/ */
public function addMessage($msg, $shortcode = 'info') { public function addMessage($msg, $shortcode = 'info') {
if(!is_array($msg)) { if (!is_array($msg)) {
$msg = array($msg); $msg = array($msg);
} }
switch($shortcode) { switch ($shortcode) {
case 'error': case 'error':
$icon = 'exclamation-sign'; $icon = 'exclamation-sign';
break; break;
@ -373,7 +373,7 @@ abstract class AbstractController implements ControllerInterface {
break; break;
} }
foreach($msg as $m) { foreach ($msg as $m) {
$this->messages[] = array( $this->messages[] = array(
'message' => $m, 'message' => $m,
'shortcode' => $shortcode, 'shortcode' => $shortcode,
@ -391,7 +391,7 @@ abstract class AbstractController implements ControllerInterface {
*/ */
public function getMessages($clear = true) { public function getMessages($clear = true) {
$msgs = $this->messages; $msgs = $this->messages;
if($clear) { if ($clear) {
$this->messages = array(); $this->messages = array();
} }
return $msgs; return $msgs;
@ -425,10 +425,10 @@ abstract class AbstractController implements ControllerInterface {
* @see setMinUserLevelRequired() * @see setMinUserLevelRequired()
*/ */
public function setMinUserLevelRequiredForAction($level, $actions) { public function setMinUserLevelRequiredForAction($level, $actions) {
if(!is_array($actions)) { if (!is_array($actions)) {
$actions = array($actions); $actions = array($actions);
} }
foreach($actions as $action) { foreach ($actions as $action) {
$this->user_level_required_actions[$action] = intval($level); $this->user_level_required_actions[$action] = intval($level);
} }
return $this; return $this;

View File

@ -39,7 +39,7 @@ class ConfigModule implements ModuleInterface {
public function getControllers() { public function getControllers() {
return array( return array(
'config' => __NAMESPACE__ . '\Controller\ConfigController', 'config' => __NAMESPACE__.'\Controller\ConfigController',
); );
} }

View File

@ -94,13 +94,13 @@ class ConfigController extends AbstractController {
$tpl_data = $this->getLabels(); $tpl_data = $this->getLabels();
$config_db = $this->db->select( $config_db = $this->db->select(
PSM_DB_PREFIX . 'config', PSM_DB_PREFIX.'config',
null, null,
array('key', 'value') array('key', 'value')
); );
$config = array(); $config = array();
foreach($config_db as $entry) { foreach ($config_db as $entry) {
$config[$entry['key']] = $entry['value']; $config[$entry['key']] = $entry['value'];
} }
@ -110,7 +110,7 @@ class ConfigController extends AbstractController {
? $config['language'] ? $config['language']
: 'en_US'; : 'en_US';
$tpl_data['languages'] = array(); $tpl_data['languages'] = array();
foreach($lang_keys as $key => $label) { foreach ($lang_keys as $key => $label) {
$tpl_data['languages'][] = array( $tpl_data['languages'][] = array(
'value' => $key, 'value' => $key,
'label' => $label, 'label' => $label,
@ -123,38 +123,38 @@ class ConfigController extends AbstractController {
? $config['sms_gateway'] ? $config['sms_gateway']
: current($sms_gateways); : current($sms_gateways);
$tpl_data['sms_gateways'] = array(); $tpl_data['sms_gateways'] = array();
foreach($sms_gateways as $sms_gateway => $label) { foreach ($sms_gateways as $sms_gateway => $label) {
$tpl_data['sms_gateways'][] = array( $tpl_data['sms_gateways'][] = array(
'value' => $sms_gateway, 'value' => $sms_gateway,
'label' => $label, 'label' => $label,
); );
} }
// @todo these selected values can easily be rewritten in the template using twig // @todo these selected values can easily be rewritten in the template using twig
$tpl_data['alert_type_selected_' . $config['alert_type']] = 'selected="selected"'; $tpl_data['alert_type_selected_'.$config['alert_type']] = 'selected="selected"';
$smtp_sec = isset($config['email_smtp_security']) ? $config['email_smtp_security'] : ''; $smtp_sec = isset($config['email_smtp_security']) ? $config['email_smtp_security'] : '';
$tpl_data['email_smtp_security_selected_' . $smtp_sec] = 'selected="selected"'; $tpl_data['email_smtp_security_selected_'.$smtp_sec] = 'selected="selected"';
$tpl_data['auto_refresh_servers'] = (isset($config['auto_refresh_servers'])) ? $config['auto_refresh_servers'] : '0'; $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['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['password_encrypt_key'] = (isset($config['password_encrypt_key'])) ? $config['password_encrypt_key'] : sha1(microtime());
foreach($this->checkboxes as $input_key) { foreach ($this->checkboxes as $input_key) {
$tpl_data[$input_key . '_checked'] = $tpl_data[$input_key.'_checked'] =
(isset($config[$input_key]) && (int) $config[$input_key] == 1) (isset($config[$input_key]) && (int) $config[$input_key] == 1)
? 'checked="checked"' ? 'checked="checked"'
: ''; : '';
} }
foreach($this->fields as $input_key) { foreach ($this->fields as $input_key) {
$tpl_data[$input_key] = (isset($config[$input_key])) ? $config[$input_key] : ''; $tpl_data[$input_key] = (isset($config[$input_key])) ? $config[$input_key] : '';
} }
$tpl_data[$this->default_tab . '_active'] = 'active'; $tpl_data[$this->default_tab.'_active'] = 'active';
$testmodals = array('email', 'sms', 'pushover', 'telegram'); $testmodals = array('email', 'sms', 'pushover', 'telegram');
foreach($testmodals as $modal_id) { 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); $this->addModal($modal);
$modal->setTitle(psm_get_lang('servers', 'send_' . $modal_id)); $modal->setTitle(psm_get_lang('servers', 'send_'.$modal_id));
$modal->setMessage(psm_get_lang('config', 'test_' . $modal_id)); $modal->setMessage(psm_get_lang('config', 'test_'.$modal_id));
$modal->setOKButtonLabel(psm_get_lang('config', 'send')); $modal->setOKButtonLabel(psm_get_lang('config', 'send'));
} }
@ -166,7 +166,7 @@ class ConfigController extends AbstractController {
* and save it to the database * and save it to the database
*/ */
protected function executeSave() { protected function executeSave() {
if(!empty($_POST)) { if (!empty($_POST)) {
// save new config // save new config
$clean = array( $clean = array(
'language' => $_POST['language'], 'language' => $_POST['language'],
@ -180,44 +180,44 @@ class ConfigController extends AbstractController {
'log_retention_period' => intval(psm_POST('log_retention_period', 365)), 'log_retention_period' => intval(psm_POST('log_retention_period', 365)),
'password_encrypt_key' => psm_POST('password_encrypt_key', sha1(microtime())), 'password_encrypt_key' => psm_POST('password_encrypt_key', sha1(microtime())),
); );
foreach($this->checkboxes as $input_key) { foreach ($this->checkboxes as $input_key) {
$clean[$input_key] = (isset($_POST[$input_key])) ? '1': '0'; $clean[$input_key] = (isset($_POST[$input_key])) ? '1' : '0';
} }
foreach($this->fields as $input_key) { foreach ($this->fields as $input_key) {
if(isset($_POST[$input_key])) { if (isset($_POST[$input_key])) {
$clean[$input_key] = $_POST[$input_key]; $clean[$input_key] = $_POST[$input_key];
} }
} }
$language_refresh = ($clean['language'] != psm_get_conf('language')); $language_refresh = ($clean['language'] != psm_get_conf('language'));
foreach($clean as $key => $value) { foreach ($clean as $key => $value) {
psm_update_conf($key, $value); psm_update_conf($key, $value);
} }
$this->addMessage(psm_get_lang('config', 'updated'), 'success'); $this->addMessage(psm_get_lang('config', 'updated'), 'success');
if(!empty($_POST['test_email'])) { if (!empty($_POST['test_email'])) {
$this->testEmail(); $this->testEmail();
} elseif(!empty($_POST['test_sms'])) { } elseif (!empty($_POST['test_sms'])) {
$this->testSMS(); $this->testSMS();
} elseif(!empty($_POST['test_pushover'])) { } elseif (!empty($_POST['test_pushover'])) {
$this->testPushover(); $this->testPushover();
} elseif(!empty($_POST['test_telegram'])) { } elseif (!empty($_POST['test_telegram'])) {
$this->testTelegram(); $this->testTelegram();
} }
if($language_refresh) { if ($language_refresh) {
header('Location: ' . psm_build_url(array('mod' => 'config'), true, false)); header('Location: '.psm_build_url(array('mod' => 'config'), true, false));
trigger_error("Redirect failed.", E_USER_ERROR); trigger_error("Redirect failed.", E_USER_ERROR);
} }
if(isset($_POST['general_submit'])) { if (isset($_POST['general_submit'])) {
$this->default_tab = 'general'; $this->default_tab = 'general';
} elseif(isset($_POST['email_submit']) || !empty($_POST['test_email'])) { } elseif (isset($_POST['email_submit']) || !empty($_POST['test_email'])) {
$this->default_tab = 'email'; $this->default_tab = 'email';
} elseif(isset($_POST['sms_submit']) || !empty($_POST['test_sms'])) { } elseif (isset($_POST['sms_submit']) || !empty($_POST['test_sms'])) {
$this->default_tab = 'sms'; $this->default_tab = 'sms';
} elseif(isset($_POST['pushover_submit']) || !empty($_POST['test_pushover'])) { } elseif (isset($_POST['pushover_submit']) || !empty($_POST['test_pushover'])) {
$this->default_tab = 'pushover'; $this->default_tab = 'pushover';
} elseif(isset($_POST['telegram_submit']) || !empty($_POST['test_telegram'])) { } elseif (isset($_POST['telegram_submit']) || !empty($_POST['test_telegram'])) {
$this->default_tab = 'telegram'; $this->default_tab = 'telegram';
} }
} }
@ -238,10 +238,10 @@ class ConfigController extends AbstractController {
$mail->AltBody = str_replace('<br/>', "\n", $message); $mail->AltBody = str_replace('<br/>', "\n", $message);
$user = $this->getUser()->getUser(); $user = $this->getUser()->getUser();
$mail->AddAddress($user->email, $user->name); $mail->AddAddress($user->email, $user->name);
if($mail->Send()) { if ($mail->Send()) {
$this->addMessage(psm_get_lang('config', 'email_sent'), 'success'); $this->addMessage(psm_get_lang('config', 'email_sent'), 'success');
} else { } else {
$this->addMessage(psm_get_lang('config', 'email_error') . ': ' . $mail->ErrorInfo, 'error'); $this->addMessage(psm_get_lang('config', 'email_error').': '.$mail->ErrorInfo, 'error');
} }
} }
@ -252,14 +252,14 @@ class ConfigController extends AbstractController {
*/ */
protected function testSMS() { protected function testSMS() {
$sms = psm_build_sms(); $sms = psm_build_sms();
if($sms) { if ($sms) {
$user = $this->getUser()->getUser(); $user = $this->getUser()->getUser();
if(empty($user->mobile)) { if (empty($user->mobile)) {
$this->addMessage(psm_get_lang('config', 'sms_error_nomobile'), 'error'); $this->addMessage(psm_get_lang('config', 'sms_error_nomobile'), 'error');
} else { } else {
$sms->addRecipients($user->mobile); $sms->addRecipients($user->mobile);
$result = $sms->sendSMS(psm_get_lang('config', 'test_message')); $result = $sms->sendSMS(psm_get_lang('config', 'test_message'));
if($result === 1) { if ($result === 1) {
$this->addMessage(psm_get_lang('config', 'sms_sent'), 'success'); $this->addMessage(psm_get_lang('config', 'sms_sent'), 'success');
} else { } else {
$this->addMessage(sprintf(psm_get_lang('config', 'sms_error'), $result), 'error'); $this->addMessage(sprintf(psm_get_lang('config', 'sms_error'), $result), 'error');
@ -279,24 +279,24 @@ class ConfigController extends AbstractController {
$user = $this->getUser()->getUser(); $user = $this->getUser()->getUser();
$apiToken = psm_get_conf('pushover_api_token'); $apiToken = psm_get_conf('pushover_api_token');
if(empty($apiToken)) { if (empty($apiToken)) {
$this->addMessage(psm_get_lang('config', 'pushover_error_noapp'), 'error'); $this->addMessage(psm_get_lang('config', 'pushover_error_noapp'), 'error');
} elseif(empty($user->pushover_key)) { } elseif (empty($user->pushover_key)) {
$this->addMessage(psm_get_lang('config', 'pushover_error_nokey'), 'error'); $this->addMessage(psm_get_lang('config', 'pushover_error_nokey'), 'error');
} else { } else {
$pushover->setPriority(0); $pushover->setPriority(0);
$pushover->setTitle(psm_get_lang('config', 'test_subject')); $pushover->setTitle(psm_get_lang('config', 'test_subject'));
$pushover->setMessage(psm_get_lang('config', 'test_message')); $pushover->setMessage(psm_get_lang('config', 'test_message'));
$pushover->setUser($user->pushover_key); $pushover->setUser($user->pushover_key);
if($user->pushover_device != '') { if ($user->pushover_device != '') {
$pushover->setDevice($user->pushover_device); $pushover->setDevice($user->pushover_device);
} }
$result = $pushover->send(); $result = $pushover->send();
if(isset($result['output']->status) && $result['output']->status == 1) { if (isset($result['output']->status) && $result['output']->status == 1) {
$this->addMessage(psm_get_lang('config', 'pushover_sent'), 'success'); $this->addMessage(psm_get_lang('config', 'pushover_sent'), 'success');
} else { } else {
if(isset($result['output']->errors->error)) { if (isset($result['output']->errors->error)) {
$error = $result['output']->errors->error; $error = $result['output']->errors->error;
} else { } else {
$error = 'Unknown'; $error = 'Unknown';
@ -316,9 +316,9 @@ class ConfigController extends AbstractController {
$user = $this->getUser()->getUser(); $user = $this->getUser()->getUser();
$apiToken = psm_get_conf('telegram_api_token'); $apiToken = psm_get_conf('telegram_api_token');
if(empty($apiToken)) { if (empty($apiToken)) {
$this->addMessage(psm_get_lang('config', 'telegram_error_notoken'), 'error'); $this->addMessage(psm_get_lang('config', 'telegram_error_notoken'), 'error');
} elseif(empty($user->telegram_id)) { } elseif (empty($user->telegram_id)) {
$this->addMessage(psm_get_lang('config', 'telegram_error_noid'), 'error'); $this->addMessage(psm_get_lang('config', 'telegram_error_noid'), 'error');
} else { } else {
$telegram->setMessage(psm_get_lang('config', 'test_message')); $telegram->setMessage(psm_get_lang('config', 'test_message'));
@ -326,10 +326,10 @@ class ConfigController extends AbstractController {
$result = $telegram->send(); $result = $telegram->send();
if(isset($result['ok']) && $result['ok'] != false) { if (isset($result['ok']) && $result['ok'] != false) {
$this->addMessage(psm_get_lang('config', 'telegram_sent'), 'success'); $this->addMessage(psm_get_lang('config', 'telegram_sent'), 'success');
} else { } else {
if(isset($result['description'])) { if (isset($result['description'])) {
$error = $result['description']; $error = $result['description'];
} else { } else {
$error = 'Unknown'; $error = 'Unknown';

View File

@ -39,7 +39,7 @@ class ErrorModule implements ModuleInterface {
public function getControllers() { public function getControllers() {
return array( return array(
'error' => __NAMESPACE__ . '\Controller\ErrorController', 'error' => __NAMESPACE__.'\Controller\ErrorController',
); );
} }

View File

@ -51,8 +51,8 @@ class InstallController extends AbstractController {
$this->setCSRFKey('install'); $this->setCSRFKey('install');
$this->addMenu(false); $this->addMenu(false);
$this->path_config = PSM_PATH_SRC . '../config.php'; $this->path_config = PSM_PATH_SRC.'../config.php';
$this->path_config_old = PSM_PATH_SRC . '../config.inc.php'; $this->path_config_old = PSM_PATH_SRC.'../config.inc.php';
$this->setActions(array( $this->setActions(array(
'index', 'config', 'install' 'index', 'config', 'install'
@ -69,27 +69,27 @@ class InstallController extends AbstractController {
$errors = 0; $errors = 0;
$phpv = phpversion(); $phpv = phpversion();
if(version_compare($phpv, '5.3.7', '<')) { if (version_compare($phpv, '5.3.7', '<')) {
$errors++; $errors++;
$this->addMessage('PHP 5.3.7+ is required to run PHP Server Monitor.', 'error'); $this->addMessage('PHP 5.3.7+ is required to run PHP Server Monitor.', 'error');
} else { } else {
$this->addMessage('PHP version: ' . $phpv, 'success'); $this->addMessage('PHP version: '.$phpv, 'success');
} }
if(!function_exists('curl_init')) { if (!function_exists('curl_init')) {
$this->addMessage('PHP is installed without the cURL module. Please install cURL.', 'warning'); $this->addMessage('PHP is installed without the cURL module. Please install cURL.', 'warning');
} else { } else {
$this->addMessage('PHP cURL module found', 'success'); $this->addMessage('PHP cURL module found', 'success');
} }
if(!in_array('mysql', \PDO::getAvailableDrivers())) { if (!in_array('mysql', \PDO::getAvailableDrivers())) {
$errors++; $errors++;
$this->addMessage('The PDO MySQL driver needs to be installed.', 'error'); $this->addMessage('The PDO MySQL driver needs to be installed.', 'error');
} }
if(!ini_get('date.timezone')) { 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">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">this page</a> for more info.', 'warning');
} }
if($errors > 0) { 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( return $this->twig->render('module/install/index.tpl.html', array(
@ -104,13 +104,13 @@ class InstallController extends AbstractController {
$tpl_name = 'module/install/config_new.tpl.html'; $tpl_name = 'module/install/config_new.tpl.html';
$tpl_data = array(); $tpl_data = array();
if(!defined('PSM_DB_PREFIX')) { if (!defined('PSM_DB_PREFIX')) {
// first detect "old" config file (2.0) // first detect "old" config file (2.0)
if(file_exists($this->path_config_old)) { if (file_exists($this->path_config_old)) {
// oldtimer huh // oldtimer huh
$this->addMessage('Configuration file for v2.0 found.', 'success'); $this->addMessage('Configuration file for v2.0 found.', 'success');
$this->addMessage( $this->addMessage(
'The location of the config file has been changed since v2.0.<br/>' . 'The location of the config file has been changed since v2.0.<br/>'.
'We will attempt to create a new config file for you.' 'We will attempt to create a new config file for you.'
, 'warning'); , 'warning');
$values = $this->parseConfig20(); $values = $this->parseConfig20();
@ -130,8 +130,8 @@ class InstallController extends AbstractController {
); );
$changed = false; $changed = false;
foreach($config as $ckey => &$cvalue) { foreach ($config as $ckey => &$cvalue) {
if(isset($values[$ckey])) { if (isset($values[$ckey])) {
$changed = true; $changed = true;
$cvalue = $values[$ckey]; $cvalue = $values[$ckey];
} }
@ -139,7 +139,7 @@ class InstallController extends AbstractController {
// add config to template data for prefilling the form // add config to template data for prefilling the form
$tpl_data = $config; $tpl_data = $config;
if($changed) { if ($changed) {
// test db connection // test db connection
$this->db = new \psm\Service\Database( $this->db = new \psm\Service\Database(
$config['db_host'], $config['db_host'],
@ -149,10 +149,10 @@ class InstallController extends AbstractController {
$config['db_port'] $config['db_port']
); );
if($this->db->status()) { if ($this->db->status()) {
$this->addMessage('Connection to MySQL successful.', 'success'); $this->addMessage('Connection to MySQL successful.', 'success');
$config_php = $this->writeConfigFile($config); $config_php = $this->writeConfigFile($config);
if($config_php === true) { if ($config_php === true) {
$this->addMessage('Configuration file written successfully.', 'success'); $this->addMessage('Configuration file written successfully.', 'success');
} else { } else {
$this->addMessage('Config file is not writable, we cannot save it for you.', 'error'); $this->addMessage('Config file is not writable, we cannot save it for you.', 'error');
@ -165,11 +165,11 @@ class InstallController extends AbstractController {
} }
} }
if(defined('PSM_DB_PREFIX')) { if (defined('PSM_DB_PREFIX')) {
if($this->db->status()) { if ($this->db->status()) {
if($this->isUpgrade()) { if ($this->isUpgrade()) {
// upgrade // upgrade
if(version_compare($this->getPreviousVersion(), '3.0.0', '<')) { if (version_compare($this->getPreviousVersion(), '3.0.0', '<')) {
// upgrade from before 3.0, does not have passwords yet.. create new user first // 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.', 'info'); $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.', 'info');
$tpl_name = 'module/install/config_new_user.tpl.html'; $tpl_name = 'module/install/config_new_user.tpl.html';
@ -196,7 +196,7 @@ class InstallController extends AbstractController {
* Execute the install and upgrade process to a newer version * Execute the install and upgrade process to a newer version
*/ */
protected function executeInstall() { protected function executeInstall() {
if(!defined('PSM_DB_PREFIX') || !$this->db->status()) { if (!defined('PSM_DB_PREFIX') || !$this->db->status()) {
return $this->executeConfig(); return $this->executeConfig();
} }
$add_user = false; $add_user = false;
@ -222,23 +222,23 @@ class InstallController extends AbstractController {
$logger = array($this, 'addMessage'); $logger = array($this, 'addMessage');
$installer = new \psm\Util\Install\Installer($this->db, $logger); $installer = new \psm\Util\Install\Installer($this->db, $logger);
if($this->isUpgrade()) { if ($this->isUpgrade()) {
$this->addMessage('Upgrade process started.', 'info'); $this->addMessage('Upgrade process started.', 'info');
$version_from = $this->getPreviousVersion(); $version_from = $this->getPreviousVersion();
if($version_from === false) { if ($version_from === false) {
$this->addMessage('Unable to locate your previous version. Please run a fresh install.', 'error'); $this->addMessage('Unable to locate your previous version. Please run a fresh install.', 'error');
} else { } else {
if(version_compare($version_from, PSM_VERSION, '=')) { if (version_compare($version_from, PSM_VERSION, '=')) {
$this->addMessage('Your installation is already at the latest version.', 'success'); $this->addMessage('Your installation is already at the latest version.', 'success');
} elseif(version_compare($version_from, PSM_VERSION, '>')) { } elseif (version_compare($version_from, PSM_VERSION, '>')) {
$this->addMessage('This installer does not support downgrading, sorry.', 'error'); $this->addMessage('This installer does not support downgrading, sorry.', 'error');
} else { } else {
$this->addMessage('Upgrading from ' . $version_from . ' to ' . PSM_VERSION, 'info'); $this->addMessage('Upgrading from '.$version_from.' to '.PSM_VERSION, 'info');
$installer->upgrade($version_from, PSM_VERSION); $installer->upgrade($version_from, PSM_VERSION);
} }
if(version_compare($version_from, '3.0.0', '<')) { if (version_compare($version_from, '3.0.0', '<')) {
$add_user = true; $add_user = true;
} }
} }
@ -248,8 +248,8 @@ class InstallController extends AbstractController {
$validator->username_new($new_user['user_name']); $validator->username_new($new_user['user_name']);
$validator->email($new_user['email']); $validator->email($new_user['email']);
$validator->password($new_user['password'], $new_user['password_repeat']); $validator->password($new_user['password'], $new_user['password_repeat']);
} catch(\InvalidArgumentException $e) { } catch (\InvalidArgumentException $e) {
$this->addMessage(psm_get_lang('users', 'error_' . $e->getMessage()), 'error'); $this->addMessage(psm_get_lang('users', 'error_'.$e->getMessage()), 'error');
return $this->executeConfig(); return $this->executeConfig();
} }
@ -259,10 +259,10 @@ class InstallController extends AbstractController {
$add_user = true; $add_user = true;
} }
if($add_user) { if ($add_user) {
unset($new_user['password_repeat']); unset($new_user['password_repeat']);
$user_id = $this->db->save(PSM_DB_PREFIX.'users', $new_user); $user_id = $this->db->save(PSM_DB_PREFIX.'users', $new_user);
if(intval($user_id) > 0) { if (intval($user_id) > 0) {
$this->getUser()->changePassword($user_id, $new_user['password']); $this->getUser()->changePassword($user_id, $new_user['password']);
$this->addMessage('User account has been created successfully.', 'success'); $this->addMessage('User account has been created successfully.', 'success');
} else { } else {
@ -283,7 +283,7 @@ class InstallController extends AbstractController {
protected function writeConfigFile($array_config) { protected function writeConfigFile($array_config) {
$config = "<?php".PHP_EOL; $config = "<?php".PHP_EOL;
foreach($array_config as $key => $value) { foreach ($array_config as $key => $value) {
$line = "define('PSM_{key}', '{value}');".PHP_EOL; $line = "define('PSM_{key}', '{value}');".PHP_EOL;
$line = str_replace( $line = str_replace(
array('{key}', '{value}'), array('{key}', '{value}'),
@ -292,7 +292,7 @@ class InstallController extends AbstractController {
); );
$config .= $line; $config .= $line;
} }
if(is_writeable($this->path_config)) { if (is_writeable($this->path_config)) {
file_put_contents($this->path_config, $config); file_put_contents($this->path_config, $config);
return true; return true;
} else { } else {
@ -316,7 +316,7 @@ class InstallController extends AbstractController {
); );
$pattern = "/define\('SM_{key}', '(.*?)'/u"; $pattern = "/define\('SM_{key}', '(.*?)'/u";
foreach($vars as $key => $value) { foreach ($vars as $key => $value) {
$pattern_key = str_replace('{key}', strtoupper($key), $pattern); $pattern_key = str_replace('{key}', strtoupper($key), $pattern);
preg_match($pattern_key, $config_old, $value_matches); preg_match($pattern_key, $config_old, $value_matches);
$vars[$key] = (isset($value_matches[1])) ? $value_matches[1] : ''; $vars[$key] = (isset($value_matches[1])) ? $value_matches[1] : '';
@ -329,7 +329,7 @@ class InstallController extends AbstractController {
* Is it an upgrade or install? * Is it an upgrade or install?
*/ */
protected function isUpgrade() { protected function isUpgrade() {
if(!$this->db->status()) { if (!$this->db->status()) {
return false; return false;
} }
return $this->db->ifTableExists(PSM_DB_PREFIX.'config'); return $this->db->ifTableExists(PSM_DB_PREFIX.'config');
@ -340,15 +340,15 @@ class InstallController extends AbstractController {
* @return boolean|string FALSE on failure, string otherwise * @return boolean|string FALSE on failure, string otherwise
*/ */
protected function getPreviousVersion() { protected function getPreviousVersion() {
if(!$this->isUpgrade()) { if (!$this->isUpgrade()) {
return false; return false;
} }
$version_conf = $this->db->selectRow(PSM_DB_PREFIX . 'config', array('key' => 'version'), array('value')); $version_conf = $this->db->selectRow(PSM_DB_PREFIX.'config', array('key' => 'version'), array('value'));
if(empty($version_conf)) { if (empty($version_conf)) {
return false; return false;
} else { } else {
$version_from = $version_conf['value']; $version_from = $version_conf['value'];
if(strpos($version_from, '.') === false) { if (strpos($version_from, '.') === false) {
// yeah, my bad.. previous version did not follow proper naming scheme // yeah, my bad.. previous version did not follow proper naming scheme
$version_from = rtrim(chunk_split($version_from, 1, '.'), '.'); $version_from = rtrim(chunk_split($version_from, 1, '.'), '.');
} }
@ -363,6 +363,6 @@ class InstallController extends AbstractController {
protected function getBaseUrl() { protected function getBaseUrl() {
$sym_request = \Symfony\Component\HttpFoundation\Request::createFromGlobals(); $sym_request = \Symfony\Component\HttpFoundation\Request::createFromGlobals();
return $sym_request->getSchemeAndHttpHost() . $sym_request->getBasePath(); return $sym_request->getSchemeAndHttpHost().$sym_request->getBasePath();
} }
} }

View File

@ -39,7 +39,7 @@ class InstallModule implements ModuleInterface {
public function getControllers() { public function getControllers() {
return array( return array(
'install' => __NAMESPACE__ . '\Controller\InstallController', 'install' => __NAMESPACE__.'\Controller\InstallController',
); );
} }

View File

@ -45,16 +45,16 @@ abstract class AbstractServerController extends AbstractController {
$sql_join = ''; $sql_join = '';
$sql_where = ''; $sql_where = '';
if($this->getUser()->getUserLevel() > PSM_USER_ADMIN) { if ($this->getUser()->getUserLevel() > PSM_USER_ADMIN) {
// restrict by user_id // restrict by user_id
$sql_join = "JOIN `".PSM_DB_PREFIX."users_servers` AS `us` ON ( $sql_join = "JOIN `".PSM_DB_PREFIX."users_servers` AS `us` ON (
`us`.`user_id`={$this->getUser()->getUserId()} `us`.`user_id`={$this->getUser()->getUserId()}
AND `us`.`server_id`=`s`.`server_id` AND `us`.`server_id`=`s`.`server_id`
)"; )";
} }
if($server_id !== null) { if ($server_id !== null) {
$server_id = intval($server_id); $server_id = intval($server_id);
$sql_where ="WHERE `s`.`server_id`={$server_id} "; $sql_where = "WHERE `s`.`server_id`={$server_id} ";
} }
$sql = "SELECT $sql = "SELECT
@ -90,7 +90,7 @@ abstract class AbstractServerController extends AbstractController {
ORDER BY `active` ASC, `status` DESC, `label` ASC"; ORDER BY `active` ASC, `status` DESC, `label` ASC";
$servers = $this->db->query($sql); $servers = $this->db->query($sql);
if($server_id !== null && count($servers) == 1) { if ($server_id !== null && count($servers) == 1) {
$servers = $servers[0]; $servers = $servers[0];
} }
@ -117,17 +117,17 @@ abstract class AbstractServerController extends AbstractController {
$server['pushover'] = psm_get_lang('system', $server['pushover']); $server['pushover'] = psm_get_lang('system', $server['pushover']);
$server['telegram'] = psm_get_lang('system', $server['telegram']); $server['telegram'] = psm_get_lang('system', $server['telegram']);
if($server['status'] == 'on' && $server['warning_threshold_counter'] > 0) { if ($server['status'] == 'on' && $server['warning_threshold_counter'] > 0) {
$server['status'] = 'warning'; $server['status'] = 'warning';
} }
$server['error'] = htmlentities($server['error']); $server['error'] = htmlentities($server['error']);
$server['type'] = psm_get_lang('servers', 'type_' . $server['type']); $server['type'] = psm_get_lang('servers', 'type_'.$server['type']);
$server['timeout'] = ($server['timeout'] > 0) ? $server['timeout'] : PSM_CURL_TIMEOUT; $server['timeout'] = ($server['timeout'] > 0) ? $server['timeout'] : PSM_CURL_TIMEOUT;
$url_actions = array('delete', 'edit', 'view'); $url_actions = array('delete', 'edit', 'view');
foreach($url_actions as $action) { foreach ($url_actions as $action) {
$server['url_' . $action] = psm_build_url(array( $server['url_'.$action] = psm_build_url(array(
'mod' => 'server', 'mod' => 'server',
'action' => $action, 'action' => $action,
'id' => $server['server_id'], 'id' => $server['server_id'],

View File

@ -63,7 +63,7 @@ class LogController extends AbstractServerController {
'tabs' => array(), 'tabs' => array(),
); );
if($this->getUser()->getUserLevel() == PSM_USER_ADMIN) { if ($this->getUser()->getUserLevel() == PSM_USER_ADMIN) {
$modal = new \psm\Util\Module\Modal($this->twig, 'delete', \psm\Util\Module\Modal::MODAL_TYPE_DANGER); $modal = new \psm\Util\Module\Modal($this->twig, 'delete', \psm\Util\Module\Modal::MODAL_TYPE_DANGER);
$this->addModal($modal); $this->addModal($modal);
$modal->setTitle(psm_get_lang('log', 'delete_title')); $modal->setTitle(psm_get_lang('log', 'delete_title'));
@ -74,7 +74,7 @@ class LogController extends AbstractServerController {
$log_types = array('status', 'email', 'sms', 'pushover', 'telegram'); $log_types = array('status', 'email', 'sms', 'pushover', 'telegram');
foreach($log_types as $key) { foreach ($log_types as $key) {
$records = $this->getEntries($key); $records = $this->getEntries($key);
$log_count = count($records); $log_count = count($records);
@ -91,10 +91,10 @@ class LogController extends AbstractServerController {
$record['users'] = ''; $record['users'] = '';
$record['server'] = $record['label']; $record['server'] = $record['label'];
$record['type_icon'] = ($record['server_type'] == 'website') ? 'icon-globe' : 'icon-cog'; $record['type_icon'] = ($record['server_type'] == 'website') ? 'icon-globe' : 'icon-cog';
$record['type_title'] = psm_get_lang('servers', 'type_' . $record['server_type']); $record['type_title'] = psm_get_lang('servers', 'type_'.$record['server_type']);
$ip = '(' . $record['ip']; $ip = '('.$record['ip'];
if(!empty($record['port']) && (($record['server_type'] != 'website') || ($record['port'] != 80))) { if (!empty($record['port']) && (($record['server_type'] != 'website') || ($record['port'] != 80))) {
$ip .= ':' . $record['port']; $ip .= ':'.$record['port'];
} }
$ip .= ')'; $ip .= ')';
$record['ip'] = $ip; $record['ip'] = $ip;
@ -102,9 +102,9 @@ class LogController extends AbstractServerController {
// fix up user list // fix up user list
$users = $this->getLogUsers($record['log_id']); $users = $this->getLogUsers($record['log_id']);
if(!empty($users)) { if (!empty($users)) {
$names = array(); $names = array();
foreach($users as $user) { foreach ($users as $user) {
$names[] = $user['name']; $names[] = $user['name'];
} }
$record['users'] = implode('<br/>', $names); $record['users'] = implode('<br/>', $names);
@ -126,7 +126,7 @@ class LogController extends AbstractServerController {
* Empty table log and log_users. * Empty table log and log_users.
* Only when user is admin. * Only when user is admin.
*/ */
if($this->getUser()->getUserLevel() == PSM_USER_ADMIN) { if ($this->getUser()->getUserLevel() == PSM_USER_ADMIN) {
$archiver = new \psm\Util\Server\Archiver\LogsArchiver($this->db); $archiver = new \psm\Util\Server\Archiver\LogsArchiver($this->db);
$archiver->cleanupall(); $archiver->cleanupall();
} }
@ -141,7 +141,7 @@ class LogController extends AbstractServerController {
*/ */
public function getEntries($type) { public function getEntries($type) {
$sql_join = ''; $sql_join = '';
if($this->getUser()->getUserLevel() > PSM_USER_ADMIN) { if ($this->getUser()->getUserLevel() > PSM_USER_ADMIN) {
// restrict by user_id // restrict by user_id
$sql_join = "JOIN `".PSM_DB_PREFIX."users_servers` AS `us` ON ( $sql_join = "JOIN `".PSM_DB_PREFIX."users_servers` AS `us` ON (
`us`.`user_id`={$this->getUser()->getUserId()} `us`.`user_id`={$this->getUser()->getUserId()}
@ -160,7 +160,7 @@ class LogController extends AbstractServerController {
'`log`.`datetime` '. '`log`.`datetime` '.
'FROM `'.PSM_DB_PREFIX.'log` AS `log` '. 'FROM `'.PSM_DB_PREFIX.'log` AS `log` '.
'JOIN `'.PSM_DB_PREFIX.'servers` AS `servers` ON (`servers`.`server_id`=`log`.`server_id`) '. 'JOIN `'.PSM_DB_PREFIX.'servers` AS `servers` ON (`servers`.`server_id`=`log`.`server_id`) '.
$sql_join . $sql_join.
'WHERE `log`.`type`=\''.$type.'\' '. 'WHERE `log`.`type`=\''.$type.'\' '.
'ORDER BY `datetime` DESC '. 'ORDER BY `datetime` DESC '.
'LIMIT 0,20' 'LIMIT 0,20'
@ -179,9 +179,9 @@ class LogController extends AbstractServerController {
"SELECT "SELECT
u.`user_id`, u.`user_id`,
u.`name` u.`name`
FROM `" . PSM_DB_PREFIX . "log_users` AS lu FROM `".PSM_DB_PREFIX."log_users` AS lu
LEFT JOIN `" . PSM_DB_PREFIX . "users` AS u ON lu.`user_id` = u.`user_id` LEFT JOIN `".PSM_DB_PREFIX."users` AS u ON lu.`user_id` = u.`user_id`
WHERE lu.`log_id` = " . (int)$log_id . " WHERE lu.`log_id` = ".(int) $log_id."
ORDER BY u.`name` ASC" ORDER BY u.`name` ASC"
); );
} }

View File

@ -66,7 +66,7 @@ class ServerController extends AbstractServerController {
$this->setSidebar($sidebar); $this->setSidebar($sidebar);
// check if user is admin, in that case we add the buttons // check if user is admin, in that case we add the buttons
if($this->getUser()->getUserLevel() == PSM_USER_ADMIN) { if ($this->getUser()->getUserLevel() == PSM_USER_ADMIN) {
$modal = new \psm\Util\Module\Modal($this->twig, 'delete', \psm\Util\Module\Modal::MODAL_TYPE_DANGER); $modal = new \psm\Util\Module\Modal($this->twig, 'delete', \psm\Util\Module\Modal::MODAL_TYPE_DANGER);
$this->addModal($modal); $this->addModal($modal);
$modal->setTitle(psm_get_lang('servers', 'delete_title')); $modal->setTitle(psm_get_lang('servers', 'delete_title'));
@ -101,26 +101,26 @@ class ServerController extends AbstractServerController {
for ($x = 0; $x < $server_count; $x++) { for ($x = 0; $x < $server_count; $x++) {
$servers[$x]['class'] = ($x & 1) ? 'odd' : 'even'; $servers[$x]['class'] = ($x & 1) ? 'odd' : 'even';
if($servers[$x]['type'] == 'website') { if ($servers[$x]['type'] == 'website') {
$servers[$x]['type_icon'] = 'icon-globe'; $servers[$x]['type_icon'] = 'icon-globe';
// add link to label // add link to label
$ip = $servers[$x]['ip']; $ip = $servers[$x]['ip'];
if(!empty($servers[$x]['port']) && ($servers[$x]['port'] != 80)) { if (!empty($servers[$x]['port']) && ($servers[$x]['port'] != 80)) {
$ip .= ' : ' . $servers[$x]['port']; $ip .= ' : '.$servers[$x]['port'];
} }
$servers[$x]['ip'] = '<a href="'.$servers[$x]['ip'].'" target="_blank">'.$ip.'</a>'; $servers[$x]['ip'] = '<a href="'.$servers[$x]['ip'].'" target="_blank">'.$ip.'</a>';
$servers[$x]['ip_short'] = $ip; $servers[$x]['ip_short'] = $ip;
} else { } else {
$servers[$x]['type_icon'] = 'icon-cog'; $servers[$x]['type_icon'] = 'icon-cog';
$servers[$x]['ip_short'] = $servers[$x]['ip'] . ' : ' . $servers[$x]['port']; $servers[$x]['ip_short'] = $servers[$x]['ip'].' : '.$servers[$x]['port'];
} }
if(($servers[$x]['active'] == 'yes')) { if (($servers[$x]['active'] == 'yes')) {
$servers[$x]['active_icon'] = 'icon-eye-open'; $servers[$x]['active_icon'] = 'icon-eye-open';
$servers[$x]['active_title'] = psm_get_lang('servers', 'monitoring'); $servers[$x]['active_title'] = psm_get_lang('servers', 'monitoring');
foreach($icons as $i_id => $i_icon) { foreach ($icons as $i_id => $i_icon) {
if(psm_get_conf($i_id . '_status') && $servers[$x][$i_id] == 'yes') { if (psm_get_conf($i_id.'_status') && $servers[$x][$i_id] == 'yes') {
$servers[$x][$i_id . '_icon'] = $i_icon; $servers[$x][$i_id.'_icon'] = $i_icon;
} }
} }
} else { } else {
@ -150,7 +150,7 @@ class ServerController extends AbstractServerController {
)); ));
// depending on where the user came from, add the go back url: // depending on where the user came from, add the go back url:
if($back_to == 'view' && $this->server_id > 0) { 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 { } else {
$tpl_data['url_go_back'] = psm_build_url(array('mod' => 'server')); $tpl_data['url_go_back'] = psm_build_url(array('mod' => 'server'));
@ -158,7 +158,7 @@ class ServerController extends AbstractServerController {
$tpl_data['users'] = $this->db->select(PSM_DB_PREFIX.'users', null, array('user_id', 'name'), '', 'name'); $tpl_data['users'] = $this->db->select(PSM_DB_PREFIX.'users', null, array('user_id', 'name'), '', 'name');
switch($this->server_id) { switch ($this->server_id) {
case 0: case 0:
// insert mode // insert mode
$tpl_data['titlemode'] = psm_get_lang('system', 'insert'); $tpl_data['titlemode'] = psm_get_lang('system', 'insert');
@ -170,15 +170,15 @@ class ServerController extends AbstractServerController {
// edit mode // edit mode
// get server entry // get server entry
$edit_server = $this->getServers($this->server_id); $edit_server = $this->getServers($this->server_id);
if(empty($edit_server)) { if (empty($edit_server)) {
$this->addMessage(psm_get_lang('servers', 'error_server_no_match'), 'error'); $this->addMessage(psm_get_lang('servers', 'error_server_no_match'), 'error');
return $this->runAction('index'); return $this->runAction('index');
} }
$tpl_data['titlemode'] = psm_get_lang('system', 'edit') . ' ' . $edit_server['label']; $tpl_data['titlemode'] = psm_get_lang('system', 'edit').' '.$edit_server['label'];
$user_idc_selected = $this->getServerUsers($this->server_id); $user_idc_selected = $this->getServerUsers($this->server_id);
foreach($tpl_data['users'] as &$user) { foreach ($tpl_data['users'] as &$user) {
if(in_array($user['user_id'], $user_idc_selected)) { if (in_array($user['user_id'], $user_idc_selected)) {
$user['edit_selected'] = 'selected="selected"'; $user['edit_selected'] = 'selected="selected"';
} }
} }
@ -186,9 +186,9 @@ class ServerController extends AbstractServerController {
break; break;
} }
if(!empty($edit_server)) { if (!empty($edit_server)) {
// attempt to prefill previously posted fields // attempt to prefill previously posted fields
foreach($edit_server as $key => $value) { foreach ($edit_server as $key => $value) {
$edit_server[$key] = psm_POST($key, $value); $edit_server[$key] = psm_POST($key, $value);
} }
@ -199,31 +199,31 @@ class ServerController extends AbstractServerController {
'edit_value_timeout' => $edit_server['timeout'], 'edit_value_timeout' => $edit_server['timeout'],
'default_value_timeout' => PSM_CURL_TIMEOUT, 'default_value_timeout' => PSM_CURL_TIMEOUT,
'edit_value_pattern' => $edit_server['pattern'], 'edit_value_pattern' => $edit_server['pattern'],
'edit_pattern_selected_' . $edit_server['pattern_online'] => 'selected="selected"', 'edit_pattern_selected_'.$edit_server['pattern_online'] => 'selected="selected"',
'edit_value_header_name' => $edit_server['header_name'], 'edit_value_header_name' => $edit_server['header_name'],
'edit_value_header_value' => $edit_server['header_value'], 'edit_value_header_value' => $edit_server['header_value'],
'edit_value_warning_threshold' => $edit_server['warning_threshold'], 'edit_value_warning_threshold' => $edit_server['warning_threshold'],
'edit_website_username' => $edit_server['website_username'], 'edit_website_username' => $edit_server['website_username'],
'edit_website_password' => empty($edit_server['website_password']) ? '' : sha1($edit_server['website_password']), 'edit_website_password' => empty($edit_server['website_password']) ? '' : sha1($edit_server['website_password']),
'edit_type_selected_' . $edit_server['type'] => 'selected="selected"', 'edit_type_selected_'.$edit_server['type'] => 'selected="selected"',
'edit_active_selected_' . $edit_server['active'] => 'selected="selected"', 'edit_active_selected_'.$edit_server['active'] => 'selected="selected"',
'edit_email_selected_' . $edit_server['email'] => 'selected="selected"', 'edit_email_selected_'.$edit_server['email'] => 'selected="selected"',
'edit_sms_selected_' . $edit_server['sms'] => 'selected="selected"', 'edit_sms_selected_'.$edit_server['sms'] => 'selected="selected"',
'edit_pushover_selected_' . $edit_server['pushover'] => 'selected="selected"', 'edit_pushover_selected_'.$edit_server['pushover'] => 'selected="selected"',
'edit_telegram_selected_' . $edit_server['telegram'] => 'selected="selected"', 'edit_telegram_selected_'.$edit_server['telegram'] => 'selected="selected"',
)); ));
} }
$notifications = array('email', 'sms', 'pushover', 'telegram'); $notifications = array('email', 'sms', 'pushover', 'telegram');
foreach($notifications as $notification) { foreach ($notifications as $notification) {
if(psm_get_conf($notification . '_status') == 0) { if (psm_get_conf($notification.'_status') == 0) {
$tpl_data['warning_' . $notification] = true; $tpl_data['warning_'.$notification] = true;
$tpl_data['control_class_' . $notification] = 'warning'; $tpl_data['control_class_'.$notification] = 'warning';
$tpl_data['label_warning_' . $notification] = psm_get_lang( $tpl_data['label_warning_'.$notification] = psm_get_lang(
'servers', 'warning_notifications_disabled_' . $notification 'servers', 'warning_notifications_disabled_'.$notification
); );
} else { } else {
$tpl_data['warning_' . $notification] = false; $tpl_data['warning_'.$notification] = false;
} }
} }
@ -241,7 +241,7 @@ class ServerController extends AbstractServerController {
$encrypted_password = ''; $encrypted_password = '';
if ( !empty( $_POST['website_password'] )) { if (!empty($_POST['website_password'])) {
$new_password = psm_POST('website_password'); $new_password = psm_POST('website_password');
if ($this->server_id > 0) { if ($this->server_id > 0) {
@ -251,7 +251,7 @@ class ServerController extends AbstractServerController {
if ($new_password == $hash) { if ($new_password == $hash) {
$encrypted_password = $edit_server['website_password']; $encrypted_password = $edit_server['website_password'];
} else { } else {
$encrypted_password = psm_password_encrypt($this->server_id . psm_get_conf('password_encrypt_key'), $new_password); $encrypted_password = psm_password_encrypt($this->server_id.psm_get_conf('password_encrypt_key'), $new_password);
} }
} else { } else {
// We need the server id to encrypt the password. Encryption will be done after the server is added // We need the server id to encrypt the password. Encryption will be done after the server is added
@ -280,17 +280,17 @@ class ServerController extends AbstractServerController {
'telegram' => in_array($_POST['telegram'], array('yes', 'no')) ? $_POST['telegram'] : 'no', 'telegram' => in_array($_POST['telegram'], array('yes', 'no')) ? $_POST['telegram'] : 'no',
); );
// make sure websites start with http:// // make sure websites start with http://
if($clean['type'] == 'website' && substr($clean['ip'], 0, 4) != 'http') { if ($clean['type'] == 'website' && substr($clean['ip'], 0, 4) != 'http') {
$clean['ip'] = 'http://' . $clean['ip']; $clean['ip'] = 'http://'.$clean['ip'];
} }
// validate the lot // validate the lot
$server_validator = new \psm\Util\Server\ServerValidator($this->db); $server_validator = new \psm\Util\Server\ServerValidator($this->db);
// format port from http/s url // format port from http/s url
if($clean['type'] == 'website' && empty($clean['port'])) { if ($clean['type'] == 'website' && empty($clean['port'])) {
$tmp = parse_url($clean["ip"]); $tmp = parse_url($clean["ip"]);
if(isset($tmp["port"])) { if (isset($tmp["port"])) {
$clean["port"] = $tmp["port"]; $clean["port"] = $tmp["port"];
} elseif ($tmp["scheme"] === "https") { } elseif ($tmp["scheme"] === "https") {
$clean["port"] = 443; $clean["port"] = 443;
@ -302,20 +302,20 @@ class ServerController extends AbstractServerController {
} }
try { try {
if($this->server_id > 0) { if ($this->server_id > 0) {
$server_validator->serverId($this->server_id); $server_validator->serverId($this->server_id);
} }
$server_validator->label($clean['label']); $server_validator->label($clean['label']);
$server_validator->type($clean['type']); $server_validator->type($clean['type']);
$server_validator->ip($clean['ip'], $clean['type']); $server_validator->ip($clean['ip'], $clean['type']);
$server_validator->warningThreshold($clean['warning_threshold']); $server_validator->warningThreshold($clean['warning_threshold']);
} catch(\InvalidArgumentException $ex) { } catch (\InvalidArgumentException $ex) {
$this->addMessage(psm_get_lang('servers', 'error_' . $ex->getMessage()), 'error'); $this->addMessage(psm_get_lang('servers', 'error_'.$ex->getMessage()), 'error');
return $this->executeEdit(); return $this->executeEdit();
} }
// check for edit or add // check for edit or add
if($this->server_id > 0) { if ($this->server_id > 0) {
// edit // edit
$this->db->save( $this->db->save(
PSM_DB_PREFIX.'servers', PSM_DB_PREFIX.'servers',
@ -332,13 +332,13 @@ class ServerController extends AbstractServerController {
if (!empty($_POST['website_password'])) { if (!empty($_POST['website_password'])) {
$cleanWebsitePassword = array( $cleanWebsitePassword = array(
'website_password' => psm_password_encrypt( 'website_password' => psm_password_encrypt(
$this->server_id . psm_get_conf('password_encrypt_key'), $this->server_id.psm_get_conf('password_encrypt_key'),
psm_POST('website_password') psm_POST('website_password')
), ),
); );
$this->db->save( $this->db->save(
PSM_DB_PREFIX . 'servers', PSM_DB_PREFIX.'servers',
$cleanWebsitePassword, $cleanWebsitePassword,
array('server_id' => $this->server_id) array('server_id' => $this->server_id)
); );
@ -351,20 +351,20 @@ class ServerController extends AbstractServerController {
$user_idc = psm_POST('user_id', array()); $user_idc = psm_POST('user_id', array());
$user_idc_save = array(); $user_idc_save = array();
foreach($user_idc as $user_id) { foreach ($user_idc as $user_id) {
$user_idc_save[] = array( $user_idc_save[] = array(
'user_id' => intval($user_id), 'user_id' => intval($user_id),
'server_id' => intval($this->server_id), 'server_id' => intval($this->server_id),
); );
} }
$this->db->delete(PSM_DB_PREFIX.'users_servers', array('server_id' => $this->server_id)); $this->db->delete(PSM_DB_PREFIX.'users_servers', array('server_id' => $this->server_id));
if(!empty($user_idc_save)) { if (!empty($user_idc_save)) {
// add all new users // add all new users
$this->db->insertMultiple(PSM_DB_PREFIX.'users_servers', $user_idc_save); $this->db->insertMultiple(PSM_DB_PREFIX.'users_servers', $user_idc_save);
} }
$back_to = isset($_GET['back_to']) ? $_GET['back_to'] : 'index'; $back_to = isset($_GET['back_to']) ? $_GET['back_to'] : 'index';
if($back_to == 'view') { if ($back_to == 'view') {
return $this->runAction('view'); return $this->runAction('view');
} else { } else {
return $this->runAction('index'); return $this->runAction('index');
@ -375,12 +375,12 @@ class ServerController extends AbstractServerController {
* Executes the deletion of one of the servers * Executes the deletion of one of the servers
*/ */
protected function executeDelete() { protected function executeDelete() {
if(isset($_GET['id'])) { if (isset($_GET['id'])) {
$id = intval($_GET['id']); $id = intval($_GET['id']);
// do delete // do delete
$res = $this->db->delete(PSM_DB_PREFIX . 'servers', array('server_id' => $id)); $res = $this->db->delete(PSM_DB_PREFIX.'servers', array('server_id' => $id));
if($res === 1) { if ($res === 1) {
$this->db->delete(PSM_DB_PREFIX.'log', array('server_id' => $id)); $this->db->delete(PSM_DB_PREFIX.'log', array('server_id' => $id));
$this->db->delete(PSM_DB_PREFIX.'users_servers', array('server_id' => $id)); $this->db->delete(PSM_DB_PREFIX.'users_servers', array('server_id' => $id));
$this->db->delete(PSM_DB_PREFIX.'servers_uptime', array('server_id' => $id)); $this->db->delete(PSM_DB_PREFIX.'servers_uptime', array('server_id' => $id));
@ -395,12 +395,12 @@ class ServerController extends AbstractServerController {
* Prepare the view template * Prepare the view template
*/ */
protected function executeView() { protected function executeView() {
if($this->server_id == 0) { if ($this->server_id == 0) {
return $this->runAction('index'); return $this->runAction('index');
} }
$server = $this->getServers($this->server_id); $server = $this->getServers($this->server_id);
if(empty($server)) { if (empty($server)) {
return $this->runAction('index'); return $this->runAction('index');
} }
@ -412,7 +412,7 @@ class ServerController extends AbstractServerController {
$tpl_data['html_history'] = $history->createHTML($this->server_id); $tpl_data['html_history'] = $history->createHTML($this->server_id);
// add edit/delete buttons for admins // add edit/delete buttons for admins
if($this->getUser()->getUserLevel() == PSM_USER_ADMIN) { if ($this->getUser()->getUserLevel() == PSM_USER_ADMIN) {
$tpl_data['has_admin_actions'] = true; $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'));
@ -426,7 +426,7 @@ class ServerController extends AbstractServerController {
// add all available servers to the menu // add all available servers to the menu
$servers = $this->getServers(); $servers = $this->getServers();
$tpl_data['options'] = array(); $tpl_data['options'] = array();
foreach($servers as $i => $server_available) { foreach ($servers as $i => $server_available) {
$tpl_data['options'][] = array( $tpl_data['options'][] = array(
'class_active' => ($server_available['server_id'] == $this->server_id) ? 'active' : '', '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'])),
@ -517,7 +517,7 @@ class ServerController extends AbstractServerController {
array('user_id') array('user_id')
); );
$result = array(); $result = array();
foreach($users as $user) { foreach ($users as $user) {
$result[] = $user['user_id']; $result[] = $user['user_id'];
} }
return $result; return $result;

View File

@ -71,7 +71,7 @@ class StatusController extends AbstractServerController {
$layout_data['servers_online'] = array(); $layout_data['servers_online'] = array();
foreach ($servers as $server) { foreach ($servers as $server) {
if($server['active'] == 'no') { if ($server['active'] == 'no') {
continue; continue;
} }
$server['last_checked_nice'] = psm_timespan($server['last_check']); $server['last_checked_nice'] = psm_timespan($server['last_check']);
@ -85,7 +85,7 @@ class StatusController extends AbstractServerController {
if ($server['status'] == "off") { if ($server['status'] == "off") {
$layout_data['servers_offline'][] = $server; $layout_data['servers_offline'][] = $server;
} elseif($server['warning_threshold_counter'] > 0) { } elseif ($server['warning_threshold_counter'] > 0) {
$server['class_warning'] = 'warning'; $server['class_warning'] = 'warning';
$layout_data['servers_offline'][] = $server; $layout_data['servers_offline'][] = $server;
} else { } else {
@ -94,12 +94,12 @@ class StatusController extends AbstractServerController {
} }
$auto_refresh_seconds = psm_get_conf('auto_refresh_servers'); $auto_refresh_seconds = psm_get_conf('auto_refresh_servers');
if(intval($auto_refresh_seconds) > 0) { if (intval($auto_refresh_seconds) > 0) {
$this->twig->addGlobal('auto_refresh', true); $this->twig->addGlobal('auto_refresh', true);
$this->twig->addGlobal('auto_refresh_seconds', $auto_refresh_seconds); $this->twig->addGlobal('auto_refresh_seconds', $auto_refresh_seconds);
} }
if($this->isXHR() || isset($_SERVER["HTTP_X_REQUESTED_WITH"])) { if ($this->isXHR() || isset($_SERVER["HTTP_X_REQUESTED_WITH"])) {
$this->xhr = true; $this->xhr = true;
//disable auto refresh in ajax return html //disable auto refresh in ajax return html
$layout_data["auto_refresh"] = 0; $layout_data["auto_refresh"] = 0;
@ -109,7 +109,7 @@ class StatusController extends AbstractServerController {
} }
protected function executeSaveLayout() { protected function executeSaveLayout() {
if($this->isXHR()) { if ($this->isXHR()) {
$layout = psm_POST('layout', 0); $layout = psm_POST('layout', 0);
$this->getUser()->setUserPref('status_layout', $layout); $this->getUser()->setUserPref('status_layout', $layout);

View File

@ -43,7 +43,7 @@ class UpdateController extends AbstractController {
$autorun = $this->container->get('util.server.updatemanager'); $autorun = $this->container->get('util.server.updatemanager');
$autorun->run(); $autorun->run();
header('Location: ' . psm_build_url(array( header('Location: '.psm_build_url(array(
'mod' => 'server_status' 'mod' => 'server_status'
), true, false)); ), true, false));
trigger_error("Redirect failed.", E_USER_ERROR); trigger_error("Redirect failed.", E_USER_ERROR);

View File

@ -39,10 +39,10 @@ class ServerModule implements ModuleInterface {
public function getControllers() { public function getControllers() {
return array( return array(
'server' => __NAMESPACE__ . '\Controller\ServerController', 'server' => __NAMESPACE__.'\Controller\ServerController',
'log' => __NAMESPACE__ . '\Controller\LogController', 'log' => __NAMESPACE__.'\Controller\LogController',
'status' => __NAMESPACE__ . '\Controller\StatusController', 'status' => __NAMESPACE__.'\Controller\StatusController',
'update' => __NAMESPACE__ . '\Controller\UpdateController', 'update' => __NAMESPACE__.'\Controller\UpdateController',
); );
} }

View File

@ -45,7 +45,7 @@ class LoginController extends AbstractController {
} }
protected function executeLogin() { protected function executeLogin() {
if(isset($_POST['user_name']) && isset($_POST['user_password'])) { if (isset($_POST['user_name']) && isset($_POST['user_password'])) {
$rememberme = (isset($_POST['user_rememberme'])) ? true : false; $rememberme = (isset($_POST['user_rememberme'])) ? true : false;
$result = $this->getUser()->loginWithPostData( $result = $this->getUser()->loginWithPostData(
$_POST['user_name'], $_POST['user_name'],
@ -53,9 +53,9 @@ class LoginController extends AbstractController {
$rememberme $rememberme
); );
if($result) { if ($result) {
// success login, redirect // success login, redirect
header('Location: ' . psm_build_url($_SERVER['QUERY_STRING'])); header('Location: '.psm_build_url($_SERVER['QUERY_STRING']));
trigger_error("Redirect failed.", E_USER_ERROR); trigger_error("Redirect failed.", E_USER_ERROR);
} else { } else {
$this->addMessage(psm_get_lang('login', 'error_login_incorrect'), 'error'); $this->addMessage(psm_get_lang('login', 'error_login_incorrect'), 'error');
@ -82,10 +82,10 @@ class LoginController extends AbstractController {
* @return string * @return string
*/ */
protected function executeForgot() { protected function executeForgot() {
if(isset($_POST['user_name'])) { if (isset($_POST['user_name'])) {
$user = $this->getUser()->getUserByUsername($_POST['user_name']); $user = $this->getUser()->getUserByUsername($_POST['user_name']);
if(!empty($user)) { if (!empty($user)) {
$token = $this->getUser()->generatePasswordResetToken($user->user_id); $token = $this->getUser()->generatePasswordResetToken($user->user_id);
// we have a token, send it along // we have a token, send it along
$this->sendPasswordForgotMail( $this->sendPasswordForgotMail(
@ -118,18 +118,18 @@ class LoginController extends AbstractController {
$user_id = (isset($_GET['user_id'])) ? intval($_GET['user_id']) : 0; $user_id = (isset($_GET['user_id'])) ? intval($_GET['user_id']) : 0;
$token = (isset($_GET['token'])) ? $_GET['token'] : ''; $token = (isset($_GET['token'])) ? $_GET['token'] : '';
if(!$service_user->verifyPasswordResetToken($user_id, $token)) { if (!$service_user->verifyPasswordResetToken($user_id, $token)) {
$this->addMessage(psm_get_lang('login', 'error_reset_invalid_link'), 'error'); $this->addMessage(psm_get_lang('login', 'error_reset_invalid_link'), 'error');
return $this->executeLogin(); return $this->executeLogin();
} }
if(!empty($_POST['user_password_new']) && !empty($_POST['user_password_repeat'])) { if (!empty($_POST['user_password_new']) && !empty($_POST['user_password_repeat'])) {
if($_POST['user_password_new'] !== $_POST['user_password_repeat']) { if ($_POST['user_password_new'] !== $_POST['user_password_repeat']) {
$this->addMessage(psm_get_lang('login', 'error_login_passwords_nomatch'), 'error'); $this->addMessage(psm_get_lang('login', 'error_login_passwords_nomatch'), 'error');
} else { } else {
$result = $service_user->changePassword($user_id, $_POST['user_password_new']); $result = $service_user->changePassword($user_id, $_POST['user_password_new']);
if($result) { if ($result) {
$this->addMessage(psm_get_lang('login', 'success_password_reset'), 'success'); $this->addMessage(psm_get_lang('login', 'success_password_reset'), 'success');
return $this->executeLogin(); return $this->executeLogin();
} else { } else {
@ -159,7 +159,7 @@ class LoginController extends AbstractController {
*/ */
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 = psm_build_mail();
$mail->Subject = psm_get_lang('login' ,'password_reset_email_subject'); $mail->Subject = psm_get_lang('login', 'password_reset_email_subject');
$url = psm_build_url(array( $url = psm_build_url(array(
'action' => 'reset', 'action' => 'reset',

View File

@ -54,7 +54,7 @@ class ProfileController extends AbstractController {
$this->twig->addGlobal('subtitle', psm_get_lang('users', 'profile')); $this->twig->addGlobal('subtitle', psm_get_lang('users', 'profile'));
$user = $this->getUser()->getUser(null, true); $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); $this->addModal($modal);
$modal->setTitle(psm_get_lang('users', 'activate_telegram')); $modal->setTitle(psm_get_lang('users', 'activate_telegram'));
$modal->setMessage(psm_get_lang('users', 'activate_telegram_description')); $modal->setMessage(psm_get_lang('users', 'activate_telegram_description'));
@ -85,10 +85,10 @@ class ProfileController extends AbstractController {
'mod' => 'user_profile', 'mod' => 'user_profile',
'action' => 'save', 'action' => 'save',
)), )),
'level' => psm_get_lang('users', 'level_' . $user->level), 'level' => psm_get_lang('users', 'level_'.$user->level),
'placeholder_password' => psm_get_lang('users', 'password_leave_blank'), 'placeholder_password' => psm_get_lang('users', 'password_leave_blank'),
); );
foreach($this->profile_fields as $field) { foreach ($this->profile_fields as $field) {
$tpl_data[$field] = (isset($user->$field)) ? $user->$field : ''; $tpl_data[$field] = (isset($user->$field)) ? $user->$field : '';
} }
return $this->twig->render('module/user/profile.tpl.html', $tpl_data); return $this->twig->render('module/user/profile.tpl.html', $tpl_data);
@ -98,7 +98,7 @@ class ProfileController extends AbstractController {
* Save the profile * Save the profile
*/ */
protected function executeSave() { protected function executeSave() {
if(empty($_POST)) { if (empty($_POST)) {
// dont process anything if no data has been posted // dont process anything if no data has been posted
return $this->executeIndex(); return $this->executeIndex();
} }
@ -108,8 +108,8 @@ class ProfileController extends AbstractController {
$fields[] = 'password_repeat'; $fields[] = 'password_repeat';
$clean = array(); $clean = array();
foreach($fields as $field) { foreach ($fields as $field) {
if(isset($_POST[$field])) { if (isset($_POST[$field])) {
$clean[$field] = trim(strip_tags($_POST[$field])); $clean[$field] = trim(strip_tags($_POST[$field]));
} else { } else {
$clean[$field] = ''; $clean[$field] = '';
@ -123,14 +123,14 @@ class ProfileController extends AbstractController {
// always validate password for new users, // always validate password for new users,
// but only validate it for existing users when they change it. // but only validate it for existing users when they change it.
if($clean['password'] != '') { if ($clean['password'] != '') {
$validator->password($clean['password'], $clean['password_repeat']); $validator->password($clean['password'], $clean['password_repeat']);
} }
} catch(\InvalidArgumentException $e) { } catch (\InvalidArgumentException $e) {
$this->addMessage(psm_get_lang('users', 'error_' . $e->getMessage()), 'error'); $this->addMessage(psm_get_lang('users', 'error_'.$e->getMessage()), 'error');
return $this->executeIndex(); return $this->executeIndex();
} }
if(!empty($clean['password'])) { if (!empty($clean['password'])) {
$password = $clean['password']; $password = $clean['password'];
} }
unset($clean['password']); unset($clean['password']);
@ -141,11 +141,11 @@ class ProfileController extends AbstractController {
\psm\Module\User\UserEvents::USER_EDIT, \psm\Module\User\UserEvents::USER_EDIT,
new \psm\Module\User\Event\UserEvent($this->getUser()->getUserId()) new \psm\Module\User\Event\UserEvent($this->getUser()->getUserId())
); );
if(isset($password)) { if (isset($password)) {
$this->getUser()->changePassword($this->getUser()->getUserId(), $password); $this->getUser()->changePassword($this->getUser()->getUserId(), $password);
} }
$this->addMessage(psm_get_lang('users', 'profile_updated'), 'success'); $this->addMessage(psm_get_lang('users', 'profile_updated'), 'success');
if(!empty($_POST['activate_telegram'])) { if (!empty($_POST['activate_telegram'])) {
$this->activateTelegram(); $this->activateTelegram();
} }
return $this->executeIndex(); return $this->executeIndex();
@ -159,16 +159,16 @@ class ProfileController extends AbstractController {
$telegram = psm_build_telegram(); $telegram = psm_build_telegram();
$apiToken = psm_get_conf('telegram_api_token'); $apiToken = psm_get_conf('telegram_api_token');
if(empty($apiToken)) { if (empty($apiToken)) {
$this->addMessage(psm_get_lang('config', 'telegram_error_notoken'), 'error'); $this->addMessage(psm_get_lang('config', 'telegram_error_notoken'), 'error');
} else { } else {
$result = $telegram->getBotUsername(); $result = $telegram->getBotUsername();
if(isset($result['ok']) && $result['ok'] != false) { if (isset($result['ok']) && $result['ok'] != false) {
$url = "https://t.me/".$result["result"]["username"]; $url = "https://t.me/".$result["result"]["username"];
$this->addMessage(sprintf(psm_get_lang('users', 'telegram_bot_username_found'), $url), 'success'); $this->addMessage(sprintf(psm_get_lang('users', 'telegram_bot_username_found'), $url), 'success');
} else { } else {
if(isset($result['error_code']) && $result['error_code'] == 401) { if (isset($result['error_code']) && $result['error_code'] == 401) {
$error = psm_get_lang('users', 'telegram_bot_username_error_token'); $error = psm_get_lang('users', 'telegram_bot_username_error_token');
} elseif (isset($result['description'])) { } elseif (isset($result['description'])) {
$error = $result['description']; $error = $result['description'];

View File

@ -51,7 +51,7 @@ class UserController extends AbstractController {
public function run($action = NULL) { public function run($action = NULL) {
$servers = $this->db->select(PSM_DB_PREFIX.'servers', null, array('server_id', 'label'), '', "ORDER BY `active` ASC, `status` DESC, `label` ASC"); $servers = $this->db->select(PSM_DB_PREFIX.'servers', null, array('server_id', 'label'), '', "ORDER BY `active` ASC, `status` DESC, `label` ASC");
// change the indexes to reflect their server ids // change the indexes to reflect their server ids
foreach($servers as $server) { foreach ($servers as $server) {
$this->servers[$server['server_id']] = $server; $this->servers[$server['server_id']] = $server;
} }
@ -94,16 +94,18 @@ class UserController extends AbstractController {
array('name') array('name')
); );
foreach($users as $x => &$user) { foreach ($users as $x => &$user) {
$user_servers = $this->getUserServers($user['user_id']); $user_servers = $this->getUserServers($user['user_id']);
$user['class'] = ($x & 1) ? 'odd' : 'even'; $user['class'] = ($x & 1) ? 'odd' : 'even';
$user['level_text'] = psm_get_lang('users', 'level_' . $user['level']); $user['level_text'] = psm_get_lang('users', 'level_'.$user['level']);
$user['emp_servers'] = array(); $user['emp_servers'] = array();
// fix server list // fix server list
foreach($user_servers as $server_id) { foreach ($user_servers as $server_id) {
if (!isset($servers_labels[$server_id])) continue; if (!isset($servers_labels[$server_id])) {
continue;
}
$user['emp_servers'][] = array( $user['emp_servers'][] = array(
'label' => $servers_labels[$server_id] 'label' => $servers_labels[$server_id]
); );
@ -135,7 +137,7 @@ class UserController extends AbstractController {
$user_id = isset($_GET['id']) ? intval($_GET['id']) : 0; $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) { if ($user_id == 0) {
// insert mode // insert mode
$title = psm_get_lang('system', 'insert'); $title = psm_get_lang('system', 'insert');
$placeholder_password = ''; $placeholder_password = '';
@ -143,32 +145,32 @@ class UserController extends AbstractController {
// attempt to prefill previously posted fields // attempt to prefill previously posted fields
$edit_user = new \stdClass(); $edit_user = new \stdClass();
foreach($fields_prefill as $field) { foreach ($fields_prefill as $field) {
$edit_user->$field = (isset($_POST[$field])) ? $_POST[$field] : ''; $edit_user->$field = (isset($_POST[$field])) ? $_POST[$field] : '';
} }
// add inactive class to all servers // add inactive class to all servers
foreach($this->servers as &$server) { foreach ($this->servers as &$server) {
$server['class'] = 'inactive'; $server['class'] = 'inactive';
} }
} else { } else {
// edit mode // edit mode
try { try {
$this->container->get('util.user.validator')->userId($user_id); $this->container->get('util.user.validator')->userId($user_id);
} catch(\InvalidArgumentException $e) { } catch (\InvalidArgumentException $e) {
$this->addMessage(psm_get_lang('users', 'error_' . $e->getMessage()), 'error'); $this->addMessage(psm_get_lang('users', 'error_'.$e->getMessage()), 'error');
return $this->executeIndex(); return $this->executeIndex();
} }
$edit_user = $this->getUser()->getUser($user_id); $edit_user = $this->getUser()->getUser($user_id);
$title = psm_get_lang('system', 'edit') . ' ' . $edit_user->name; $title = psm_get_lang('system', 'edit').' '.$edit_user->name;
$placeholder_password = psm_get_lang('users', 'password_leave_blank'); $placeholder_password = psm_get_lang('users', 'password_leave_blank');
$lvl_selected = $edit_user->level; $lvl_selected = $edit_user->level;
// select servers for this user // select servers for this user
$user_servers = $this->getUserServers($user_id); $user_servers = $this->getUserServers($user_id);
foreach($this->servers as &$server) { foreach ($this->servers as &$server) {
if(in_array($server['server_id'], $user_servers)) { if (in_array($server['server_id'], $user_servers)) {
$server['edit_selected'] = 'selected="selected"'; $server['edit_selected'] = 'selected="selected"';
$server['class'] = 'active'; $server['class'] = 'active';
} }
@ -186,17 +188,17 @@ class UserController extends AbstractController {
'servers' => $this->servers, 'servers' => $this->servers,
'user_level' => $lvl_selected, 'user_level' => $lvl_selected,
); );
foreach($fields_prefill as $field) { foreach ($fields_prefill as $field) {
if(isset($edit_user->$field)) { if (isset($edit_user->$field)) {
$tpl_data['edit_value_' . $field] = $edit_user->$field; $tpl_data['edit_value_'.$field] = $edit_user->$field;
} }
} }
$tpl_data['levels'] = array(); $tpl_data['levels'] = array();
foreach($this->container->get('util.user.validator')->getUserLevels() as $lvl) { foreach ($this->container->get('util.user.validator')->getUserLevels() as $lvl) {
$tpl_data['levels'][] = array( $tpl_data['levels'][] = array(
'value' => $lvl, 'value' => $lvl,
'label' => psm_get_lang('users', 'level_' . $lvl), 'label' => psm_get_lang('users', 'level_'.$lvl),
); );
} }
@ -209,7 +211,7 @@ class UserController extends AbstractController {
* Executes the saving of a user * Executes the saving of a user
*/ */
protected function executeSave() { protected function executeSave() {
if(empty($_POST)) { if (empty($_POST)) {
// dont process anything if no data has been posted // dont process anything if no data has been posted
return $this->executeIndex(); return $this->executeIndex();
} }
@ -217,8 +219,8 @@ class UserController extends AbstractController {
$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(); $clean = array();
foreach($fields as $field) { foreach ($fields as $field) {
if(isset($_POST[$field])) { if (isset($_POST[$field])) {
$clean[$field] = trim(strip_tags($_POST[$field])); $clean[$field] = trim(strip_tags($_POST[$field]));
} else { } else {
$clean[$field] = ''; $clean[$field] = '';
@ -234,22 +236,22 @@ class UserController extends AbstractController {
// always validate password for new users, // always validate password for new users,
// but only validate it for existing users when they change it. // but only validate it for existing users when they change it.
if($user_id == 0 || ($user_id > 0 && $clean['password'] != '')) { if ($user_id == 0 || ($user_id > 0 && $clean['password'] != '')) {
$user_validator->password($clean['password'], $clean['password_repeat']); $user_validator->password($clean['password'], $clean['password_repeat']);
} }
if($user_id > 0) { if ($user_id > 0) {
$user_validator->userId($user_id); $user_validator->userId($user_id);
} }
} catch(\InvalidArgumentException $e) { } catch (\InvalidArgumentException $e) {
$this->addMessage(psm_get_lang('users', 'error_' . $e->getMessage()), 'error'); $this->addMessage(psm_get_lang('users', 'error_'.$e->getMessage()), 'error');
return $this->executeEdit(); return $this->executeEdit();
} }
if(!empty($clean['password'])) { if (!empty($clean['password'])) {
$password = $clean['password']; $password = $clean['password'];
} }
unset($clean['password_repeat']); unset($clean['password_repeat']);
if($user_id > 0) { if ($user_id > 0) {
// edit user // edit user
unset($clean['password']); // password update is executed separately unset($clean['password']); // password update is executed separately
$this->db->save(PSM_DB_PREFIX.'users', $clean, array('user_id' => $user_id)); $this->db->save(PSM_DB_PREFIX.'users', $clean, array('user_id' => $user_id));
@ -268,7 +270,7 @@ class UserController extends AbstractController {
$event, $event,
new \psm\Module\User\Event\UserEvent($user_id, $this->getUser()->getUserId()) new \psm\Module\User\Event\UserEvent($user_id, $this->getUser()->getUserId())
); );
if(isset($password)) { if (isset($password)) {
$this->getUser()->changePassword($user_id, $password); $this->getUser()->changePassword($user_id, $password);
} }
@ -276,7 +278,7 @@ class UserController extends AbstractController {
$server_idc = psm_POST('server_id', array()); $server_idc = psm_POST('server_id', array());
$server_idc_save = array(); $server_idc_save = array();
foreach($server_idc as $server_id) { foreach ($server_idc as $server_id) {
$server_idc_save[] = array( $server_idc_save[] = array(
'user_id' => $user_id, 'user_id' => $user_id,
'server_id' => intval($server_id), 'server_id' => intval($server_id),
@ -284,7 +286,7 @@ class UserController extends AbstractController {
} }
// delete all existing records // delete all existing records
$this->db->delete(PSM_DB_PREFIX.'users_servers', array('user_id' => $user_id)); $this->db->delete(PSM_DB_PREFIX.'users_servers', array('user_id' => $user_id));
if(!empty($server_idc_save)) { if (!empty($server_idc_save)) {
// add all new servers // add all new servers
$this->db->insertMultiple(PSM_DB_PREFIX.'users_servers', $server_idc_save); $this->db->insertMultiple(PSM_DB_PREFIX.'users_servers', $server_idc_save);
} }
@ -301,7 +303,7 @@ class UserController extends AbstractController {
try { try {
$this->container->get('util.user.validator')->userId($id); $this->container->get('util.user.validator')->userId($id);
$this->db->delete(PSM_DB_PREFIX . 'users', array('user_id' => $id,)); $this->db->delete(PSM_DB_PREFIX.'users', array('user_id' => $id,));
$this->db->delete(PSM_DB_PREFIX.'users_servers', array('user_id' => $id)); $this->db->delete(PSM_DB_PREFIX.'users_servers', array('user_id' => $id));
$this->container->get('event')->dispatch( $this->container->get('event')->dispatch(
@ -310,8 +312,8 @@ class UserController extends AbstractController {
); );
$this->addMessage(psm_get_lang('users', 'deleted'), 'success'); $this->addMessage(psm_get_lang('users', 'deleted'), 'success');
} catch(\InvalidArgumentException $e) { } catch (\InvalidArgumentException $e) {
$this->addMessage(psm_get_lang('users', 'error_' . $e->getMessage()), 'error'); $this->addMessage(psm_get_lang('users', 'error_'.$e->getMessage()), 'error');
} }
return $this->executeIndex(); return $this->executeIndex();
@ -361,7 +363,7 @@ class UserController extends AbstractController {
array('server_id') array('server_id')
); );
$result = array(); $result = array();
foreach($servers as $server) { foreach ($servers as $server) {
$result[] = $server['server_id']; $result[] = $server['server_id'];
} }
return $result; return $result;

View File

@ -40,9 +40,9 @@ class UserModule implements ModuleInterface {
public function getControllers() { public function getControllers() {
return array( return array(
'user' => __NAMESPACE__ . '\Controller\UserController', 'user' => __NAMESPACE__.'\Controller\UserController',
'login' => __NAMESPACE__ . '\Controller\LoginController', 'login' => __NAMESPACE__.'\Controller\LoginController',
'profile' => __NAMESPACE__ . '\Controller\ProfileController', 'profile' => __NAMESPACE__.'\Controller\ProfileController',
); );
} }

View File

@ -55,7 +55,7 @@ class Router {
$mods = $this->container->getParameter('modules'); $mods = $this->container->getParameter('modules');
foreach($mods as $mod) { foreach ($mods as $mod) {
$mod_loader = $this->container->get($mod); $mod_loader = $this->container->get($mod);
$mod_loader->load($this->container); $mod_loader->load($this->container);
} }
@ -73,7 +73,7 @@ class Router {
* @throws \LogicException * @throws \LogicException
*/ */
public function run($mod) { public function run($mod) {
if(strpos($mod, '_') !== false) { if (strpos($mod, '_') !== false) {
list($mod, $controller) = explode('_', $mod); list($mod, $controller) = explode('_', $mod);
} else { } else {
$controller = $mod; $controller = $mod;
@ -86,7 +86,7 @@ class Router {
try { try {
$this->validateRequest($controller); $this->validateRequest($controller);
} catch (\InvalidArgumentException $ex) { } catch (\InvalidArgumentException $ex) {
switch($ex->getMessage()) { switch ($ex->getMessage()) {
case 'login_required': case 'login_required':
$controller = $this->getController('user', 'login'); $controller = $this->getController('user', 'login');
break; break;
@ -101,7 +101,7 @@ class Router {
$response = $controller->run($action); $response = $controller->run($action);
if(!($response instanceof Response)) { if (!($response instanceof Response)) {
throw new \LogicException('Controller did not return a Response object.'); throw new \LogicException('Controller did not return a Response object.');
} }
$response->send(); $response->send();
@ -115,22 +115,22 @@ class Router {
* @throws \InvalidArgumentException * @throws \InvalidArgumentException
*/ */
public function getController($module_id, $controller_id = null) { public function getController($module_id, $controller_id = null) {
if($controller_id === null) { if ($controller_id === null) {
// by default, we use the controller with the same id as the module. // by default, we use the controller with the same id as the module.
$controller_id = $module_id; $controller_id = $module_id;
} }
$module = $this->container->get('module.' . $module_id); $module = $this->container->get('module.'.$module_id);
$controllers = $module->getControllers(); $controllers = $module->getControllers();
if(!isset($controllers[$controller_id]) || !class_exists($controllers[$controller_id])) { 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]( $controller = new $controllers[$controller_id](
$this->container->get('db'), $this->container->get('db'),
$this->container->get('twig') $this->container->get('twig')
); );
if(!$controller instanceof \psm\Module\ControllerInterface) { if (!$controller instanceof \psm\Module\ControllerInterface) {
throw new \Exception('Controller does not implement ControllerInterface'); throw new \Exception('Controller does not implement ControllerInterface');
} }
$controller->setContainer($this->container); $controller->setContainer($this->container);
@ -156,18 +156,18 @@ class Router {
protected function validateRequest(\psm\Module\ControllerInterface $controller) { protected function validateRequest(\psm\Module\ControllerInterface $controller) {
$request = Request::createFromGlobals(); $request = Request::createFromGlobals();
if($request->getMethod() == 'POST') { if ($request->getMethod() == 'POST') {
// require CSRF token for all POST calls // require CSRF token for all POST calls
$session = $this->container->get('user')->getSession(); $session = $this->container->get('user')->getSession();
$token_in = $request->request->get('csrf', ''); $token_in = $request->request->get('csrf', '');
$csrf_key = $controller->getCSRFKey(); $csrf_key = $controller->getCSRFKey();
if(empty($csrf_key)) { if (empty($csrf_key)) {
if(!hash_equals($session->get('csrf_token'), $token_in)) { if (!hash_equals($session->get('csrf_token'), $token_in)) {
throw new \InvalidArgumentException('invalid_csrf_token'); throw new \InvalidArgumentException('invalid_csrf_token');
} }
} else { } else {
if(!hash_equals( if (!hash_equals(
hash_hmac('sha256', $csrf_key, $session->get('csrf_token2')), hash_hmac('sha256', $csrf_key, $session->get('csrf_token2')),
$token_in $token_in
)) { )) {
@ -179,11 +179,11 @@ class Router {
// get min required level for this controller and make sure the user matches // get min required level for this controller and make sure the user matches
$min_lvl = $controller->getMinUserLevelRequired(); $min_lvl = $controller->getMinUserLevelRequired();
if($min_lvl < PSM_USER_ANONYMOUS) { if ($min_lvl < PSM_USER_ANONYMOUS) {
// if user is not logged in, load login module // if user is not logged in, load login module
if(!$this->container->get('user')->isUserLoggedIn()) { if (!$this->container->get('user')->isUserLoggedIn()) {
throw new \InvalidArgumentException('login_required'); throw new \InvalidArgumentException('login_required');
} elseif($this->container->get('user')->getUserLevel() > $min_lvl) { } elseif ($this->container->get('user')->getUserLevel() > $min_lvl) {
throw new \InvalidArgumentException('invalid_user_level'); throw new \InvalidArgumentException('invalid_user_level');
} }
} }
@ -210,10 +210,10 @@ class Router {
protected function buildTwigEnvironment() { protected function buildTwigEnvironment() {
$twig = $this->container->get('twig'); $twig = $this->container->get('twig');
$session = $this->container->get('user')->getSession(); $session = $this->container->get('user')->getSession();
if(!$session->has('csrf_token')) { if (!$session->has('csrf_token')) {
$session->set('csrf_token', bin2hex(random_bytes(32))); $session->set('csrf_token', bin2hex(random_bytes(32)));
} }
if(!$session->has('csrf_token2')) { if (!$session->has('csrf_token2')) {
$session->set('csrf_token2', random_bytes(32)); $session->set('csrf_token2', random_bytes(32));
} }
@ -221,7 +221,7 @@ class Router {
new \Twig_SimpleFunction( new \Twig_SimpleFunction(
'csrf_token', 'csrf_token',
function($lock_to = null) use ($session) { function($lock_to = null) use ($session) {
if(empty($lock_to)) { if (empty($lock_to)) {
return $session->get('csrf_token'); return $session->get('csrf_token');
} }
return hash_hmac('sha256', $lock_to, $session->get('csrf_token2')); return hash_hmac('sha256', $lock_to, $session->get('csrf_token2'));

View File

@ -88,7 +88,7 @@ class Database {
* @param string $db * @param string $db
*/ */
function __construct($host = null, $user = null, $pass = null, $db = null, $port = null) { function __construct($host = null, $user = null, $pass = null, $db = null, $port = null) {
if($host != null && $user != null && $pass !== null && $db != null) { if ($host != null && $user != null && $pass !== null && $db != null) {
$this->db_host = $host; $this->db_host = $host;
$this->db_port = (!empty($port)) ? $port : 3306; $this->db_port = (!empty($port)) ? $port : 3306;
$this->db_name = $db; $this->db_name = $db;
@ -114,10 +114,10 @@ class Database {
$this->error($e); $this->error($e);
} }
if($fetch && $this->last != false) { if ($fetch && $this->last != false) {
$cmd = strtolower(substr($query, 0, 6)); $cmd = strtolower(substr($query, 0, 6));
switch($cmd) { switch ($cmd) {
case 'insert': case 'insert':
// insert query, return insert id // insert query, return insert id
$result = $this->getLastInsertedId(); $result = $this->getLastInsertedId();
@ -167,7 +167,7 @@ class Database {
$this->error($e); $this->error($e);
} }
if($fetch && $this->last != false) { if ($fetch && $this->last != false) {
$result = $this->last->fetchAll(\PDO::FETCH_ASSOC); $result = $this->last->fetchAll(\PDO::FETCH_ASSOC);
} else { } else {
$result = $this->last; $result = $this->last;
@ -185,7 +185,7 @@ class Database {
* @param string $direction ASC or DESC. Defaults to ASC * @param string $direction ASC or DESC. Defaults to ASC
* @return array multi dimensional array with results * @return 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 // build query
$query_parts = array(); $query_parts = array();
$query_parts[] = 'SELECT SQL_CALC_FOUND_ROWS'; $query_parts[] = 'SELECT SQL_CALC_FOUND_ROWS';
@ -204,13 +204,13 @@ class Database {
$query_parts[] = $this->buildSQLClauseWhere($table, $where); $query_parts[] = $this->buildSQLClauseWhere($table, $where);
// Order by // Order by
if($orderby) { if ($orderby) {
$query_parts[] = $this->buildSQLClauseOrderBy($orderby, $direction); $query_parts[] = $this->buildSQLClauseOrderBy($orderby, $direction);
} }
// Limit // Limit
if ($limit != '') { if ($limit != '') {
$query_parts[] = 'LIMIT ' . $limit; $query_parts[] = 'LIMIT '.$limit;
} }
$query = implode(' ', $query_parts); $query = implode(' ', $query_parts);
@ -230,7 +230,7 @@ class Database {
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); $result = $this->select($table, $where, $fields, '1', $orderby, $direction);
if(isset($result[0])) { if (isset($result[0])) {
$result = $result[0]; $result = $result[0];
} }
@ -243,8 +243,8 @@ class Database {
* @param mixed $where Where clause array or primary Id (string) or where clause (string) * @param mixed $where Where clause array or primary Id (string) or where clause (string)
* @return int number of affected rows * @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); $sql = 'DELETE FROM `'.$table.'` '.$this->buildSQLClauseWhere($table, $where);
return $this->exec($sql); return $this->exec($sql);
} }
@ -267,8 +267,8 @@ class Database {
$query .= "`{$table}` SET "; $query .= "`{$table}` SET ";
foreach($data as $field => $value) { foreach ($data as $field => $value) {
if(is_null($value)) { if (is_null($value)) {
$value = 'NULL'; $value = 'NULL';
} else { } else {
$value = $this->quote($value); $value = $this->quote($value);
@ -276,9 +276,9 @@ class Database {
$query .= "`{$table}`.`{$field}`={$value}, "; $query .= "`{$table}`.`{$field}`={$value}, ";
} }
$query = substr($query, 0, -2) . ' ' . $this->buildSQLClauseWhere($table, $where); $query = substr($query, 0, -2).' '.$this->buildSQLClauseWhere($table, $where);
if($exec) { if ($exec) {
return $this->exec($query); return $this->exec($query);
} else { } else {
return $this->query($query); return $this->query($query);
@ -300,7 +300,9 @@ class Database {
* @see insert() * @see insert()
*/ */
public function insertMultiple($table, array $data) { public function insertMultiple($table, array $data) {
if(empty($data)) return false; if (empty($data)) {
return false;
}
// prepare first part // prepare first part
$query = "INSERT INTO `{$table}` "; $query = "INSERT INTO `{$table}` ";
@ -317,14 +319,14 @@ class Database {
$pst = $this->pdo()->prepare($query); $pst = $this->pdo()->prepare($query);
$i = 1; $i = 1;
foreach($data as $row) { foreach ($data as $row) {
// make sure the fields of this row are identical to first row // make sure the fields of this row are identical to first row
$diff_keys = array_diff_key($fields, array_keys($row)); $diff_keys = array_diff_key($fields, array_keys($row));
if(!empty($diff_keys)) { if (!empty($diff_keys)) {
continue; continue;
} }
foreach($fields as $field) { foreach ($fields as $field) {
$pst->bindParam($i++, $row[$field]); $pst->bindParam($i++, $row[$field]);
} }
} }
@ -353,7 +355,7 @@ class Database {
"; ";
$if_exists = $this->query($if_exists); $if_exists = $this->query($if_exists);
if(isset($if_exists[0]['cnt']) && $if_exists[0]['cnt'] == 1) { if (isset($if_exists[0]['cnt']) && $if_exists[0]['cnt'] == 1) {
return true; return true;
} else { } else {
false; false;
@ -408,7 +410,7 @@ class Database {
if (is_array($where)) { if (is_array($where)) {
$query .= " WHERE "; $query .= " WHERE ";
foreach($where as $field => $value) { foreach ($where as $field => $value) {
$query .= "`{$table}`.`{$field}`={$this->quote($value)} AND "; $query .= "`{$table}`.`{$field}`={$this->quote($value)} AND ";
} }
$query = substr($query, 0, -5); $query = substr($query, 0, -5);
@ -441,7 +443,7 @@ class Database {
if (is_array($order_by)) { if (is_array($order_by)) {
$query .= " ORDER BY "; $query .= " ORDER BY ";
foreach($order_by as $field) { foreach ($order_by as $field) {
$query .= "`{$field}`, "; $query .= "`{$field}`, ";
} }
// remove trailing ", " // remove trailing ", "
@ -454,9 +456,9 @@ class Database {
} }
} }
} }
if(strlen($query) > 0) { if (strlen($query) > 0) {
// check if "ASC" or "DESC" is already in the order by clause // 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; $query .= ' '.$direction;
} }
} }
@ -538,6 +540,6 @@ class Database {
* @param \PDOException $e * @param \PDOException $e
*/ */
protected function error(\PDOException $e) { protected function error(\PDOException $e) {
trigger_error('SQL error: ' . $e->getMessage(), E_USER_WARNING); trigger_error('SQL error: '.$e->getMessage(), E_USER_WARNING);
} }
} }

View File

@ -89,20 +89,20 @@ class User {
public function __construct(Database $db, SessionInterface $session = null) { public function __construct(Database $db, SessionInterface $session = null) {
$this->db_connection = $db->pdo(); $this->db_connection = $db->pdo();
if(!psm_is_cli()) { if (!psm_is_cli()) {
if($session == null) { if ($session == null) {
$session = new Session(); $session = new Session();
$session->start(); $session->start();
} }
$this->session = $session; $this->session = $session;
if((!defined('PSM_INSTALL') || !PSM_INSTALL)) { if ((!defined('PSM_INSTALL') || !PSM_INSTALL)) {
// check the possible login actions: // 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 // 2. login via cookie
// if user has an active session on the server // if user has an active session on the server
if(!$this->loginWithSessionData()) { if (!$this->loginWithSessionData()) {
$this->loginWithCookieData(); $this->loginWithCookieData();
} }
} }
@ -116,15 +116,15 @@ class User {
* @return object|boolean FALSE if user not found, object otherwise * @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 ($user_id == null) {
if(!$this->isUserLoggedIn()) { if (!$this->isUserLoggedIn()) {
return false; return false;
} else { } else {
$user_id = $this->getUserId(); $user_id = $this->getUserId();
} }
} }
if(!isset($this->user_data[$user_id]) || $flush) { 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->bindValue(':user_id', $user_id, \PDO::PARAM_INT);
$query_user->execute(); $query_user->execute();
@ -153,12 +153,12 @@ class User {
* @return boolean * @return boolean
*/ */
protected function loginWithSessionData() { protected function loginWithSessionData() {
if(!$this->session->has('user_id')) { if (!$this->session->has('user_id')) {
return false; return false;
} }
$user = $this->getUser($this->session->get('user_id')); $user = $this->getUser($this->session->get('user_id'));
if(!empty($user)) { if (!empty($user)) {
$this->setUserLoggedIn($user->user_id); $this->setUserLoggedIn($user->user_id);
return true; return true;
} else { } else {
@ -178,12 +178,12 @@ class User {
// extract data from the cookie // extract data from the cookie
list ($user_id, $token, $hash) = explode(':', $_COOKIE['rememberme']); list ($user_id, $token, $hash) = explode(':', $_COOKIE['rememberme']);
// check cookie hash validity // check cookie hash validity
if($hash == hash('sha256', $user_id . ':' . $token . PSM_LOGIN_COOKIE_SECRET_KEY) && !empty($token)) { if ($hash == hash('sha256', $user_id.':'.$token.PSM_LOGIN_COOKIE_SECRET_KEY) && !empty($token)) {
// cookie looks good, try to select corresponding user // cookie looks good, try to select corresponding user
// get real token from database (and all other data) // get real token from database (and all other data)
$user = $this->getUser($user_id); $user = $this->getUser($user_id);
if(!empty($user) && $token === $user->rememberme_token) { if (!empty($user) && $token === $user->rememberme_token) {
$this->setUserLoggedIn($user->user_id, true); $this->setUserLoggedIn($user->user_id, true);
// Cookie token usable only once // Cookie token usable only once
@ -208,23 +208,23 @@ class User {
$user_name = trim($user_name); $user_name = trim($user_name);
$user_password = trim($user_password); $user_password = trim($user_password);
if(empty($user_name) && empty($user_password)) { if (empty($user_name) && empty($user_password)) {
return false; return false;
} }
$user = $this->getUserByUsername($user_name); $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)) { if (!isset($user->user_id)) {
password_verify($user_password, 'dummy_call_against_timing'); password_verify($user_password, 'dummy_call_against_timing');
return false; return false;
} else if(!password_verify($user_password, $user->password)) { } else if (!password_verify($user_password, $user->password)) {
return false; return false;
} }
$this->setUserLoggedIn($user->user_id, true); $this->setUserLoggedIn($user->user_id, true);
// if user has check the "remember me" checkbox, then generate token and write cookie // if user has check the "remember me" checkbox, then generate token and write cookie
if($user_rememberme) { if ($user_rememberme) {
$this->newRememberMeCookie(); $this->newRememberMeCookie();
} }
@ -232,9 +232,9 @@ class User {
// 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. // 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 // check if the have defined a cost factor in config/hashing.php
if(defined('PSM_LOGIN_HASH_COST_FACTOR')) { if (defined('PSM_LOGIN_HASH_COST_FACTOR')) {
// check if the hash needs to be rehashed // check if the hash needs to be rehashed
if(password_needs_rehash($user->password, PASSWORD_DEFAULT, array('cost' => PSM_LOGIN_HASH_COST_FACTOR))) { if (password_needs_rehash($user->password, PASSWORD_DEFAULT, array('cost' => PSM_LOGIN_HASH_COST_FACTOR))) {
$this->changePassword($user->user_id, $user_password); $this->changePassword($user->user_id, $user_password);
} }
} }
@ -247,7 +247,7 @@ class User {
* @param boolean $regenerate regenerate session id against session fixation? * @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) { if ($regenerate) {
$this->session->invalidate(); $this->session->invalidate();
} }
$this->session->set('user_id', $user_id); $this->session->set('user_id', $user_id);
@ -268,9 +268,9 @@ class User {
$sth->execute(array(':user_rememberme_token' => $random_token_string, ':user_id' => $this->getUserId())); $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 // generate cookie string that consists of userid, randomstring and combined hash of both
$cookie_string_first_part = $this->getUserId() . ':' . $random_token_string; $cookie_string_first_part = $this->getUserId().':'.$random_token_string;
$cookie_string_hash = hash('sha256', $cookie_string_first_part . PSM_LOGIN_COOKIE_SECRET_KEY); $cookie_string_hash = hash('sha256', $cookie_string_first_part.PSM_LOGIN_COOKIE_SECRET_KEY);
$cookie_string = $cookie_string_first_part . ':' . $cookie_string_hash; $cookie_string = $cookie_string_first_part.':'.$cookie_string_hash;
// set cookie // set cookie
setcookie('rememberme', $cookie_string, time() + PSM_LOGIN_COOKIE_RUNTIME, "/", PSM_LOGIN_COOKIE_DOMAIN); setcookie('rememberme', $cookie_string, time() + PSM_LOGIN_COOKIE_RUNTIME, "/", PSM_LOGIN_COOKIE_DOMAIN);
@ -281,7 +281,7 @@ class User {
*/ */
protected function deleteRememberMeCookie() { protected function deleteRememberMeCookie() {
// Reset rememberme token // Reset rememberme token
if($this->session->has('user_id')) { 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'))); $sth->execute(array(':user_id' => $this->session->get('user_id')));
} }
@ -321,7 +321,7 @@ class User {
public function generatePasswordResetToken($user_id) { public function generatePasswordResetToken($user_id) {
$user_id = intval($user_id); $user_id = intval($user_id);
if($user_id == 0) { if ($user_id == 0) {
return false; return false;
} }
// generate timestamp (to see when exactly the user (or an attacker) requested the password reset mail) // generate timestamp (to see when exactly the user (or an attacker) requested the password reset mail)
@ -356,16 +356,16 @@ class User {
public function verifyPasswordResetToken($user_id, $token) { public function verifyPasswordResetToken($user_id, $token) {
$user_id = intval($user_id); $user_id = intval($user_id);
if(empty($user_id) || empty($token)) { if (empty($user_id) || empty($token)) {
return false; return false;
} }
$user = $this->getUser($user_id); $user = $this->getUser($user_id);
if(isset($user->user_id) && $user->password_reset_hash == $token) { if (isset($user->user_id) && $user->password_reset_hash == $token) {
$runtime = (defined('PSM_LOGIN_RESET_RUNTIME')) ? PSM_LOGIN_RESET_RUNTIME : 3600; $runtime = (defined('PSM_LOGIN_RESET_RUNTIME')) ? PSM_LOGIN_RESET_RUNTIME : 3600;
$timestamp_max_interval = time() - $runtime; $timestamp_max_interval = time() - $runtime;
if($user->password_reset_timestamp > $timestamp_max_interval) { if ($user->password_reset_timestamp > $timestamp_max_interval) {
return true; return true;
} }
} }
@ -381,7 +381,7 @@ class User {
public function changePassword($user_id, $password) { public function changePassword($user_id, $password) {
$user_id = intval($user_id); $user_id = intval($user_id);
if(empty($user_id) || empty($password)) { if (empty($user_id) || empty($password)) {
return false; 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),
@ -434,7 +434,7 @@ class User {
public function getUserLevel() { public function getUserLevel() {
$user = $this->getUser(); $user = $this->getUser();
if(isset($user->level)) { if (isset($user->level)) {
return $user->level; return $user->level;
} else { } else {
return PSM_USER_ANONYMOUS; return PSM_USER_ANONYMOUS;
@ -446,13 +446,13 @@ class User {
* @return boolean return false is user not connected * @return boolean return false is user not connected
*/ */
protected function loadPreferences() { protected function loadPreferences() {
if($this->user_preferences === null) { if ($this->user_preferences === null) {
if(!$this->getUser()) { if (!$this->getUser()) {
return false; return false;
} }
$this->user_preferences = array(); $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']; $this->user_preferences[$row['key']] = $row['value'];
} }
} }
@ -466,7 +466,7 @@ class User {
* @return mixed * @return mixed
*/ */
public function getUserPref($key, $default = '') { public function getUserPref($key, $default = '') {
if(!$this->loadPreferences() || !isset($this->user_preferences[$key])) { if (!$this->loadPreferences() || !isset($this->user_preferences[$key])) {
return $default; return $default;
} }
@ -481,14 +481,14 @@ class User {
* @param mixed $value * @param mixed $value
*/ */
public function setUserPref($key, $value) { public function setUserPref($key, $value) {
if($this->loadPreferences()) { if ($this->loadPreferences()) {
if(isset($this->user_preferences[$key])) { if (isset($this->user_preferences[$key])) {
if($this->user_preferences[$key] == $value) { if ($this->user_preferences[$key] == $value) {
return; // no change return; // no change
} }
$sql = 'UPDATE `' . PSM_DB_PREFIX . 'users_preferences` SET `key` = ?, `value` = ? WHERE `user_id` = ?'; $sql = 'UPDATE `'.PSM_DB_PREFIX.'users_preferences` SET `key` = ?, `value` = ? WHERE `user_id` = ?';
} else{ } else {
$sql = 'INSERT INTO `' . PSM_DB_PREFIX . 'users_preferences` SET `key` = ?, `value` = ?, `user_id` = ?'; $sql = 'INSERT INTO `'.PSM_DB_PREFIX.'users_preferences` SET `key` = ?, `value` = ?, `user_id` = ?';
} }
$sth = $this->db_connection->prepare($sql); $sth = $this->db_connection->prepare($sql);
$sth->execute(array($key, $value, $this->user_id)); $sth->execute(array($key, $value, $this->user_id));

View File

@ -79,12 +79,12 @@ class CMBulkSMS extends Core {
*/ */
public function sendSMS($message) { public function sendSMS($message) {
// Check if recipient and text message are available // Check if recipient and text message are available
if(count($this->recipients) < 1 || empty($message)) { if (count($this->recipients) < 1 || empty($message)) {
return false; return false;
} }
// Prepare the message in CM's XML or JSON format // Prepare the message in CM's XML or JSON format
switch($this->apiType) { switch ($this->apiType) {
case 'xml': case 'xml':
$this->request = $this->buildMessageXml(); $this->request = $this->buildMessageXml();
$this->contentType = 'Content-Type: application/xml'; $this->contentType = 'Content-Type: application/xml';
@ -115,7 +115,7 @@ class CMBulkSMS extends Core {
protected function buildMessageJson() { protected function buildMessageJson() {
// Prepare recipient array for batch message // Prepare recipient array for batch message
$recipients = array(); $recipients = array();
foreach($this->recipients as $recipient) { foreach ($this->recipients as $recipient) {
$recipients[] = array('number' => $recipient); $recipients[] = array('number' => $recipient);
} }
@ -138,7 +138,7 @@ class CMBulkSMS extends Core {
); );
// Multipart message // Multipart message
if($this->multipartMessage) { if ($this->multipartMessage) {
$msgArray['messages']['msg'][0]['minimumNumberOfMessageParts'] = 1; $msgArray['messages']['msg'][0]['minimumNumberOfMessageParts'] = 1;
$msgArray['messages']['msg'][0]['maximumNumberOfMessageParts'] = 8; $msgArray['messages']['msg'][0]['maximumNumberOfMessageParts'] = 8;
} }
@ -170,12 +170,12 @@ class CMBulkSMS extends Core {
$msg->addChild('FROM', substr($this->originator, 0, 11)); $msg->addChild('FROM', substr($this->originator, 0, 11));
// Recipients // Recipients
foreach($this->recipients as $recipient) { foreach ($this->recipients as $recipient) {
$msg->addChild('TO', $recipient); $msg->addChild('TO', $recipient);
} }
// Multipart message // Multipart message
if($this->multipartMessage) { if ($this->multipartMessage) {
$msg->addChild('MINIMUMNUMBEROFMESSAGEPARTS', 1); $msg->addChild('MINIMUMNUMBEROFMESSAGEPARTS', 1);
$msg->addChild('MAXIMUMNUMBEROFMESSAGEPARTS', 8); $msg->addChild('MAXIMUMNUMBEROFMESSAGEPARTS', 8);
} }
@ -211,16 +211,16 @@ class CMBulkSMS extends Core {
$this->result = 1; $this->result = 1;
// set result and log error if needed // set result and log error if needed
if($cError) { 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); error_log($this->error, E_USER_ERROR);
$this->result = $this->error; $this->result = $this->error;
} }
// Debug output // Debug output
// Note: CM's XML gateway gives no response when message is sent successfully :/ // Note: CM's XML gateway gives no response when message is sent successfully :/
if($this->debug || PSM_DEBUG) { if ($this->debug || PSM_DEBUG) {
$debug = '<pre>Request: '. $this->request . '<br>Response: ' . $cResponse.'</pre>'; $debug = '<pre>Request: '.$this->request.'<br>Response: '.$cResponse.'</pre>';
error_log("Request: $this->request\r\nResponse: $cResponse", E_USER_NOTICE); error_log("Request: $this->request\r\nResponse: $cResponse", E_USER_NOTICE);
echo $debug; echo $debug;
} }

View File

@ -56,7 +56,7 @@ class Callr extends Core {
$error = ""; $error = "";
$success = 1; $success = 1;
foreach($this->recipients as $recipient) { foreach ($this->recipients as $recipient) {
$curl = curl_init(); $curl = curl_init();
curl_setopt_array($curl, array( curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.callr.com/rest/v1.1/sms", CURLOPT_URL => "https://api.callr.com/rest/v1.1/sms",
@ -74,7 +74,7 @@ class Callr extends Core {
) )
), ),
CURLOPT_HTTPHEADER => array( CURLOPT_HTTPHEADER => array(
"authorization: Basic " . base64_encode($this->username . ":" . $this->password), "authorization: Basic ".base64_encode($this->username.":".$this->password),
"content-type: application/json" "content-type: application/json"
), ),
)); ));
@ -82,13 +82,15 @@ class Callr extends Core {
$result = json_decode(curl_exec($curl), true); $result = json_decode(curl_exec($curl), true);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if($err = curl_errno($curl) || $httpcode != 200 || $result['status'] == "error") { if ($err = curl_errno($curl) || $httpcode != 200 || $result['status'] == "error") {
$success = 0; $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); curl_close($curl);
} }
if($success) return 1; if ($success) {
return 1;
}
return $error; return $error;
} }
} }

View File

@ -53,13 +53,15 @@ class ClickSend extends Core {
$error = ""; $error = "";
$success = 1; $success = 1;
if(empty($this->recipients)) return false; if (empty($this->recipients)) {
return false;
}
$data = array('messages' => array()); $data = array('messages' => array());
foreach($this->recipients as $recipient) { foreach ($this->recipients as $recipient) {
$data['messages'][] = array( $data['messages'][] = array(
'source' => 'phpservermon', 'source' => 'phpservermon',
'from' => substr($this->originator,0,11), 'from' => substr($this->originator, 0, 11),
'to' => $recipient, 'to' => $recipient,
'body' => $message, 'body' => $message,
); );
@ -76,21 +78,23 @@ class ClickSend extends Core {
CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($data), CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => array( CURLOPT_HTTPHEADER => array(
"authorization: Basic " . base64_encode($this->username . ":" . $this->password), "authorization: Basic ".base64_encode($this->username.":".$this->password),
"content-type: application/json" "content-type: application/json"
), ),
)); ));
$result = json_decode(curl_exec($curl),true); $result = json_decode(curl_exec($curl), true);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if($err = curl_errno($curl) || ($httpcode != '200' && $httpcode != '201' && $httpcode != '202' && $result['response_code'] != "SUCCESS")) { if ($err = curl_errno($curl) || ($httpcode != '200' && $httpcode != '201' && $httpcode != '202' && $result['response_code'] != "SUCCESS")) {
$success = 0; $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); curl_close($curl);
if($success) return 1; if ($success) {
return 1;
}
return $error; return $error;
} }
} }

View File

@ -47,7 +47,7 @@ class Clickatell extends Core {
public function sendSMS($message) { public function sendSMS($message) {
$success = 1; $success = 1;
$error = ''; $error = '';
foreach($this->recipients as $recipient) { foreach ($this->recipients as $recipient) {
$ch = curl_init(); $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); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
@ -63,7 +63,7 @@ class Clickatell extends Core {
$success = 0; $success = 0;
} }
} }
if($success == 1){ if ($success) {
return 1; return 1;
} }
return $error; return $error;

View File

@ -50,8 +50,8 @@ class FreeMobileSMS extends Core {
$error = ""; $error = "";
$curl = curl_init(); $curl = curl_init();
curl_setopt($curl,CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl,CURLOPT_URL, "https://smsapi.free-mobile.fr/sendmsg?" . http_build_query( curl_setopt($curl, CURLOPT_URL, "https://smsapi.free-mobile.fr/sendmsg?".http_build_query(
array( array(
"user" => $this->username, "user" => $this->username,
"pass" => $this->password, "pass" => $this->password,
@ -63,13 +63,15 @@ class FreeMobileSMS extends Core {
$result = curl_exec($curl); $result = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if($err = curl_errno($curl) || $httpcode != 200) { if ($err = curl_errno($curl) || $httpcode != 200) {
$success = 0; $success = 0;
$error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err); $error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err);
} }
curl_close($curl); curl_close($curl);
if($success) return 1; if ($success) {
return 1;
}
return $error; return $error;
} }
} }

View File

@ -54,10 +54,10 @@ class FreeVoipDeal extends Core {
$message = rawurlencode($message); $message = rawurlencode($message);
foreach($this->recipients as $recipient) { foreach ($this->recipients as $recipient) {
$curl = curl_init(); $curl = curl_init();
curl_setopt($curl,CURLOPT_URL, "https://www.freevoipdeal.com/myaccount/sendsms.php?" . http_build_query( curl_setopt($curl, CURLOPT_URL, "https://www.freevoipdeal.com/myaccount/sendsms.php?".http_build_query(
array( array(
"username" => $this->username, "username" => $this->username,
"password" => $this->password, "password" => $this->password,
@ -67,19 +67,21 @@ class FreeVoipDeal extends Core {
) )
) )
); );
curl_setopt($curl,CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl); $result = curl_exec($curl);
$err = curl_error($curl); $err = curl_error($curl);
curl_close($curl); curl_close($curl);
if($err || is_numeric(strpos($result, "failure"))) { if ($err || is_numeric(strpos($result, "failure"))) {
$success = 0; $success = 0;
$error = $result; $error = $result;
} }
} }
if($success) return 1; if ($success) {
return 1;
}
return $error; return $error;
} }
} }

View File

@ -53,7 +53,9 @@ class GatewayAPI extends Core {
$error = ""; $error = "";
$success = 1; $success = 1;
if(empty($this->recipients)) return false; if (empty($this->recipients)) {
return false;
}
$json = [ $json = [
'sender' => isset($this->originator) ? $this->originator : "PHPServerMon", 'sender' => isset($this->originator) ? $this->originator : "PHPServerMon",
@ -61,28 +63,30 @@ class GatewayAPI extends Core {
'recipients' => [], 'recipients' => [],
]; ];
foreach($this->recipients as $recipient) { foreach ($this->recipients as $recipient) {
$json['recipients'][] = ['msisdn' => $recipient]; $json['recipients'][] = ['msisdn' => $recipient];
} }
$curl = curl_init(); $curl = curl_init();
curl_setopt($curl,CURLOPT_URL, "https://gatewayapi.com/rest/mtsms"); curl_setopt($curl, CURLOPT_URL, "https://gatewayapi.com/rest/mtsms");
curl_setopt($curl,CURLOPT_HTTPHEADER, array("Content-Type: application/json")); curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
curl_setopt($curl,CURLOPT_USERPWD, $this->password . ":"); curl_setopt($curl, CURLOPT_USERPWD, $this->password.":");
curl_setopt($curl,CURLOPT_POSTFIELDS, json_encode($json)); curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($json));
curl_setopt($curl,CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = json_decode(curl_exec($curl),true); $result = json_decode(curl_exec($curl), true);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$err = curl_error($curl); $err = curl_error($curl);
curl_close($curl); curl_close($curl);
if($err || $httpcode != 200) { if ($err || $httpcode != 200) {
$success = 0; $success = 0;
$error = $result['code']." - ".$result['message']; $error = $result['code']." - ".$result['message'];
} }
if($success) return 1; if ($success) {
return 1;
}
return $error; return $error;
} }
} }

View File

@ -53,7 +53,7 @@ class Inetworx extends Core {
$error = ""; $error = "";
$success = 1; $success = 1;
foreach($this->recipients as $recipient) { foreach ($this->recipients as $recipient) {
$curl = curl_init(); $curl = curl_init();
curl_setopt_array($curl, array( curl_setopt_array($curl, array(
@ -74,7 +74,7 @@ class Inetworx extends Core {
) )
), ),
CURLOPT_HTTPHEADER => array( CURLOPT_HTTPHEADER => array(
"authorization: Basic " . base64_encode("inetworxag:conn2smsapp"), "authorization: Basic ".base64_encode("inetworxag:conn2smsapp"),
"content-type: application/x-www-form-urlencoded" "content-type: application/x-www-form-urlencoded"
), ),
)); ));
@ -82,14 +82,16 @@ class Inetworx extends Core {
$result = curl_exec($curl); $result = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if($err = curl_errno($curl) || $httpcode != 200 || strpos($result, "200") === false) { if ($err = curl_errno($curl) || $httpcode != 200 || strpos($result, "200") === false) {
$success = 0; $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); curl_close($curl);
} }
if($success) return 1; if ($success) {
return 1;
}
return $error; return $error;
} }
} }

View File

@ -76,7 +76,7 @@ class Messagebird extends Core {
$success = 0; $success = 0;
} }
} }
if($success == 1){ if ($success) {
return 1; return 1;
} }
return $error; return $error;

View File

@ -53,10 +53,10 @@ class Mosms extends Core {
$message = rawurlencode($message); $message = rawurlencode($message);
foreach($this->recipients as $recipient) { foreach ($this->recipients as $recipient) {
$curl = curl_init(); $curl = curl_init();
curl_setopt($curl,CURLOPT_URL, "https://www.mosms.com/se/sms-send.php?" . http_build_query( curl_setopt($curl, CURLOPT_URL, "https://www.mosms.com/se/sms-send.php?".http_build_query(
array( array(
"username" => $this->username, "username" => $this->username,
"password" => $this->password, "password" => $this->password,
@ -67,13 +67,13 @@ class Mosms extends Core {
) )
) )
); );
curl_setopt($curl,CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$result = curl_exec($curl); $result = curl_exec($curl);
$err = curl_error($curl); $err = curl_error($curl);
if($err = curl_errno($curl) || $httpcode != 200 || $result == 2 || $result == 5) { if ($err = curl_errno($curl) || $httpcode != 200 || $result == 2 || $result == 5) {
$success = 0; $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;
} }
@ -81,7 +81,9 @@ class Mosms extends Core {
} }
if($success) return 1; if ($success) {
return 1;
}
return $error; return $error;
} }
} }

View File

@ -56,11 +56,11 @@ class Nexmo extends Core {
$message = rawurlencode($message); $message = rawurlencode($message);
foreach($this->recipients as $recipient) { foreach ($this->recipients as $recipient) {
$curl = curl_init(); $curl = curl_init();
curl_setopt($curl,CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl,CURLOPT_URL, "https://rest.nexmo.com/sms/json?" . http_build_query( curl_setopt($curl, CURLOPT_URL, "https://rest.nexmo.com/sms/json?".http_build_query(
array( array(
"api_key" => $this->username, "api_key" => $this->username,
"api_secret" => $this->password, "api_secret" => $this->password,
@ -71,12 +71,12 @@ class Nexmo extends Core {
) )
); );
$result = json_decode(curl_exec($curl),true); $result = json_decode(curl_exec($curl), true);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$err = curl_error($curl); $err = curl_error($curl);
if($err = curl_errno($curl) || $httpcode != 200 || $result['messages'][0]['status'] != "0") { if ($err = curl_errno($curl) || $httpcode != 200 || $result['messages'][0]['status'] != "0") {
$success = 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'];
} }
@ -84,7 +84,9 @@ class Nexmo extends Core {
} }
if($success) return 1; if ($success) {
return 1;
}
return $error; return $error;
} }
} }

View File

@ -60,10 +60,10 @@ class Octopush extends Core {
$recipients = join(',', $this->recipients); $recipients = join(',', $this->recipients);
$message = ($smsType == "FR") ? urlencode($message . " STOP au XXXX") : urlencode($message); $message = ($smsType == "FR") ? urlencode($message." STOP au XXXX") : urlencode($message);
$curl = curl_init(); $curl = curl_init();
curl_setopt($curl,CURLOPT_URL, "http://www.octopush-dm.com/api/sms/?" . http_build_query( curl_setopt($curl, CURLOPT_URL, "http://www.octopush-dm.com/api/sms/?".http_build_query(
array( array(
"user_login" => $this->username, "user_login" => $this->username,
"api_key" => $this->password, "api_key" => $this->password,
@ -74,19 +74,21 @@ class Octopush extends Core {
) )
) )
); );
curl_setopt($curl,CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl); $result = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$xmlResults = simplexml_load_string($result); $xmlResults = simplexml_load_string($result);
if($err = curl_errno($curl) || $httpcode != 200 || $xmlResults === false || $xmlResults->error_code != '000') { if ($err = curl_errno($curl) || $httpcode != 200 || $xmlResults === false || $xmlResults->error_code != '000') {
$success = 0; $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); curl_close($curl);
if($success) return 1; if ($success) {
return 1;
}
return $error; return $error;
} }
} }

View File

@ -52,13 +52,15 @@ class Plivo extends Core {
$error = ""; $error = "";
$success = 1; $success = 1;
if(empty($this->recipients)) return false; if (empty($this->recipients)) {
return false;
}
$recipients = join('<', $this->recipients); $recipients = join('<', $this->recipients);
$curl = curl_init(); $curl = curl_init();
curl_setopt_array($curl, array( curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.plivo.com/v1/Account/" . $this->username . "/Message/", CURLOPT_URL => "https://api.plivo.com/v1/Account/".$this->username."/Message/",
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "", CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10, CURLOPT_MAXREDIRS => 10,
@ -73,20 +75,22 @@ class Plivo extends Core {
) )
), ),
CURLOPT_HTTPHEADER => array( CURLOPT_HTTPHEADER => array(
"authorization: Basic " . base64_encode($this->username . ":" . $this->password), "authorization: Basic ".base64_encode($this->username.":".$this->password),
"content-type: application/json" "content-type: application/json"
), ),
)); ));
$result = curl_exec($curl); $result = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if($err = curl_errno($curl) || ($httpcode != '200' && $httpcode != '201' && $httpcode != '202')) { if ($err = curl_errno($curl) || ($httpcode != '200' && $httpcode != '201' && $httpcode != '202')) {
$success = 0; $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); curl_close($curl);
if($success) return 1; if ($success) {
return 1;
}
return $error; return $error;
} }
} }

View File

@ -55,13 +55,13 @@ class Smsglobal extends Core {
$recipients = join(',', $this->recipients); $recipients = join(',', $this->recipients);
$from = substr($this->originator,0 , 11); // Max 11 Characters $from = substr($this->originator, 0, 11); // Max 11 Characters
$message = substr(rawurlencode($message), 0, 153); $message = substr(rawurlencode($message), 0, 153);
$curl = curl_init(); $curl = curl_init();
curl_setopt($curl,CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl,CURLOPT_TIMEOUT, 30); curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl,CURLOPT_URL, "https://www.smsglobal.com/http-api.php?" . http_build_query( curl_setopt($curl, CURLOPT_URL, "https://www.smsglobal.com/http-api.php?".http_build_query(
array( array(
"action" => "sendsms", "action" => "sendsms",
"user" => $this->username, "user" => $this->username,
@ -79,14 +79,16 @@ class Smsglobal extends Core {
$result = curl_exec($curl); $result = curl_exec($curl);
$err = curl_error($curl); $err = curl_error($curl);
if($err = curl_errno($curl) || substr($result, 0, 5) != "OK: 0") { if ($err = curl_errno($curl) || substr($result, 0, 5) != "OK: 0") {
$success = 0; $success = 0;
$result = ($result == '') ? 'Wrong input, please check if all values are correct!' : $result; $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); curl_close($curl);
if($success) return 1; if ($success) {
return 1;
}
return $error; return $error;
} }
} }

View File

@ -74,13 +74,15 @@ class Smsgw extends Core {
$result = curl_exec($curl); $result = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if($err = curl_errno($curl) || ($httpcode != '200' && $httpcode != '201' && $httpcode != '202' && $result != "1")) { if ($err = curl_errno($curl) || ($httpcode != '200' && $httpcode != '201' && $httpcode != '202' && $result != "1")) {
$success = 0; $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); curl_close($curl);
if($success) return 1; if ($success) {
return 1;
}
return $error; return $error;
} }
} }

View File

@ -53,31 +53,33 @@ class Smsit extends Core {
$success = 1; $success = 1;
$error = ""; $error = "";
foreach( $this->recipients as $recipient ){ foreach ($this->recipients as $recipient) {
$curl = curl_init(); $curl = curl_init();
curl_setopt($curl,CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl,CURLOPT_URL, "https://www.smsit.dk/api/v2?" . http_build_query( curl_setopt($curl, CURLOPT_URL, "https://www.smsit.dk/api/v2?".http_build_query(
array( array(
"apiKey" => $this->password, "apiKey" => $this->password,
"mobile" => $recipient, "mobile" => $recipient,
"message" => urlencode($message), "message" => urlencode($message),
"senderId" => substr($this->originator,0,11), "senderId" => substr($this->originator, 0, 11),
) )
) )
); );
$result = curl_exec($curl); $result = curl_exec($curl);
$err =curl_error($curl); $err = curl_error($curl);
curl_close($curl); curl_close($curl);
if($err || is_numeric(strpos($result, "{\"errors\":[{\"code\":"))) { if ($err || is_numeric(strpos($result, "{\"errors\":[{\"code\":"))) {
$success = 0; $success = 0;
$error = $result; $error = $result;
} }
} }
if($success) return 1; if ($success) {
return 1;
}
return $error; return $error;
} }
} }

View File

@ -58,7 +58,7 @@ class SolutionsInfini extends Core {
$recipients = join(',', $this->recipients); $recipients = join(',', $this->recipients);
$curl = curl_init(); $curl = curl_init();
curl_setopt($curl,CURLOPT_URL, "https://api-alerts.solutionsinfini.com/v4/?" . http_build_query( curl_setopt($curl, CURLOPT_URL, "https://api-alerts.solutionsinfini.com/v4/?".http_build_query(
array( array(
"api_key" => $this->password, "api_key" => $this->password,
"method" => "sms", "method" => "sms",
@ -68,18 +68,20 @@ class SolutionsInfini extends Core {
) )
) )
); );
curl_setopt($curl,CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$result = json_decode(curl_exec($curl), true); $result = json_decode(curl_exec($curl), true);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if($err = curl_errno($curl) || $httpcode != 200 || $result['status'] != "OK") { if ($err = curl_errno($curl) || $httpcode != 200 || $result['status'] != "OK") {
$success = 0; $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); curl_close($curl);
if($success) return 1; if ($success) {
return 1;
}
return $error; return $error;
} }
} }

View File

@ -36,7 +36,6 @@ class Spryng extends Core {
* @var string $this->username * @var string $this->username
* @var string $this->password * @var string $this->password
* @var string $this->originator * @var string $this->originator
* @var mixed $result * @var mixed $result
* @var array $headers * @var array $headers
* *

View File

@ -50,7 +50,7 @@ class Textmarketer extends Core {
public function sendSMS($message) { public function sendSMS($message) {
$success = 1; $success = 1;
$error = ''; $error = '';
foreach( $this->recipients as $recipient ){ foreach ($this->recipients as $recipient) {
$ch = curl_init(); $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");
@ -67,7 +67,7 @@ class Textmarketer extends Core {
$success = 0; $success = 0;
} }
} }
if($success == 1){ if ($success == 1) {
return 1; return 1;
} }
return $error; return $error;

View File

@ -51,13 +51,13 @@ class Twilio extends Core {
$success = 1; $success = 1;
$error = ''; $error = '';
foreach($this->recipients as $recipient) { foreach ($this->recipients as $recipient) {
$ch = curl_init(); $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_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_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, $this->username . ":" . $this->password); curl_setopt($ch, CURLOPT_USERPWD, $this->username.":".$this->password);
$headers = array(); $headers = array();
$headers[] = "Content-Type: application/x-www-form-urlencoded"; $headers[] = "Content-Type: application/x-www-form-urlencoded";
@ -72,7 +72,7 @@ class Twilio extends Core {
$success = 0; $success = 0;
} }
} }
if($success == 1){ if ($success) {
return 1; return 1;
} }
return $error; return $error;

View File

@ -71,14 +71,14 @@ class Installer {
public function isUpgradeRequired() { public function isUpgradeRequired() {
$version_db = psm_get_conf('version'); $version_db = psm_get_conf('version');
if(version_compare(PSM_VERSION, $version_db, '==')) { if (version_compare(PSM_VERSION, $version_db, '==')) {
// version is up to date // version is up to date
return false; return false;
} }
// different DB version, check if the version requires any changes // different DB version, check if the version requires any changes
// @todo this is currently a manual check for each version, similar to upgrade().. not a clean way // @todo this is currently a manual check for each version, similar to upgrade().. not a clean way
if(version_compare($version_db, PSM_VERSION, '<')) { if (version_compare($version_db, PSM_VERSION, '<')) {
return true; return true;
} else { } else {
// change database version to current version so this check won't be required next time // change database version to current version so this check won't be required next time
@ -93,10 +93,10 @@ class Installer {
* @return \psm\Util\Install\Installer * @return \psm\Util\Install\Installer
*/ */
protected function log($msg) { protected function log($msg) {
if(is_callable($this->logger)) { if (is_callable($this->logger)) {
$msg = (!is_array($msg)) ? array($msg) : $msg; $msg = (!is_array($msg)) ? array($msg) : $msg;
foreach($msg as $m) { foreach ($msg as $m) {
call_user_func($this->logger, $m); call_user_func($this->logger, $m);
} }
} }
@ -111,7 +111,7 @@ class Installer {
protected function execSQL($query) { protected function execSQL($query) {
$query = (!is_array($query)) ? array($query) : $query; $query = (!is_array($query)) ? array($query) : $query;
foreach($query as $q) { foreach ($query as $q) {
$this->queries[] = $q; $this->queries[] = $q;
$this->db->exec($q); $this->db->exec($q);
} }
@ -126,9 +126,9 @@ class Installer {
$this->log('Populating database...'); $this->log('Populating database...');
$queries = array(); $queries = array();
$queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "servers` (`ip`, `port`, `label`, `type`, `pattern`, `pattern_online`, `status`, `rtime`, `active`, `email`, `sms`, `pushover`, `telegram`) VALUES ('http://sourceforge.net/index.php', 80, 'SourceForge', 'website', '', 'yes','on', '0.0000000', 'yes', 'yes', 'yes', 'yes', 'yes'), ('smtp.gmail.com', 465, 'Gmail SMTP', 'service', '', 'yes', 'on', '0.0000000', 'yes', 'yes', 'yes', 'yes', 'yes')"; $queries[] = "INSERT INTO `".PSM_DB_PREFIX."servers` (`ip`, `port`, `label`, `type`, `pattern`, `pattern_online`, `status`, `rtime`, `active`, `email`, `sms`, `pushover`, `telegram`) VALUES ('http://sourceforge.net/index.php', 80, 'SourceForge', 'website', '', 'yes','on', '0.0000000', 'yes', 'yes', 'yes', 'yes', 'yes'), ('smtp.gmail.com', 465, 'Gmail SMTP', 'service', '', 'yes', '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."users_servers` (`user_id`,`server_id`) VALUES (1, 1), (1, 2);";
$queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`) VALUE $queries[] = "INSERT INTO `".PSM_DB_PREFIX."config` (`key`, `value`) VALUE
('language', 'en_US'), ('language', 'en_US'),
('proxy', '0'), ('proxy', '0'),
('proxy_url', ''), ('proxy_url', ''),
@ -152,7 +152,7 @@ class Installer {
('pushover_api_token', ''), ('pushover_api_token', ''),
('telegram_status', '0'), ('telegram_status', '0'),
('telegram_api_token', ''), ('telegram_api_token', ''),
('password_encrypt_key', '" . sha1(microtime()) . "'), ('password_encrypt_key', '".sha1(microtime())."'),
('alert_type', 'status'), ('alert_type', 'status'),
('log_status', '1'), ('log_status', '1'),
('log_email', '1'), ('log_email', '1'),
@ -160,8 +160,8 @@ class Installer {
('log_pushover', '1'), ('log_pushover', '1'),
('log_telegram', '1'), ('log_telegram', '1'),
('log_retention_period', '365'), ('log_retention_period', '365'),
('version', '" . PSM_VERSION . "'), ('version', '".PSM_VERSION."'),
('version_update_check', '" . PSM_VERSION . "'), ('version_update_check', '".PSM_VERSION."'),
('auto_refresh_servers', '0'), ('auto_refresh_servers', '0'),
('show_update', '1'), ('show_update', '1'),
('last_update_check', '0'), ('last_update_check', '0'),
@ -175,12 +175,12 @@ class Installer {
*/ */
protected function installTables() { protected function installTables() {
$tables = array( $tables = array(
PSM_DB_PREFIX . 'config' => "CREATE TABLE `" . PSM_DB_PREFIX . "config` ( PSM_DB_PREFIX.'config' => "CREATE TABLE `".PSM_DB_PREFIX."config` (
`key` varchar(255) NOT NULL, `key` varchar(255) NOT NULL,
`value` varchar(255) NOT NULL, `value` varchar(255) NOT NULL,
PRIMARY KEY (`key`) PRIMARY KEY (`key`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;", ) ENGINE=MyISAM DEFAULT CHARSET=utf8;",
PSM_DB_PREFIX . 'users' => "CREATE TABLE IF NOT EXISTS `" . PSM_DB_PREFIX . "users` ( PSM_DB_PREFIX.'users' => "CREATE TABLE IF NOT EXISTS `".PSM_DB_PREFIX."users` (
`user_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`user_name` varchar(64) NOT NULL COMMENT 'user''s name, unique', `user_name` varchar(64) NOT NULL COMMENT 'user''s name, unique',
`password` varchar(255) NOT NULL COMMENT 'user''s password in salted and hashed format', `password` varchar(255) NOT NULL COMMENT 'user''s password in salted and hashed format',
@ -197,18 +197,18 @@ class Installer {
PRIMARY KEY (`user_id`), PRIMARY KEY (`user_id`),
UNIQUE KEY `unique_username` (`user_name`) UNIQUE KEY `unique_username` (`user_name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;", ) 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, `user_id` int(11) unsigned NOT NULL,
`key` varchar(255) NOT NULL, `key` varchar(255) NOT NULL,
`value` varchar(255) NOT NULL, `value` varchar(255) NOT NULL,
PRIMARY KEY (`user_id`, `key`) PRIMARY KEY (`user_id`, `key`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;", ) ENGINE=MyISAM DEFAULT CHARSET=utf8;",
PSM_DB_PREFIX . 'users_servers' => "CREATE TABLE `" . PSM_DB_PREFIX . "users_servers` ( PSM_DB_PREFIX.'users_servers' => "CREATE TABLE `".PSM_DB_PREFIX."users_servers` (
`user_id` INT( 11 ) UNSIGNED NOT NULL , `user_id` INT( 11 ) UNSIGNED NOT NULL ,
`server_id` INT( 11 ) UNSIGNED NOT NULL , `server_id` INT( 11 ) UNSIGNED NOT NULL ,
PRIMARY KEY ( `user_id` , `server_id` ) PRIMARY KEY ( `user_id` , `server_id` )
) ENGINE = MYISAM ;", ) ENGINE = MYISAM ;",
PSM_DB_PREFIX . 'log' => "CREATE TABLE `" . PSM_DB_PREFIX . "log` ( PSM_DB_PREFIX.'log' => "CREATE TABLE `".PSM_DB_PREFIX."log` (
`log_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `log_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`server_id` int(11) unsigned NOT NULL, `server_id` int(11) unsigned NOT NULL,
`type` enum('status','email','sms','pushover','telegram') NOT NULL, `type` enum('status','email','sms','pushover','telegram') NOT NULL,
@ -216,12 +216,12 @@ class Installer {
`datetime` timestamp NOT NULL default CURRENT_TIMESTAMP, `datetime` timestamp NOT NULL default CURRENT_TIMESTAMP,
PRIMARY KEY (`log_id`) PRIMARY KEY (`log_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;", ) ENGINE=MyISAM DEFAULT CHARSET=utf8;",
PSM_DB_PREFIX . 'log_users' => "CREATE TABLE `" . PSM_DB_PREFIX . "log_users` ( PSM_DB_PREFIX.'log_users' => "CREATE TABLE `".PSM_DB_PREFIX."log_users` (
`log_id` int(11) UNSIGNED NOT NULL , `log_id` int(11) UNSIGNED NOT NULL ,
`user_id` int(11) UNSIGNED NOT NULL , `user_id` int(11) UNSIGNED NOT NULL ,
PRIMARY KEY (`log_id`, `user_id`) PRIMARY KEY (`log_id`, `user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;", ) ENGINE=MyISAM DEFAULT CHARSET=utf8;",
PSM_DB_PREFIX . 'servers' => "CREATE TABLE `" . PSM_DB_PREFIX . "servers` ( PSM_DB_PREFIX.'servers' => "CREATE TABLE `".PSM_DB_PREFIX."servers` (
`server_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `server_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`ip` varchar(500) NOT NULL, `ip` varchar(500) NOT NULL,
`port` int(5) unsigned NOT NULL, `port` int(5) unsigned NOT NULL,
@ -250,7 +250,7 @@ class Installer {
`website_password` varchar(255) DEFAULT NULL, `website_password` varchar(255) DEFAULT NULL,
PRIMARY KEY (`server_id`) PRIMARY KEY (`server_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;", ) ENGINE=MyISAM DEFAULT CHARSET=utf8;",
PSM_DB_PREFIX . 'servers_uptime' => "CREATE TABLE IF NOT EXISTS `" . PSM_DB_PREFIX . "servers_uptime` ( PSM_DB_PREFIX.'servers_uptime' => "CREATE TABLE IF NOT EXISTS `".PSM_DB_PREFIX."servers_uptime` (
`servers_uptime_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `servers_uptime_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`server_id` int(11) unsigned NOT NULL, `server_id` int(11) unsigned NOT NULL,
`date` datetime NOT NULL, `date` datetime NOT NULL,
@ -259,7 +259,7 @@ class Installer {
PRIMARY KEY (`servers_uptime_id`), PRIMARY KEY (`servers_uptime_id`),
KEY `server_id` (`server_id`) KEY `server_id` (`server_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;", ) ENGINE=MyISAM DEFAULT CHARSET=utf8;",
PSM_DB_PREFIX . 'servers_history' => "CREATE TABLE IF NOT EXISTS `" . PSM_DB_PREFIX . "servers_history` ( PSM_DB_PREFIX.'servers_history' => "CREATE TABLE IF NOT EXISTS `".PSM_DB_PREFIX."servers_history` (
`servers_history_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `servers_history_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`server_id` int(11) unsigned NOT NULL, `server_id` int(11) unsigned NOT NULL,
`date` date NOT NULL, `date` date NOT NULL,
@ -273,14 +273,14 @@ class Installer {
) ENGINE=MyISAM DEFAULT CHARSET=utf8;", ) ENGINE=MyISAM DEFAULT CHARSET=utf8;",
); );
foreach($tables as $name => $sql) { foreach ($tables as $name => $sql) {
$if_table_exists = $this->db->query("SHOW TABLES LIKE '{$name}'"); $if_table_exists = $this->db->query("SHOW TABLES LIKE '{$name}'");
if(!empty($if_table_exists)) { if (!empty($if_table_exists)) {
$this->log('Table ' . $name . ' already exists in your database!'); $this->log('Table '.$name.' already exists in your database!');
} else { } else {
$this->execSQL($sql); $this->execSQL($sql);
$this->log('Table ' . $name . ' added.'); $this->log('Table '.$name.' added.');
} }
} }
} }
@ -292,25 +292,25 @@ class Installer {
* @see isUpgradeRequired() * @see isUpgradeRequired()
*/ */
public function upgrade($version_from, $version_to) { public function upgrade($version_from, $version_to) {
if(version_compare($version_from, '2.1.0', '<')) { if (version_compare($version_from, '2.1.0', '<')) {
$this->upgrade210(); $this->upgrade210();
} }
if(version_compare($version_from, '3.0.0', '<')) { if (version_compare($version_from, '3.0.0', '<')) {
$this->upgrade300(); $this->upgrade300();
} }
if(version_compare($version_from, '3.1.0', '<')) { if (version_compare($version_from, '3.1.0', '<')) {
$this->upgrade310(); $this->upgrade310();
} }
if(version_compare($version_from, '3.2.0', '<')) { if (version_compare($version_from, '3.2.0', '<')) {
$this->upgrade320(); $this->upgrade320();
} }
if(version_compare($version_from, '3.2.1', '<')) { if (version_compare($version_from, '3.2.1', '<')) {
$this->upgrade321(); $this->upgrade321();
} }
if(version_compare($version_from, '3.2.2', '<')) { if (version_compare($version_from, '3.2.2', '<')) {
$this->upgrade322(); $this->upgrade322();
} }
if(version_compare($version_from, '3.3.0', '<')) { if (version_compare($version_from, '3.3.0', '<')) {
$this->upgrade330(); $this->upgrade330();
} }
psm_update_conf('version', $version_to); psm_update_conf('version', $version_to);
@ -321,19 +321,19 @@ class Installer {
*/ */
protected function upgrade210() { protected function upgrade210() {
$queries = array(); $queries = array();
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "config` DROP `config_id`;"; $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."config` DROP `config_id`;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "config` ADD PRIMARY KEY ( `key` );"; $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."config` ADD PRIMARY KEY ( `key` );";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "config` DROP INDEX `key`;"; $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."config` DROP INDEX `key`;";
$queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`) VALUES ('cron_running', '0');"; $queries[] = "INSERT INTO `".PSM_DB_PREFIX."config` (`key`, `value`) VALUES ('cron_running', '0');";
$queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`) VALUES ('cron_running_time', '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 `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_online` `last_online` DATETIME NULL;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` CHANGE `last_check` `last_check` DATETIME NULL;"; $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` CHANGE `last_check` `last_check` DATETIME NULL;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `pattern` VARCHAR( 255 ) NOT NULL AFTER `type`;"; $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `pattern` VARCHAR( 255 ) NOT NULL AFTER `type`;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `last_offline` DATETIME NULL;"; $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `last_offline` DATETIME NULL;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `last_offline_duration` varchar(255) NULL;"; $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `last_offline_duration` varchar(255) NULL;";
$this->execSQL($queries); $this->execSQL($queries);
} }
@ -344,32 +344,32 @@ class Installer {
protected function upgrade300() { protected function upgrade300() {
$queries = array(); $queries = array();
// language is now stored as language code (ISO 639-1) + country code (ISO 3166-1) // 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`='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`='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`='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`='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`='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`='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`='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', '');";
$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_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_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_username', '');";
$queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`) VALUES ('email_smtp_password', '');"; $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 `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 `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` 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` 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 `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` DATETIME NULL;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `last_offline_duration` varchar(255) 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` $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 `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` 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_hash` char(40) COLLATE utf8_general_ci DEFAULT NULL COMMENT 'user\'s password reset code' AFTER `password`,
@ -377,10 +377,10 @@ class Installer {
ADD `rememberme_token` varchar(64) COLLATE utf8_general_ci DEFAULT NULL COMMENT 'user\'s remember-me cookie token' AFTER `password_reset_timestamp`, 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`;"; 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): // make sure all current users are admins (previously we didnt have non-admins):
$queries[] = "UPDATE `" . PSM_DB_PREFIX . "users` SET `user_name`=`email`, `level`=10;"; $queries[] = "UPDATE `".PSM_DB_PREFIX."users` SET `user_name`=`email`, `level`=10;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "users` ADD UNIQUE `unique_username` ( `user_name` );"; $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."users` ADD UNIQUE `unique_username` ( `user_name` );";
$queries[] = "CREATE TABLE IF NOT EXISTS `" . PSM_DB_PREFIX . "servers_uptime` ( $queries[] = "CREATE TABLE IF NOT EXISTS `".PSM_DB_PREFIX."servers_uptime` (
`servers_uptime_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `servers_uptime_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`server_id` int(11) unsigned NOT NULL, `server_id` int(11) unsigned NOT NULL,
`date` datetime NOT NULL, `date` datetime NOT NULL,
@ -390,7 +390,7 @@ class Installer {
KEY `server_id` (`server_id`) KEY `server_id` (`server_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;"; ) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
$queries[] = "CREATE TABLE IF NOT EXISTS `" . PSM_DB_PREFIX . "servers_history` ( $queries[] = "CREATE TABLE IF NOT EXISTS `".PSM_DB_PREFIX."servers_history` (
`servers_history_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `servers_history_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`server_id` int(11) unsigned NOT NULL, `server_id` int(11) unsigned NOT NULL,
`date` date NOT NULL, `date` date NOT NULL,
@ -403,7 +403,7 @@ class Installer {
UNIQUE KEY `server_id_date` (`server_id`,`date`) UNIQUE KEY `server_id_date` (`server_id`,`date`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;"; ) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
$queries[] = "CREATE TABLE `" . PSM_DB_PREFIX . "users_servers` ( $queries[] = "CREATE TABLE `".PSM_DB_PREFIX."users_servers` (
`user_id` INT( 11 ) UNSIGNED NOT NULL , `user_id` INT( 11 ) UNSIGNED NOT NULL ,
`server_id` INT( 11 ) UNSIGNED NOT NULL , `server_id` INT( 11 ) UNSIGNED NOT NULL ,
PRIMARY KEY ( `user_id` , `server_id` ) PRIMARY KEY ( `user_id` , `server_id` )
@ -411,19 +411,19 @@ class Installer {
$this->execSQL($queries); $this->execSQL($queries);
// from 3.0 all user-server relations are in a separate table // from 3.0 all user-server relations are in a separate table
$users = $this->db->select(PSM_DB_PREFIX . 'users', null, array('user_id', 'server_id')); $users = $this->db->select(PSM_DB_PREFIX.'users', null, array('user_id', 'server_id'));
foreach($users as $user) { foreach ($users as $user) {
$idc = array(); $idc = array();
if($user['server_id'] == '') { if ($user['server_id'] == '') {
continue; continue;
} }
if(strpos($user['server_id'], ',') === false) { if (strpos($user['server_id'], ',') === false) {
$idc[] = $user['server_id']; $idc[] = $user['server_id'];
} else { } else {
$idc = explode(',', $user['server_id']); $idc = explode(',', $user['server_id']);
} }
foreach($idc as $id) { foreach ($idc as $id) {
$this->db->save(PSM_DB_PREFIX . 'users_servers', array( $this->db->save(PSM_DB_PREFIX.'users_servers', array(
'user_id' => $user['user_id'], 'user_id' => $user['user_id'],
'server_id' => $id, 'server_id' => $id,
)); ));
@ -442,17 +442,17 @@ class Installer {
psm_update_conf('pushover_status', 0); psm_update_conf('pushover_status', 0);
psm_update_conf('log_pushover', 1); psm_update_conf('log_pushover', 1);
psm_update_conf('pushover_api_token', ''); 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_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_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."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."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 `timeout` smallint(1) unsigned NULL DEFAULT NULL;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `last_offline` DATETIME NULL;"; $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `last_offline` DATETIME NULL;";
$queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `last_offline_duration` varchar(255) NULL;"; $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `last_offline_duration` varchar(255) NULL;";
$queries[] = "CREATE TABLE IF NOT EXISTS `" . PSM_DB_PREFIX . "users_preferences` ( $queries[] = "CREATE TABLE IF NOT EXISTS `".PSM_DB_PREFIX."users_preferences` (
`user_id` int(11) unsigned NOT NULL, `user_id` int(11) unsigned NOT NULL,
`key` varchar(255) NOT NULL, `key` varchar(255) NOT NULL,
`value` varchar(255) NOT NULL, `value` varchar(255) NOT NULL,
@ -469,9 +469,9 @@ class Installer {
$queries = array(); $queries = array();
psm_update_conf('password_encrypt_key', sha1(microtime())); 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` 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 $queries[] = "INSERT INTO `".PSM_DB_PREFIX."config` (`key`, `value`) VALUE
('proxy', '0'), ('proxy', '0'),
('proxy_url', ''), ('proxy_url', ''),
('proxy_user', ''), ('proxy_user', ''),
@ -480,14 +480,14 @@ class Installer {
$this->execSQL($queries); $this->execSQL($queries);
// Create log_users table // Create log_users table
$this->execSQL("CREATE TABLE `" . PSM_DB_PREFIX . "log_users` ( $this->execSQL("CREATE TABLE `".PSM_DB_PREFIX."log_users` (
`log_id` int(11) UNSIGNED NOT NULL , `log_id` int(11) UNSIGNED NOT NULL ,
`user_id` int(11) UNSIGNED NOT NULL , `user_id` int(11) UNSIGNED NOT NULL ,
PRIMARY KEY (`log_id`, `user_id`) PRIMARY KEY (`log_id`, `user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;"); ) ENGINE=MyISAM DEFAULT CHARSET=utf8;");
// Migrate the data // Migrate the data
$logs = $this->db->select(PSM_DB_PREFIX . 'log', null, array('log_id', 'user_id')); $logs = $this->db->select(PSM_DB_PREFIX.'log', null, array('log_id', 'user_id'));
foreach ($logs as $log) { foreach ($logs as $log) {
// Validation // Validation
if (empty($log['user_id']) || trim($log['user_id']) == '') { if (empty($log['user_id']) || trim($log['user_id']) == '') {
@ -501,7 +501,7 @@ class Installer {
} }
// Drop old user_id('s) column // Drop old user_id('s) column
$this->execSQL("ALTER TABLE `" . PSM_DB_PREFIX . "log` DROP COLUMN `user_id`;"); $this->execSQL("ALTER TABLE `".PSM_DB_PREFIX."log` DROP COLUMN `user_id`;");
} }
/** /**
@ -509,7 +509,7 @@ class Installer {
*/ */
protected function upgrade321() { protected function upgrade321() {
$queries = array(); $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); $this->execSQL($queries);
} }
@ -518,10 +518,10 @@ class Installer {
*/ */
protected function upgrade322() { protected function upgrade322() {
$queries = array(); $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."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."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."log` CHANGE `type` `type` ENUM( 'status', 'email', 'sms', 'pushover', 'telegram' ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;";
$queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`) VALUE $queries[] = "INSERT INTO `".PSM_DB_PREFIX."config` (`key`, `value`) VALUE
('telegram_status', '0'), ('telegram_status', '0'),
('log_telegram', '1'), ('log_telegram', '1'),
('telegram_api_token', '');"; ('telegram_api_token', '');";
@ -533,10 +533,10 @@ class Installer {
*/ */
protected function upgrade330() { protected function upgrade330() {
$queries = array(); $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 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 `pattern_online` ENUM( 'yes','no' ) NOT NULL DEFAULT 'yes' AFTER `pattern`;";
$this->execSQL($queries); $this->execSQL($queries);
if(psm_get_conf('sms_gateway') == 'mollie'){ if (psm_get_conf('sms_gateway') == 'mollie') {
psm_update_conf('sms_gateway', 'messagebird'); psm_update_conf('sms_gateway', 'messagebird');
} }

View File

@ -69,7 +69,7 @@ class Modal implements ModalInterface {
*/ */
protected $twig; 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->modal_id = $modal_id;
$this->twig = $twig; $this->twig = $twig;
$this->type = $type; $this->type = $type;
@ -89,7 +89,7 @@ class Modal implements ModalInterface {
* @return \psm\Util\Module\Modal * @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))) { if (in_array($type, array(self::MODAL_TYPE_OK, self::MODAL_TYPE_OKCANCEL, self::MODAL_TYPE_DANGER))) {
$this->type = $type; $this->type = $type;
} }
return $this; return $this;
@ -127,9 +127,9 @@ class Modal implements ModalInterface {
$message = !empty($this->message) ? $this->message : ''; $message = !empty($this->message) ? $this->message : '';
$matches = array(); $matches = array();
if(preg_match_all('/%(\d)/', $message, $matches, PREG_SET_ORDER)) { if (preg_match_all('/%(\d)/', $message, $matches, PREG_SET_ORDER)) {
foreach($matches as $match) { foreach ($matches as $match) {
$message = str_replace($match[0], '<span class="modalP' . $match[1] . '"></span>', $message); $message = str_replace($match[0], '<span class="modalP'.$match[1].'"></span>', $message);
} }
} }

View File

@ -88,7 +88,7 @@ class Sidebar implements SidebarInterface {
* @return \psm\Util\Module\Sidebar * @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'])) { if (!isset($this->items['link'])) {
$this->items['link'] = array(); $this->items['link'] = array();
} }
@ -112,11 +112,11 @@ class Sidebar implements SidebarInterface {
* @return \psm\Util\Module\Sidebar * @return \psm\Util\Module\Sidebar
*/ */
public function addButton($id, $label, $url, $icon = null, $btn_class = null, $url_is_onclick = false) { public function addButton($id, $label, $url, $icon = null, $btn_class = null, $url_is_onclick = false) {
if(!isset($this->items['button'])) { if (!isset($this->items['button'])) {
$this->items['button'] = array(); $this->items['button'] = array();
} }
if(!$url_is_onclick) { if (!$url_is_onclick) {
$url = "psm_goTo('" . $url . "');"; $url = "psm_goTo('".$url."');";
} }
$this->items['button'][$id] = array( $this->items['button'][$id] = array(
@ -139,7 +139,7 @@ class Sidebar implements SidebarInterface {
* @return \psm\Util\Module\Sidebar * @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'])) { if (!isset($this->items['dropdown'])) {
$this->items['dropdown'] = array(); $this->items['dropdown'] = array();
} }
$this->items['dropdown'][$id] = array( $this->items['dropdown'][$id] = array(
@ -160,14 +160,14 @@ class Sidebar implements SidebarInterface {
$tpl_data['items'] = array(); $tpl_data['items'] = array();
// loop through all types and build their html // loop through all types and build their html
foreach($types as $type) { foreach ($types as $type) {
if(empty($this->items[$type])) { if (empty($this->items[$type])) {
// no items for this type // no items for this type
continue; continue;
} }
// build html for each individual item // build html for each individual item
foreach($this->items[$type] as $id => $item) { foreach ($this->items[$type] as $id => $item) {
$item['type'] = $type; $item['type'] = $type;
$item['class_active'] = ($id === $this->active_id) ? 'active' : ''; $item['class_active'] = ($id === $this->active_id) ? 'active' : '';
$tpl_data['items'][] = $item; $tpl_data['items'][] = $item;

View File

@ -68,8 +68,8 @@ class ArchiveManager {
*/ */
public function archive($server_id = null) { public function archive($server_id = null) {
$result = true; $result = true;
foreach($this->archivers as $archiver) { foreach ($this->archivers as $archiver) {
if(!$archiver->archive($server_id)) { if (!$archiver->archive($server_id)) {
$result = false; $result = false;
} }
} }
@ -83,15 +83,15 @@ class ArchiveManager {
*/ */
public function cleanup($server_id = null) { public function cleanup($server_id = null) {
$result = true; $result = true;
if(!$this->retention_period) { if (!$this->retention_period) {
// cleanup is disabled // cleanup is disabled
return $result; return $result;
} }
$retdate = new \DateTime(); $retdate = new \DateTime();
$retdate->sub($this->retention_period); $retdate->sub($this->retention_period);
foreach($this->archivers as $archiver) { foreach ($this->archivers as $archiver) {
if(!$archiver->cleanup($retdate, $server_id)) { if (!$archiver->cleanup($retdate, $server_id)) {
$result = false; $result = false;
} }
} }
@ -106,13 +106,13 @@ class ArchiveManager {
* @return \psm\Util\Server\ArchiveManager * @return \psm\Util\Server\ArchiveManager
*/ */
public function setRetentionPeriod($period) { public function setRetentionPeriod($period) {
if(is_object($period) && $period instanceof \DateInterval) { if (is_object($period) && $period instanceof \DateInterval) {
$this->retention_period = $period; $this->retention_period = $period;
} elseif(intval($period) == 0) { } elseif (intval($period) == 0) {
// cleanup disabled // cleanup disabled
$this->retention_period = false; $this->retention_period = false;
} else { } else {
$this->retention_period = new \DateInterval('P' . intval($period) . 'D'); $this->retention_period = new \DateInterval('P'.intval($period).'D');
} }
return $this; return $this;
} }

View File

@ -57,7 +57,7 @@ class LogsArchiver implements ArchiverInterface {
public function cleanup(\DateTime $retention_date, $server_id = null) { public function cleanup(\DateTime $retention_date, $server_id = null) {
$sql_where_server = ($server_id !== null) $sql_where_server = ($server_id !== null)
// this is obviously not the cleanest way to implement this when using paramter binding.. sorry. // this is obviously not the cleanest way to implement this when using paramter binding.. sorry.
? ' `server_id` = ' . intval($server_id) . ' AND ' ? ' `server_id` = '.intval($server_id).' AND '
: ''; : '';
$this->db->execute( $this->db->execute(
@ -72,8 +72,8 @@ class LogsArchiver implements ArchiverInterface {
* Empty tables log and log_users * 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");
$this->db->delete(PSM_DB_PREFIX . "log_users"); $this->db->delete(PSM_DB_PREFIX."log_users");
return true; return true;
} }
} }

View File

@ -65,7 +65,7 @@ class UptimeArchiver implements ArchiverInterface {
// Lock tables to prevent simultaneous archiving (by other sessions or the cron job) // Lock tables to prevent simultaneous archiving (by other sessions or the cron job)
try { 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; $locked = true;
} catch (\PDOException $e) { } catch (\PDOException $e) {
// user does not have lock rights, ignore // user does not have lock rights, ignore
@ -78,17 +78,17 @@ class UptimeArchiver implements ArchiverInterface {
$records = $this->db->execute( $records = $this->db->execute(
"SELECT `server_id`,`date`,`status`,`latency` "SELECT `server_id`,`date`,`status`,`latency`
FROM `" . PSM_DB_PREFIX."servers_uptime` FROM `".PSM_DB_PREFIX."servers_uptime`
WHERE {$sql_where_server} `date` < :latest_date", WHERE {$sql_where_server} `date` < :latest_date",
array('latest_date' => $latest_date_str)); array('latest_date' => $latest_date_str));
if(!empty($records)) { if (!empty($records)) {
// first group all records by day and server_id // first group all records by day and server_id
$data_by_day = array(); $data_by_day = array();
foreach($records as $record) { foreach ($records as $record) {
$server_id = (int)$record['server_id']; $server_id = (int) $record['server_id'];
$day = date('Y-m-d', strtotime($record['date'])); $day = date('Y-m-d', strtotime($record['date']));
if(!isset($data_by_day[$day][$server_id])) { if (!isset($data_by_day[$day][$server_id])) {
$data_by_day[$day][$server_id] = array(); $data_by_day[$day][$server_id] = array();
} }
$data_by_day[$day][$server_id][] = $record; $data_by_day[$day][$server_id][] = $record;
@ -96,7 +96,7 @@ class UptimeArchiver implements ArchiverInterface {
// now get history data day by day // now get history data day by day
$histories = array(); $histories = array();
foreach($data_by_day as $day => $day_records) { foreach ($data_by_day as $day => $day_records) {
foreach ($day_records as $server_id => $server_day_records) { foreach ($day_records as $server_id => $server_day_records) {
$histories[] = $this->getHistoryForDay($day, $server_id, $server_day_records); $histories[] = $this->getHistoryForDay($day, $server_id, $server_day_records);
} }
@ -113,7 +113,7 @@ class UptimeArchiver implements ArchiverInterface {
); );
} }
if($locked) { if ($locked) {
$this->db->exec('UNLOCK TABLES'); $this->db->exec('UNLOCK TABLES');
} }
@ -141,10 +141,10 @@ class UptimeArchiver implements ArchiverInterface {
$latencies = array(); $latencies = array();
$checks_failed = 0; $checks_failed = 0;
foreach($day_records as $day_record) { foreach ($day_records as $day_record) {
$latencies[] = $day_record['latency']; $latencies[] = $day_record['latency'];
if($day_record['status'] == 0) { if ($day_record['status'] == 0) {
$checks_failed++; $checks_failed++;
} }
} }
@ -165,7 +165,7 @@ class UptimeArchiver implements ArchiverInterface {
protected function createSQLWhereServer($server_id) { protected function createSQLWhereServer($server_id) {
$sql_where_server = ($server_id !== null) $sql_where_server = ($server_id !== null)
// this is obviously not the cleanest way to implement this when using paramter binding.. sorry. // this is obviously not the cleanest way to implement this when using paramter binding.. sorry.
? ' `server_id` = ' . intval($server_id) . ' AND ' ? ' `server_id` = '.intval($server_id).' AND '
: ''; : '';
return $sql_where_server; return $sql_where_server;

View File

@ -73,12 +73,12 @@ class HistoryGraph {
'uptime' => '%01.3f%%', 'uptime' => '%01.3f%%',
); );
foreach($graphs as $i => &$graph) { foreach ($graphs as $i => &$graph) {
// add subarray for info fields // add subarray for info fields
$graph['info'] = array(); $graph['info'] = array();
foreach($info_fields as $field => $format) { foreach ($info_fields as $field => $format) {
if(!isset($graph[$field])) { if (!isset($graph[$field])) {
continue; continue;
} }
$graph['info'][] = array( $graph['info'][] = array(
@ -125,7 +125,7 @@ class HistoryGraph {
$data['buttons'][] = array('mode' => 'day', 'label' => psm_get_lang('servers', 'day')); $data['buttons'][] = array('mode' => 'day', 'label' => psm_get_lang('servers', 'day'));
$data['buttons'][] = array('mode' => 'week', 'label' => psm_get_lang('servers', 'week')); $data['buttons'][] = array('mode' => 'week', 'label' => psm_get_lang('servers', 'week'));
// make sure to add chart id after buttons so its added to those tmeplates as well // make sure to add chart id after buttons so its added to those tmeplates as well
$data['chart_id'] = $server_id . '_uptime'; $data['chart_id'] = $server_id.'_uptime';
return $data; return $data;
} }
@ -160,7 +160,7 @@ class HistoryGraph {
$data['buttons'][] = array('mode' => 'month', 'label' => psm_get_lang('servers', 'month'), 'class_active' => 'btn-info'); $data['buttons'][] = array('mode' => 'month', 'label' => psm_get_lang('servers', 'month'), 'class_active' => 'btn-info');
$data['buttons'][] = array('mode' => 'year', 'label' => psm_get_lang('servers', 'year')); $data['buttons'][] = array('mode' => 'year', 'label' => psm_get_lang('servers', 'year'));
// make sure to add chart id after buttons so its added to those tmeplates as well // make sure to add chart id after buttons so its added to those tmeplates as well
$data['chart_id'] = $server_id . '_history'; $data['chart_id'] = $server_id.'_history';
return $data; return $data;
} }
@ -174,13 +174,13 @@ class HistoryGraph {
* @return array * @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'))) { if (!in_array($type, array('history', 'uptime'))) {
return array(); return array();
} }
$records = $this->db->execute( $records = $this->db->execute(
'SELECT * 'SELECT *
FROM `' . PSM_DB_PREFIX . "servers_$type` FROM `'.PSM_DB_PREFIX."servers_$type`
WHERE `server_id` = :server_id AND `date` BETWEEN :start_time AND :end_time ORDER BY `date` ASC", WHERE `server_id` = :server_id AND `date` BETWEEN :start_time AND :end_time ORDER BY `date` ASC",
array( array(
'server_id' => $server_id, 'server_id' => $server_id,
@ -220,52 +220,52 @@ class HistoryGraph {
// use the first line to calculate average latency // use the first line to calculate average latency
$latency_avg += (float) $uptime[$latency_avg_key]; $latency_avg += (float) $uptime[$latency_avg_key];
if($cb_if_up($uptime)) { if ($cb_if_up($uptime)) {
// The server is up // The server is up
foreach($lines as $key => $value) { foreach ($lines as $key => $value) {
// add the value for each of the different lines // add the value for each of the different lines
if(isset($uptime[$key])) { if (isset($uptime[$key])) {
$lines[$key][] = '[' . number_format($time, 0, '', '') . ',' . round((float) $uptime[$key], 4) . ']'; $lines[$key][] = '['.number_format($time, 0, '', '').','.round((float) $uptime[$key], 4).']';
} }
} }
if($last_date) { if ($last_date) {
// Was down before. // Was down before.
// Record the first and last date as a string in the down array // Record the first and last date as a string in the down array
$down[] = '[' . number_format($last_date, 0, '', '') . ',' . number_format($time, 0, '', '') . ']'; $down[] = '['.number_format($last_date, 0, '', '').','.number_format($time, 0, '', '').']';
// add the number of microseconds of downtime to counter for % // add the number of microseconds of downtime to counter for %
$time_down += ($time - $last_date); $time_down += ($time - $last_date);
$last_date = 0; $last_date = 0;
} }
} else { } else {
// The server is down // The server is down
if(!$last_date) { if (!$last_date) {
$last_date = $time; $last_date = $time;
} }
} }
} }
$lines_merged = array(); $lines_merged = array();
foreach($lines as $line_key => $line_value) { foreach ($lines as $line_key => $line_value) {
if(empty($line_value)) { if (empty($line_value)) {
continue; continue;
} }
$lines_merged[] = '[' . implode(',', $line_value) . ']'; $lines_merged[] = '['.implode(',', $line_value).']';
$series[] = "{label: '".psm_get_lang('servers', $line_key)."'}"; $series[] = "{label: '".psm_get_lang('servers', $line_key)."'}";
} }
if($last_date) { if ($last_date) {
// if last_date is still set, the last check was "down" and we are still in down mode // if last_date is still set, the last check was "down" and we are still in down mode
$down[] = '[' . number_format($last_date, 0, '', '') . ',0]'; $down[] = '['.number_format($last_date, 0, '', '').',0]';
$time_down += (($end_time->getTimestamp() * 1000) - $last_date); $time_down += (($end_time->getTimestamp() * 1000) - $last_date);
} }
if($add_uptime) { if ($add_uptime) {
$data['uptime'] = 100 - (($time_down / ($end_time->getTimestamp() - $start_time->getTimestamp())) / 10); $data['uptime'] = 100 - (($time_down / ($end_time->getTimestamp() - $start_time->getTimestamp())) / 10);
} }
$data['latency_avg'] = count($records) > 0 ? ($latency_avg / count($records)) : 0; $data['latency_avg'] = count($records) > 0 ? ($latency_avg / count($records)) : 0;
$data['server_lines'] = sizeof($lines_merged) ? '[' . implode(',', $lines_merged) . ']' : ''; $data['server_lines'] = sizeof($lines_merged) ? '['.implode(',', $lines_merged).']' : '';
$data['server_down'] = sizeof($down) ? '[' . implode(',', $down) . ']' : ''; $data['server_down'] = sizeof($down) ? '['.implode(',', $down).']' : '';
$data['series'] = sizeof($series) ? '[' . implode(',', $series) . ']' : ''; $data['series'] = sizeof($series) ? '['.implode(',', $series).']' : '';
$data['end_timestamp'] = number_format($end_time->getTimestamp() * 1000, 0, '', ''); $data['end_timestamp'] = number_format($end_time->getTimestamp() * 1000, 0, '', '');
return $data; return $data;

View File

@ -50,9 +50,9 @@ class ServerValidator {
* @throws \InvalidArgumentException * @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')); $server = $this->db->selectRow(PSM_DB_PREFIX.'servers', array('server_id' => $server_id), array('server_id'));
if(empty($server)) { if (empty($server)) {
throw new \InvalidArgumentException('server_no_match'); throw new \InvalidArgumentException('server_no_match');
} }
return true; return true;
@ -66,7 +66,7 @@ class ServerValidator {
*/ */
public function label($label) { public function label($label) {
$label = trim($label); $label = trim($label);
if(empty($label) || strlen($label) > 255) { if (empty($label) || strlen($label) > 255) {
throw new \InvalidArgumentException('server_label_bad_length'); throw new \InvalidArgumentException('server_label_bad_length');
} }
return true; return true;
@ -82,22 +82,22 @@ class ServerValidator {
public function ip($value, $type = null) { public function ip($value, $type = null) {
$value = trim($value); $value = trim($value);
if(empty($value) || strlen($value) > 255) { if (empty($value) || strlen($value) > 255) {
throw new \InvalidArgumentException('server_ip_bad_length'); throw new \InvalidArgumentException('server_ip_bad_length');
} }
switch($type) { switch ($type) {
case 'website': case 'website':
if(!filter_var($value, FILTER_VALIDATE_URL)) { if (!filter_var($value, FILTER_VALIDATE_URL)) {
throw new \InvalidArgumentException('server_ip_bad_website'); throw new \InvalidArgumentException('server_ip_bad_website');
} }
break; break;
case 'service': case 'service':
case 'ping': case 'ping':
if(!filter_var($value, FILTER_VALIDATE_IP) if (!filter_var($value, FILTER_VALIDATE_IP)
// domain regex as per http://stackoverflow.com/questions/106179/regular-expression-to-match-hostname-or-ip-address : // 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) && !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');} ) {throw new \InvalidArgumentException('server_ip_bad_service'); }
break; break;
} }
@ -111,7 +111,7 @@ class ServerValidator {
* @throws \InvalidArgumentException * @throws \InvalidArgumentException
*/ */
public function type($type) { public function type($type) {
if(!in_array($type, array('ping', 'service', 'website'))) { if (!in_array($type, array('ping', 'service', 'website'))) {
throw new \InvalidArgumentException('server_type_invalid'); throw new \InvalidArgumentException('server_type_invalid');
} }
return true; return true;
@ -124,7 +124,7 @@ class ServerValidator {
* @throws \InvalidArgumentException * @throws \InvalidArgumentException
*/ */
public function warningThreshold($value) { public function warningThreshold($value) {
if(!is_numeric($value) || intval($value) == 0) { if (!is_numeric($value) || intval($value) == 0) {
throw new \InvalidArgumentException('server_warning_threshold_invalid'); throw new \InvalidArgumentException('server_warning_threshold_invalid');
} }
return true; return true;

View File

@ -51,7 +51,7 @@ class UpdateManager implements ContainerAwareInterface {
// check if we need to restrict the servers to a certain user // check if we need to restrict the servers to a certain user
$sql_join = ''; $sql_join = '';
if(!$skip_perms && $this->container->get('user')->getUserLevel() > PSM_USER_ADMIN) { if (!$skip_perms && $this->container->get('user')->getUserLevel() > PSM_USER_ADMIN) {
// restrict by user_id // restrict by user_id
$sql_join = "JOIN `".PSM_DB_PREFIX."users_servers` AS `us` ON ( $sql_join = "JOIN `".PSM_DB_PREFIX."users_servers` AS `us` ON (
`us`.`user_id`={$this->container->get('user')->getUserId()} `us`.`user_id`={$this->container->get('user')->getUserId()}
@ -69,7 +69,7 @@ class UpdateManager implements ContainerAwareInterface {
$updater = new Updater\StatusUpdater($this->container->get('db')); $updater = new Updater\StatusUpdater($this->container->get('db'));
$notifier = new Updater\StatusNotifier($this->container->get('db')); $notifier = new Updater\StatusNotifier($this->container->get('db'));
foreach($servers as $server) { foreach ($servers as $server) {
$status_old = ($server['status'] == 'on') ? true : false; $status_old = ($server['status'] == 'on') ? true : false;
$status_new = $updater->update($server['server_id']); $status_new = $updater->update($server['server_id']);
// notify the nerds if applicable // notify the nerds if applicable

View File

@ -115,7 +115,7 @@ class StatusNotifier {
* @return boolean * @return boolean
*/ */
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 && !$this->save_logs) { if (!$this->send_emails && !$this->send_sms && !$this->save_logs) {
// seems like we have nothing to do. skip the rest // seems like we have nothing to do. skip the rest
return false; return false;
} }
@ -125,45 +125,45 @@ class StatusNotifier {
$this->status_new = $status_new; $this->status_new = $status_new;
// get server info from db // get server info from db
$this->server = $this->db->selectRow(PSM_DB_PREFIX . 'servers', array( $this->server = $this->db->selectRow(PSM_DB_PREFIX.'servers', array(
'server_id' => $server_id, 'server_id' => $server_id,
), array( ), array(
'server_id', 'ip', 'port', 'label', 'type', 'pattern', 'status', 'header_name', 'header_value', 'error', 'active', 'email', 'sms', 'pushover', 'telegram', 'last_online', 'last_offline', 'last_offline_duration', 'server_id', 'ip', 'port', 'label', 'type', 'pattern', 'status', 'header_name', 'header_value', 'error', 'active', 'email', 'sms', 'pushover', 'telegram', 'last_online', 'last_offline', 'last_offline_duration',
)); ));
if(empty($this->server)) { if (empty($this->server)) {
return false; return false;
} }
$notify = false; $notify = false;
// check which type of alert the user wants // check which type of alert the user wants
switch(psm_get_conf('alert_type')) { switch (psm_get_conf('alert_type')) {
case 'always': case 'always':
if($status_new == false) { if ($status_new == false) {
// server is offline. we are in error state. // server is offline. we are in error state.
$notify = true; $notify = true;
} }
break; break;
case 'offline': case 'offline':
// only send a notification if the server goes down for the first time! // only send a notification if the server goes down for the first time!
if($status_new == false && $status_old == true) { if ($status_new == false && $status_old == true) {
$notify = true; $notify = true;
} }
break; break;
case 'status': case 'status':
if($status_new != $status_old) { if ($status_new != $status_old) {
// status has been changed! // status has been changed!
$notify = true; $notify = true;
} }
break; break;
} }
if(!$notify) { if (!$notify) {
return false; return false;
} }
// first add to log (we use the same text as the SMS message because its short..) // first add to log (we use the same text as the SMS message because its short..)
if($this->save_logs) { if ($this->save_logs) {
psm_add_log( psm_add_log(
$this->server_id, $this->server_id,
'status', 'status',
@ -173,30 +173,30 @@ class StatusNotifier {
$users = $this->getUsers($this->server_id); $users = $this->getUsers($this->server_id);
if(empty($users)) { if (empty($users)) {
return $notify; return $notify;
} }
// check if email is enabled for this server // check if email is enabled for this server
if($this->send_emails && $this->server['email'] == 'yes') { if ($this->send_emails && $this->server['email'] == 'yes') {
// send email // send email
$this->notifyByEmail($users); $this->notifyByEmail($users);
} }
// check if sms is enabled for this server // check if sms is enabled for this server
if($this->send_sms && $this->server['sms'] == 'yes') { if ($this->send_sms && $this->server['sms'] == 'yes') {
// yay lets wake those nerds up! // yay lets wake those nerds up!
$this->notifyByTxtMsg($users); $this->notifyByTxtMsg($users);
} }
// check if pushover is enabled for this server // check if pushover is enabled for this server
if($this->send_pushover && $this->server['pushover'] == 'yes') { if ($this->send_pushover && $this->server['pushover'] == 'yes') {
// yay lets wake those nerds up! // yay lets wake those nerds up!
$this->notifyByPushover($users); $this->notifyByPushover($users);
} }
// check if telegram is enabled for this server // check if telegram is enabled for this server
if($this->send_telegram && $this->server['telegram'] == 'yes') { if ($this->send_telegram && $this->server['telegram'] == 'yes') {
// yay lets wake those nerds up! // yay lets wake those nerds up!
$this->notifyByTelegram($users); $this->notifyByTelegram($users);
} }
@ -220,13 +220,13 @@ class StatusNotifier {
$mail->Body = $body; $mail->Body = $body;
$mail->AltBody = str_replace('<br/>', "\n", $body); $mail->AltBody = str_replace('<br/>', "\n", $body);
if(psm_get_conf('log_email')) { if (psm_get_conf('log_email')) {
$log_id = psm_add_log($this->server_id, 'email', $body); $log_id = psm_add_log($this->server_id, 'email', $body);
} }
// go through empl // go through empl
foreach ($users as $user) { foreach ($users as $user) {
if(!empty($log_id)) { if (!empty($log_id)) {
psm_add_log_user($log_id, $user['user_id']); psm_add_log_user($log_id, $user['user_id']);
} }
@ -245,7 +245,7 @@ class StatusNotifier {
*/ */
protected function notifyByPushover($users) { protected function notifyByPushover($users) {
// Remove users that have no pushover_key // Remove users that have no pushover_key
foreach($users as $k => $user) { foreach ($users as $k => $user) {
if (trim($user['pushover_key']) == '') { if (trim($user['pushover_key']) == '') {
unset($users[$k]); unset($users[$k]);
} }
@ -259,7 +259,7 @@ class StatusNotifier {
// Pushover // Pushover
$message = psm_parse_msg($this->status_new, 'pushover_message', $this->server); $message = psm_parse_msg($this->status_new, 'pushover_message', $this->server);
$pushover = psm_build_pushover(); $pushover = psm_build_pushover();
if($this->status_new === true) { if ($this->status_new === true) {
$pushover->setPriority(0); $pushover->setPriority(0);
} else { } else {
$pushover->setPriority(2); $pushover->setPriority(2);
@ -272,19 +272,19 @@ class StatusNotifier {
$pushover->setUrlTitle(psm_get_lang('system', 'title')); $pushover->setUrlTitle(psm_get_lang('system', 'title'));
// Log // Log
if(psm_get_conf('log_pushover')) { if (psm_get_conf('log_pushover')) {
$log_id = psm_add_log($this->server_id, 'pushover', $message); $log_id = psm_add_log($this->server_id, 'pushover', $message);
} }
foreach($users as $user) { foreach ($users as $user) {
// Log // Log
if(!empty($log_id)) { if (!empty($log_id)) {
psm_add_log_user($log_id, $user['user_id']); psm_add_log_user($log_id, $user['user_id']);
} }
// Set recipient + send // Set recipient + send
$pushover->setUser($user['pushover_key']); $pushover->setUser($user['pushover_key']);
if($user['pushover_device'] != '') { if ($user['pushover_device'] != '') {
$pushover->setDevice($user['pushover_device']); $pushover->setDevice($user['pushover_device']);
} }
$pushover->send(); $pushover->send();
@ -299,21 +299,21 @@ class StatusNotifier {
*/ */
protected function notifyByTxtMsg($users) { protected function notifyByTxtMsg($users) {
$sms = psm_build_sms(); $sms = psm_build_sms();
if(!$sms) { if (!$sms) {
return false; return false;
} }
$message = psm_parse_msg($this->status_new, 'sms', $this->server); $message = psm_parse_msg($this->status_new, 'sms', $this->server);
// Log // Log
if(psm_get_conf('log_sms')) { if (psm_get_conf('log_sms')) {
$log_id = psm_add_log($this->server_id, 'sms', $message); $log_id = psm_add_log($this->server_id, 'sms', $message);
} }
// add all users to the recipients list // add all users to the recipients list
foreach ($users as $user) { foreach ($users as $user) {
// Log // Log
if(!empty($log_id)) { if (!empty($log_id)) {
psm_add_log_user($log_id, $user['user_id']); psm_add_log_user($log_id, $user['user_id']);
} }
@ -334,7 +334,7 @@ class StatusNotifier {
*/ */
protected function notifyByTelegram($users) { protected function notifyByTelegram($users) {
// Remove users that have no telegram_id // Remove users that have no telegram_id
foreach($users as $k => $user) { foreach ($users as $k => $user) {
if (trim($user['telegram_id']) == '') { if (trim($user['telegram_id']) == '') {
unset($users[$k]); unset($users[$k]);
} }
@ -350,12 +350,12 @@ class StatusNotifier {
$telegram = psm_build_telegram(); $telegram = psm_build_telegram();
$telegram->setMessage(str_replace('<br/>', "\n", $message)); $telegram->setMessage(str_replace('<br/>', "\n", $message));
// Log // Log
if(psm_get_conf('log_telegram')) { if (psm_get_conf('log_telegram')) {
$log_id = psm_add_log($this->server_id, 'telegram', $message); $log_id = psm_add_log($this->server_id, 'telegram', $message);
} }
foreach($users as $user) { foreach ($users as $user) {
// Log // Log
if(!empty($log_id)) { if (!empty($log_id)) {
psm_add_log_user($log_id, $user['user_id']); psm_add_log_user($log_id, $user['user_id']);
} }
$telegram->setUser($user['telegram_id']); $telegram->setUser($user['telegram_id']);

View File

@ -79,17 +79,17 @@ class StatusUpdater {
$this->rtime = ''; $this->rtime = '';
// get server info from db // get server info from db
$this->server = $this->db->selectRow(PSM_DB_PREFIX . 'servers', array( $this->server = $this->db->selectRow(PSM_DB_PREFIX.'servers', array(
'server_id' => $server_id, 'server_id' => $server_id,
), array( ), array(
'server_id', 'ip', 'port', 'label', 'type', 'pattern', 'pattern_online', 'header_name', 'header_value', 'status', 'active', 'warning_threshold', 'server_id', 'ip', 'port', 'label', 'type', 'pattern', 'pattern_online', 'header_name', 'header_value', 'status', 'active', 'warning_threshold',
'warning_threshold_counter', 'timeout', 'website_username', 'website_password', 'last_offline' 'warning_threshold_counter', 'timeout', 'website_username', 'website_password', 'last_offline'
)); ));
if(empty($this->server)) { if (empty($this->server)) {
return false; return false;
} }
switch($this->server['type']) { switch ($this->server['type']) {
case 'ping': case 'ping':
$this->status_new = $this->updatePing($max_runs); $this->status_new = $this->updatePing($max_runs);
break; break;
@ -112,7 +112,7 @@ class StatusUpdater {
// so that the warnings can still be reviewed in the server history. // so that the warnings can still be reviewed in the server history.
psm_log_uptime($this->server_id, (int) $this->status_new, $this->rtime); psm_log_uptime($this->server_id, (int) $this->status_new, $this->rtime);
if($this->status_new == true) { if ($this->status_new == true) {
// if the server is on, add the last_online value and reset the error threshold counter // if the server is on, add the last_online value and reset the error threshold counter
$save['status'] = 'on'; $save['status'] = 'on';
$save['last_online'] = date('Y-m-d H:i:s'); $save['last_online'] = date('Y-m-d H:i:s');
@ -127,7 +127,7 @@ class StatusUpdater {
// server is offline, increase the error counter // server is offline, increase the error counter
$save['warning_threshold_counter'] = $this->server['warning_threshold_counter'] + 1; $save['warning_threshold_counter'] = $this->server['warning_threshold_counter'] + 1;
if($save['warning_threshold_counter'] < $this->server['warning_threshold']) { if ($save['warning_threshold_counter'] < $this->server['warning_threshold']) {
// the server is offline but the error threshold has not been met yet. // the server is offline but the error threshold has not been met yet.
// so we are going to leave the status "on" for now while we are in a sort of warning state.. // so we are going to leave the status "on" for now while we are in a sort of warning state..
$save['status'] = 'on'; $save['status'] = 'on';
@ -140,7 +140,7 @@ class StatusUpdater {
} }
} }
$this->db->save(PSM_DB_PREFIX . 'servers', $save, array('server_id' => $this->server_id)); $this->db->save(PSM_DB_PREFIX.'servers', $save, array('server_id' => $this->server_id));
return $this->status_new; return $this->status_new;
@ -177,7 +177,7 @@ class StatusUpdater {
socket_close($socket); socket_close($socket);
// check if server is available and rerun if asked. // check if server is available and rerun if asked.
if(!$status && $run < $max_runs) { if (!$status && $run < $max_runs) {
return $this->updatePing($max_runs, $run + 1); return $this->updatePing($max_runs, $run + 1);
} }
@ -195,17 +195,17 @@ class StatusUpdater {
// save response time // save response time
$starttime = microtime(true); $starttime = microtime(true);
$fp = @fsockopen ($this->server['ip'], $this->server['port'], $errno, $this->error, 10); $fp = @fsockopen($this->server['ip'], $this->server['port'], $errno, $this->error, 10);
$status = ($fp === false) ? false : true; $status = ($fp === false) ? false : true;
$this->rtime = (microtime(true) - $starttime); $this->rtime = (microtime(true) - $starttime);
if(is_resource($fp)) { if (is_resource($fp)) {
fclose($fp); fclose($fp);
} }
// check if server is available and rerun if asked. // check if server is available and rerun if asked.
if(!$status && $run < $max_runs) { if (!$status && $run < $max_runs) {
return $this->updateService($max_runs, $run + 1); return $this->updateService($max_runs, $run + 1);
} }
@ -230,7 +230,7 @@ class StatusUpdater {
$this->server['timeout'], $this->server['timeout'],
true, true,
$this->server['website_username'], $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->rtime = (microtime(true) - $starttime); $this->rtime = (microtime(true) - $starttime);
@ -243,7 +243,7 @@ class StatusUpdater {
$code_matches = array(); $code_matches = array();
preg_match_all("/[A-Z]{2,5}\/\d\.\d\s(\d{3})\s(.*)/", $status_code, $code_matches); preg_match_all("/[A-Z]{2,5}\/\d\.\d\s(\d{3})\s(.*)/", $status_code, $code_matches);
if(empty($code_matches[0])) { if (empty($code_matches[0])) {
// somehow we dont have a proper response. // somehow we dont have a proper response.
$this->error = 'TIMEOUT ERROR: no response from server'; $this->error = 'TIMEOUT ERROR: no response from server';
$result = false; $result = false;
@ -252,26 +252,26 @@ class StatusUpdater {
$msg = $code_matches[2][0]; $msg = $code_matches[2][0];
// All status codes starting with a 4 or higher mean trouble! // All status codes starting with a 4 or higher mean trouble!
if(substr($code, 0, 1) >= '4') { if (substr($code, 0, 1) >= '4') {
$this->error = "HTTP STATUS ERROR: ".$code . ' ' . $msg; $this->error = "HTTP STATUS ERROR: ".$code.' '.$msg;
$result = false; $result = false;
} else { } else {
$result = true; $result = true;
//Okay, the HTTP status is good : 2xx or 3xx. Now we have to test the pattern if it's set up //Okay, the HTTP status is good : 2xx or 3xx. Now we have to test the pattern if it's set up
if($this->server['pattern'] != '') { if ($this->server['pattern'] != '') {
// Check to see if the body should not contain specified pattern // Check to see if the body should not contain specified pattern
// Check to see if the pattern was [not] found. // 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->error = "TEXT ERROR : Pattern '{$this->server['pattern']}' ".
($this->server['pattern_online'] == 'yes' ? 'not' : 'was') . ($this->server['pattern_online'] == 'yes' ? 'not' : 'was').
' found.'; ' found.';
$result = false; $result = false;
} }
} }
// Should we check a header ? // Should we check a header ?
if($this->server['header_name'] != '' && $this->server['header_value'] != '') { if ($this->server['header_name'] != '' && $this->server['header_value'] != '') {
$header_flag = false; $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 $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
foreach (explode("\r\n", $header_text) as $i => $line) { foreach (explode("\r\n", $header_text) as $i => $line) {
@ -280,7 +280,7 @@ class StatusUpdater {
} else { } else {
list ($key, $value) = explode(': ', $line); list ($key, $value) = explode(': ', $line);
if (strcasecmp($key, $this->server['header_name']) == 0) { // Header found (case-insensitive) 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 if (!preg_match("/{$this->server['header_value']}/i", $value)) { // The value doesn't match what we needed
$result = false; $result = false;
} else { } else {
$header_flag = true; $header_flag = true;
@ -290,13 +290,16 @@ class StatusUpdater {
} }
} }
if(!$header_flag) $result = false; // Header was not present if (!$header_flag) {
// Header was not present
$result = false;
}
} }
} }
} }
// check if server is available and rerun if asked. // check if server is available and rerun if asked.
if(!$result && $run < $max_runs) { if (!$result && $run < $max_runs) {
return $this->updateWebsite($max_runs, $run + 1); return $this->updateWebsite($max_runs, $run + 1);
} }

View File

@ -57,7 +57,7 @@ class UserValidator {
*/ */
public function userId($user_id) { public function userId($user_id) {
$user = $this->user->getUser($user_id); $user = $this->user->getUser($user_id);
if(empty($user)) { if (empty($user)) {
throw new \InvalidArgumentException('user_no_match'); throw new \InvalidArgumentException('user_no_match');
} }
return true; return true;
@ -75,7 +75,7 @@ class UserValidator {
* @throws \InvalidArgumentException * @throws \InvalidArgumentException
*/ */
public function username($username, $user_id = 0) { public function username($username, $user_id = 0) {
if(strlen($username) > 64 || strlen($username) < 2) { if (strlen($username) > 64 || strlen($username) < 2) {
throw new \InvalidArgumentException('user_name_bad_length'); throw new \InvalidArgumentException('user_name_bad_length');
} }
if (!preg_match('/^[a-zA-Z\d_\.]{2,64}$/i', $username)) { if (!preg_match('/^[a-zA-Z\d_\.]{2,64}$/i', $username)) {
@ -83,7 +83,7 @@ class UserValidator {
} }
$user_exists = $this->user->getUserByUsername($username); $user_exists = $this->user->getUserByUsername($username);
if(!empty($user_exists) && ($user_id == 0 || $user_id != $user_exists->user_id)) { if (!empty($user_exists) && ($user_id == 0 || $user_id != $user_exists->user_id)) {
throw new \InvalidArgumentException('user_name_exists'); throw new \InvalidArgumentException('user_name_exists');
} }
return true; return true;
@ -97,10 +97,10 @@ class UserValidator {
* @throws \InvalidArgumentException * @throws \InvalidArgumentException
*/ */
public function password($password, $password_repeat) { public function password($password, $password_repeat) {
if(empty($password) || empty($password_repeat)) { if (empty($password) || empty($password_repeat)) {
throw new \InvalidArgumentException('user_password_invalid'); throw new \InvalidArgumentException('user_password_invalid');
} }
if($password !== $password_repeat) { if ($password !== $password_repeat) {
throw new \InvalidArgumentException('user_password_no_match'); throw new \InvalidArgumentException('user_password_no_match');
} }
return true; return true;
@ -116,7 +116,7 @@ class UserValidator {
* @throws \InvalidArgumentException * @throws \InvalidArgumentException
*/ */
public function username_new($username) { public function username_new($username) {
if(strlen($username) > 64 || strlen($username) < 2) { if (strlen($username) > 64 || strlen($username) < 2) {
throw new \InvalidArgumentException('user_name_bad_length'); throw new \InvalidArgumentException('user_name_bad_length');
} }
if (!preg_match('/^[a-zA-Z\d_\.]{2,64}$/i', $username)) { if (!preg_match('/^[a-zA-Z\d_\.]{2,64}$/i', $username)) {
@ -132,10 +132,10 @@ class UserValidator {
* @throws \InvalidArgumentException * @throws \InvalidArgumentException
*/ */
public function email($email) { public function email($email) {
if(strlen($email) > 255 || strlen($email) < 5) { if (strlen($email) > 255 || strlen($email) < 5) {
throw new \InvalidArgumentException('user_email_bad_length'); throw new \InvalidArgumentException('user_email_bad_length');
} }
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) { if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new \InvalidArgumentException('user_email_invalid'); throw new \InvalidArgumentException('user_email_invalid');
} }
return true; return true;
@ -148,7 +148,7 @@ class UserValidator {
* @throws \InvalidArgumentException * @throws \InvalidArgumentException
*/ */
public function level($level) { public function level($level) {
if(!in_array($level, $this->user_levels)) { if (!in_array($level, $this->user_levels)) {
throw new \InvalidArgumentException('user_level_invalid'); throw new \InvalidArgumentException('user_level_invalid');
} }
return true; return true;

View File

@ -67,10 +67,10 @@
{% if auto_refresh %} {% if auto_refresh %}
<script> <script>
setInterval(function(){ setInterval(function() {
$.ajax({ $.ajax({
url:"?", url:"?",
success: function(html, status){ success: function(html, status) {
$("#page-container").html(html); $("#page-container").html(html);
} }
}); });