From 2c51ad12f75c5b7041ea18a76882da1d09a0b991 Mon Sep 17 00:00:00 2001 From: TimZ99 Date: Wed, 11 Dec 2019 20:19:38 +0100 Subject: [PATCH] Implementing the PSR12 standard Using PHPCS and PHPSBF. --- cron/status.cron.php | 111 +- index.php | 23 +- install.php | 9 +- src/bootstrap.php | 151 +- src/includes/functions.inc.php | 1215 +++++++++-------- .../password_compatibility_library.inc.php | 415 +++--- src/includes/psmconfig.inc.php | 17 +- src/lang/da_DK.lang.php | 557 ++++---- src/psm/Module/AbstractController.php | 872 ++++++------ src/psm/Module/Config/ConfigModule.php | 24 +- .../Config/Controller/ConfigController.php | 759 +++++----- src/psm/Module/ControllerInterface.php | 37 +- .../Error/Controller/ErrorController.php | 43 +- src/psm/Module/Error/ErrorModule.php | 22 +- .../Install/Controller/InstallController.php | 654 ++++----- src/psm/Module/Install/InstallModule.php | 24 +- src/psm/Module/ModuleInterface.php | 13 +- .../Controller/AbstractServerController.php | 130 +- .../Server/Controller/LogController.php | 296 ++-- .../Server/Controller/ServerController.php | 980 ++++++------- .../Server/Controller/StatusController.php | 166 +-- .../Server/Controller/UpdateController.php | 34 +- src/psm/Module/Server/ServerModule.php | 30 +- .../User/Controller/LoginController.php | 263 ++-- .../User/Controller/ProfileController.php | 286 ++-- .../Module/User/Controller/UserController.php | 652 ++++----- src/psm/Module/User/Event/UserEvent.php | 33 +- .../User/EventListener/UserSubscriber.php | 36 +- src/psm/Module/User/UserEvents.php | 31 +- src/psm/Module/User/UserModule.php | 33 +- src/psm/Router.php | 349 ++--- src/psm/Service/Database.php | 928 +++++++------ src/psm/Service/User.php | 844 ++++++------ src/psm/Txtmsg/CMBulkSMS.php | 336 ++--- src/psm/Txtmsg/Callr.php | 148 +- src/psm/Txtmsg/ClickSend.php | 149 +- src/psm/Txtmsg/Clickatell.php | 94 +- src/psm/Txtmsg/Core.php | 67 +- src/psm/Txtmsg/FreeMobileSMS.php | 96 +- src/psm/Txtmsg/FreeVoipDeal.php | 127 +- src/psm/Txtmsg/GatewayAPI.php | 123 +- src/psm/Txtmsg/Inetworx.php | 140 +- src/psm/Txtmsg/Messagebird.php | 106 +- src/psm/Txtmsg/Mosms.php | 132 +- src/psm/Txtmsg/Nexmo.php | 131 +- src/psm/Txtmsg/Octopush.php | 144 +- src/psm/Txtmsg/Plivo.php | 154 ++- src/psm/Txtmsg/Smsglobal.php | 142 +- src/psm/Txtmsg/Smsgw.php | 110 +- src/psm/Txtmsg/Smsit.php | 125 +- src/psm/Txtmsg/SolutionsInfini.php | 119 +- src/psm/Txtmsg/Spryng.php | 88 +- src/psm/Txtmsg/Textmarketer.php | 106 +- src/psm/Txtmsg/Twilio.php | 105 +- src/psm/Txtmsg/TxtmsgInterface.php | 13 +- src/psm/Util/Install/Installer.php | 952 +++++++------ src/psm/Util/Module/Modal.php | 211 +-- src/psm/Util/Module/ModalInterface.php | 12 +- src/psm/Util/Module/Sidebar.php | 279 ++-- src/psm/Util/Module/SidebarInterface.php | 11 +- src/psm/Util/Server/ArchiveManager.php | 158 +-- .../Server/Archiver/ArchiverInterface.php | 32 +- src/psm/Util/Server/Archiver/LogsArchiver.php | 82 +- .../Util/Server/Archiver/UptimeArchiver.php | 229 ++-- src/psm/Util/Server/HistoryGraph.php | 466 ++++--- src/psm/Util/Server/ServerValidator.php | 200 +-- src/psm/Util/Server/UpdateManager.php | 79 +- .../Util/Server/Updater/StatusNotifier.php | 747 +++++----- src/psm/Util/Server/Updater/StatusUpdater.php | 575 ++++---- src/psm/Util/User/UserValidator.php | 248 ++-- 70 files changed, 8944 insertions(+), 8129 deletions(-) diff --git a/cron/status.cron.php b/cron/status.cron.php index a42e4e04..92b70182 100644 --- a/cron/status.cron.php +++ b/cron/status.cron.php @@ -1,4 +1,5 @@ 403 Forbidden

Forbidden

IP address not allowed. See the documentation for more info.

'); - } - echo "OK"; -} + if (!in_array($_SERVER['REMOTE_ADDR'], $allow) && !in_array($_SERVER["HTTP_X_FORWARDED_FOR"], $allow)) { + header('HTTP/1.0 403 Forbidden'); + die(' + + 403 Forbidden + +

Forbidden

IP address not allowed. See the + documentation + for more info.

+ + '); + } + echo "OK"; + } -$cron_timeout = PSM_CRON_TIMEOUT; + $cron_timeout = PSM_CRON_TIMEOUT; // parse a couple of arguments -if (!empty($_SERVER['argv'])) { - foreach ($_SERVER['argv'] as $argv) { - $argi = explode('=', ltrim($argv, '--')); - if (count($argi) !== 2) { - continue; - } - switch ($argi[0]) { - case 'uri': - if (!defined('PSM_BASE_URL')) { - define('PSM_BASE_URL', $argi[1]); - } - break; - case 'timeout': - $cron_timeout = intval($argi[1]); - break; - } - } -} + if (!empty($_SERVER['argv'])) { + foreach ($_SERVER['argv'] as $argv) { + $argi = explode('=', ltrim($argv, '--')); + if (count($argi) !== 2) { + continue; + } + switch ($argi[0]) { + case 'uri': + if (!defined('PSM_BASE_URL')) { + define('PSM_BASE_URL', $argi[1]); + } + break; + case 'timeout': + $cron_timeout = intval($argi[1]); + break; + } + } + } // prevent cron from running twice at the same time // however if the cron has been running for X mins, we'll assume it died and run anyway // if you want to change PSM_CRON_TIMEOUT, have a look in src/includes/psmconfig.inc.php. // or you can provide the --timeout=x argument -$time = time(); -if ( - psm_get_conf('cron_running') == 1 - && $cron_timeout > 0 - && ($time - psm_get_conf('cron_running_time') < $cron_timeout) -) { - die('Cron is already running. Exiting.'); -} -if (!defined('PSM_DEBUG') || !PSM_DEBUG) { - psm_update_conf('cron_running', 1); -} -psm_update_conf('cron_running_time', $time); + $time = time(); + if ( + psm_get_conf('cron_running') == 1 + && $cron_timeout > 0 + && ($time - psm_get_conf('cron_running_time') < $cron_timeout) + ) { + die('Cron is already running. Exiting.'); + } + if (!defined('PSM_DEBUG') || !PSM_DEBUG) { + psm_update_conf('cron_running', 1); + } + psm_update_conf('cron_running_time', $time); -$autorun = $router->getService('util.server.updatemanager'); -$autorun->run(true); + $autorun = $router->getService('util.server.updatemanager'); + $autorun->run(true); -psm_update_conf('cron_running', 0); + psm_update_conf('cron_running', 0); +} diff --git a/index.php b/index.php index 668e21f1..797fa81d 100644 --- a/index.php +++ b/index.php @@ -1,4 +1,5 @@ getService('user')->doLogout(); - // logged out, redirect to login - header('Location: '.psm_build_url()); - die(); + $router->getService('user')->doLogout(); + // logged out, redirect to login + header('Location: ' . psm_build_url()); + die(); } $mod = psm_GET('mod', PSM_MODULE_DEFAULT); try { - $router->run($mod); + $router->run($mod); } catch (\InvalidArgumentException $e) { - // invalid module, try the default one - // it that somehow also doesnt exist, we have a bit of an issue - // and we really have no reason catch it - $router->run(PSM_MODULE_DEFAULT); -} \ No newline at end of file + // invalid module, try the default one + // it that somehow also doesnt exist, we have a bit of an issue + // and we really have no reason catch it + $router->run(PSM_MODULE_DEFAULT); +} diff --git a/install.php b/install.php index f5434bd2..ba6f925f 100644 --- a/install.php +++ b/install.php @@ -1,4 +1,5 @@ run('install'); + $router->run('install'); +} diff --git a/src/bootstrap.php b/src/bootstrap.php index a9b54da8..225aaeb3 100644 --- a/src/bootstrap.php +++ b/src/bootstrap.php @@ -1,4 +1,5 @@ getService('db'); + + // sanity check! + if (!defined('PSM_INSTALL') || !PSM_INSTALL) { + if ($db->getDbHost() === null) { + // no config file has been loaded, redirect the user to the install + header('Location: install.php'); + die(); + } + // config file has been loaded, check if we have a connection + if (!$db->status()) { + trigger_error("Unable to establish database connection...", E_USER_ERROR); + } + // attempt to load configuration from database + if (!psm_load_conf()) { + // unable to load from config table + header('Location: install.php'); + die(); + } + // config load OK, make sure database version is up to date + $installer = new \psm\Util\Install\Installer($db); + if ($installer->isUpgradeRequired()) { + trigger_error( + "Your database is for an older version and requires an upgrade, + please click here to update your database to the latest version.", + E_USER_ERROR + ); + } + } + + $lang = psm_get_conf('language', 'en_US'); + psm_load_lang($lang); } - -// find config file -$path_conf = PSM_PATH_SRC.'../config.php'; -if (file_exists($path_conf)) { - include_once $path_conf; -} -// check for a debug var -if (!defined('PSM_DEBUG')) { - define('PSM_DEBUG', false); -} - -// Debug enabled: report everything -// Debug disabled: report error only if created manually -ini_set('display_errors', 1); -PSM_DEBUG ? error_reporting(E_ALL) : error_reporting(E_USER_ERROR); - -// check for a cron allowed ip array -if (!defined('PSM_CRON_ALLOW')) { - //serialize for php version lower than 7.0.0 - define('PSM_CRON_ALLOW', serialize(array())); -} - -$vendor_autoload = PSM_PATH_SRC.'..'.DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'autoload.php'; -if (!file_exists($vendor_autoload)) { - trigger_error("No dependencies found in vendor dir. Did you install the dependencies? Please run \"php composer.phar install\".", E_USER_ERROR); -} -require_once $vendor_autoload; - -$router = new psm\Router(); -// this may seem insignificant, but right now lots of functions depend on the following global var definition: -$db = $router->getService('db'); - -// sanity check! -if (!defined('PSM_INSTALL') || !PSM_INSTALL) { - if ($db->getDbHost() === null) { - // no config file has been loaded, redirect the user to the install - header('Location: install.php'); - die(); - } - // config file has been loaded, check if we have a connection - if (!$db->status()) { - trigger_error("Unable to establish database connection...", E_USER_ERROR); - } - // attempt to load configuration from database - if (!psm_load_conf()) { - // unable to load from config table - header('Location: install.php'); - die(); - } - // config load OK, make sure database version is up to date - $installer = new \psm\Util\Install\Installer($db); - if ($installer->isUpgradeRequired()) { - trigger_error("Your database is for an older version and requires an upgrade, please click here to update your database to the latest version.", E_USER_ERROR); - } -} - -$lang = psm_get_conf('language', 'en_US'); -psm_load_lang($lang); \ No newline at end of file diff --git a/src/includes/functions.inc.php b/src/includes/functions.inc.php index c4aad069..783aa795 100644 --- a/src/includes/functions.inc.php +++ b/src/includes/functions.inc.php @@ -1,4 +1,5 @@ status()) { - return false; - } - if (!$db->ifTableExists(PSM_DB_PREFIX.'config')) { - return false; - } - $config_db = $db->select(PSM_DB_PREFIX.'config', null, array('key', 'value')); + if (!defined('PSM_DB_PREFIX') || !$db->status()) { + return false; + } + if (!$db->ifTableExists(PSM_DB_PREFIX . 'config')) { + return false; + } + $config_db = $db->select(PSM_DB_PREFIX . 'config', null, array('key', 'value')); - if (is_array($config_db) && !empty($config_db)) { - foreach ($config_db as $setting) { - $GLOBALS['sm_config'][$setting['key']] = $setting['value']; - } - return true; - } else { - return false; - } -} + if (is_array($config_db) && !empty($config_db)) { + foreach ($config_db as $setting) { + $GLOBALS['sm_config'][$setting['key']] = $setting['value']; + } + return true; + } else { + return false; + } + } /** * Update a config setting. @@ -198,29 +212,30 @@ function psm_load_conf() { * @param string $key * @param string $value */ -function psm_update_conf($key, $value) { - global $db; + function psm_update_conf($key, $value) + { + global $db; - // check if key exists - $exists = psm_get_conf($key, false); - if ($exists === false) { - // add new config record - $db->save( - PSM_DB_PREFIX.'config', - array( - 'key' => $key, - 'value' => $value, - ) - ); - } else { - $db->save( - PSM_DB_PREFIX.'config', - array('value' => $value), - array('key' => $key) - ); - } - $GLOBALS['sm_config'][$key] = $value; -} + // check if key exists + $exists = psm_get_conf($key, false); + if ($exists === false) { + // add new config record + $db->save( + PSM_DB_PREFIX . 'config', + array( + 'key' => $key, + 'value' => $value, + ) + ); + } else { + $db->save( + PSM_DB_PREFIX . 'config', + array('value' => $value), + array('key' => $key) + ); + } + $GLOBALS['sm_config'][$key] = $value; + } ############################################### # @@ -238,18 +253,19 @@ function psm_update_conf($key, $value) { * * @return int log_id */ -function psm_add_log($server_id, $type, $message) { - global $db; + function psm_add_log($server_id, $type, $message) + { + global $db; - return $db->save( - PSM_DB_PREFIX.'log', - array( - 'server_id' => $server_id, - 'type' => $type, - 'message' => $message, - ) - ); -} + return $db->save( + PSM_DB_PREFIX . 'log', + array( + 'server_id' => $server_id, + 'type' => $type, + 'message' => $message, + ) + ); + } /** * This function just adds a user to the log_users table. @@ -257,17 +273,18 @@ function psm_add_log($server_id, $type, $message) { * @param $log_id * @param $user_id */ -function psm_add_log_user($log_id, $user_id) { - global $db; + function psm_add_log_user($log_id, $user_id) + { + global $db; - $db->save( - PSM_DB_PREFIX.'log_users', - array( - 'log_id' => $log_id, - 'user_id' => $user_id, - ) - ); -} + $db->save( + PSM_DB_PREFIX . 'log_users', + array( + 'log_id' => $log_id, + 'user_id' => $user_id, + ) + ); + } /** * This function adds the result of a check to the uptime table for logging purposes. @@ -276,19 +293,20 @@ function psm_add_log_user($log_id, $user_id) { * @param int $status * @param string $latency */ -function psm_log_uptime($server_id, $status, $latency) { - global $db; + function psm_log_uptime($server_id, $status, $latency) + { + global $db; - $db->save( - PSM_DB_PREFIX.'servers_uptime', - array( - 'server_id' => $server_id, - 'date' => date('Y-m-d H:i:s'), - 'status' => $status, - 'latency' => $latency, - ) - ); -} + $db->save( + PSM_DB_PREFIX . 'servers_uptime', + array( + 'server_id' => $server_id, + 'date' => date('Y-m-d H:i:s'), + 'status' => $status, + 'latency' => $latency, + ) + ); + } /** * Converts an interval into a string @@ -296,49 +314,70 @@ function psm_log_uptime($server_id, $status, $latency) { * @param DateInterval $interval * @return string */ - function psm_format_interval(DateInterval $interval) { - $result = ""; + function psm_format_interval(DateInterval $interval) + { + $result = ""; - if ($interval->y) { $result .= $interval->format("%y ").(($interval->y == 1) ? psm_get_lang('system', 'year') : psm_get_lang('system', 'years'))." "; } - if ($interval->m) { $result .= $interval->format("%m ").(($interval->m == 1) ? psm_get_lang('system', 'month') : psm_get_lang('system', 'months'))." "; } - if ($interval->d) { $result .= $interval->format("%d ").(($interval->d == 1) ? psm_get_lang('system', 'day') : psm_get_lang('system', 'days'))." "; } - if ($interval->h) { $result .= $interval->format("%h ").(($interval->h == 1) ? psm_get_lang('system', 'hour') : psm_get_lang('system', 'hours'))." "; } - if ($interval->i) { $result .= $interval->format("%i ").(($interval->i == 1) ? psm_get_lang('system', 'minute') : psm_get_lang('system', 'minutes'))." "; } - if ($interval->s) { $result .= $interval->format("%s ").(($interval->s == 1) ? psm_get_lang('system', 'second') : psm_get_lang('system', 'seconds'))." "; } + if ($interval->y) { + $result .= $interval->format("%y ") . (($interval->y == 1) ? + psm_get_lang('system', 'year') : psm_get_lang('system', 'years')) . " "; + } + if ($interval->m) { + $result .= $interval->format("%m ") . (($interval->m == 1) ? + psm_get_lang('system', 'month') : psm_get_lang('system', 'months')) . " "; + } + if ($interval->d) { + $result .= $interval->format("%d ") . (($interval->d == 1) ? + psm_get_lang('system', 'day') : psm_get_lang('system', 'days')) . " "; + } + if ($interval->h) { + $result .= $interval->format("%h ") . (($interval->h == 1) ? + psm_get_lang('system', 'hour') : psm_get_lang('system', 'hours')) . " "; + } + if ($interval->i) { + $result .= $interval->format("%i ") . (($interval->i == 1) ? + psm_get_lang('system', 'minute') : psm_get_lang('system', 'minutes')) . " "; + } + if ($interval->s) { + $result .= $interval->format("%s ") . (($interval->s == 1) ? + psm_get_lang('system', 'second') : psm_get_lang('system', 'seconds')) . " "; + } - return $result; -} + return $result; + } /** * Parses a string from the language file with the correct variables replaced in the message * * @param boolean|null $status * @param string $type is either 'sms', 'email', 'pushover_title', 'pushover_message' or 'telegram_message' - * @param array $vars server information about the server which may be placed in a message: %KEY% will be replaced by your value + * @param array $vars server information about the server which may be placed in a message: + * %KEY% will be replaced by your value * @param boolean $combi parse other message if notifications need to be send combined * @return string parsed message */ -function psm_parse_msg($status, $type, $vars, $combi = false) { - if(is_bool($status)) { - $status = ($status === true) ? 'on_' : 'off_'; + function psm_parse_msg($status, $type, $vars, $combi = false) + { + if (is_bool($status)) { + $status = ($status === true) ? 'on_' : 'off_'; + } + + $combi = ($combi === true) ? 'combi_' : ''; + + $message = psm_get_lang('notifications', $combi . $status . $type); + + if (!$message) { + return $message; + } + $vars['date'] = date('Y-m-d H:i:s'); + + foreach ($vars as $k => $v) { + $message = str_replace('%' . strtoupper($k) . '%', $v, $message); + } + + return $message; } - $combi = ($combi === true) ? 'combi_' : ''; - - $message = psm_get_lang('notifications', $combi.$status.$type); - - if (!$message) { - return $message; - } - $vars['date'] = date('Y-m-d H:i:s'); - - foreach ($vars as $k => $v) { - $message = str_replace('%'.strtoupper($k).'%', $v, $message); - } - - return $message; -} - /** * Shortcut to curl_init(), curl_exec and curl_close() * @@ -353,64 +392,82 @@ function psm_parse_msg($status, $type, $vars, $combi = false) { * @param string|null $post_field POST data * @return string cURL result */ -function psm_curl_get($href, $header = false, $body = true, $timeout = null, $add_agent = true, $website_username = false, $website_password = false, $request_method = null, $post_field = null) { - ($timeout === null || $timeout > 0) ? PSM_CURL_TIMEOUT : intval($timeout); + function psm_curl_get( + $href, + $header = false, + $body = true, + $timeout = null, + $add_agent = true, + $website_username = false, + $website_password = false, + $request_method = null, + $post_field = null + ) { + ($timeout === null || $timeout > 0) ? PSM_CURL_TIMEOUT : intval($timeout); - $ch = curl_init(); - if(defined('PSM_DEBUG') && PSM_DEBUG === true && psm_is_cli()) { - curl_setopt($ch, CURLOPT_VERBOSE, true); - } - curl_setopt($ch, CURLOPT_HEADER, $header); - curl_setopt($ch, CURLOPT_NOBODY, (!$body)); - curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); - curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); - curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); - curl_setopt($ch, CURLOPT_ENCODING, ''); - - if (!empty($request_method)) { - curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request_method); - } + $ch = curl_init(); + if (defined('PSM_DEBUG') && PSM_DEBUG === true && psm_is_cli()) { + curl_setopt($ch, CURLOPT_VERBOSE, true); + } + curl_setopt($ch, CURLOPT_HEADER, $header); + curl_setopt($ch, CURLOPT_NOBODY, (!$body)); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); + curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); + curl_setopt($ch, CURLOPT_ENCODING, ''); + + if (!empty($request_method)) { + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request_method); + } - if (!empty($post_field)) { - curl_setopt($ch, CURLOPT_POSTFIELDS, $post_field); - } + if (!empty($post_field)) { + curl_setopt($ch, CURLOPT_POSTFIELDS, $post_field); + } - if ($website_username !== false && $website_password !== false && !empty($website_username) && !empty($website_password)) { - curl_setopt($ch, CURLOPT_USERPWD, $website_username.":".$website_password); - } + if ( + $website_username !== false && + $website_password !== false && + !empty($website_username) && + !empty($website_password) + ) { + curl_setopt($ch, CURLOPT_USERPWD, $website_username . ":" . $website_password); + } - $href = preg_replace('/(.*)(%cachebuster%)/', '$0'.time(), $href); + $href = preg_replace('/(.*)(%cachebuster%)/', '$0' . time(), $href); - curl_setopt($ch, CURLOPT_URL, $href); + curl_setopt($ch, CURLOPT_URL, $href); - $proxy_url = psm_get_conf('proxy_url', ''); - if (psm_get_conf('proxy', '0') === '1') { - curl_setopt($ch, CURLOPT_PROXY, $proxy_url); - $proxy_user = psm_get_conf('proxy_user', ''); - $proxy_password = psm_get_conf('proxy_password', ''); - if (!empty($proxy_user) && !empty($proxy_password)) { - curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxy_user.':'.$proxy_password); - } - } + $proxy_url = psm_get_conf('proxy_url', ''); + if (psm_get_conf('proxy', '0') === '1') { + curl_setopt($ch, CURLOPT_PROXY, $proxy_url); + $proxy_user = psm_get_conf('proxy_user', ''); + $proxy_password = psm_get_conf('proxy_password', ''); + if (!empty($proxy_user) && !empty($proxy_password)) { + curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxy_user . ':' . $proxy_password); + } + } - if ($add_agent) { - curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; phpservermon/'.PSM_VERSION.'; +https://github.com/phpservermon/phpservermon)'); - } + if ($add_agent) { + curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; phpservermon/' . + PSM_VERSION . '; +https://github.com/phpservermon/phpservermon)'); + } - $result = curl_exec($ch); - curl_close($ch); - - if(defined('PSM_DEBUG') && PSM_DEBUG === true && psm_is_cli()) { - echo PHP_EOL.'==============cURL Result for: '.$href.'==========================================='.PHP_EOL; - print_r($result); - echo PHP_EOL.'==============END cURL Resul for: '.$href.'==========================================='.PHP_EOL; - } + $result = curl_exec($ch); + curl_close($ch); + + if (defined('PSM_DEBUG') && PSM_DEBUG === true && psm_is_cli()) { + echo PHP_EOL . + '==============cURL Result for: ' . $href . '===========================================' . PHP_EOL; + print_r($result); + echo PHP_EOL . + '==============END cURL Resul for: ' . $href . '===========================================' . PHP_EOL; + } - return $result; -} + return $result; + } /** * Get a "nice" timespan message @@ -419,45 +476,61 @@ function psm_curl_get($href, $header = false, $body = true, $timeout = null, $ad * @param string $time * @return string */ -function psm_timespan($time) { - if (empty($time) || $time == '0000-00-00 00:00:00') { - return psm_get_lang('system', 'never'); - } - if ($time !== intval($time)) { $time = strtotime($time); } - if ($time < 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'); - // Check for Windows to find and replace the %e - // modifier correctly - if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') { - $format = preg_replace('#(?= 60 * 60 * 24) { - $format = psm_get_lang('system', (date('l', time() - 60 * 60 * 24) == date('l', $time)) ? 'yesterday_format' : 'other_day_format'); - return strftime($format, $time); - } - if ($d >= 60 * 60 * 2) { return sprintf(psm_get_lang('system', 'hours_ago'), intval($d / (60 * 60))); } - if ($d >= 60 * 60) { return psm_get_lang('system', 'an_hour_ago'); } - if ($d >= 60 * 2) { return sprintf(psm_get_lang('system', 'minutes_ago'), intval($d / 60)); } - if ($d >= 60) { return psm_get_lang('system', 'a_minute_ago'); } - if ($d >= 2) { return sprintf(psm_get_lang('system', 'seconds_ago'), intval($d)); } + function psm_timespan($time) + { + if (empty($time) || $time == '0000-00-00 00:00:00') { + return psm_get_lang('system', 'never'); + } + if ($time !== intval($time)) { + $time = strtotime($time); + } + if ($time < 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'); + // Check for Windows to find and replace the %e + // modifier correctly + if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') { + $format = preg_replace('#(?= 60 * 60 * 24) { + $format = psm_get_lang('system', (date('l', time() - 60 * 60 * 24) == date('l', $time)) ? + 'yesterday_format' : 'other_day_format'); + return strftime($format, $time); + } + if ($d >= 60 * 60 * 2) { + return sprintf(psm_get_lang('system', 'hours_ago'), intval($d / (60 * 60))); + } + if ($d >= 60 * 60) { + return psm_get_lang('system', 'an_hour_ago'); + } + if ($d >= 60 * 2) { + return sprintf(psm_get_lang('system', 'minutes_ago'), intval($d / 60)); + } + if ($d >= 60) { + return psm_get_lang('system', 'a_minute_ago'); + } + if ($d >= 2) { + return sprintf(psm_get_lang('system', 'seconds_ago'), intval($d)); + } - return psm_get_lang('system', 'a_second_ago'); -} + return psm_get_lang('system', 'a_second_ago'); + } /** * Get a localised date from MySQL date format * @param string $time * @return string */ -function psm_date($time) { - if (empty($time) || $time == '0000-00-00 00:00:00') { - return psm_get_lang('system', 'never'); - } - return strftime('%x %X', strtotime($time)); -} + function psm_date($time) + { + if (empty($time) || $time == '0000-00-00 00:00:00') { + return psm_get_lang('system', 'never'); + } + return strftime('%x %X', strtotime($time)); + } /** * Check if an update is available for PHP Server Monitor. @@ -465,36 +538,37 @@ function psm_date($time) { * Will only check for new version if user turned updates on in config. * @return boolean */ -function psm_update_available() { - if (!psm_get_conf('show_update')) { - // user does not want updates, fair enough. - return false; - } + function psm_update_available() + { + if (!psm_get_conf('show_update')) { + // user does not want updates, fair enough. + 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) { - // been more than a week since update, lets go - // update last check date - psm_update_conf('last_update_check', time()); - $latest = psm_curl_get(PSM_UPDATE_URL); - // extract latest version from Github. - preg_match('/"tag_name":"[v](([\d][.][\d][.][\d])(-?\w*))"/', $latest, $latest); - // add latest version to database - if (!empty($latest) && strlen($latest[2]) < 15) { - psm_update_conf('version_update_check', $latest[2]); - } - } else { - $latest[2] = psm_get_conf('version_update_check'); - } + if ((time() - PSM_UPDATE_INTERVAL) > $last_update) { + // been more than a week since update, lets go + // update last check date + psm_update_conf('last_update_check', time()); + $latest = psm_curl_get(PSM_UPDATE_URL); + // extract latest version from Github. + preg_match('/"tag_name":"[v](([\d][.][\d][.][\d])(-?\w*))"/', $latest, $latest); + // add latest version to database + if (!empty($latest) && strlen($latest[2]) < 15) { + psm_update_conf('version_update_check', $latest[2]); + } + } else { + $latest[2] = psm_get_conf('version_update_check'); + } - if (!empty($latest)) { - $current = psm_get_conf('version'); - return version_compare($latest[2], $current, '>'); - } else { - return false; - } -} + if (!empty($latest)) { + $current = psm_get_conf('version'); + return version_compare($latest[2], $current, '>'); + } else { + return false; + } + } /** * Prepare a new phpmailer instance. @@ -504,144 +578,148 @@ function psm_update_available() { * @param string $from_email * @return \PHPMailer\PHPMailer\PHPMailer */ -function psm_build_mail($from_name = null, $from_email = null) { - $phpmailer = new \PHPMailer\PHPMailer\PHPMailer(); - $phpmailer->Encoding = "base64"; - $phpmailer->CharSet = 'UTF-8'; - $phpmailer->SMTPDebug = 0; + function psm_build_mail($from_name = null, $from_email = null) + { + $phpmailer = new \PHPMailer\PHPMailer\PHPMailer(); + $phpmailer->Encoding = "base64"; + $phpmailer->CharSet = 'UTF-8'; + $phpmailer->SMTPDebug = 0; - if (psm_get_conf('email_smtp') == '1') { - $phpmailer->IsSMTP(); - $phpmailer->Host = psm_get_conf('email_smtp_host'); - $phpmailer->Port = (int) psm_get_conf('email_smtp_port'); - $phpmailer->SMTPSecure = psm_get_conf('email_smtp_security'); + if (psm_get_conf('email_smtp') == '1') { + $phpmailer->IsSMTP(); + $phpmailer->Host = psm_get_conf('email_smtp_host'); + $phpmailer->Port = (int) psm_get_conf('email_smtp_port'); + $phpmailer->SMTPSecure = psm_get_conf('email_smtp_security'); - $smtp_user = psm_get_conf('email_smtp_username'); - $smtp_pass = psm_get_conf('email_smtp_password'); + $smtp_user = psm_get_conf('email_smtp_username'); + $smtp_pass = psm_get_conf('email_smtp_password'); - if ($smtp_user != '' && $smtp_pass != '') { - $phpmailer->SMTPAuth = true; - $phpmailer->Username = $smtp_user; - $phpmailer->Password = $smtp_pass; - } - } else { - $phpmailer->IsMail(); - } - if ($from_name == null) { - $from_name = psm_get_conf('email_from_name'); - } - if ($from_email == null) { - $from_email = psm_get_conf('email_from_email'); - } - $phpmailer->SetFrom($from_email, $from_name); + if ($smtp_user != '' && $smtp_pass != '') { + $phpmailer->SMTPAuth = true; + $phpmailer->Username = $smtp_user; + $phpmailer->Password = $smtp_pass; + } + } else { + $phpmailer->IsMail(); + } + if ($from_name == null) { + $from_name = psm_get_conf('email_from_name'); + } + if ($from_email == null) { + $from_email = psm_get_conf('email_from_email'); + } + $phpmailer->SetFrom($from_email, $from_name); - return $phpmailer; -} + return $phpmailer; + } /** * Prepare a new Pushover util. * * @return \Pushover */ -function psm_build_pushover() { - $pushover = new \Pushover(); - $pushover->setToken(psm_get_conf('pushover_api_token')); + function psm_build_pushover() + { + $pushover = new \Pushover(); + $pushover->setToken(psm_get_conf('pushover_api_token')); - return $pushover; -} + return $pushover; + } /** * * @return \Telegram */ -function psm_build_telegram() { - $telegram = new \Telegram(); - $telegram->setToken(psm_get_conf('telegram_api_token')); + function psm_build_telegram() + { + $telegram = new \Telegram(); + $telegram->setToken(psm_get_conf('telegram_api_token')); - return $telegram; -} + return $telegram; + } /** * Prepare a new SMS util. * * @return \psm\Txtmsg\TxtmsgInterface */ -function psm_build_sms() { - $sms = null; + function psm_build_sms() + { + $sms = null; - // open the right class - // not making this any more dynamic, because perhaps some gateways need custom settings - switch (strtolower(psm_get_conf('sms_gateway'))) { - case 'mosms': - $sms = new \psm\Txtmsg\Mosms(); - break; - case 'smsit': - $sms = new \psm\Txtmsg\Smsit(); - break; - case 'inetworx': - $sms = new \psm\Txtmsg\Inetworx(); - break; - case 'messagebird': - $sms = new \psm\Txtmsg\Messagebird(); - break; - case 'spryng': - $sms = new \psm\Txtmsg\Spryng(); - break; - case 'clickatell': - $sms = new \psm\Txtmsg\Clickatell(); - break; - case 'textmarketer': - $sms = new \psm\Txtmsg\Textmarketer(); - break; - case 'smsglobal': - $sms = new \psm\Txtmsg\Smsglobal(); - break; - case 'freevoipdeal': - $sms = new \psm\Txtmsg\FreeVoipDeal(); - break; - case 'nexmo': - $sms = new \psm\Txtmsg\Nexmo(); - break; - case 'freemobilesms': - $sms = new \psm\Txtmsg\FreeMobileSMS(); - break; - case 'clicksend': - $sms = new \psm\Txtmsg\ClickSend(); - break; - case 'octopush': - $sms = new \psm\Txtmsg\Octopush(); - break; - case 'smsgw': - $sms = new \psm\Txtmsg\Smsgw(); - break; - case 'twilio': - $sms = new \psm\Txtmsg\Twilio(); - break; - case 'cmbulksms': - $sms = new \psm\Txtmsg\CMBulkSMS(); - break; - case 'gatewayapi': - $sms = new \psm\Txtmsg\GatewayAPI(); - break; - case 'callr': - $sms = new \psm\Txtmsg\Callr(); - break; - case 'plivo': - $sms = new \psm\Txtmsg\Plivo(); - break; - case 'solutionsinfini': - $sms = new \psm\Txtmsg\SolutionsInfini(); - break; - } + // open the right class + // not making this any more dynamic, because perhaps some gateways need custom settings + switch (strtolower(psm_get_conf('sms_gateway'))) { + case 'mosms': + $sms = new \psm\Txtmsg\Mosms(); + break; + case 'smsit': + $sms = new \psm\Txtmsg\Smsit(); + break; + case 'inetworx': + $sms = new \psm\Txtmsg\Inetworx(); + break; + case 'messagebird': + $sms = new \psm\Txtmsg\Messagebird(); + break; + case 'spryng': + $sms = new \psm\Txtmsg\Spryng(); + break; + case 'clickatell': + $sms = new \psm\Txtmsg\Clickatell(); + break; + case 'textmarketer': + $sms = new \psm\Txtmsg\Textmarketer(); + break; + case 'smsglobal': + $sms = new \psm\Txtmsg\Smsglobal(); + break; + case 'freevoipdeal': + $sms = new \psm\Txtmsg\FreeVoipDeal(); + break; + case 'nexmo': + $sms = new \psm\Txtmsg\Nexmo(); + break; + case 'freemobilesms': + $sms = new \psm\Txtmsg\FreeMobileSMS(); + break; + case 'clicksend': + $sms = new \psm\Txtmsg\ClickSend(); + break; + case 'octopush': + $sms = new \psm\Txtmsg\Octopush(); + break; + case 'smsgw': + $sms = new \psm\Txtmsg\Smsgw(); + break; + case 'twilio': + $sms = new \psm\Txtmsg\Twilio(); + break; + case 'cmbulksms': + $sms = new \psm\Txtmsg\CMBulkSMS(); + break; + case 'gatewayapi': + $sms = new \psm\Txtmsg\GatewayAPI(); + break; + case 'callr': + $sms = new \psm\Txtmsg\Callr(); + break; + case 'plivo': + $sms = new \psm\Txtmsg\Plivo(); + break; + case 'solutionsinfini': + $sms = new \psm\Txtmsg\SolutionsInfini(); + break; + } - // copy login information from the config file - if ($sms) { - $sms->setLogin(psm_get_conf('sms_gateway_username'), psm_get_conf('sms_gateway_password')); - $sms->setOriginator(psm_get_conf('sms_from')); - } + // copy login information from the config file + if ($sms) { + $sms->setLogin(psm_get_conf('sms_gateway_username'), psm_get_conf('sms_gateway_password')); + $sms->setOriginator(psm_get_conf('sms_from')); + } - return $sms; -} + return $sms; + } /** * Generate a new link to the current monitor @@ -650,36 +728,38 @@ function psm_build_sms() { * @param boolean $htmlentities use entities in url? * @return string */ -function psm_build_url($params = array(), $urlencode = true, $htmlentities = true) { - if (defined('PSM_BASE_URL') && PSM_BASE_URL !== null) { - $url = PSM_BASE_URL; - } else { - $url = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443 ? 'https' : 'http').'://'.$_SERVER['HTTP_HOST']; - // on Windows, dirname() adds both back- and forward slashes (http://php.net/dirname). - // for urls, we only want the forward slashes. - $url .= dirname($_SERVER['SCRIPT_NAME']); - $url = str_replace('\\', '', $url); - } - $url = rtrim($url, '/').'/'; + function psm_build_url($params = array(), $urlencode = true, $htmlentities = true) + { + if (defined('PSM_BASE_URL') && PSM_BASE_URL !== null) { + $url = PSM_BASE_URL; + } else { + $url = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || + $_SERVER['SERVER_PORT'] == 443 ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST']; + // on Windows, dirname() adds both back- and forward slashes (http://php.net/dirname). + // for urls, we only want the forward slashes. + $url .= dirname($_SERVER['SCRIPT_NAME']); + $url = str_replace('\\', '', $url); + } + $url = rtrim($url, '/') . '/'; - if ($params != null) { - $url .= '?'; - if (is_array($params)) { - $delim = ($htmlentities) ? '&' : '&'; + if ($params != null) { + $url .= '?'; + if (is_array($params)) { + $delim = ($htmlentities) ? '&' : '&'; - foreach ($params as $k => $v) { - if ($urlencode) { - $v = urlencode($v); - } - $url .= $delim.$k.'='.$v; - } - } else { - $url .= $params; - } - } + foreach ($params as $k => $v) { + if ($urlencode) { + $v = urlencode($v); + } + $url .= $delim . $k . '=' . $v; + } + } else { + $url .= $params; + } + } - return $url; -} + return $url; + } /** * Try existence of a GET var, if not return the alternative @@ -687,13 +767,14 @@ function psm_build_url($params = array(), $urlencode = true, $htmlentities = tru * @param string $alt * @return mixed */ -function psm_GET($key, $alt = null) { - if (isset($_GET[$key])) { - return $_GET[$key]; - } else { - return $alt; - } -} + function psm_GET($key, $alt = null) + { + if (isset($_GET[$key])) { + return $_GET[$key]; + } else { + return $alt; + } + } /** * Try existence of a POST var, if not return the alternative @@ -701,13 +782,14 @@ function psm_GET($key, $alt = null) { * @param string|array|bool $alt * @return mixed */ -function psm_POST($key, $alt = null) { - if (isset($_POST[$key])) { - return $_POST[$key]; - } else { - return $alt; - } -} + function psm_POST($key, $alt = null) + { + if (isset($_POST[$key])) { + return $_POST[$key]; + } else { + return $alt; + } + } /** * Check if we are in CLI mode @@ -715,9 +797,10 @@ function psm_POST($key, $alt = null) { * Note, php_sapi cannot be used because cgi-fcgi returns both for web and cli. * @return boolean */ -function psm_is_cli() { - return (!isset($_SERVER['SERVER_SOFTWARE']) || php_sapi_name() == 'cli'); -} + function psm_is_cli() + { + return (!isset($_SERVER['SERVER_SOFTWARE']) || php_sapi_name() == 'cli'); + } ############################################### # @@ -730,24 +813,26 @@ function psm_is_cli() { * * @param mixed $arr */ -function pre($arr = null) { - echo "
";
-	if ($arr === null) {
-		debug_print_backtrace();
-	}
-	print_r($arr);
-	echo "
"; -} + function pre($arr = null) + { + echo "
";
+        if ($arr === null) {
+            debug_print_backtrace();
+        }
+        print_r($arr);
+        echo "
"; + } /** * Send headers to the browser to avoid caching */ -function psm_no_cache() { - header("Expires: Mon, 20 Dec 1998 01:00:00 GMT"); - header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT"); - header("Cache-Control: no-cache, must-revalidate"); - header("Pragma: no-cache"); -} + function psm_no_cache() + { + header("Expires: Mon, 20 Dec 1998 01:00:00 GMT"); + header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); + header("Cache-Control: no-cache, must-revalidate"); + header("Pragma: no-cache"); + } /** * Encrypts the password for storage in the database @@ -757,33 +842,33 @@ function psm_no_cache() { * @return string * @author Pavel Laupe Dvorak */ -function psm_password_encrypt($key, $password) -{ - if (empty($password)) { - return ''; - } + function psm_password_encrypt($key, $password) + { + if (empty($password)) { + return ''; + } - if (empty($key)) { - throw new \InvalidArgumentException('invalid_encryption_key'); - } + if (empty($key)) { + throw new \InvalidArgumentException('invalid_encryption_key'); + } - // using open ssl - $cipher="AES-256-CBC"; - $ivlen = openssl_cipher_iv_length($cipher); - $iv = openssl_random_pseudo_bytes( $ivlen ); - $encrypted = base64_encode( - $iv . - openssl_encrypt( - $password, - $cipher, - hash('sha256', $key, true), - OPENSSL_RAW_DATA, // OPENSSL_ZERO_PADDING OPENSSL_RAW_DATA - $iv - ) - ); + // using open ssl + $cipher = "AES-256-CBC"; + $ivlen = openssl_cipher_iv_length($cipher); + $iv = openssl_random_pseudo_bytes($ivlen); + $encrypted = base64_encode( + $iv . + openssl_encrypt( + $password, + $cipher, + hash('sha256', $key, true), + OPENSSL_RAW_DATA, // OPENSSL_ZERO_PADDING OPENSSL_RAW_DATA + $iv + ) + ); - return $encrypted; -} + return $encrypted; + } /** * Decrypts password stored in the database for future use @@ -793,33 +878,34 @@ function psm_password_encrypt($key, $password) * @return string * @author Pavel Laupe Dvorak */ -function psm_password_decrypt($key, $encryptedString) -{ - if (empty($encryptedString)) { - return ''; - } + function psm_password_decrypt($key, $encryptedString) + { + if (empty($encryptedString)) { + return ''; + } - if (empty($key)) { - throw new \InvalidArgumentException('invalid_encryption_key'); - } + if (empty($key)) { + throw new \InvalidArgumentException('invalid_encryption_key'); + } - // using open ssl - $data = base64_decode($encryptedString); - $cipher="AES-256-CBC"; - $ivlen = openssl_cipher_iv_length($cipher); - $iv = substr($data, 0, $ivlen); - $decrypted = rtrim( - openssl_decrypt( - base64_encode(substr($data, $ivlen)), - $cipher, - hash('sha256', $key, true), - OPENSSL_ZERO_PADDING, - $iv), - "\0" - ); - - return $decrypted; -} + // using open ssl + $data = base64_decode($encryptedString); + $cipher = "AES-256-CBC"; + $ivlen = openssl_cipher_iv_length($cipher); + $iv = substr($data, 0, $ivlen); + $decrypted = rtrim( + openssl_decrypt( + base64_encode(substr($data, $ivlen)), + $cipher, + hash('sha256', $key, true), + OPENSSL_ZERO_PADDING, + $iv + ), + "\0" + ); + + return $decrypted; + } /** * Send notification to Telegram @@ -827,50 +913,57 @@ function psm_password_decrypt($key, $encryptedString) * @return string * @author Tim Zandbergen */ -class telegram -{ - private $_token; - private $_user; - private $_message; - private $_url; + class Telegram + { + private $token; + private $user; + private $message; + private $url; - public function setToken($token) { - $this->_token = (string) $token; - } - public function setUser($user) { - $this->_user = (string) $user; - } - public function setMessage($message) { - $message = str_replace("
    ","",$message); - $message = str_replace("
","\n",$message); - $message = str_replace("
  • ","- ",$message); - $message = str_replace("
  • ","\n",$message); - $message = str_replace("
    ","\n",$message); - $message = str_replace("
    ","\n",$message); - $this->_message = (string) $message; - } - public function sendurl() { - $con = curl_init($this->_url); - curl_setopt($con, CURLOPT_RETURNTRANSFER, true); - curl_setopt($con, CURLOPT_CONNECTTIMEOUT, 5); - curl_setopt($con, CURLOPT_TIMEOUT, 60); - $response = curl_exec($con); - $response = json_decode($response, true); - return $response; - } - public function send() { - if (!Empty($this->_token) && !Empty($this->_user) && !Empty($this->_message)) { - $this->_url = 'https://api.telegram.org/bot'.urlencode($this->_token). - '/sendMessage?chat_id='.urlencode($this->_user).'&text='. - urlencode($this->_message).'&parse_mode=HTML'; - } - return $this->sendurl(); - } - // Get the bots username - public function getBotUsername() { - if (!Empty($this->_token)) { - $this->_url = 'https://api.telegram.org/bot'.urlencode($this->_token).'/getMe'; - } - return $this->sendurl(); - } + public function setToken($token) + { + $this->token = (string) $token; + } + public function setUser($user) + { + $this->user = (string) $user; + } + public function setMessage($message) + { + $message = str_replace("
      ", "", $message); + $message = str_replace("
    ", "\n", $message); + $message = str_replace("
  • ", "- ", $message); + $message = str_replace("
  • ", "\n", $message); + $message = str_replace("
    ", "\n", $message); + $message = str_replace("
    ", "\n", $message); + $this->message = (string) $message; + } + public function sendurl() + { + $con = curl_init($this->url); + curl_setopt($con, CURLOPT_RETURNTRANSFER, true); + curl_setopt($con, CURLOPT_CONNECTTIMEOUT, 5); + curl_setopt($con, CURLOPT_TIMEOUT, 60); + $response = curl_exec($con); + $response = json_decode($response, true); + return $response; + } + public function send() + { + if (!empty($this->token) && !empty($this->user) && !empty($this->message)) { + $this->url = 'https://api.telegram.org/bot' . urlencode($this->token) . + '/sendMessage?chat_id=' . urlencode($this->user) . '&text=' . + urlencode($this->message) . '&parse_mode=HTML'; + } + return $this->sendurl(); + } + // Get the bots username + public function getBotUsername() + { + if (!empty($this->token)) { + $this->url = 'https://api.telegram.org/bot' . urlencode($this->token) . '/getMe'; + } + return $this->sendurl(); + } + } } diff --git a/src/includes/password_compatibility_library.inc.php b/src/includes/password_compatibility_library.inc.php index 641e7550..1f083c7d 100644 --- a/src/includes/password_compatibility_library.inc.php +++ b/src/includes/password_compatibility_library.inc.php @@ -1,4 +1,5 @@ 31) { + trigger_error( + sprintf("password_hash(): Invalid bcrypt cost parameter specified: %d", $cost), + E_USER_WARNING + ); + return null; + } + } + // The length of salt to generate + $raw_salt_len = 16; + // The length required in the final serialization + $required_salt_len = 22; + $hash_format = sprintf("$2y$%02d$", $cost); + break; + default: + trigger_error( + sprintf("password_hash(): Unknown password hashing algorithm: %s", $algo), + E_USER_WARNING + ); + return null; + } + if (isset($options['salt'])) { + switch (gettype($options['salt'])) { + case 'NULL': + case 'boolean': + case 'integer': + case 'double': + case 'string': + $salt = (string) $options['salt']; + break; + case 'object': + if (method_exists($options['salt'], '__tostring')) { + $salt = (string) $options['salt']; + break; + } + // no break + case 'array': + case 'resource': + default: + trigger_error('password_hash(): Non-string salt parameter supplied', E_USER_WARNING); + return null; + } + if (strlen($salt) < $required_salt_len) { + trigger_error( + sprintf( + "password_hash(): Provided salt is too short: %d expecting %d", + strlen($salt), + $required_salt_len + ), + E_USER_WARNING + ); + return null; + } elseif (0 == preg_match('#^[a-zA-Z0-9./]+$#D', $salt)) { + $salt = str_replace('+', '.', base64_encode($salt)); + } + } else { + $buffer = ''; + $buffer_valid = false; + if (function_exists('mcrypt_create_iv') && !defined('PHALANGER')) { + $buffer = mcrypt_create_iv($raw_salt_len, MCRYPT_DEV_URANDOM); + if ($buffer) { + $buffer_valid = true; + } + } + if (!$buffer_valid && function_exists('openssl_random_pseudo_bytes')) { + $buffer = openssl_random_pseudo_bytes($raw_salt_len); + if ($buffer) { + $buffer_valid = true; + } + } + if (!$buffer_valid && is_readable('/dev/urandom')) { + $f = fopen('/dev/urandom', 'r'); + $read = strlen($buffer); + while ($read < $raw_salt_len) { + $buffer .= fread($f, $raw_salt_len - $read); + $read = strlen($buffer); + } + fclose($f); + if ($read >= $raw_salt_len) { + $buffer_valid = true; + } + } + if (!$buffer_valid || strlen($buffer) < $raw_salt_len) { + $bl = strlen($buffer); + for ($i = 0; $i < $raw_salt_len; $i++) { + if ($i < $bl) { + $buffer[$i] = $buffer[$i] ^ chr(mt_rand(0, 255)); + } else { + $buffer .= chr(mt_rand(0, 255)); + } + } + } + $salt = str_replace('+', '.', base64_encode($buffer)); + } + $salt = substr($salt, 0, $required_salt_len); - /** - * Hash the password using the specified algorithm - * - * @param string $password The password to hash - * @param int $algo The algorithm to use (Defined by PASSWORD_* constants) - * @param array $options The options for the algorithm to use - * - * @return string|false The hashed password, or false on error. - */ - function password_hash($password, $algo, array $options = array()) { - if (!function_exists('crypt')) { - trigger_error("Crypt must be loaded for password_hash to function", E_USER_WARNING); - return null; - } - if (!is_string($password)) { - trigger_error("password_hash(): Password must be a string", E_USER_WARNING); - return null; - } - if (!is_int($algo)) { - trigger_error("password_hash() expects parameter 2 to be long, ".gettype($algo)." given", E_USER_WARNING); - return null; - } - switch ($algo) { - case PASSWORD_BCRYPT: - // Note that this is a C constant, but not exposed to PHP, so we don't define it here. - $cost = 10; - if (isset($options['cost'])) { - $cost = $options['cost']; - if ($cost < 4 || $cost > 31) { - trigger_error(sprintf("password_hash(): Invalid bcrypt cost parameter specified: %d", $cost), E_USER_WARNING); - return null; - } - } - // The length of salt to generate - $raw_salt_len = 16; - // The length required in the final serialization - $required_salt_len = 22; - $hash_format = sprintf("$2y$%02d$", $cost); - break; - default: - trigger_error(sprintf("password_hash(): Unknown password hashing algorithm: %s", $algo), E_USER_WARNING); - return null; - } - if (isset($options['salt'])) { - switch (gettype($options['salt'])) { - case 'NULL': - case 'boolean': - case 'integer': - case 'double': - case 'string': - $salt = (string) $options['salt']; - break; - case 'object': - if (method_exists($options['salt'], '__tostring')) { - $salt = (string) $options['salt']; - break; - } - case 'array': - case 'resource': - default: - trigger_error('password_hash(): Non-string salt parameter supplied', E_USER_WARNING); - return null; - } - if (strlen($salt) < $required_salt_len) { - trigger_error(sprintf("password_hash(): Provided salt is too short: %d expecting %d", strlen($salt), $required_salt_len), E_USER_WARNING); - return null; - } elseif (0 == preg_match('#^[a-zA-Z0-9./]+$#D', $salt)) { - $salt = str_replace('+', '.', base64_encode($salt)); - } - } else { - $buffer = ''; - $buffer_valid = false; - if (function_exists('mcrypt_create_iv') && !defined('PHALANGER')) { - $buffer = mcrypt_create_iv($raw_salt_len, MCRYPT_DEV_URANDOM); - if ($buffer) { - $buffer_valid = true; - } - } - if (!$buffer_valid && function_exists('openssl_random_pseudo_bytes')) { - $buffer = openssl_random_pseudo_bytes($raw_salt_len); - if ($buffer) { - $buffer_valid = true; - } - } - if (!$buffer_valid && is_readable('/dev/urandom')) { - $f = fopen('/dev/urandom', 'r'); - $read = strlen($buffer); - while ($read < $raw_salt_len) { - $buffer .= fread($f, $raw_salt_len - $read); - $read = strlen($buffer); - } - fclose($f); - if ($read >= $raw_salt_len) { - $buffer_valid = true; - } - } - if (!$buffer_valid || strlen($buffer) < $raw_salt_len) { - $bl = strlen($buffer); - for ($i = 0; $i < $raw_salt_len; $i++) { - if ($i < $bl) { - $buffer[$i] = $buffer[$i] ^ chr(mt_rand(0, 255)); - } else { - $buffer .= chr(mt_rand(0, 255)); - } - } - } - $salt = str_replace('+', '.', base64_encode($buffer)); - } - $salt = substr($salt, 0, $required_salt_len); + $hash = $hash_format . $salt; - $hash = $hash_format.$salt; + $ret = crypt($password, $hash); - $ret = crypt($password, $hash); + if (!is_string($ret) || strlen($ret) <= 13) { + return false; + } - if (!is_string($ret) || strlen($ret) <= 13) { - return false; - } + return $ret; + } - return $ret; - } + /** + * Get information about the password hash. Returns an array of the information + * that was used to generate the password hash. + * + * array( + * 'algo' => 1, + * 'algoName' => 'bcrypt', + * 'options' => array( + * 'cost' => 10, + * ), + * ) + * + * @param string $hash The password hash to extract info from + * + * @return array The array of information about the hash. + */ + function password_get_info($hash) + { + $return = array( + 'algo' => 0, + 'algoName' => 'unknown', + 'options' => array(), + ); + if (substr($hash, 0, 4) == '$2y$' && strlen($hash) == 60) { + $return['algo'] = PASSWORD_BCRYPT; + $return['algoName'] = 'bcrypt'; + list($cost) = sscanf($hash, "$2y$%d$"); + $return['options']['cost'] = $cost; + } + return $return; + } - /** - * Get information about the password hash. Returns an array of the information - * that was used to generate the password hash. - * - * array( - * 'algo' => 1, - * 'algoName' => 'bcrypt', - * 'options' => array( - * 'cost' => 10, - * ), - * ) - * - * @param string $hash The password hash to extract info from - * - * @return array The array of information about the hash. - */ - function password_get_info($hash) { - $return = array( - 'algo' => 0, - 'algoName' => 'unknown', - 'options' => array(), - ); - if (substr($hash, 0, 4) == '$2y$' && strlen($hash) == 60) { - $return['algo'] = PASSWORD_BCRYPT; - $return['algoName'] = 'bcrypt'; - list($cost) = sscanf($hash, "$2y$%d$"); - $return['options']['cost'] = $cost; - } - return $return; - } + /** + * Determine if the password hash needs to be rehashed according to the options provided + * + * If the answer is true, after validating the password using password_verify, rehash it. + * + * @param string $hash The hash to test + * @param int $algo The algorithm used for new password hashes + * @param array $options The options array passed to password_hash + * + * @return boolean True if the password needs to be rehashed. + */ + function password_needs_rehash($hash, $algo, array $options = array()) + { + $info = password_get_info($hash); + if ($info['algo'] != $algo) { + return true; + } + switch ($algo) { + case PASSWORD_BCRYPT: + $cost = isset($options['cost']) ? $options['cost'] : 10; + if ($cost != $info['options']['cost']) { + return true; + } + break; + } + return false; + } - /** - * Determine if the password hash needs to be rehashed according to the options provided - * - * If the answer is true, after validating the password using password_verify, rehash it. - * - * @param string $hash The hash to test - * @param int $algo The algorithm used for new password hashes - * @param array $options The options array passed to password_hash - * - * @return boolean True if the password needs to be rehashed. - */ - function password_needs_rehash($hash, $algo, array $options = array()) { - $info = password_get_info($hash); - if ($info['algo'] != $algo) { - return true; - } - switch ($algo) { - case PASSWORD_BCRYPT: - $cost = isset($options['cost']) ? $options['cost'] : 10; - if ($cost != $info['options']['cost']) { - return true; - } - break; - } - return false; - } + /** + * Verify a password against a hash using a timing attack resistant approach + * + * @param string $password The password to verify + * @param string $hash The hash to verify against + * + * @return boolean If the password matches the hash + */ + function password_verify($password, $hash) + { + if (!function_exists('crypt')) { + trigger_error("Crypt must be loaded for password_verify to function", E_USER_WARNING); + return false; + } + $ret = crypt($password, $hash); + if (!is_string($ret) || strlen($ret) != strlen($hash) || strlen($ret) <= 13) { + return false; + } - /** - * Verify a password against a hash using a timing attack resistant approach - * - * @param string $password The password to verify - * @param string $hash The hash to verify against - * - * @return boolean If the password matches the hash - */ - function password_verify($password, $hash) { - if (!function_exists('crypt')) { - trigger_error("Crypt must be loaded for password_verify to function", E_USER_WARNING); - return false; - } - $ret = crypt($password, $hash); - if (!is_string($ret) || strlen($ret) != strlen($hash) || strlen($ret) <= 13) { - return false; - } + $status = 0; + for ($i = 0; $i < strlen($ret); $i++) { + $status |= (ord($ret[$i]) ^ ord($hash[$i])); + } - $status = 0; - for ($i = 0; $i < strlen($ret); $i++) { - $status |= (ord($ret[$i]) ^ ord($hash[$i])); - } - - return $status === 0; - } + return $status === 0; + } } diff --git a/src/includes/psmconfig.inc.php b/src/includes/psmconfig.inc.php index 3b2830d0..530753c8 100644 --- a/src/includes/psmconfig.inc.php +++ b/src/includes/psmconfig.inc.php @@ -1,4 +1,5 @@ 'Dansk - Danish', - 'locale' => array('da_DK.UTF-8', 'da_DK', 'danish', 'danish-dk'), - 'system' => array( - 'title' => 'Server Monitor', - 'install' => 'Installér', - 'action' => 'Action', - 'save' => 'Gem', - 'edit' => 'Redigér', - 'delete' => 'Slet', - 'date' => 'Dato', - 'message' => 'Besked', - 'yes' => 'Ja', - 'no' => 'Nej', - 'insert' => 'Indsæt', - 'add_new' => 'Tilføj ny', - 'update_available' => 'En ny version ({version}) er tilgængelig på http://www.phpservermonitor.org.', - 'back_to_top' => 'Til toppen', - 'go_back' => 'Tilbage', - 'ok' => 'OK', - 'cancel' => 'Annullér', - // date/time format according the strftime php function format parameter http://php.net/manual/function.strftime.php - 'short_day_format' => '%B %e', - 'long_day_format' => '%B %e, %Y', - 'yesterday_format' => 'Igår %k:%M', - 'other_day_format' => '%A %k:%M', - 'never' => 'Aldrig', - 'hours_ago' => '%d timer siden', - 'an_hour_ago' => 'omkring en time siden', - 'minutes_ago' => '%d minutter siden', - 'a_minute_ago' => 'omkring et minut siden', - 'seconds_ago' => '%d sekunder siden', - 'a_second_ago' => 'et sekund siden', - 'year' => 'year', - 'years' => 'years', - 'month' => 'month', - 'months' => 'months', - 'day' => 'day', - 'days' => 'days', - 'hour' => 'hour', - 'hours' => 'hours', - 'minute' => 'minute', - 'minutes' => 'minutes', - 'second' => 'second', - 'seconds' => 'seconds', - ), - 'menu' => array( - 'config' => 'Indstillinger', - 'server' => 'Servere', - 'server_log' => 'Log', - 'server_status' => 'Status', - 'server_update' => 'Opdatér', - 'user' => 'Brugere', - 'help' => 'Hjælp', - ), - 'users' => array( - 'user' => 'Bruger', - 'name' => 'Navn', - 'user_name' => 'Brugernavn', - 'password' => 'Adgangskode', - 'password_repeat' => 'Adgangskode igen', - 'password_leave_blank' => 'Udfyldes hvis du vil skifte adgangskode', - 'level' => 'Niveau', - 'level_10' => 'Administrator', - 'level_20' => 'Bruger', - 'level_description' => 'Administratorer har fuld adgang: De kan styre servere, brugere og indstillinger.
    Brugere kan kun se og opdatere servere som er de har adgang til.', - 'mobile' => 'Mobil', - 'email' => 'E-mail', - 'pushover' => 'Pushover', - 'pushover_description' => 'Pushover er en service der gør det let at modtage real-time notifikationer. Se deres website for mere information.', - 'pushover_key' => 'Pushover nøgle', - 'pushover_device' => 'Pushover enhed', - 'pushover_device_description' => 'Navnet på enheden som beskeden skal sendes til. Lad denne være tom hvis alle skal modtage beskeden.', - 'delete_title' => 'Slet bruger', - 'delete_message' => 'Er du sikker på du vil slette bruger \'%1\'?', - 'deleted' => 'Bruger slettet.', - 'updated' => 'Bruger opdateret.', - 'inserted' => 'Bruger tilføjet.', - 'profile' => 'Profil', - 'profile_updated' => 'Din profil er opdateret.', - 'error_user_name_bad_length' => 'Brugernavn skal være mellem 2 til 64 tegn.', - 'error_user_name_invalid' => 'Brugernavn må kun indholde alfabetiske tegn (a-z, A-Z), tal (0-9), prikker (.) og (_).', - 'error_user_name_exists' => 'Det valgte brugernavn findes allerede.', - 'error_user_email_bad_length' => 'E-mail addresser skal være mellem 5 til 255 tegn.', - 'error_user_email_invalid' => 'Den valgte e-mail er ugyldig.', - 'error_user_level_invalid' => 'Det angivet bruger niveau er ugyldig.', - 'error_user_no_match' => 'Brugeren findes ikke.', - 'error_user_password_invalid' => 'Den indtastede adgangskode er ugyldig.', - 'error_user_password_no_match' => 'De to adgangskode er ikke ens.', - ), - 'log' => array( - 'title' => 'Logposter', - 'type' => 'Type', - 'status' => 'Status', - 'email' => 'E-mail', - 'sms' => 'SMS', - 'pushover' => 'Pushover', - 'no_logs' => 'Intet i loggen', - 'clear' => 'Ryd log', - 'delete_title' => 'Slet log', - 'delete_message' => 'Er du sikker på, at du vil slette alle logfiler?', - ), - 'servers' => array( - 'server' => 'Server', - 'status' => 'Status', - 'label' => 'Label', - 'domain' => 'Domæne/IP', - 'timeout' => 'Timeout', - 'timeout_description' => 'Antal sekunder som serveren har til at svare.', - 'port' => 'Port', - 'type' => 'Type', - 'type_website' => 'Hjemmeside', - 'type_service' => 'Tjeneste', - 'pattern' => 'Søgestreng/mønster', - 'pattern_description' => 'Hvis dette mønster ikke findes på hjemmesiden, vil serveren blive markeret som værende offline. Regulære udtryk er tilladt.', - 'last_check' => 'Sidst kontrolleret', - 'last_online' => 'Sidst online', - 'last_offline' => 'Sidst offline', - 'monitoring' => 'Overvågning', - 'no_monitoring' => 'Ingen overvågning', - 'email' => 'E-mail', - 'send_email' => 'Send E-mail', - 'sms' => 'SMS', - 'send_sms' => 'Send SMS', - 'pushover' => 'Pushover', - 'users' => 'Users', - 'delete_title' => 'Slet server', - 'delete_message' => 'Er du sikker på du vil slette server \'%1\'?', - 'deleted' => 'Server slettet.', - 'updated' => 'Server opdateret.', - 'inserted' => 'Server tilføjet.', - 'latency' => 'Forsinkelse', - 'latency_max' => 'Forsinkelse (maksimum)', - 'latency_min' => 'Forsinkelse (minimum)', - 'latency_avg' => 'Forsinkelse (gennemsnitlig)', - 'uptime' => 'Oppetid', - 'year' => 'År', - 'month' => 'Måned', - 'week' => 'Uge', - 'day' => 'Dag', - 'hour' => 'Time', - 'warning_threshold' => 'Advarsel grænse', - 'warning_threshold_description' => 'Antallet af fejl, før status skifter til offline.', - 'chart_last_week' => 'Sidste uge', - 'chart_history' => 'Historie', - // Charts date format according jqPlot date format http://www.jqplot.com/docs/files/plugins/jqplot-dateAxisRenderer-js.html - 'chart_day_format' => '%d-%m-%Y', - 'chart_long_date_format' => '%d-%m-%Y %H:%M:%S', - 'chart_short_date_format' => '%d/%m %H:%M', - 'chart_short_time_format' => '%H:%M', - 'warning_notifications_disabled_sms' => 'SMS notifikationer er deaktiveret.', - 'warning_notifications_disabled_email' => 'E-mail notifikationer er deaktiveret.', - 'warning_notifications_disabled_pushover' => 'Pushover notifikationer er deaktiveret.', - 'error_server_no_match' => 'Server ikke fundet.', - 'error_server_label_bad_length' => 'Label skal være mellem et og 255 karakterer.', - 'error_server_ip_bad_length' => 'Domænet/IP skal være mellem et og 255 karakterer.', - 'error_server_ip_bad_service' => 'IP adressen er ikke gyldig.', - 'error_server_ip_bad_website' => 'Websitets URL er ikke gyldigt.', - 'error_server_type_invalid' => 'Den valgte servertype er ikke gyldig.', - 'error_server_warning_threshold_invalid' => 'Advarsels-tærskel skal være et gyldigt tal større end 0.', - ), - 'config' => array( - 'general' => 'Generelt', - 'language' => 'Sprog', - 'show_update' => 'Opdateringer', - 'email_status' => 'Tillad at sende e-mail', - 'email_from_email' => 'E-mail fra adresse', - 'email_from_name' => 'E-mail fra navn', - 'email_smtp' => 'Aktiver SMTP', - 'email_smtp_host' => 'SMTP vært', - 'email_smtp_port' => 'SMTP port', - 'email_smtp_security' => 'SMTP c', - 'email_smtp_security_none' => 'Ingen', - 'email_smtp_username' => 'SMTP brugernavn', - 'email_smtp_password' => 'SMTP adgangskode', - 'email_smtp_noauth' => 'Efterlad blank hvis det ikke er krævet', - 'sms_status' => 'Tillad at sende SMS beskeder', - 'sms_gateway' => 'SMS Gateway', - 'sms_gateway_username' => 'Gateway brugernavn/apikey', - 'sms_gateway_password' => 'Gateway adgangskode', - 'sms_from' => 'Afsenderens navn.', - 'pushover_status' => 'Tillad at sende Pushover beskeder', - 'pushover_description' => 'Pushover er en service det gør det nemt at modtage real-time notifikationer. Se deres website for yderligere information.', - 'pushover_clone_app' => 'Klik her for at oprette din Pushover app', - 'pushover_api_token' => 'Pushover App API Token', - 'pushover_api_token_description' => 'Før du kan benytte Pushover, skal du registrere en app på deres website og indtaste en App API Token her.', - 'alert_type' => 'Vælg hvornår du vil modtage beskeden', - 'alert_type_description' => 'Status ændring: '. - 'Du vil modtage en notifkation når en server har en ændring i status. Fra online -> offline eller offline -> online.
    '. - '
    Offline: '. - 'Du vil modtage en meddelelse, når en server går offline for første gang. Eksempelvis '. - 'hvis dit cronjob kører hvert kvarter, og din server går ned kl 01 og kommer først op kl 06, '. - ' vil du kun modtage en mail kl 01.
    '. - '
    Altid: '. - 'Du vil modtage en besked, hver gang scriptet kører og et websted er nede, selvom site har været offline i flere timer.', - 'alert_type_status' => 'Status ændret', - 'alert_type_offline' => 'Offline', - 'alert_type_always' => 'Altid', - 'log_status' => 'Log status', - 'log_status_description' => 'Hvis log status er sat til TRUE, vil monitoren logge hændelsen hver gang status ændre sig.', - 'log_email' => 'Log e-mails sendt af systemet', - 'log_sms' => 'Log SMS sendt af systemet', - 'log_pushover' => 'Log pushover messages sent by the script', - 'updated' => 'Indstillingerne er blevet opdateret.', - 'tab_email' => 'E-mail', - 'tab_sms' => 'SMS', - 'tab_pushover' => 'Pushover', - 'settings_email' => 'E-mail indstillinger', - 'settings_sms' => 'SMS indstillinger', - 'settings_pushover' => 'Pushover settings', - 'settings_notification' => 'Meddelelse indstillinger', - 'settings_log' => 'Log indstillinger', - 'auto_refresh' => 'Genopfrisk automatisk', - 'auto_refresh_description' => - 'Genopfrisk automatisk serversider.
    '. - ''. - 'Tid i sekunder. Hvis 0 vil siden ikke genopfriske automatisk'. - '', - 'seconds' => 'sekunder', - 'test' => 'Test', - 'test_email' => 'En e-mail vil blive sendt til den adresse, der er angivet i din brugerprofil.', - 'test_sms' => 'En SMS vil blive sendt til det nummer, der er angivet i din brugerprofil.', - 'test_pushover' => 'En Pushover notifikation vil blive sendt til brugerens enhed, specificeret i brugerprofilen.', - 'send' => 'Send', - 'test_subject' => 'Test', - 'test_message' => 'Test besked', - 'email_sent' => 'E-mail sendt', - 'email_error' => 'Fejl ved afsendelse af e-mail', - 'sms_sent' => 'Sms sendt', - 'sms_error' => 'Fejl ved afsendelse af SMS. %s', - 'sms_error_nomobile' => 'Ikke muligt at sende SMS: Intet gyldigt telefonnummer blev fundet i din profil.', - 'pushover_sent' => 'Pushover notifikation blev sendt', - 'pushover_error' => 'En fejl opstod under afsendelse af Pushover notifikation: %s', - 'pushover_error_noapp' => 'Ikke muligt at sende test notifikation: Intet Pushover App API token fundet i den globale konfiguration.', - 'pushover_error_nokey' => 'Ikke muligt at sende test notifikation: Ingen Pushover key fundet i din profil.', - 'log_retention_period' => 'Logs gemmes', - 'log_retention_period_description' => 'Antal dage over hvor længe logs med notifikationer og arkiverede serveres oppetid skal gemmes. Indtast 0 for at deaktivere logoprydning.', - 'log_retention_days' => 'dage', - ), - // for newlines in the email messages use
    - 'notifications' => array( - 'off_sms' => 'Serveren \'%LABEL%\' er NEDE: ip=%IP%, port=%PORT%. Fejl=%ERROR%', - 'off_email_subject' => 'VIGTIGT: Server \'%LABEL%\' er NEDE', - 'off_email_body' => "Det lykkedes ikke at oprette forbindelse til følgende server:

    Server: %LABEL%
    IP: %IP%
    Port: %PORT%
    Fejl: %ERROR%
    Dato: %DATE%", - 'off_pushover_title' => 'Serveren \'%LABEL%\' er NEDE', - 'off_pushover_message' => "Det lykkedes ikke at oprette forbindelse til følgende server:

    Server: %LABEL%
    IP: %IP%
    Port: %PORT%
    Fejl: %ERROR%
    Dato: %DATE%", - 'on_sms' => 'Serveren \'%LABEL%\' KØRER: ip=%IP%, port=%PORT%, it was down for %LAST_OFFLINE_DURATION%', - 'on_email_subject' => 'VIGTIGT: Serveren \'%LABEL%\' KØRER', - 'on_email_body' => "Serveren '%LABEL%' kører igen, it was down for %LAST_OFFLINE_DURATION%:

    Server: %LABEL%
    IP: %IP%
    Port: %PORT%
    Dato: %DATE%", - 'on_pushover_title' => 'Serveren \'%LABEL%\' KØRER', - 'on_pushover_message' => "Serveren '%LABEL%' kører igen, it was down for %LAST_OFFLINE_DURATION%:

    Server: %LABEL%
    IP: %IP%
    Port: %PORT%
    Dato: %DATE%", - ), - 'login' => array( - 'welcome_usermenu' => 'Velkommen, %user_name%', - 'title_sign_in' => 'Log ind', - 'title_forgot' => 'Glemt adgangskode?', - 'title_reset' => 'Nulstil din adgangskode', - 'submit' => 'Indsend', - 'remember_me' => 'Husk kode', - 'login' => 'Log ind', - 'logout' => 'Log ud', - 'username' => 'Brugernavn', - 'password' => 'Adgangskode', - 'password_repeat' => 'Skriv adgangskode igen', - 'password_forgot' => 'Glemt adgangskode?', - 'password_reset' => 'Nulstil adgangskode', - 'password_reset_email_subject' => 'Nulstil din adgangskode for PHP Server Monitor', - 'password_reset_email_body' => 'Brug venligst følgende link for at nulstille din adgangskode. Bemærk at linkets gyldighed udløber efter en time.

    %link%', - 'error_user_incorrect' => 'Det angivet brugernavn kunne ikke findes.', - 'error_login_incorrect' => 'Oplysningerne stemmer ikke overens.', - 'error_login_passwords_nomatch' => 'De angivne adgangskoder er ikke ens.', - 'error_reset_invalid_link' => 'Følgende link er ugyldigt.', - 'success_password_forgot' => 'En e-mail er blevet sendt til dig med oplysninger om, hvordan du nulstiller din adgangskode.', - 'success_password_reset' => 'Din adgangskode er blevet nulstillet. Log venligst ind igen.', - ), - 'error' => array( - '401_unauthorized' => 'Uautoriseret', - '401_unauthorized_description' => 'Du har ikke rettigheder til at se denne side.', - ), + 'name' => 'Dansk - Danish', + 'locale' => array('da_DK.UTF-8', 'da_DK', 'danish', 'danish-dk'), + 'system' => array( + 'title' => 'Server Monitor', + 'install' => 'Installér', + 'action' => 'Action', + 'save' => 'Gem', + 'edit' => 'Redigér', + 'delete' => 'Slet', + 'date' => 'Dato', + 'message' => 'Besked', + 'yes' => 'Ja', + 'no' => 'Nej', + 'insert' => 'Indsæt', + 'add_new' => 'Tilføj ny', + 'update_available' => 'En ny version ({version}) er tilgængelig på http://www.phpservermonitor.org.', + 'back_to_top' => 'Til toppen', + 'go_back' => 'Tilbage', + 'ok' => 'OK', + 'cancel' => 'Annullér', + // date/time format according the strftime php function format parameter http://php.net/manual/function.strftime.php + 'short_day_format' => '%B %e', + 'long_day_format' => '%B %e, %Y', + 'yesterday_format' => 'Igår %k:%M', + 'other_day_format' => '%A %k:%M', + 'never' => 'Aldrig', + 'hours_ago' => '%d timer siden', + 'an_hour_ago' => 'omkring en time siden', + 'minutes_ago' => '%d minutter siden', + 'a_minute_ago' => 'omkring et minut siden', + 'seconds_ago' => '%d sekunder siden', + 'a_second_ago' => 'et sekund siden', + 'year' => 'year', + 'years' => 'years', + 'month' => 'month', + 'months' => 'months', + 'day' => 'day', + 'days' => 'days', + 'hour' => 'hour', + 'hours' => 'hours', + 'minute' => 'minute', + 'minutes' => 'minutes', + 'second' => 'second', + 'seconds' => 'seconds', + ), + 'menu' => array( + 'config' => 'Indstillinger', + 'server' => 'Servere', + 'server_log' => 'Log', + 'server_status' => 'Status', + 'server_update' => 'Opdatér', + 'user' => 'Brugere', + 'help' => 'Hjælp', + ), + 'users' => array( + 'user' => 'Bruger', + 'name' => 'Navn', + 'user_name' => 'Brugernavn', + 'password' => 'Adgangskode', + 'password_repeat' => 'Adgangskode igen', + 'password_leave_blank' => 'Udfyldes hvis du vil skifte adgangskode', + 'level' => 'Niveau', + 'level_10' => 'Administrator', + 'level_20' => 'Bruger', + 'level_description' => 'Administratorer har fuld adgang: De kan styre servere, brugere og indstillinger.
    Brugere kan kun se og opdatere servere som er de har adgang til.', + 'mobile' => 'Mobil', + 'email' => 'E-mail', + 'pushover' => 'Pushover', + 'pushover_description' => 'Pushover er en service der gør det let at modtage real-time notifikationer. Se deres website for mere information.', + 'pushover_key' => 'Pushover nøgle', + 'pushover_device' => 'Pushover enhed', + 'pushover_device_description' => 'Navnet på enheden som beskeden skal sendes til. Lad denne være tom hvis alle skal modtage beskeden.', + 'delete_title' => 'Slet bruger', + 'delete_message' => 'Er du sikker på du vil slette bruger \'%1\'?', + 'deleted' => 'Bruger slettet.', + 'updated' => 'Bruger opdateret.', + 'inserted' => 'Bruger tilføjet.', + 'profile' => 'Profil', + 'profile_updated' => 'Din profil er opdateret.', + 'error_user_name_bad_length' => 'Brugernavn skal være mellem 2 til 64 tegn.', + 'error_user_name_invalid' => 'Brugernavn må kun indholde alfabetiske tegn (a-z, A-Z), tal (0-9), prikker (.) og (_).', + 'error_user_name_exists' => 'Det valgte brugernavn findes allerede.', + 'error_user_email_bad_length' => 'E-mail addresser skal være mellem 5 til 255 tegn.', + 'error_user_email_invalid' => 'Den valgte e-mail er ugyldig.', + 'error_user_level_invalid' => 'Det angivet bruger niveau er ugyldig.', + 'error_user_no_match' => 'Brugeren findes ikke.', + 'error_user_password_invalid' => 'Den indtastede adgangskode er ugyldig.', + 'error_user_password_no_match' => 'De to adgangskode er ikke ens.', + ), + 'log' => array( + 'title' => 'Logposter', + 'type' => 'Type', + 'status' => 'Status', + 'email' => 'E-mail', + 'sms' => 'SMS', + 'pushover' => 'Pushover', + 'no_logs' => 'Intet i loggen', + 'clear' => 'Ryd log', + 'delete_title' => 'Slet log', + 'delete_message' => 'Er du sikker på, at du vil slette alle logfiler?', + ), + 'servers' => array( + 'server' => 'Server', + 'status' => 'Status', + 'label' => 'Label', + 'domain' => 'Domæne/IP', + 'timeout' => 'Timeout', + 'timeout_description' => 'Antal sekunder som serveren har til at svare.', + 'port' => 'Port', + 'type' => 'Type', + 'type_website' => 'Hjemmeside', + 'type_service' => 'Tjeneste', + 'pattern' => 'Søgestreng/mønster', + 'pattern_description' => 'Hvis dette mønster ikke findes på hjemmesiden, vil serveren blive markeret som værende offline. Regulære udtryk er tilladt.', + 'last_check' => 'Sidst kontrolleret', + 'last_online' => 'Sidst online', + 'last_offline' => 'Sidst offline', + 'monitoring' => 'Overvågning', + 'no_monitoring' => 'Ingen overvågning', + 'email' => 'E-mail', + 'send_email' => 'Send E-mail', + 'sms' => 'SMS', + 'send_sms' => 'Send SMS', + 'pushover' => 'Pushover', + 'users' => 'Users', + 'delete_title' => 'Slet server', + 'delete_message' => 'Er du sikker på du vil slette server \'%1\'?', + 'deleted' => 'Server slettet.', + 'updated' => 'Server opdateret.', + 'inserted' => 'Server tilføjet.', + 'latency' => 'Forsinkelse', + 'latency_max' => 'Forsinkelse (maksimum)', + 'latency_min' => 'Forsinkelse (minimum)', + 'latency_avg' => 'Forsinkelse (gennemsnitlig)', + 'uptime' => 'Oppetid', + 'year' => 'År', + 'month' => 'Måned', + 'week' => 'Uge', + 'day' => 'Dag', + 'hour' => 'Time', + 'warning_threshold' => 'Advarsel grænse', + 'warning_threshold_description' => 'Antallet af fejl, før status skifter til offline.', + 'chart_last_week' => 'Sidste uge', + 'chart_history' => 'Historie', + // Charts date format according jqPlot date format http://www.jqplot.com/docs/files/plugins/jqplot-dateAxisRenderer-js.html + 'chart_day_format' => '%d-%m-%Y', + 'chart_long_date_format' => '%d-%m-%Y %H:%M:%S', + 'chart_short_date_format' => '%d/%m %H:%M', + 'chart_short_time_format' => '%H:%M', + 'warning_notifications_disabled_sms' => 'SMS notifikationer er deaktiveret.', + 'warning_notifications_disabled_email' => 'E-mail notifikationer er deaktiveret.', + 'warning_notifications_disabled_pushover' => 'Pushover notifikationer er deaktiveret.', + 'error_server_no_match' => 'Server ikke fundet.', + 'error_server_label_bad_length' => 'Label skal være mellem et og 255 karakterer.', + 'error_server_ip_bad_length' => 'Domænet/IP skal være mellem et og 255 karakterer.', + 'error_server_ip_bad_service' => 'IP adressen er ikke gyldig.', + 'error_server_ip_bad_website' => 'Websitets URL er ikke gyldigt.', + 'error_server_type_invalid' => 'Den valgte servertype er ikke gyldig.', + 'error_server_warning_threshold_invalid' => 'Advarsels-tærskel skal være et gyldigt tal større end 0.', + ), + 'config' => array( + 'general' => 'Generelt', + 'language' => 'Sprog', + 'show_update' => 'Opdateringer', + 'email_status' => 'Tillad at sende e-mail', + 'email_from_email' => 'E-mail fra adresse', + 'email_from_name' => 'E-mail fra navn', + 'email_smtp' => 'Aktiver SMTP', + 'email_smtp_host' => 'SMTP vært', + 'email_smtp_port' => 'SMTP port', + 'email_smtp_security' => 'SMTP c', + 'email_smtp_security_none' => 'Ingen', + 'email_smtp_username' => 'SMTP brugernavn', + 'email_smtp_password' => 'SMTP adgangskode', + 'email_smtp_noauth' => 'Efterlad blank hvis det ikke er krævet', + 'sms_status' => 'Tillad at sende SMS beskeder', + 'sms_gateway' => 'SMS Gateway', + 'sms_gateway_username' => 'Gateway brugernavn/apikey', + 'sms_gateway_password' => 'Gateway adgangskode', + 'sms_from' => 'Afsenderens navn.', + 'pushover_status' => 'Tillad at sende Pushover beskeder', + 'pushover_description' => 'Pushover er en service det gør det nemt at modtage real-time notifikationer. Se deres website for yderligere information.', + 'pushover_clone_app' => 'Klik her for at oprette din Pushover app', + 'pushover_api_token' => 'Pushover App API Token', + 'pushover_api_token_description' => 'Før du kan benytte Pushover, skal du registrere en app på deres website og indtaste en App API Token her.', + 'alert_type' => 'Vælg hvornår du vil modtage beskeden', + 'alert_type_description' => 'Status ændring: ' . + 'Du vil modtage en notifkation når en server har en ændring i status. Fra online -> offline eller offline -> online.
    ' . + '
    Offline: ' . + 'Du vil modtage en meddelelse, når en server går offline for første gang. Eksempelvis ' . + 'hvis dit cronjob kører hvert kvarter, og din server går ned kl 01 og kommer først op kl 06, ' . + ' vil du kun modtage en mail kl 01.
    ' . + '
    Altid: ' . + 'Du vil modtage en besked, hver gang scriptet kører og et websted er nede, selvom site har været offline i flere timer.', + 'alert_type_status' => 'Status ændret', + 'alert_type_offline' => 'Offline', + 'alert_type_always' => 'Altid', + 'log_status' => 'Log status', + 'log_status_description' => 'Hvis log status er sat til TRUE, vil monitoren logge hændelsen hver gang status ændre sig.', + 'log_email' => 'Log e-mails sendt af systemet', + 'log_sms' => 'Log SMS sendt af systemet', + 'log_pushover' => 'Log pushover messages sent by the script', + 'updated' => 'Indstillingerne er blevet opdateret.', + 'tab_email' => 'E-mail', + 'tab_sms' => 'SMS', + 'tab_pushover' => 'Pushover', + 'settings_email' => 'E-mail indstillinger', + 'settings_sms' => 'SMS indstillinger', + 'settings_pushover' => 'Pushover settings', + 'settings_notification' => 'Meddelelse indstillinger', + 'settings_log' => 'Log indstillinger', + 'auto_refresh' => 'Genopfrisk automatisk', + 'auto_refresh_description' => + 'Genopfrisk automatisk serversider.
    ' . + '' . + 'Tid i sekunder. Hvis 0 vil siden ikke genopfriske automatisk' . + '', + 'seconds' => 'sekunder', + 'test' => 'Test', + 'test_email' => 'En e-mail vil blive sendt til den adresse, der er angivet i din brugerprofil.', + 'test_sms' => 'En SMS vil blive sendt til det nummer, der er angivet i din brugerprofil.', + 'test_pushover' => 'En Pushover notifikation vil blive sendt til brugerens enhed, specificeret i brugerprofilen.', + 'send' => 'Send', + 'test_subject' => 'Test', + 'test_message' => 'Test besked', + 'email_sent' => 'E-mail sendt', + 'email_error' => 'Fejl ved afsendelse af e-mail', + 'sms_sent' => 'Sms sendt', + 'sms_error' => 'Fejl ved afsendelse af SMS. %s', + 'sms_error_nomobile' => 'Ikke muligt at sende SMS: Intet gyldigt telefonnummer blev fundet i din profil.', + 'pushover_sent' => 'Pushover notifikation blev sendt', + 'pushover_error' => 'En fejl opstod under afsendelse af Pushover notifikation: %s', + 'pushover_error_noapp' => 'Ikke muligt at sende test notifikation: Intet Pushover App API token fundet i den globale konfiguration.', + 'pushover_error_nokey' => 'Ikke muligt at sende test notifikation: Ingen Pushover key fundet i din profil.', + 'log_retention_period' => 'Logs gemmes', + 'log_retention_period_description' => 'Antal dage over hvor længe logs med notifikationer og arkiverede serveres oppetid skal gemmes. Indtast 0 for at deaktivere logoprydning.', + 'log_retention_days' => 'dage', + ), + // for newlines in the email messages use
    + 'notifications' => array( + 'off_sms' => 'Serveren \'%LABEL%\' er NEDE: ip=%IP%, port=%PORT%. Fejl=%ERROR%', + 'off_email_subject' => 'VIGTIGT: Server \'%LABEL%\' er NEDE', + 'off_email_body' => "Det lykkedes ikke at oprette forbindelse til følgende server:

    Server: %LABEL%
    IP: %IP%
    Port: %PORT%
    Fejl: %ERROR%
    Dato: %DATE%", + 'off_pushover_title' => 'Serveren \'%LABEL%\' er NEDE', + 'off_pushover_message' => "Det lykkedes ikke at oprette forbindelse til følgende server:

    Server: %LABEL%
    IP: %IP%
    Port: %PORT%
    Fejl: %ERROR%
    Dato: %DATE%", + 'on_sms' => 'Serveren \'%LABEL%\' KØRER: ip=%IP%, port=%PORT%, it was down for %LAST_OFFLINE_DURATION%', + 'on_email_subject' => 'VIGTIGT: Serveren \'%LABEL%\' KØRER', + 'on_email_body' => "Serveren '%LABEL%' kører igen, it was down for %LAST_OFFLINE_DURATION%:

    Server: %LABEL%
    IP: %IP%
    Port: %PORT%
    Dato: %DATE%", + 'on_pushover_title' => 'Serveren \'%LABEL%\' KØRER', + 'on_pushover_message' => "Serveren '%LABEL%' kører igen, it was down for %LAST_OFFLINE_DURATION%:

    Server: %LABEL%
    IP: %IP%
    Port: %PORT%
    Dato: %DATE%", + ), + 'login' => array( + 'welcome_usermenu' => 'Velkommen, %user_name%', + 'title_sign_in' => 'Log ind', + 'title_forgot' => 'Glemt adgangskode?', + 'title_reset' => 'Nulstil din adgangskode', + 'submit' => 'Indsend', + 'remember_me' => 'Husk kode', + 'login' => 'Log ind', + 'logout' => 'Log ud', + 'username' => 'Brugernavn', + 'password' => 'Adgangskode', + 'password_repeat' => 'Skriv adgangskode igen', + 'password_forgot' => 'Glemt adgangskode?', + 'password_reset' => 'Nulstil adgangskode', + 'password_reset_email_subject' => 'Nulstil din adgangskode for PHP Server Monitor', + 'password_reset_email_body' => 'Brug venligst følgende link for at nulstille din adgangskode. Bemærk at linkets gyldighed udløber efter en time.

    %link%', + 'error_user_incorrect' => 'Det angivet brugernavn kunne ikke findes.', + 'error_login_incorrect' => 'Oplysningerne stemmer ikke overens.', + 'error_login_passwords_nomatch' => 'De angivne adgangskoder er ikke ens.', + 'error_reset_invalid_link' => 'Følgende link er ugyldigt.', + 'success_password_forgot' => 'En e-mail er blevet sendt til dig med oplysninger om, hvordan du nulstiller din adgangskode.', + 'success_password_reset' => 'Din adgangskode er blevet nulstillet. Log venligst ind igen.', + ), + 'error' => array( + '401_unauthorized' => 'Uautoriseret', + '401_unauthorized_description' => 'Du har ikke rettigheder til at se denne side.', + ), ); diff --git a/src/psm/Module/AbstractController.php b/src/psm/Module/AbstractController.php index d080934c..ba703637 100644 --- a/src/psm/Module/AbstractController.php +++ b/src/psm/Module/AbstractController.php @@ -1,4 +1,5 @@ db = $db; + $this->twig = $twig; + } - function __construct(Database $db, \Twig_Environment $twig) { - $this->db = $db; - $this->twig = $twig; - } + /** + * Run the controller. + * + * @param string $action if NULL, the action will be retrieved from user input (GET/POST) + * @return \Symfony\Component\HttpFoundation\Response + */ + public function run($action = null) + { + if ($action === null) { + $action = psm_GET('action', psm_POST('action', $this->action_default)); + } + $this->xhr = (bool) psm_GET('xhr', psm_POST('xhr', false)); - /** - * Run the controller. - * - * @param string $action if NULL, the action will be retrieved from user input (GET/POST) - * @return \Symfony\Component\HttpFoundation\Response - */ - public function run($action = null) { - if ($action === null) { - $action = psm_GET('action', psm_POST('action', $this->action_default)); - } - $this->xhr = (bool) psm_GET('xhr', psm_POST('xhr', false)); + if (!in_array($action, $this->actions) || !($result = $this->runAction($action))) { + $result = $this->runAction($this->action_default); + } - if (!in_array($action, $this->actions) || !($result = $this->runAction($action))) { - $result = $this->runAction($this->action_default); - } + if ($result instanceof Response) { + return $result; + } - if ($result instanceof Response) { - return $result; - } + // no response returned from execute, create regular HTML + return $this->createHTML($result); + } - // no response returned from execute, create regular HTML - return $this->createHTML($result); - } + /** + * Run a specified action + * + * For it to run, the "execute$action" method must exist. + * @param string $action + * @return mixed FALSE when action couldnt be initialized, response otherwise + */ + protected function runAction($action) + { + if (isset($this->user_level_required_actions[$action])) { + if ($this->getUser()->getUserLevel() > $this->user_level_required_actions[$action]) { + // user is not allowed to access this action.. + return false; + } + } + $method = 'execute' . ucfirst($action); + if (method_exists($this, $method)) { + $this->action = $action; + $result = $this->$method(); + // if result from execute is null, no return value given so return true to indicate a successful execute + return ($result === null) ? true : $result; + } + return false; + } - /** - * Run a specified action - * - * For it to run, the "execute$action" method must exist. - * @param string $action - * @return mixed FALSE when action couldnt be initialized, response otherwise - */ - protected function runAction($action) { - if (isset($this->user_level_required_actions[$action])) { - if ($this->getUser()->getUserLevel() > $this->user_level_required_actions[$action]) { - // user is not allowed to access this action.. - return false; - } - } - $method = 'execute'.ucfirst($action); - if (method_exists($this, $method)) { - $this->action = $action; - $result = $this->$method(); - // if result from execute is null, no return value given so return true to indicate a successful execute - return ($result === null) ? true : $result; - } - return false; - } + /** + * Create the HTML code for the module. + * + * If XHR is on, no main template will be added. + * + * @param string $html HTML code to add to the main body + * @return \Symfony\Component\HttpFoundation\Response + */ + protected function createHTML($html = null) + { + if (!$this->xhr) { + // in XHR mode, we will not add the main template + $tpl_data = array( + 'title' => strtoupper(psm_get_lang('system', 'title')), + 'label_back_to_top' => psm_get_lang('system', 'back_to_top'), + 'add_footer' => $this->add_footer, + 'version' => 'v' . PSM_VERSION, + 'messages' => $this->getMessages(), + 'html_content' => $html, + ); - /** - * Create the HTML code for the module. - * - * If XHR is on, no main template will be added. - * - * @param string $html HTML code to add to the main body - * @return \Symfony\Component\HttpFoundation\Response - */ - protected function createHTML($html = null) { - if (!$this->xhr) { - // in XHR mode, we will not add the main template - $tpl_data = array( - 'title' => strtoupper(psm_get_lang('system', 'title')), - 'label_back_to_top' => psm_get_lang('system', 'back_to_top'), - 'add_footer' => $this->add_footer, - 'version' => 'v'.PSM_VERSION, - 'messages' => $this->getMessages(), - 'html_content' => $html, - ); + // add menu to page? + if ($this->add_menu) { + $tpl_data['html_menu'] = $this->createHTMLMenu(); + } + // add header accessories to page ? + if ($this->header_accessories) { + $tpl_data['header_accessories'] = $this->header_accessories; + } + // add modal dialog to page ? + if (sizeof($this->modal)) { + $html_modal = ''; + foreach ($this->modal as $modal) { + $html_modal .= $modal->createHTML(); + } + $tpl_data['html_modal'] = $html_modal; + } + // add sidebar to page? + if ($this->sidebar !== null) { + $tpl_data['html_sidebar'] = $this->sidebar->createHTML(); + } - // add menu to page? - if ($this->add_menu) { - $tpl_data['html_menu'] = $this->createHTMLMenu(); - } - // add header accessories to page ? - if ($this->header_accessories) { - $tpl_data['header_accessories'] = $this->header_accessories; - } - // add modal dialog to page ? - if (sizeof($this->modal)) { - $html_modal = ''; - foreach ($this->modal as $modal) { - $html_modal .= $modal->createHTML(); - } - $tpl_data['html_modal'] = $html_modal; - } - // add sidebar to page? - if ($this->sidebar !== null) { - $tpl_data['html_sidebar'] = $this->sidebar->createHTML(); - } + if (psm_update_available()) { + $tpl_data['update_available'] = str_replace( + '{version}', + 'v' . + psm_get_conf('version_update_check'), + psm_get_lang('system', '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')); - } + if ($this->black_background) { + $tpl_data['body_class'] = 'black_background'; + } + $html = $this->twig->render('main/body.tpl.html', $tpl_data); + } - if ($this->black_background) { - $tpl_data['body_class'] = 'black_background'; - } - $html = $this->twig->render('main/body.tpl.html', $tpl_data); - } + $response = new Response($html); - $response = new Response($html); + return $response; + } - return $response; - } + /** + * Create HTML code for the menu + * @return string + */ + protected function createHTMLMenu() + { + $ulvl = $this->getUser()->getUserLevel(); - /** - * Create HTML code for the menu - * @return string - */ - protected function createHTMLMenu() { - $ulvl = $this->getUser()->getUserLevel(); + $tpl_data = array( + 'label_help' => psm_get_lang('menu', 'help'), + 'label_profile' => psm_get_lang('users', 'profile'), + 'label_logout' => psm_get_lang('login', 'logout'), + 'url_profile' => psm_build_url(array('mod' => 'user_profile')), + 'url_logout' => psm_build_url(array('logout' => 1)), + 'label_current' => psm_get_lang('system', 'current'), + ); - $tpl_data = array( - 'label_help' => psm_get_lang('menu', 'help'), - 'label_profile' => psm_get_lang('users', 'profile'), - 'label_logout' => psm_get_lang('login', 'logout'), - 'url_profile' => psm_build_url(array('mod' => 'user_profile')), - 'url_logout' => psm_build_url(array('logout' => 1)), - 'label_current' => psm_get_lang('system', 'current'), - ); + switch ($ulvl) { + case PSM_USER_ADMIN: + $items = array('server_status', 'server', 'server_log', 'user', 'config', 'server_update'); + break; + case PSM_USER_USER: + $items = array('server_status', 'server', 'server_log', 'server_update'); + break; + default: + $items = array(); + break; + } + $tpl_data['menu'] = array(); + foreach ($items as $key) { + $tpl_data['menu'][] = array( + 'active' => ($key == psm_GET('mod')) ? 'active' : '', + 'url' => psm_build_url(array('mod' => $key)), + 'label' => psm_get_lang('menu', $key), + ); + } - switch ($ulvl) { - case PSM_USER_ADMIN: - $items = array('server_status', 'server', 'server_log', 'user', 'config', 'server_update'); - break; - case PSM_USER_USER: - $items = array('server_status', 'server', 'server_log', 'server_update'); - break; - default: - $items = array(); - break; - } - $tpl_data['menu'] = array(); - foreach ($items as $key) { - $tpl_data['menu'][] = array( - 'active' => ($key == psm_GET('mod')) ? 'active' : '', - 'url' => psm_build_url(array('mod' => $key)), - 'label' => psm_get_lang('menu', $key), - ); - } + if ($ulvl != PSM_USER_ANONYMOUS) { + $user = $this->getUser()->getUser(); + $tpl_data['label_usermenu'] = str_replace( + '%user_name%', + $user->name, + psm_get_lang('login', 'welcome_usermenu') + ); + } + return $this->twig->render('main/menu.tpl.html', $tpl_data); + } - if ($ulvl != PSM_USER_ANONYMOUS) { - $user = $this->getUser()->getUser(); - $tpl_data['label_usermenu'] = str_replace( - '%user_name%', - $user->name, - psm_get_lang('login', 'welcome_usermenu') - ); - } - return $this->twig->render('main/menu.tpl.html', $tpl_data); - } + /** + * Hide or show the footer of the page + * @param boolean $value + */ + protected function addFooter($value) + { + $this->add_footer = $value; + } - /** - * Hide or show the footer of the page - * @param boolean $value - */ - protected function addFooter($value) { - $this->add_footer = $value; - } + /** + * Hide or show the menu of the page + * @param boolean $value + */ + protected function addMenu($value) + { + $this->add_menu = $value; + } - /** - * Hide or show the menu of the page - * @param boolean $value - */ - protected function addMenu($value) { - $this->add_menu = $value; - } + /** + * Set actions available + * @param string|array $actions + * @param string $default default action + * @param boolean $append if TRUE, the actions will be added to the current actions + * @return psm\Module\AbstractModule + * @see getAction() + */ + protected function setActions($actions, $default = null, $append = true) + { + if (!is_array($actions)) { + $actions = array($actions); + } + if ($append) { + $this->actions = array_merge($actions); + } else { + $this->actions = $actions; + } + if ($default !== null) { + $this->action_default = $default; + } + return $this; + } - /** - * Set actions available - * @param string|array $actions - * @param string $default default action - * @param boolean $append if TRUE, the actions will be added to the current actions - * @return psm\Module\AbstractModule - * @see getAction() - */ - protected function setActions($actions, $default = null, $append = true) { - if (!is_array($actions)) { - $actions = array($actions); - } - if ($append) { - $this->actions = array_merge($actions); - } else { - $this->actions = $actions; - } - if ($default !== null) { - $this->action_default = $default; - } - return $this; - } + /** + * Get the current action + * @return string + * @see setActions() + */ + public function getAction() + { + return $this->action; + } - /** - * Get the current action - * @return string - * @see setActions() - */ - public function getAction() { - return $this->action; - } + /** + * Add one or multiple message to the stack to be displayed to the user + * @param string|array $msg + * @param string $shortcode primary/success/warning/danger + * @return \psm\Module\ControllerInterface + * @see getMessages() + */ + public function addMessage($msg, $shortcode = 'primary') + { + if (!is_array($msg)) { + $msg = array($msg); + } + $class = $shortcode; + switch ($shortcode) { + case 'error': + $icon = 'exclamation-circle'; + $class = 'danger'; + break; + case 'success': + $icon = 'check-circle'; + break; + case 'warning': + $icon = 'exclamation-triangle'; + break; + case 'primary': + default: + $icon = 'info-circle'; + $shortcode = 'info'; + break; + } - /** - * Add one or multiple message to the stack to be displayed to the user - * @param string|array $msg - * @param string $shortcode primary/success/warning/danger - * @return \psm\Module\ControllerInterface - * @see getMessages() - */ - public function addMessage($msg, $shortcode = 'primary') { - if (!is_array($msg)) { - $msg = array($msg); - } - $class= $shortcode; - switch ($shortcode) { - case 'error': - $icon = 'exclamation-circle'; - $class= 'danger'; - break; - case 'success': - $icon = 'check-circle'; - break; - case 'warning': - $icon = 'exclamation-triangle'; - break; - case 'primary': - default: - $icon = 'info-circle'; - $shortcode = 'info'; - break; - } + foreach ($msg as $m) { + $this->messages[] = array( + 'message' => $m, + 'shortcode' => $shortcode, + 'class' => $class, + 'icon' => $icon, + ); + } + return $this; + } - foreach ($msg as $m) { - $this->messages[] = array( - 'message' => $m, - 'shortcode' => $shortcode, - 'class' => $class, - 'icon' => $icon, - ); - } - return $this; - } + /** + * Get all messages (and optionally clear them) + * @param boolean $clear + * @return array + * @see addMessage() + */ + public function getMessages($clear = true) + { + $msgs = $this->messages; + if ($clear) { + $this->messages = array(); + } + return $msgs; + } - /** - * Get all messages (and optionally clear them) - * @param boolean $clear - * @return array - * @see addMessage() - */ - public function getMessages($clear = true) { - $msgs = $this->messages; - if ($clear) { - $this->messages = array(); - } - return $msgs; - } + /** + * Set the minimum required user level for this controller + * @param int $level + * @return \psm\Module\AbstractController + */ + public function setMinUserLevelRequired($level) + { + $this->user_level_required = intval($level); + return $this; + } - /** - * Set the minimum required user level for this controller - * @param int $level - * @return \psm\Module\AbstractController - */ - public function setMinUserLevelRequired($level) { - $this->user_level_required = intval($level); - return $this; - } + /** + * Get the minimum required user level for this controller + * @return int + */ + public function getMinUserLevelRequired() + { + return $this->user_level_required; + } - /** - * Get the minimum required user level for this controller - * @return int - */ - public function getMinUserLevelRequired() { - return $this->user_level_required; - } + /** + * Set the minimum required user level for a certain action. + * + * Use this only if one of the access is more restricted than the entire controller + * @param int $level + * @param string|array $actions one or more actions to set this level for + * @return \psm\Module\AbstractController + * @see setMinUserLevelRequired() + */ + public function setMinUserLevelRequiredForAction($level, $actions) + { + if (!is_array($actions)) { + $actions = array($actions); + } + foreach ($actions as $action) { + $this->user_level_required_actions[$action] = intval($level); + } + return $this; + } - /** - * Set the minimum required user level for a certain action. - * - * Use this only if one of the access is more restricted than the entire controller - * @param int $level - * @param string|array $actions one or more actions to set this level for - * @return \psm\Module\AbstractController - * @see setMinUserLevelRequired() - */ - public function setMinUserLevelRequiredForAction($level, $actions) { - if (!is_array($actions)) { - $actions = array($actions); - } - foreach ($actions as $action) { - $this->user_level_required_actions[$action] = intval($level); - } - return $this; - } + /** + * Add a sidebar to the page + * @param \psm\Util\Module\SidebarInterface $sidebar + * @return \psm\Module\ControllerInterface + */ + public function setSidebar(\psm\Util\Module\SidebarInterface $sidebar) + { + $this->sidebar = $sidebar; + return $this; + } - /** - * Add a sidebar to the page - * @param \psm\Util\Module\SidebarInterface $sidebar - * @return \psm\Module\ControllerInterface - */ - public function setSidebar(\psm\Util\Module\SidebarInterface $sidebar) { - $this->sidebar = $sidebar; - return $this; - } + /** + * Add a modal dialog to the page + * @param \psm\Util\Module\ModalInterface $modal + * @return \psm\Module\ControllerInterface + */ + public function addModal(\psm\Util\Module\ModalInterface $modal) + { + $this->modal[$modal->getModalID()] = $modal; + return $this; + } - /** - * Add a modal dialog to the page - * @param \psm\Util\Module\ModalInterface $modal - * @return \psm\Module\ControllerInterface - */ - public function addModal(\psm\Util\Module\ModalInterface $modal) { - $this->modal[$modal->getModalID()] = $modal; - return $this; - } + /** + * Set the html code of the header accessories + * @param string $html + */ + public function setHeaderAccessories($html) + { + $this->header_accessories = $html; + } - /** - * Set the html code of the header accessories - * @param string $html - */ - public function setHeaderAccessories($html) { - $this->header_accessories = $html; - } + /** + * Check if XHR is on + * @return boolean + */ + public function isXHR() + { + return $this->xhr; + } - /** - * Check if XHR is on - * @return boolean - */ - public function isXHR() { - return $this->xhr; - } + /** + * Get user service + * @return \psm\Service\User + */ + public function getUser() + { + return $this->container->get('user'); + } - /** - * Get user service - * @return \psm\Service\User - */ - public function getUser() { - return $this->container->get('user'); - } + /** + * Get custom key for CSRF validation + * @return string + */ + public function getCSRFKey() + { + return $this->csrf_key; + } - /** - * Get custom key for CSRF validation - * @return string - */ - public function getCSRFKey() { - return $this->csrf_key; - } - - /** - * Set CSRF key for validation - * @param string $key - * @return \psm\Module\ControllerInterface - */ - protected function setCSRFKey($key) { - $this->csrf_key = $key; - $this->twig->addGlobal('csrf_key', $key); - return $this; - } + /** + * Set CSRF key for validation + * @param string $key + * @return \psm\Module\ControllerInterface + */ + protected function setCSRFKey($key) + { + $this->csrf_key = $key; + $this->twig->addGlobal('csrf_key', $key); + return $this; + } } diff --git a/src/psm/Module/Config/ConfigModule.php b/src/psm/Module/Config/ConfigModule.php index 3e33ceb3..7d72756f 100644 --- a/src/psm/Module/Config/ConfigModule.php +++ b/src/psm/Module/Config/ConfigModule.php @@ -1,4 +1,5 @@ __NAMESPACE__.'\Controller\ConfigController', - ); - - } + public function getControllers() + { + return array( + 'config' => __NAMESPACE__ . '\Controller\ConfigController', + ); + } } diff --git a/src/psm/Module/Config/Controller/ConfigController.php b/src/psm/Module/Config/Controller/ConfigController.php index 6e19c037..52b6920c 100644 --- a/src/psm/Module/Config/Controller/ConfigController.php +++ b/src/psm/Module/Config/Controller/ConfigController.php @@ -1,4 +1,5 @@ setMinUserLevelRequired(PSM_USER_ADMIN); - $this->setCSRFKey('config'); + $this->setMinUserLevelRequired(PSM_USER_ADMIN); + $this->setCSRFKey('config'); - $this->setActions(array( - 'index', 'save', - ), 'index'); - } + $this->setActions(array( + 'index', 'save', + ), 'index'); + } - /** - * Populate all the config fields with values from the database - * - * @return string - */ - protected function executeIndex() { - $this->twig->addGlobal('subtitle', psm_get_lang('menu', 'config')); - $tpl_data = $this->getLabels(); + /** + * Populate all the config fields with values from the database + * + * @return string + */ + protected function executeIndex() + { + $this->twig->addGlobal('subtitle', psm_get_lang('menu', 'config')); + $tpl_data = $this->getLabels(); - $config_db = $this->db->select( - PSM_DB_PREFIX.'config', - null, - array('key', 'value') - ); + $config_db = $this->db->select( + PSM_DB_PREFIX . 'config', + null, + array('key', 'value') + ); - $config = array(); - foreach ($config_db as $entry) { - $config[$entry['key']] = $entry['value']; - } + $config = array(); + foreach ($config_db as $entry) { + $config[$entry['key']] = $entry['value']; + } - // generate language array - $lang_keys = psm_get_langs(); - $tpl_data['language_current'] = (isset($config['language'])) - ? $config['language'] - : 'en_US'; - $tpl_data['languages'] = array(); - foreach ($lang_keys as $key => $label) { - $tpl_data['languages'][] = array( - 'value' => $key, - 'label' => $label, - ); - } + // generate language array + $lang_keys = psm_get_langs(); + $tpl_data['language_current'] = (isset($config['language'])) + ? $config['language'] + : 'en_US'; + $tpl_data['languages'] = array(); + foreach ($lang_keys as $key => $label) { + $tpl_data['languages'][] = array( + 'value' => $key, + 'label' => $label, + ); + } - // generate sms_gateway array - $sms_gateways = psm_get_sms_gateways(); - $tpl_data['sms_gateway'] = array(); - foreach ($sms_gateways as $sms_gateway => $label) { - $tpl_data['sms_gateway'][] = array( - 'value' => $sms_gateway, - 'label' => $label, - ); - } + // generate sms_gateway array + $sms_gateways = psm_get_sms_gateways(); + $tpl_data['sms_gateway'] = array(); + foreach ($sms_gateways as $sms_gateway => $label) { + $tpl_data['sms_gateway'][] = array( + 'value' => $sms_gateway, + 'label' => $label, + ); + } - foreach (array("status", "offline", "always") as $alert_type) { - $tpl_data['alert_type'][] = array( - 'value' => $alert_type, - 'label' => psm_get_lang('config', 'alert_type_'.$alert_type), - ); - } + foreach (array("status", "offline", "always") as $alert_type) { + $tpl_data['alert_type'][] = array( + 'value' => $alert_type, + 'label' => psm_get_lang('config', 'alert_type_' . $alert_type), + ); + } - $tpl_data['email_smtp_security'] = array( - array( - 'value' => '', - 'label' => psm_get_lang('config', 'email_smtp_security_none') - ), - array( - 'value' => 'ssl', - 'label' => 'SSL' - ), - array( - 'value' => 'tls', - 'label' => 'TLS' - ) - ); + $tpl_data['email_smtp_security'] = array( + array( + 'value' => '', + 'label' => psm_get_lang('config', 'email_smtp_security_none') + ), + array( + 'value' => 'ssl', + 'label' => 'SSL' + ), + array( + 'value' => 'tls', + 'label' => 'TLS' + ) + ); - $tpl_data['sms_gateway_selected'] = isset($config['sms_gateway']) ? $config['sms_gateway'] : current($sms_gateways); - $tpl_data['alert_type_selected'] = isset($config['alert_type']) ? $config['alert_type'] : ''; - $tpl_data['email_smtp_security_selected'] = isset($config['email_smtp_security']) ? $config['email_smtp_security'] : ''; - $tpl_data['auto_refresh_servers'] = isset($config['auto_refresh_servers']) ? $config['auto_refresh_servers'] : '0'; - $tpl_data['log_retention_period'] = isset($config['log_retention_period']) ? $config['log_retention_period'] : '365'; - $tpl_data['password_encrypt_key'] = isset($config['password_encrypt_key']) ? $config['password_encrypt_key'] : sha1(microtime()); + $tpl_data['sms_gateway_selected'] = isset($config['sms_gateway']) ? + $config['sms_gateway'] : current($sms_gateways); + $tpl_data['alert_type_selected'] = isset($config['alert_type']) ? + $config['alert_type'] : ''; + $tpl_data['email_smtp_security_selected'] = isset($config['email_smtp_security']) ? + $config['email_smtp_security'] : ''; + $tpl_data['auto_refresh_servers'] = isset($config['auto_refresh_servers']) ? + $config['auto_refresh_servers'] : '0'; + $tpl_data['log_retention_period'] = isset($config['log_retention_period']) ? + $config['log_retention_period'] : '365'; + $tpl_data['password_encrypt_key'] = isset($config['password_encrypt_key']) ? + $config['password_encrypt_key'] : sha1(microtime()); - foreach ($this->checkboxes as $input_key) { - $tpl_data[$input_key.'_checked'] = - (isset($config[$input_key]) && (int) $config[$input_key] == 1) - ? 'checked="checked"' - : ''; - } - foreach ($this->fields as $input_key) { - $tpl_data[$input_key] = (isset($config[$input_key])) ? $config[$input_key] : ''; - } + foreach ($this->checkboxes as $input_key) { + $tpl_data[$input_key . '_checked'] = + (isset($config[$input_key]) && (int) $config[$input_key] == 1) + ? 'checked="checked"' + : ''; + } + foreach ($this->fields as $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'); - foreach ($testmodals as $modal_id) { - $modal = new \psm\Util\Module\Modal($this->twig, 'test'.ucfirst($modal_id), \psm\Util\Module\Modal::MODAL_TYPE_OKCANCEL); - $this->addModal($modal); - $modal->setTitle(psm_get_lang('servers', 'send_'.$modal_id)); - $modal->setMessage(psm_get_lang('config', 'test_'.$modal_id)); - $modal->setOKButtonLabel(psm_get_lang('config', 'send')); - } + $testmodals = array('email', 'sms', 'pushover', 'telegram'); + foreach ($testmodals as $modal_id) { + $modal = new \psm\Util\Module\Modal( + $this->twig, + 'test' . ucfirst($modal_id), + \psm\Util\Module\Modal::MODAL_TYPE_OKCANCEL + ); + $this->addModal($modal); + $modal->setTitle(psm_get_lang('servers', 'send_' . $modal_id)); + $modal->setMessage(psm_get_lang('config', 'test_' . $modal_id)); + $modal->setOKButtonLabel(psm_get_lang('config', 'send')); + } - return $this->twig->render('module/config/config.tpl.html', $tpl_data); - } + return $this->twig->render('module/config/config.tpl.html', $tpl_data); + } - /** - * If a post has been done, gather all the posted data - * and save it to the database - */ - protected function executeSave() { - if (!empty($_POST)) { - // save new config - $clean = array( - 'language' => $_POST['language'], - 'sms_gateway' => $_POST['sms_gateway'], - 'alert_type' => $_POST['alert_type'], - 'email_smtp_security' => - in_array($_POST['email_smtp_security'], array('', 'ssl', 'tls')) - ? $_POST['email_smtp_security'] - : '', - 'auto_refresh_servers' => intval(psm_POST('auto_refresh_servers', 0)), - 'log_retention_period' => intval(psm_POST('log_retention_period', 365)), - 'password_encrypt_key' => psm_POST('password_encrypt_key', sha1(microtime())), - ); - foreach ($this->checkboxes as $input_key) { - $clean[$input_key] = (isset($_POST[$input_key])) ? '1' : '0'; - } - foreach ($this->fields as $input_key) { - if (isset($_POST[$input_key])) { - $clean[$input_key] = $_POST[$input_key]; - } - } - $language_refresh = ($clean['language'] != psm_get_conf('language')); - foreach ($clean as $key => $value) { - psm_update_conf($key, $value); - } - $this->addMessage(psm_get_lang('config', 'updated'), 'success'); + /** + * If a post has been done, gather all the posted data + * and save it to the database + */ + protected function executeSave() + { + if (!empty($_POST)) { + // save new config + $clean = array( + 'language' => $_POST['language'], + 'sms_gateway' => $_POST['sms_gateway'], + 'alert_type' => $_POST['alert_type'], + 'email_smtp_security' => + in_array($_POST['email_smtp_security'], array('', 'ssl', 'tls')) + ? $_POST['email_smtp_security'] + : '', + 'auto_refresh_servers' => intval(psm_POST('auto_refresh_servers', 0)), + 'log_retention_period' => intval(psm_POST('log_retention_period', 365)), + 'password_encrypt_key' => psm_POST('password_encrypt_key', sha1(microtime())), + ); + foreach ($this->checkboxes as $input_key) { + $clean[$input_key] = (isset($_POST[$input_key])) ? '1' : '0'; + } + foreach ($this->fields as $input_key) { + if (isset($_POST[$input_key])) { + $clean[$input_key] = $_POST[$input_key]; + } + } + $language_refresh = ($clean['language'] != psm_get_conf('language')); + foreach ($clean as $key => $value) { + psm_update_conf($key, $value); + } + $this->addMessage(psm_get_lang('config', 'updated'), 'success'); - if (!empty($_POST['test_email'])) { - $this->testEmail(); - } elseif (!empty($_POST['test_sms'])) { - $this->testSMS(); - } elseif (!empty($_POST['test_pushover'])) { - $this->testPushover(); - } elseif (!empty($_POST['test_telegram'])) { - $this->testTelegram(); - } + if (!empty($_POST['test_email'])) { + $this->testEmail(); + } elseif (!empty($_POST['test_sms'])) { + $this->testSMS(); + } elseif (!empty($_POST['test_pushover'])) { + $this->testPushover(); + } elseif (!empty($_POST['test_telegram'])) { + $this->testTelegram(); + } - if ($language_refresh) { - header('Location: '.psm_build_url(array('mod' => 'config'), true, false)); - die(); - } + if ($language_refresh) { + header('Location: ' . psm_build_url(array('mod' => 'config'), true, false)); + die(); + } - if (isset($_POST['general_submit'])) { - $this->default_tab = 'general'; - } elseif (isset($_POST['email_submit']) || !empty($_POST['test_email'])) { - $this->default_tab = 'email'; - } elseif (isset($_POST['sms_submit']) || !empty($_POST['test_sms'])) { - $this->default_tab = 'sms'; - } elseif (isset($_POST['pushover_submit']) || !empty($_POST['test_pushover'])) { - $this->default_tab = 'pushover'; - } elseif (isset($_POST['telegram_submit']) || !empty($_POST['test_telegram'])) { - $this->default_tab = 'telegram'; - } - } - return $this->runAction('index'); - } + if (isset($_POST['general_submit'])) { + $this->default_tab = 'general'; + } elseif (isset($_POST['email_submit']) || !empty($_POST['test_email'])) { + $this->default_tab = 'email'; + } elseif (isset($_POST['sms_submit']) || !empty($_POST['test_sms'])) { + $this->default_tab = 'sms'; + } elseif (isset($_POST['pushover_submit']) || !empty($_POST['test_pushover'])) { + $this->default_tab = 'pushover'; + } elseif (isset($_POST['telegram_submit']) || !empty($_POST['test_telegram'])) { + $this->default_tab = 'telegram'; + } + } + return $this->runAction('index'); + } - /** - * Execute email test - * - * @todo move test to separate class - */ - protected function testEmail() { - $mail = psm_build_mail(); - $message = psm_get_lang('config', 'test_message'); - $mail->Subject = psm_get_lang('config', 'test_subject'); - $mail->Priority = 1; - $mail->Body = $message; - $mail->AltBody = str_replace('
    ', "\n", $message); - $user = $this->getUser()->getUser(); - $mail->AddAddress($user->email, $user->name); - if ($mail->Send()) { - $this->addMessage(psm_get_lang('config', 'email_sent'), 'success'); - } else { - $this->addMessage(psm_get_lang('config', 'email_error').': '.$mail->ErrorInfo, 'error'); - } - } + /** + * Execute email test + * + * @todo move test to separate class + */ + protected function testEmail() + { + $mail = psm_build_mail(); + $message = psm_get_lang('config', 'test_message'); + $mail->Subject = psm_get_lang('config', 'test_subject'); + $mail->Priority = 1; + $mail->Body = $message; + $mail->AltBody = str_replace('
    ', "\n", $message); + $user = $this->getUser()->getUser(); + $mail->AddAddress($user->email, $user->name); + if ($mail->Send()) { + $this->addMessage(psm_get_lang('config', 'email_sent'), 'success'); + } else { + $this->addMessage(psm_get_lang('config', 'email_error') . ': ' . $mail->ErrorInfo, 'error'); + } + } - /** - * Execute SMS test - * - * @todo move test to separate class - */ - protected function testSMS() { - $sms = psm_build_sms(); - if ($sms) { - $user = $this->getUser()->getUser(); - if (empty($user->mobile)) { - $this->addMessage(psm_get_lang('config', 'sms_error_nomobile'), 'error'); - } else { - $sms->addRecipients($user->mobile); - $result = $sms->sendSMS(psm_get_lang('config', 'test_message')); - if ($result === 1) { - $this->addMessage(psm_get_lang('config', 'sms_sent'), 'success'); - } else { - $this->addMessage(sprintf(psm_get_lang('config', 'sms_error'), $result), 'error'); - } - } - } - } + /** + * Execute SMS test + * + * @todo move test to separate class + */ + protected function testSMS() + { + $sms = psm_build_sms(); + if ($sms) { + $user = $this->getUser()->getUser(); + if (empty($user->mobile)) { + $this->addMessage(psm_get_lang('config', 'sms_error_nomobile'), 'error'); + } else { + $sms->addRecipients($user->mobile); + $result = $sms->sendSMS(psm_get_lang('config', 'test_message')); + if ($result === 1) { + $this->addMessage(psm_get_lang('config', 'sms_sent'), 'success'); + } else { + $this->addMessage(sprintf(psm_get_lang('config', 'sms_error'), $result), 'error'); + } + } + } + } - /** - * Execute pushover test - * - * @todo move test to separate class - */ - protected function testPushover() { - $pushover = psm_build_pushover(); - $pushover->setDebug(true); - $user = $this->getUser()->getUser(); - $apiToken = psm_get_conf('pushover_api_token'); + /** + * Execute pushover test + * + * @todo move test to separate class + */ + protected function testPushover() + { + $pushover = psm_build_pushover(); + $pushover->setDebug(true); + $user = $this->getUser()->getUser(); + $apiToken = psm_get_conf('pushover_api_token'); - if (empty($apiToken)) { - $this->addMessage(psm_get_lang('config', 'pushover_error_noapp'), 'error'); - } elseif (empty($user->pushover_key)) { - $this->addMessage(psm_get_lang('config', 'pushover_error_nokey'), 'error'); - } else { - $pushover->setPriority(0); - $pushover->setTitle(psm_get_lang('config', 'test_subject')); - $pushover->setMessage(psm_get_lang('config', 'test_message')); - $pushover->setUser($user->pushover_key); - if ($user->pushover_device != '') { - $pushover->setDevice($user->pushover_device); - } - $result = $pushover->send(); + if (empty($apiToken)) { + $this->addMessage(psm_get_lang('config', 'pushover_error_noapp'), 'error'); + } elseif (empty($user->pushover_key)) { + $this->addMessage(psm_get_lang('config', 'pushover_error_nokey'), 'error'); + } else { + $pushover->setPriority(0); + $pushover->setTitle(psm_get_lang('config', 'test_subject')); + $pushover->setMessage(psm_get_lang('config', 'test_message')); + $pushover->setUser($user->pushover_key); + if ($user->pushover_device != '') { + $pushover->setDevice($user->pushover_device); + } + $result = $pushover->send(); - if (isset($result['output']->status) && $result['output']->status == 1) { - $this->addMessage(psm_get_lang('config', 'pushover_sent'), 'success'); - } else { - if (isset($result['output']->errors->error)) { - $error = $result['output']->errors->error; - } else { - $error = 'Unknown'; - } - $this->addMessage(sprintf(psm_get_lang('config', 'pushover_error'), $error), 'error'); - } - } - } + if (isset($result['output']->status) && $result['output']->status == 1) { + $this->addMessage(psm_get_lang('config', 'pushover_sent'), 'success'); + } else { + if (isset($result['output']->errors->error)) { + $error = $result['output']->errors->error; + } else { + $error = 'Unknown'; + } + $this->addMessage(sprintf(psm_get_lang('config', 'pushover_error'), $error), 'error'); + } + } + } - /** - * Execute telegram test - * - * @todo move test to separate class - */ - protected function testTelegram() { - $telegram = psm_build_telegram(); - $user = $this->getUser()->getUser(); - $apiToken = psm_get_conf('telegram_api_token'); + /** + * Execute telegram test + * + * @todo move test to separate class + */ + protected function testTelegram() + { + $telegram = psm_build_telegram(); + $user = $this->getUser()->getUser(); + $apiToken = psm_get_conf('telegram_api_token'); - if (empty($apiToken)) { - $this->addMessage(psm_get_lang('config', 'telegram_error_notoken'), 'error'); - } elseif (empty($user->telegram_id)) { - $this->addMessage(psm_get_lang('config', 'telegram_error_noid'), 'error'); - } else { - $telegram->setMessage(psm_get_lang('config', 'test_message')); - $telegram->setUser($user->telegram_id); + if (empty($apiToken)) { + $this->addMessage(psm_get_lang('config', 'telegram_error_notoken'), 'error'); + } elseif (empty($user->telegram_id)) { + $this->addMessage(psm_get_lang('config', 'telegram_error_noid'), 'error'); + } else { + $telegram->setMessage(psm_get_lang('config', 'test_message')); + $telegram->setUser($user->telegram_id); - $result = $telegram->send(); + $result = $telegram->send(); - if (isset($result['ok']) && $result['ok'] != false) { - $this->addMessage(psm_get_lang('config', 'telegram_sent'), 'success'); - } else { - if (isset($result['description'])) { - $error = $result['description']; - } else { - $error = 'Unknown'; - } - $this->addMessage(sprintf(psm_get_lang('config', 'telegram_error'), $error), 'error'); - } - } - } + if (isset($result['ok']) && $result['ok'] != false) { + $this->addMessage(psm_get_lang('config', 'telegram_sent'), 'success'); + } else { + if (isset($result['description'])) { + $error = $result['description']; + } else { + $error = 'Unknown'; + } + $this->addMessage(sprintf(psm_get_lang('config', 'telegram_error'), $error), 'error'); + } + } + } - protected function getLabels() { - return array( - 'label_tab_email' => psm_get_lang('config', 'tab_email'), - 'label_tab_sms' => psm_get_lang('config', 'tab_sms'), - 'label_tab_pushover' => psm_get_lang('config', 'tab_pushover'), - 'label_tab_telegram' => psm_get_lang('config', 'tab_telegram'), - 'label_settings_email' => psm_get_lang('config', 'settings_email'), - 'label_settings_sms' => psm_get_lang('config', 'settings_sms'), - 'label_settings_pushover' => psm_get_lang('config', 'settings_pushover'), - 'label_settings_telegram' => psm_get_lang('config', 'settings_telegram'), - 'label_settings_notification' => psm_get_lang('config', 'settings_notification'), - 'label_settings_log' => psm_get_lang('config', 'settings_log'), - 'label_settings_proxy' => psm_get_lang('config', 'settings_proxy'), - 'label_general' => psm_get_lang('config', 'general'), - 'label_language' => psm_get_lang('config', 'language'), - 'label_show_update' => psm_get_lang('config', 'show_update'), - 'label_password_encrypt_key' => psm_get_lang('config', 'password_encrypt_key'), - 'label_password_encrypt_key_note' => psm_get_lang('config', 'password_encrypt_key_note'), - 'label_proxy' => psm_get_lang('config', 'proxy'), - 'label_proxy_url' => psm_get_lang('config', 'proxy_url'), - 'label_proxy_user' => psm_get_lang('config', 'proxy_user'), - 'label_proxy_password' => psm_get_lang('config', 'proxy_password'), - 'label_email_status' => psm_get_lang('config', 'email_status'), - 'label_email_from_email' => psm_get_lang('config', 'email_from_email'), - 'label_email_from_name' => psm_get_lang('config', 'email_from_name'), - 'label_email_smtp' => psm_get_lang('config', 'email_smtp'), - 'label_email_smtp_host' => psm_get_lang('config', 'email_smtp_host'), - 'label_email_smtp_port' => psm_get_lang('config', 'email_smtp_port'), - 'label_email_smtp_security' => psm_get_lang('config', 'email_smtp_security'), - 'label_email_smtp_username' => psm_get_lang('config', 'email_smtp_username'), - 'label_email_smtp_password' => psm_get_lang('config', 'email_smtp_password'), - 'label_email_smtp_noauth' => psm_get_lang('config', 'email_smtp_noauth'), - 'label_sms_status' => psm_get_lang('config', 'sms_status'), - 'label_sms_gateway' => psm_get_lang('config', 'sms_gateway'), - 'label_sms_gateway_username' => psm_get_lang('config', 'sms_gateway_username'), - 'label_sms_gateway_password' => psm_get_lang('config', 'sms_gateway_password'), - 'label_sms_from' => psm_get_lang('config', 'sms_from'), - 'label_pushover_description' => psm_get_lang('config', 'pushover_description'), - 'label_pushover_status' => psm_get_lang('config', 'pushover_status'), - 'label_pushover_clone_app' => psm_get_lang('config', 'pushover_clone_app'), - 'pushover_clone_url' => PSM_PUSHOVER_CLONE_URL, - 'label_pushover_api_token' => psm_get_lang('config', 'pushover_api_token'), - 'label_pushover_api_token_description' => sprintf( - psm_get_lang('config', 'pushover_api_token_description'), - PSM_PUSHOVER_CLONE_URL - ), - 'label_telegram_description' => psm_get_lang('config', 'telegram_description'), - 'label_telegram_status' => psm_get_lang('config', 'telegram_status'), - 'label_telegram_api_token' => psm_get_lang('config', 'telegram_api_token'), - 'label_telegram_api_token_description' => psm_get_lang('config', 'telegram_api_token_description'), - 'label_alert_type' => psm_get_lang('config', 'alert_type'), - 'label_alert_type_description' => psm_get_lang('config', 'alert_type_description'), - 'label_combine_notifications' => psm_get_lang('config', 'combine_notifications'), + protected function getLabels() + { + return array( + 'label_tab_email' => psm_get_lang('config', 'tab_email'), + 'label_tab_sms' => psm_get_lang('config', 'tab_sms'), + 'label_tab_pushover' => psm_get_lang('config', 'tab_pushover'), + 'label_tab_telegram' => psm_get_lang('config', 'tab_telegram'), + 'label_settings_email' => psm_get_lang('config', 'settings_email'), + 'label_settings_sms' => psm_get_lang('config', 'settings_sms'), + 'label_settings_pushover' => psm_get_lang('config', 'settings_pushover'), + 'label_settings_telegram' => psm_get_lang('config', 'settings_telegram'), + 'label_settings_notification' => psm_get_lang('config', 'settings_notification'), + 'label_settings_log' => psm_get_lang('config', 'settings_log'), + 'label_settings_proxy' => psm_get_lang('config', 'settings_proxy'), + 'label_general' => psm_get_lang('config', 'general'), + 'label_language' => psm_get_lang('config', 'language'), + 'label_show_update' => psm_get_lang('config', 'show_update'), + 'label_password_encrypt_key' => psm_get_lang('config', 'password_encrypt_key'), + 'label_password_encrypt_key_note' => psm_get_lang('config', 'password_encrypt_key_note'), + 'label_proxy' => psm_get_lang('config', 'proxy'), + 'label_proxy_url' => psm_get_lang('config', 'proxy_url'), + 'label_proxy_user' => psm_get_lang('config', 'proxy_user'), + 'label_proxy_password' => psm_get_lang('config', 'proxy_password'), + 'label_email_status' => psm_get_lang('config', 'email_status'), + 'label_email_from_email' => psm_get_lang('config', 'email_from_email'), + 'label_email_from_name' => psm_get_lang('config', 'email_from_name'), + 'label_email_smtp' => psm_get_lang('config', 'email_smtp'), + 'label_email_smtp_host' => psm_get_lang('config', 'email_smtp_host'), + 'label_email_smtp_port' => psm_get_lang('config', 'email_smtp_port'), + 'label_email_smtp_security' => psm_get_lang('config', 'email_smtp_security'), + 'label_email_smtp_username' => psm_get_lang('config', 'email_smtp_username'), + 'label_email_smtp_password' => psm_get_lang('config', 'email_smtp_password'), + 'label_email_smtp_noauth' => psm_get_lang('config', 'email_smtp_noauth'), + 'label_sms_status' => psm_get_lang('config', 'sms_status'), + 'label_sms_gateway' => psm_get_lang('config', 'sms_gateway'), + 'label_sms_gateway_username' => psm_get_lang('config', 'sms_gateway_username'), + 'label_sms_gateway_password' => psm_get_lang('config', 'sms_gateway_password'), + 'label_sms_from' => psm_get_lang('config', 'sms_from'), + 'label_pushover_description' => psm_get_lang('config', 'pushover_description'), + 'label_pushover_status' => psm_get_lang('config', 'pushover_status'), + 'label_pushover_clone_app' => psm_get_lang('config', 'pushover_clone_app'), + 'pushover_clone_url' => PSM_PUSHOVER_CLONE_URL, + 'label_pushover_api_token' => psm_get_lang('config', 'pushover_api_token'), + 'label_pushover_api_token_description' => sprintf( + psm_get_lang('config', 'pushover_api_token_description'), + PSM_PUSHOVER_CLONE_URL + ), + 'label_telegram_description' => psm_get_lang('config', 'telegram_description'), + 'label_telegram_status' => psm_get_lang('config', 'telegram_status'), + 'label_telegram_api_token' => psm_get_lang('config', 'telegram_api_token'), + 'label_telegram_api_token_description' => psm_get_lang('config', 'telegram_api_token_description'), + 'label_alert_type' => psm_get_lang('config', 'alert_type'), + 'label_alert_type_description' => psm_get_lang('config', 'alert_type_description'), + 'label_combine_notifications' => psm_get_lang('config', 'combine_notifications'), 'label_combine_notifications_description' => psm_get_lang('config', 'combine_notifications_description'), - 'label_log_status' => psm_get_lang('config', 'log_status'), - 'label_log_status_description' => psm_get_lang('config', 'log_status_description'), - 'label_log_email' => psm_get_lang('config', 'log_email'), - 'label_log_sms' => psm_get_lang('config', 'log_sms'), - 'label_log_pushover' => psm_get_lang('config', 'log_pushover'), - 'label_log_telegram' => psm_get_lang('config', 'log_telegram'), - 'label_alert_proxy' => psm_get_lang('config', 'alert_proxy'), - 'label_alert_proxy_url' => psm_get_lang('config', 'alert_proxy_url'), - 'label_auto_refresh' => psm_get_lang('config', 'auto_refresh'), - 'label_auto_refresh_description' => psm_get_lang('config', 'auto_refresh_description'), - 'label_seconds' => psm_get_lang('config', 'seconds'), - 'label_save' => psm_get_lang('system', 'save'), - 'label_test' => psm_get_lang('config', 'test'), - 'label_log_retention_period' => psm_get_lang('config', 'log_retention_period'), - 'label_log_retention_period_description' => psm_get_lang('config', 'log_retention_period_description'), - 'label_log_retention_days' => psm_get_lang('config', 'log_retention_days'), - 'label_days' => psm_get_lang('config', 'log_retention_days'), + 'label_log_status' => psm_get_lang('config', 'log_status'), + 'label_log_status_description' => psm_get_lang('config', 'log_status_description'), + 'label_log_email' => psm_get_lang('config', 'log_email'), + 'label_log_sms' => psm_get_lang('config', 'log_sms'), + 'label_log_pushover' => psm_get_lang('config', 'log_pushover'), + 'label_log_telegram' => psm_get_lang('config', 'log_telegram'), + 'label_alert_proxy' => psm_get_lang('config', 'alert_proxy'), + 'label_alert_proxy_url' => psm_get_lang('config', 'alert_proxy_url'), + 'label_auto_refresh' => psm_get_lang('config', 'auto_refresh'), + 'label_auto_refresh_description' => psm_get_lang('config', 'auto_refresh_description'), + 'label_seconds' => psm_get_lang('config', 'seconds'), + 'label_save' => psm_get_lang('system', 'save'), + 'label_test' => psm_get_lang('config', 'test'), + 'label_log_retention_period' => psm_get_lang('config', 'log_retention_period'), + 'label_log_retention_period_description' => psm_get_lang('config', 'log_retention_period_description'), + 'label_log_retention_days' => psm_get_lang('config', 'log_retention_days'), + 'label_days' => psm_get_lang('config', 'log_retention_days'), - ); - } + ); + } } diff --git a/src/psm/Module/ControllerInterface.php b/src/psm/Module/ControllerInterface.php index 6ebefb71..672fbe1a 100644 --- a/src/psm/Module/ControllerInterface.php +++ b/src/psm/Module/ControllerInterface.php @@ -1,4 +1,5 @@ setMinUserLevelRequired(PSM_USER_ANONYMOUS); + $this->setMinUserLevelRequired(PSM_USER_ANONYMOUS); - $this->setActions(array( - '401', - ), '401'); - } + $this->setActions(array( + '401', + ), '401'); + } - /** - * 401 error page - * - * @return string - */ - protected function execute401() { - return $this->twig->render('module/error/401.tpl.html', array( - 'label_title' => psm_get_lang('error', '401_unauthorized'), - 'label_description' => psm_get_lang('error', '401_unauthorized_description'), - )); - } + /** + * 401 error page + * + * @return string + */ + protected function execute401() + { + return $this->twig->render('module/error/401.tpl.html', array( + 'label_title' => psm_get_lang('error', '401_unauthorized'), + 'label_description' => psm_get_lang('error', '401_unauthorized_description'), + )); + } } diff --git a/src/psm/Module/Error/ErrorModule.php b/src/psm/Module/Error/ErrorModule.php index 52496e22..a9ad9f44 100644 --- a/src/psm/Module/Error/ErrorModule.php +++ b/src/psm/Module/Error/ErrorModule.php @@ -1,4 +1,5 @@ __NAMESPACE__.'\Controller\ErrorController', - ); - - } + public function getControllers() + { + return array( + 'error' => __NAMESPACE__ . '\Controller\ErrorController', + ); + } } diff --git a/src/psm/Module/Install/Controller/InstallController.php b/src/psm/Module/Install/Controller/InstallController.php index 667a2696..3a4ee208 100644 --- a/src/psm/Module/Install/Controller/InstallController.php +++ b/src/psm/Module/Install/Controller/InstallController.php @@ -1,4 +1,5 @@ setMinUserLevelRequired(PSM_USER_ANONYMOUS); - $this->setCSRFKey('install'); - $this->addMenu(false); + $this->setMinUserLevelRequired(PSM_USER_ANONYMOUS); + $this->setCSRFKey('install'); + $this->addMenu(false); - $this->path_config = PSM_PATH_SRC.'../config.php'; - $this->path_config_old = PSM_PATH_SRC.'../config.inc.php'; + $this->path_config = PSM_PATH_SRC . '../config.php'; + $this->path_config_old = PSM_PATH_SRC . '../config.inc.php'; - $this->setActions(array( - 'index', 'config', 'install' - ), 'index'); + $this->setActions(array( + 'index', 'config', 'install' + ), 'index'); - $this->twig->addGlobal('subtitle', psm_get_lang('system', 'install')); - } + $this->twig->addGlobal('subtitle', psm_get_lang('system', 'install')); + } - /** - * Say hi to our new user - */ - protected function executeIndex() { - // build prerequisites - $errors = 0; + /** + * Say hi to our new user + */ + protected function executeIndex() + { + // build prerequisites + $errors = 0; - $phpv = phpversion(); - if (version_compare($phpv, '5.5.9', '<') || (version_compare($phpv, '7.0.8', '<') && version_compare($phpv, '7.0.0', '>='))) { - $errors++; - $this->addMessage('PHP 5.5.9+ or 7.0.8+ is required to run PHP Server Monitor. You\'re using '.$phpv.'.', 'error'); - } else { - $this->addMessage('PHP version: '.$phpv, 'success'); - } - if (version_compare(PHP_RELEASE_VERSION, '7', '<')) { - $this->addMessage('PHP 5 reaches the end of life (January 1, 2019), please update to PHP 7. PHP supported versions can be found here.', 'warning'); - } - if (!function_exists('curl_init')) { - $this->addMessage('PHP is installed without the cURL module. Please install cURL.', 'warning'); - } else { - $this->addMessage('PHP cURL module found', 'success'); - } - if (!in_array('mysql', \PDO::getAvailableDrivers())) { - $errors++; - $this->addMessage('The PDO MySQL driver needs to be installed.', 'error'); - } - if (!ini_get('date.timezone')) { - $this->addMessage('You should set a timezone in your php.ini file (e.g. \'date.timezone = UTC\'). See this page for more info.', 'warning'); - } + $phpv = phpversion(); + if ( + version_compare($phpv, '5.5.9', '<') || + (version_compare($phpv, '7.0.8', '<') && version_compare($phpv, '7.0.0', '>=')) + ) { + $errors++; + $this->addMessage('PHP 5.5.9+ or 7.0.8+ is required to run PHP Server Monitor. You\'re using ' . + $phpv . '.', 'error'); + } else { + $this->addMessage('PHP version: ' . $phpv, 'success'); + } + if (version_compare(PHP_RELEASE_VERSION, '7', '<')) { + $this->addMessage( + 'PHP 5 reaches the end of life (January 1, 2019), please update to PHP 7. + PHP supported versions can be found + here.', + 'warning' + ); + } + if (!function_exists('curl_init')) { + $this->addMessage('PHP is installed without the cURL module. Please install cURL.', 'warning'); + } else { + $this->addMessage('PHP cURL module found', 'success'); + } + if (!in_array('mysql', \PDO::getAvailableDrivers())) { + $errors++; + $this->addMessage('The PDO MySQL driver needs to be installed.', 'error'); + } + if (!ini_get('date.timezone')) { + $this->addMessage( + 'You should set a timezone in your php.ini file (e.g. \'date.timezone = UTC\'). + See this page + for more info.', + 'warning' + ); + } - if ($errors > 0) { - $this->addMessage($errors.' error(s) have been encountered. Please fix them and refresh this page.', 'error'); - } + if ($errors > 0) { + $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( - 'messages' => $this->getMessages() - )); - } + return $this->twig->render('module/install/index.tpl.html', array( + 'messages' => $this->getMessages() + )); + } - /** - * Help the user create a new config file - */ - protected function executeConfig() { - $tpl_name = 'module/install/config_new.tpl.html'; - $tpl_data = array(); + /** + * Help the user create a new config file + */ + protected function executeConfig() + { + $tpl_name = 'module/install/config_new.tpl.html'; + $tpl_data = array(); - if (!defined('PSM_DB_PREFIX')) { - // first detect "old" config file (2.0) - if (file_exists($this->path_config_old)) { - // oldtimer huh - $this->addMessage('Configuration file for v2.0 found.', 'success'); - $this->addMessage( - 'The location of the config file has been changed since v2.0.
    '. - 'We will attempt to create a new config file for you.' - , 'warning'); - $values = $this->parseConfig20(); - } else { - // fresh install - $values = $_POST; - } + if (!defined('PSM_DB_PREFIX')) { + // first detect "old" config file (2.0) + if (file_exists($this->path_config_old)) { + // oldtimer huh + $this->addMessage('Configuration file for v2.0 found.', 'success'); + $this->addMessage( + 'The location of the config file has been changed since v2.0.
    ' . + 'We will attempt to create a new config file for you.', + 'warning' + ); + $values = $this->parseConfig20(); + } else { + // fresh install + $values = $_POST; + } - $config = array( - 'db_host' => 'localhost', - 'db_port' => '', - 'db_name' => '', - 'db_user' => '', - 'db_pass' => '', - 'db_prefix' => 'psm_', - 'base_url' => $this->getBaseUrl(), - ); + $config = array( + 'db_host' => 'localhost', + 'db_port' => '', + 'db_name' => '', + 'db_user' => '', + 'db_pass' => '', + 'db_prefix' => 'psm_', + 'base_url' => $this->getBaseUrl(), + ); - $changed = false; - foreach ($config as $ckey => &$cvalue) { - if (isset($values[$ckey])) { - $changed = true; - $cvalue = $values[$ckey]; - } - } - // add config to template data for prefilling the form - $tpl_data = $config; + $changed = false; + foreach ($config as $ckey => &$cvalue) { + if (isset($values[$ckey])) { + $changed = true; + $cvalue = $values[$ckey]; + } + } + // add config to template data for prefilling the form + $tpl_data = $config; - if ($changed) { - // test db connection - $this->db = new \psm\Service\Database( - $config['db_host'], - $config['db_user'], - $config['db_pass'], - $config['db_name'], - $config['db_port'] - ); + if ($changed) { + // test db connection + $this->db = new \psm\Service\Database( + $config['db_host'], + $config['db_user'], + $config['db_pass'], + $config['db_name'], + $config['db_port'] + ); - if ($this->db->status()) { - $this->addMessage('Connection to MySQL successful.', 'success'); - $config_php = $this->writeConfigFile($config); - if ($config_php === true) { - $this->addMessage('Configuration file written successfully.', 'success'); - } else { - $this->addMessage('Config file is not writable, we cannot save it for you.', 'error'); - $tpl_data['include_config_new_copy'] = true; - $tpl_data['php_config'] = $config_php; - } - } else { - $this->addMessage('Unable to connect to MySQL. Please check your information.', 'error'); - } - } - } + if ($this->db->status()) { + $this->addMessage('Connection to MySQL successful.', 'success'); + $config_php = $this->writeConfigFile($config); + if ($config_php === true) { + $this->addMessage('Configuration file written successfully.', 'success'); + } else { + $this->addMessage('Config file is not writable, we cannot save it for you.', 'error'); + $tpl_data['include_config_new_copy'] = true; + $tpl_data['php_config'] = $config_php; + } + } else { + $this->addMessage('Unable to connect to MySQL. Please check your information.', 'error'); + } + } + } - if (defined('PSM_DB_PREFIX')) { - if ($this->db->status()) { - if ($this->isUpgrade()) { - // upgrade - $version_from = $this->getPreviousVersion(); - if (version_compare($version_from, '3.0.0', '<')) { - // upgrade from before 3.0, does not have passwords yet.. create new user first - $this->addMessage('Your current version does not have an authentication system, but since v3.0 access to the monitor is restricted by user accounts. Please set up a new account to be able to login after the upgrade, and which you can use to change the passwords for your other accounts.'); - $tpl_name = 'module/install/config_new_user.tpl.html'; - } - elseif (version_compare($version_from, PSM_VERSION, '=')) { - $this->addMessage('Your installation is already at the latest version.', 'success'); - $tpl_name = 'module/install/success.tpl.html'; - } - else { - $this->addMessage('We have discovered a previous version.'); - $tpl_name = 'module/install/config_upgrade.tpl.html'; - $tpl_data['version'] = PSM_VERSION; - } - } else { - // fresh install ahead - $tpl_name = 'module/install/config_new_user.tpl.html'; + if (defined('PSM_DB_PREFIX')) { + if ($this->db->status()) { + if ($this->isUpgrade()) { + // upgrade + $version_from = $this->getPreviousVersion(); + if (version_compare($version_from, '3.0.0', '<')) { + // upgrade from before 3.0, does not have passwords yet.. create new user first + $this->addMessage( + 'Your current version does not have an authentication system, + but since v3.0 access to the monitor is restricted by user accounts. + Please set up a new account to be able to login after the upgrade, + and which you can use to change the passwords for your other accounts.' + ); + $tpl_name = 'module/install/config_new_user.tpl.html'; + } elseif (version_compare($version_from, PSM_VERSION, '=')) { + $this->addMessage('Your installation is already at the latest version.', 'success'); + $tpl_name = 'module/install/success.tpl.html'; + } else { + $this->addMessage('We have discovered a previous version.'); + $tpl_name = 'module/install/config_upgrade.tpl.html'; + $tpl_data['version'] = PSM_VERSION; + } + } else { + // fresh install ahead + $tpl_name = 'module/install/config_new_user.tpl.html'; - $tpl_data['username'] = (isset($_POST['username'])) ? $_POST['username'] : ''; - $tpl_data['email'] = (isset($_POST['email'])) ? $_POST['email'] : ''; - } - } else { - $this->addMessage('Configuration file found, but unable to connect to MySQL. Please check your information.', 'error'); - } - } - $tpl_data['messages'] = $this->getMessages(); - return $this->twig->render($tpl_name, $tpl_data); - } + $tpl_data['username'] = (isset($_POST['username'])) ? $_POST['username'] : ''; + $tpl_data['email'] = (isset($_POST['email'])) ? $_POST['email'] : ''; + } + } else { + $this->addMessage( + 'Configuration file found, but unable to connect to MySQL. Please check your information.', + 'error' + ); + } + } + $tpl_data['messages'] = $this->getMessages(); + return $this->twig->render($tpl_name, $tpl_data); + } - /** - * Execute the install and upgrade process to a newer version - */ - protected function executeInstall() { - if (!defined('PSM_DB_PREFIX') || !$this->db->status()) { - return $this->executeConfig(); - } - $add_user = false; + /** + * Execute the install and upgrade process to a newer version + */ + protected function executeInstall() + { + if (!defined('PSM_DB_PREFIX') || !$this->db->status()) { + return $this->executeConfig(); + } + $add_user = false; - // check if user submitted username + password in previous step - // this would only be the case for new installs, and install from - // before 3.0 - $new_user = array( - 'user_name' => psm_POST('username'), - 'name' => psm_POST('username'), - 'password' => psm_POST('password'), - 'password_repeat' => psm_POST('password_repeat'), - 'email' => psm_POST('email', ''), - 'mobile' => '', - 'level' => PSM_USER_ADMIN, - 'pushover_key' => '', - 'pushover_device' => '', - 'telegram_id' => '', - ); + // check if user submitted username + password in previous step + // this would only be the case for new installs, and install from + // before 3.0 + $new_user = array( + 'user_name' => psm_POST('username'), + 'name' => psm_POST('username'), + 'password' => psm_POST('password'), + 'password_repeat' => psm_POST('password_repeat'), + 'email' => psm_POST('email', ''), + 'mobile' => '', + 'level' => PSM_USER_ADMIN, + 'pushover_key' => '', + 'pushover_device' => '', + 'telegram_id' => '', + ); - $validator = $this->container->get('util.user.validator'); + $validator = $this->container->get('util.user.validator'); - $logger = array($this, 'addMessage'); - $installer = new \psm\Util\Install\Installer($this->db, $logger); + $logger = array($this, 'addMessage'); + $installer = new \psm\Util\Install\Installer($this->db, $logger); - if ($this->isUpgrade()) { - $this->addMessage('Upgrade process started.'); + if ($this->isUpgrade()) { + $this->addMessage('Upgrade process started.'); - $version_from = $this->getPreviousVersion(); - if ($version_from === false) { - $this->addMessage('Unable to locate your previous version. Please run a fresh install.', 'error'); - } else { - if (version_compare($version_from, PSM_VERSION, '=')) { - $this->addMessage('Your installation is already at the latest version.', 'success'); - } elseif (version_compare($version_from, PSM_VERSION, '>')) { - $this->addMessage('This installer does not support downgrading, sorry.', 'error'); - } else { - $this->addMessage('Upgrading from '.$version_from.' to '.PSM_VERSION); - $installer->upgrade($version_from, PSM_VERSION); + $version_from = $this->getPreviousVersion(); + if ($version_from === false) { + $this->addMessage('Unable to locate your previous version. Please run a fresh install.', 'error'); + } else { + if (version_compare($version_from, PSM_VERSION, '=')) { + $this->addMessage('Your installation is already at the latest version.', 'success'); + } elseif (version_compare($version_from, PSM_VERSION, '>')) { + $this->addMessage('This installer does not support downgrading, sorry.', 'error'); + } else { + $this->addMessage('Upgrading from ' . $version_from . ' to ' . PSM_VERSION); + $installer->upgrade($version_from, PSM_VERSION); + } + if (version_compare($version_from, '3.0.0', '<')) { + $add_user = true; + } + } + } else { + // validate the lot + try { + $validator->usernameNew($new_user['user_name']); + $validator->email($new_user['email']); + $validator->password($new_user['password'], $new_user['password_repeat']); + } catch (\InvalidArgumentException $e) { + $this->addMessage(psm_get_lang('users', 'error_' . $e->getMessage()), 'error'); + return $this->executeConfig(); + } - } - if (version_compare($version_from, '3.0.0', '<')) { - $add_user = true; - } - } - } else { - // validate the lot - try { - $validator->username_new($new_user['user_name']); - $validator->email($new_user['email']); - $validator->password($new_user['password'], $new_user['password_repeat']); - } catch (\InvalidArgumentException $e) { - $this->addMessage(psm_get_lang('users', 'error_'.$e->getMessage()), 'error'); - return $this->executeConfig(); - } + $this->addMessage('Installation process started.', 'success'); + $installer->install(); + // add user + $add_user = true; + } - $this->addMessage('Installation process started.', 'success'); - $installer->install(); - // add user - $add_user = true; - } + if ($add_user) { + unset($new_user['password_repeat']); + $user_id = $this->db->save(PSM_DB_PREFIX . 'users', $new_user); + if (intval($user_id) > 0) { + $this->getUser()->changePassword($user_id, $new_user['password']); + $this->addMessage('User account has been created successfully.', 'success'); + } else { + $this->addMessage('There was an error adding your user account.', 'error'); + } + } - if ($add_user) { - unset($new_user['password_repeat']); - $user_id = $this->db->save(PSM_DB_PREFIX.'users', $new_user); - if (intval($user_id) > 0) { - $this->getUser()->changePassword($user_id, $new_user['password']); - $this->addMessage('User account has been created successfully.', 'success'); - } else { - $this->addMessage('There was an error adding your user account.', 'error'); - } - } + return $this->twig->render('module/install/success.tpl.html', array( + 'messages' => $this->getMessages() + )); + } - return $this->twig->render('module/install/success.tpl.html', array( - 'messages' => $this->getMessages() - )); - } + /** + * Write config file with db variables + * @param array $array_config prefix,user,pass,name,host + * @return boolean|string TRUE on success, string with config otherwise + */ + protected function writeConfigFile($array_config) + { + $config = " $value) { + $line = "define('PSM_{key}', '{value}');" . PHP_EOL; + $line = str_replace( + array('{key}', '{value}'), + array(strtoupper($key), $value), + $line + ); + $config .= $line; + } + if (is_writeable($this->path_config)) { + file_put_contents($this->path_config, $config); + return true; + } else { + return $config; + } + } - foreach ($array_config as $key => $value) { - $line = "define('PSM_{key}', '{value}');".PHP_EOL; - $line = str_replace( - array('{key}', '{value}'), - array(strtoupper($key), $value), - $line - ); - $config .= $line; - } - if (is_writeable($this->path_config)) { - file_put_contents($this->path_config, $config); - return true; - } else { - return $config; - } - } + /** + * Parse the 2.0 config file for prefilling + * @return array + */ + protected function parseConfig20() + { + $config_old = file_get_contents($this->path_config_old); + $vars = array( + 'prefix' => '', + 'user' => '', + 'pass' => '', + 'name' => '', + 'host' => '', + 'port' => '' + ); + $pattern = "/define\('SM_{key}', '(.*?)'/u"; - /** - * Parse the 2.0 config file for prefilling - * @return array - */ - protected function parseConfig20() { - $config_old = file_get_contents($this->path_config_old); - $vars = array( - 'prefix' => '', - 'user' => '', - 'pass' => '', - 'name' => '', - 'host' => '', - 'port' => '' - ); - $pattern = "/define\('SM_{key}', '(.*?)'/u"; + foreach ($vars as $key => $value) { + $pattern_key = str_replace('{key}', strtoupper($key), $pattern); + preg_match($pattern_key, $config_old, $value_matches); + $vars[$key] = (isset($value_matches[1])) ? $value_matches[1] : ''; + } - foreach ($vars as $key => $value) { - $pattern_key = str_replace('{key}', strtoupper($key), $pattern); - preg_match($pattern_key, $config_old, $value_matches); - $vars[$key] = (isset($value_matches[1])) ? $value_matches[1] : ''; - } + return $vars; + } - return $vars; - } + /** + * Is it an upgrade or install? + */ + protected function isUpgrade() + { + if (!$this->db->status()) { + return false; + } + return $this->db->ifTableExists(PSM_DB_PREFIX . 'config'); + } - /** - * Is it an upgrade or install? - */ - protected function isUpgrade() { - if (!$this->db->status()) { - return false; - } - return $this->db->ifTableExists(PSM_DB_PREFIX.'config'); - } + /** + * Get the previous version from the config table + * @return boolean|string FALSE on failure, string otherwise + */ + protected function getPreviousVersion() + { + if (!$this->isUpgrade()) { + return false; + } + $version_conf = $this->db->selectRow(PSM_DB_PREFIX . 'config', array('key' => 'version'), array('value')); + if (empty($version_conf)) { + return false; + } else { + $version_from = $version_conf['value']; + if (strpos($version_from, '.') === false) { + // yeah, my bad.. previous version did not follow proper naming scheme + $version_from = rtrim(chunk_split($version_from, 1, '.'), '.'); + } + return $version_from; + } + } - /** - * Get the previous version from the config table - * @return boolean|string FALSE on failure, string otherwise - */ - protected function getPreviousVersion() { - if (!$this->isUpgrade()) { - return false; - } - $version_conf = $this->db->selectRow(PSM_DB_PREFIX.'config', array('key' => 'version'), array('value')); - if (empty($version_conf)) { - return false; - } else { - $version_from = $version_conf['value']; - if (strpos($version_from, '.') === false) { - // yeah, my bad.. previous version did not follow proper naming scheme - $version_from = rtrim(chunk_split($version_from, 1, '.'), '.'); - } - return $version_from; - } - } + /** + * Get base url of the current application + * @return string + */ + protected function getBaseUrl() + { + $sym_request = \Symfony\Component\HttpFoundation\Request::createFromGlobals(); - /** - * Get base url of the current application - * @return string - */ - protected function getBaseUrl() { - $sym_request = \Symfony\Component\HttpFoundation\Request::createFromGlobals(); - - return $sym_request->getSchemeAndHttpHost().$sym_request->getBasePath(); - } + return $sym_request->getSchemeAndHttpHost() . $sym_request->getBasePath(); + } } diff --git a/src/psm/Module/Install/InstallModule.php b/src/psm/Module/Install/InstallModule.php index cfd6c067..9bc5babc 100644 --- a/src/psm/Module/Install/InstallModule.php +++ b/src/psm/Module/Install/InstallModule.php @@ -1,4 +1,5 @@ __NAMESPACE__.'\Controller\InstallController', - ); - - } + public function getControllers() + { + return array( + 'install' => __NAMESPACE__ . '\Controller\InstallController', + ); + } } diff --git a/src/psm/Module/ModuleInterface.php b/src/psm/Module/ModuleInterface.php index a680973b..63923515 100644 --- a/src/psm/Module/ModuleInterface.php +++ b/src/psm/Module/ModuleInterface.php @@ -1,4 +1,5 @@ getUser()->getUserLevel() > PSM_USER_ADMIN) { - // restrict by user_id - $sql_join = "JOIN `".PSM_DB_PREFIX."users_servers` AS `us` ON ( + if ($this->getUser()->getUserLevel() > PSM_USER_ADMIN) { + // restrict by user_id + $sql_join = "JOIN `" . PSM_DB_PREFIX . "users_servers` AS `us` ON ( `us`.`user_id`={$this->getUser()->getUserId()} AND `us`.`server_id`=`s`.`server_id` )"; - } - if ($server_id !== null) { - $server_id = intval($server_id); - $sql_where = "WHERE `s`.`server_id`={$server_id} "; - } + } + if ($server_id !== null) { + $server_id = intval($server_id); + $sql_where = "WHERE `s`.`server_id`={$server_id} "; + } - $sql = "SELECT + $sql = "SELECT `s`.`server_id`, `s`.`ip`, `s`.`port`, @@ -91,55 +96,56 @@ abstract class AbstractServerController extends AbstractController { `s`.`last_error`, `s`.`last_error_output`, `s`.`last_output` - FROM `".PSM_DB_PREFIX."servers` AS `s` + FROM `" . PSM_DB_PREFIX . "servers` AS `s` {$sql_join} {$sql_where} ORDER BY `active` ASC, `status` DESC, `label` ASC"; - $servers = $this->db->query($sql); + $servers = $this->db->query($sql); - if ($server_id !== null && count($servers) == 1) { - $servers = $servers[0]; - } + if ($server_id !== null && count($servers) == 1) { + $servers = $servers[0]; + } - return $servers; - } + return $servers; + } - /** - * Format server data for display - * @param array $server - * @return array - */ - protected function formatServer($server) { - $server['rtime'] = round((float) $server['rtime'], 4); - $server['last_online'] = psm_timespan($server['last_online']); - $server['last_offline'] = psm_timespan($server['last_offline']); - if ($server['last_offline'] != psm_get_lang('system', 'never')) { - $server['last_offline_duration'] = is_null($server['last_offline_duration']) ? - null : "(".$server['last_offline_duration'].")"; - } - $server['last_check'] = psm_timespan($server['last_check']); + /** + * Format server data for display + * @param array $server + * @return array + */ + protected function formatServer($server) + { + $server['rtime'] = round((float) $server['rtime'], 4); + $server['last_online'] = psm_timespan($server['last_online']); + $server['last_offline'] = psm_timespan($server['last_offline']); + if ($server['last_offline'] != psm_get_lang('system', 'never')) { + $server['last_offline_duration'] = is_null($server['last_offline_duration']) ? + null : "(" . $server['last_offline_duration'] . ")"; + } + $server['last_check'] = psm_timespan($server['last_check']); - if ($server['status'] == 'on' && $server['warning_threshold_counter'] > 0) { - $server['status'] = 'warning'; - } + if ($server['status'] == 'on' && $server['warning_threshold_counter'] > 0) { + $server['status'] = 'warning'; + } - $server['error'] = htmlentities($server['error']); - $server['type'] = psm_get_lang('servers', 'type_'.$server['type']); - $server['timeout'] = ($server['timeout'] > 0) ? $server['timeout'] : PSM_CURL_TIMEOUT; + $server['error'] = htmlentities($server['error']); + $server['type'] = psm_get_lang('servers', 'type_' . $server['type']); + $server['timeout'] = ($server['timeout'] > 0) ? $server['timeout'] : PSM_CURL_TIMEOUT; - $server['last_error'] = htmlentities($server['last_error']); - $server['last_error_output'] = htmlentities($server['last_error_output']); - $server['last_output'] = htmlentities($server['last_output']); + $server['last_error'] = htmlentities($server['last_error']); + $server['last_error_output'] = htmlentities($server['last_error_output']); + $server['last_output'] = htmlentities($server['last_output']); - $url_actions = array('delete', 'edit', 'view'); - foreach ($url_actions as $action) { - $server['url_'.$action] = psm_build_url(array( - 'mod' => 'server', - 'action' => $action, - 'id' => $server['server_id'], - )); - } + $url_actions = array('delete', 'edit', 'view'); + foreach ($url_actions as $action) { + $server['url_' . $action] = psm_build_url(array( + 'mod' => 'server', + 'action' => $action, + 'id' => $server['server_id'], + )); + } - return $server; - } + return $server; + } } diff --git a/src/psm/Module/Server/Controller/LogController.php b/src/psm/Module/Server/Controller/LogController.php index 3fc68060..b84ac85d 100644 --- a/src/psm/Module/Server/Controller/LogController.php +++ b/src/psm/Module/Server/Controller/LogController.php @@ -1,4 +1,5 @@ setActions(array( - 'index', 'delete', - ), 'index'); - } + $this->setActions(array( + 'index', 'delete', + ), 'index'); + } - /** - * Prepare the template with a list of all log entries - */ - protected function executeIndex() { - $this->twig->addGlobal('subtitle', psm_get_lang('menu', 'server_log')); - $tpl_data = array( - 'label_status' => psm_get_lang('log', 'status'), - 'label_email' => psm_get_lang('log', 'email'), - 'label_sms' => psm_get_lang('log', 'sms'), - 'label_pushover' => psm_get_lang('log', 'pushover'), - 'label_telegram' => psm_get_lang('log', 'telegram'), - 'label_title' => psm_get_lang('log', 'title'), - 'label_server' => psm_get_lang('servers', 'server'), - 'label_type' => psm_get_lang('log', 'type'), - 'label_message' => psm_get_lang('system', 'message'), - 'label_date' => psm_get_lang('system', 'date'), - 'label_users' => ucfirst(psm_get_lang('menu', 'user')), - 'label_no_logs' => psm_get_lang('log', 'no_logs'), - 'tabs' => array(), - ); + /** + * Prepare the template with a list of all log entries + */ + protected function executeIndex() + { + $this->twig->addGlobal('subtitle', psm_get_lang('menu', 'server_log')); + $tpl_data = array( + 'label_status' => psm_get_lang('log', 'status'), + 'label_email' => psm_get_lang('log', 'email'), + 'label_sms' => psm_get_lang('log', 'sms'), + 'label_pushover' => psm_get_lang('log', 'pushover'), + 'label_telegram' => psm_get_lang('log', 'telegram'), + 'label_title' => psm_get_lang('log', 'title'), + 'label_server' => psm_get_lang('servers', 'server'), + 'label_type' => psm_get_lang('log', 'type'), + 'label_message' => psm_get_lang('system', 'message'), + 'label_date' => psm_get_lang('system', 'date'), + 'label_users' => ucfirst(psm_get_lang('menu', 'user')), + 'label_no_logs' => psm_get_lang('log', 'no_logs'), + 'tabs' => array(), + ); - $sidebar = new \psm\Util\Module\Sidebar($this->twig); - $this->setSidebar($sidebar); + $sidebar = new \psm\Util\Module\Sidebar($this->twig); + $this->setSidebar($sidebar); - if ($this->getUser()->getUserLevel() == PSM_USER_ADMIN) { - $modal = new \psm\Util\Module\Modal($this->twig, 'delete', \psm\Util\Module\Modal::MODAL_TYPE_DANGER); - $this->addModal($modal); - $modal->setTitle(psm_get_lang('log', 'delete_title')); - $modal->setMessage(psm_get_lang('log', 'delete_message')); - $modal->setOKButtonLabel(psm_get_lang('system', 'delete')); - - $sidebar->addButton( - 'clear_logn', - psm_get_lang('log', 'clear'), - psm_build_url(array('mod' => 'server_log', 'action' => 'delete')), - 'trash', - 'danger show-modal', - psm_get_lang('log', 'delete_title'), - 'delete' - ); - } + if ($this->getUser()->getUserLevel() == PSM_USER_ADMIN) { + $modal = new \psm\Util\Module\Modal($this->twig, 'delete', \psm\Util\Module\Modal::MODAL_TYPE_DANGER); + $this->addModal($modal); + $modal->setTitle(psm_get_lang('log', 'delete_title')); + $modal->setMessage(psm_get_lang('log', 'delete_message')); + $modal->setOKButtonLabel(psm_get_lang('system', 'delete')); + + $sidebar->addButton( + 'clear_logn', + psm_get_lang('log', 'clear'), + psm_build_url(array('mod' => 'server_log', 'action' => 'delete')), + 'trash', + 'danger show-modal', + psm_get_lang('log', 'delete_title'), + 'delete' + ); + } - $log_types = array('status', 'email', 'sms', 'pushover', 'telegram'); + $log_types = array('status', 'email', 'sms', 'pushover', 'telegram'); - foreach ($log_types as $key) { - $records = $this->getEntries($key); - $log_count = count($records); + foreach ($log_types as $key) { + $records = $this->getEntries($key); + $log_count = count($records); - $tab_data = array( - 'id' => $key, - 'label' => psm_get_lang('log', $key), - 'has_users' => ($key == 'status') ? false : true, - 'no_logs' => ($log_count == 0) ? true : false, - 'tab_active' => ($key == 'status') ? 'active' : '', - ); + $tab_data = array( + 'id' => $key, + 'label' => psm_get_lang('log', $key), + 'has_users' => ($key == 'status') ? false : true, + 'no_logs' => ($log_count == 0) ? true : false, + 'tab_active' => ($key == 'status') ? 'active' : '', + ); - for ($x = 0; $x < $log_count; $x++) { - $record = &$records[$x]; - $record['users'] = ''; - if($key == 'status'){ - $record['server'] = $record['label']; - $record['type_icon'] = ($record['server_type'] == 'website') ? 'globe-americas' : 'cogs'; - $record['type_title'] = psm_get_lang('servers', 'type_'.$record['server_type']); - $ip = '('.$record['ip']; - if (!empty($record['port']) && (($record['server_type'] != 'website') || ($record['port'] != 80))) { - $ip .= ':'.$record['port']; - } - $ip .= ')'; - $record['ip'] = $ip; - } - $record['datetime_format'] = psm_date($record['datetime']); + for ($x = 0; $x < $log_count; $x++) { + $record = &$records[$x]; + $record['users'] = ''; + if ($key == 'status') { + $record['server'] = $record['label']; + $record['type_icon'] = ($record['server_type'] == 'website') ? 'globe-americas' : 'cogs'; + $record['type_title'] = psm_get_lang('servers', 'type_' . $record['server_type']); + $ip = '(' . $record['ip']; + if (!empty($record['port']) && (($record['server_type'] != 'website') || ($record['port'] != 80))) { + $ip .= ':' . $record['port']; + } + $ip .= ')'; + $record['ip'] = $ip; + } + $record['datetime_format'] = psm_date($record['datetime']); - // fix up user list - $users = $this->getLogUsers($record['log_id']); - if (!empty($users)) { - $names = array(); - foreach ($users as $user) { - $names[] = $user['name']; - } - $record['users'] = implode('
    ', $names); - $record['user_list'] = implode(' • ', $names); - } - } - $tab_data['entries'] = $records; - $tpl_data['tabs'][] = $tab_data; - } - return $this->twig->render('module/server/log.tpl.html', $tpl_data); - } + // fix up user list + $users = $this->getLogUsers($record['log_id']); + if (!empty($users)) { + $names = array(); + foreach ($users as $user) { + $names[] = $user['name']; + } + $record['users'] = implode('
    ', $names); + $record['user_list'] = implode(' • ', $names); + } + } + $tab_data['entries'] = $records; + $tpl_data['tabs'][] = $tab_data; + } + return $this->twig->render('module/server/log.tpl.html', $tpl_data); + } - protected function executeDelete() { - /** - * Empty table log and log_users. - * Only when user is admin. - */ - if ($this->getUser()->getUserLevel() == PSM_USER_ADMIN) { - $archiver = new \psm\Util\Server\Archiver\LogsArchiver($this->db); - $archiver->cleanupall(); - } - return $this->runAction('index'); - } + protected function executeDelete() + { + /** + * Empty table log and log_users. + * Only when user is admin. + */ + if ($this->getUser()->getUserLevel() == PSM_USER_ADMIN) { + $archiver = new \psm\Util\Server\Archiver\LogsArchiver($this->db); + $archiver->cleanupall(); + } + return $this->runAction('index'); + } - /** - * Get all the log entries for a specific $type - * - * @param string $type status/email/sms - * @return \PDOStatement array - */ - public function getEntries($type) { - $sql_join = ''; - if ($this->getUser()->getUserLevel() > PSM_USER_ADMIN) { - // restrict by user_id - $sql_join = "JOIN `".PSM_DB_PREFIX."users_servers` AS `us` ON ( + /** + * Get all the log entries for a specific $type + * + * @param string $type status/email/sms + * @return \PDOStatement array + */ + public function getEntries($type) + { + $sql_join = ''; + if ($this->getUser()->getUserLevel() > PSM_USER_ADMIN) { + // restrict by user_id + $sql_join = "JOIN `" . PSM_DB_PREFIX . "users_servers` AS `us` ON ( `us`.`user_id`={$this->getUser()->getUserId()} AND `us`.`server_id`=`servers`.`server_id` )"; - } - $entries = $this->db->query( - 'SELECT '. - '`servers`.`label`, '. - '`servers`.`ip`, '. - '`servers`.`port`, '. - '`servers`.`type` AS server_type, '. - '`log`.`log_id`, '. - '`log`.`type`, '. - '`log`.`message`, '. - '`log`.`datetime` '. - 'FROM `'.PSM_DB_PREFIX.'log` AS `log` '. - 'JOIN `'.PSM_DB_PREFIX.'servers` AS `servers` ON (`servers`.`server_id`=`log`.`server_id`) '. - $sql_join. - 'WHERE `log`.`type`=\''.$type.'\' '. - 'ORDER BY `datetime` DESC '. - 'LIMIT 0,20' - ); - return $entries; - } + } + $entries = $this->db->query( + 'SELECT ' . + '`servers`.`label`, ' . + '`servers`.`ip`, ' . + '`servers`.`port`, ' . + '`servers`.`type` AS server_type, ' . + '`log`.`log_id`, ' . + '`log`.`type`, ' . + '`log`.`message`, ' . + '`log`.`datetime` ' . + 'FROM `' . PSM_DB_PREFIX . 'log` AS `log` ' . + 'JOIN `' . PSM_DB_PREFIX . 'servers` AS `servers` ON (`servers`.`server_id`=`log`.`server_id`) ' . + $sql_join . + 'WHERE `log`.`type`=\'' . $type . '\' ' . + 'ORDER BY `datetime` DESC ' . + 'LIMIT 0,20' + ); + return $entries; + } - /** - * Get all the user entries for a specific $log_id - * - * @param $log_id - * @return \PDOStatement array - */ - protected function getLogUsers($log_id) { - return $this->db->query( - "SELECT + /** + * Get all the user entries for a specific $log_id + * + * @param $log_id + * @return \PDOStatement array + */ + protected function getLogUsers($log_id) + { + return $this->db->query( + "SELECT u.`user_id`, u.`name` - FROM `".PSM_DB_PREFIX."log_users` AS lu - LEFT JOIN `".PSM_DB_PREFIX."users` AS u ON lu.`user_id` = u.`user_id` - WHERE lu.`log_id` = ".(int) $log_id." + FROM `" . PSM_DB_PREFIX . "log_users` AS lu + LEFT JOIN `" . PSM_DB_PREFIX . "users` AS u ON lu.`user_id` = u.`user_id` + WHERE lu.`log_id` = " . (int) $log_id . " ORDER BY u.`name` ASC" - ); - } + ); + } } diff --git a/src/psm/Module/Server/Controller/ServerController.php b/src/psm/Module/Server/Controller/ServerController.php index f01c92a3..097329fd 100644 --- a/src/psm/Module/Server/Controller/ServerController.php +++ b/src/psm/Module/Server/Controller/ServerController.php @@ -1,4 +1,5 @@ server_id = isset($_GET['id']) ? intval($_GET['id']) : 0; + $this->server_id = isset($_GET['id']) ? intval($_GET['id']) : 0; - $this->setCSRFKey('server'); - $this->setActions(array( - 'index', 'edit', 'save', 'delete', 'view', - ), 'index'); + $this->setCSRFKey('server'); + $this->setActions(array( + 'index', 'edit', 'save', 'delete', 'view', + ), 'index'); - // make sure only admins are allowed to edit/delete servers: - $this->setMinUserLevelRequiredForAction(PSM_USER_ADMIN, array( - 'delete', 'edit', 'save' - )); - $this->twig->addGlobal('subtitle', psm_get_lang('menu', 'server')); - } + // make sure only admins are allowed to edit/delete servers: + $this->setMinUserLevelRequiredForAction(PSM_USER_ADMIN, array( + 'delete', 'edit', 'save' + )); + $this->twig->addGlobal('subtitle', psm_get_lang('menu', 'server')); + } - /** - * Prepare the template to show a list of all servers - */ - protected function executeIndex() { - $tpl_data = $this->getLabels(); - $tpl_data['user_level'] = $this->getUser()->getUserLevel(); - $sidebar = new \psm\Util\Module\Sidebar($this->twig); - $this->setSidebar($sidebar); + /** + * Prepare the template to show a list of all servers + */ + protected function executeIndex() + { + $tpl_data = $this->getLabels(); + $tpl_data['user_level'] = $this->getUser()->getUserLevel(); + $sidebar = new \psm\Util\Module\Sidebar($this->twig); + $this->setSidebar($sidebar); - // check if user is admin, in that case we add the buttons - if ($this->getUser()->getUserLevel() == PSM_USER_ADMIN) { - $modal = new \psm\Util\Module\Modal($this->twig, 'delete', \psm\Util\Module\Modal::MODAL_TYPE_DANGER); - $this->addModal($modal); - $modal->setTitle(psm_get_lang('servers', 'delete_title')); - $modal->setMessage(psm_get_lang('servers', 'delete_message')); - $modal->setOKButtonLabel(psm_get_lang('system', 'delete')); + // check if user is admin, in that case we add the buttons + if ($this->getUser()->getUserLevel() == PSM_USER_ADMIN) { + $modal = new \psm\Util\Module\Modal($this->twig, 'delete', \psm\Util\Module\Modal::MODAL_TYPE_DANGER); + $this->addModal($modal); + $modal->setTitle(psm_get_lang('servers', 'delete_title')); + $modal->setMessage(psm_get_lang('servers', 'delete_message')); + $modal->setOKButtonLabel(psm_get_lang('system', 'delete')); - $sidebar->addButton( - 'add_new', - psm_get_lang('system', 'add_new'), - psm_build_url(array('mod' => 'server', 'action' => 'edit')), - 'plus', - 'success', - psm_get_lang('system', 'add_new') - ); - } + $sidebar->addButton( + 'add_new', + psm_get_lang('system', 'add_new'), + psm_build_url(array('mod' => 'server', 'action' => 'edit')), + 'plus', + 'success', + psm_get_lang('system', 'add_new') + ); + } - $sidebar->addButton( - 'update', - psm_get_lang('menu', 'server_update'), - psm_build_url(array('mod' => 'server_update')), - 'sync-alt', - 'primary', - psm_get_lang('menu', 'server_update') - ); + $sidebar->addButton( + 'update', + psm_get_lang('menu', 'server_update'), + psm_build_url(array('mod' => 'server_update')), + 'sync-alt', + 'primary', + psm_get_lang('menu', 'server_update') + ); - $icons = array( - 'email' => 'icon-envelope', - 'sms' => 'icon-mobile', - 'pushover' => 'icon-pushover', - 'telegram' => 'icon-telegram', - ); + $icons = array( + 'email' => 'icon-envelope', + 'sms' => 'icon-mobile', + 'pushover' => 'icon-pushover', + 'telegram' => 'icon-telegram', + ); - $servers = $this->getServers(); - $server_count = count($servers); + $servers = $this->getServers(); + $server_count = count($servers); - for ($x = 0; $x < $server_count; $x++) { - if ($servers[$x]['type'] == 'website') { - // add link to label - $ip = $servers[$x]['ip']; - $servers[$x]['ip'] = ''.$ip.''; - } - if (($servers[$x]['active'] == 'yes')) { - $servers[$x]['active_title'] = psm_get_lang('servers', 'monitoring'); - } else { - $servers[$x]['active_title'] = psm_get_lang('servers', 'no_monitoring'); - } + for ($x = 0; $x < $server_count; $x++) { + if ($servers[$x]['type'] == 'website') { + // add link to label + $ip = $servers[$x]['ip']; + $servers[$x]['ip'] = '' . $ip . ''; + } + if (($servers[$x]['active'] == 'yes')) { + $servers[$x]['active_title'] = psm_get_lang('servers', 'monitoring'); + } else { + $servers[$x]['active_title'] = psm_get_lang('servers', 'no_monitoring'); + } - $servers[$x] = $this->formatServer($servers[$x]); - } - $tpl_data['servers'] = $servers; - return $this->twig->render('module/server/server/list.tpl.html', $tpl_data); - } + $servers[$x] = $this->formatServer($servers[$x]); + } + $tpl_data['servers'] = $servers; + return $this->twig->render('module/server/server/list.tpl.html', $tpl_data); + } - /** - * Prepare the template to show the update screen for a single server - */ - protected function executeEdit() { - $back_to = isset($_GET['back_to']) ? $_GET['back_to'] : ''; + /** + * Prepare the template to show the update screen for a single server + */ + protected function executeEdit() + { + $back_to = isset($_GET['back_to']) ? $_GET['back_to'] : ''; - $tpl_data = $this->getLabels(); - $tpl_data['edit_server_id'] = $this->server_id; - $tpl_data['url_save'] = psm_build_url(array( - 'mod' => 'server', - 'action' => 'save', - 'id' => $this->server_id, - 'back_to' => $back_to, - )); + $tpl_data = $this->getLabels(); + $tpl_data['edit_server_id'] = $this->server_id; + $tpl_data['url_save'] = psm_build_url(array( + 'mod' => 'server', + 'action' => 'save', + 'id' => $this->server_id, + 'back_to' => $back_to, + )); - // depending on where the user came from, add the go back url: - if ($back_to == 'view' && $this->server_id > 0) { - $tpl_data['url_go_back'] = psm_build_url(array('mod' => 'server', 'action' => 'view', 'id' => $this->server_id)); - } else { - $tpl_data['url_go_back'] = psm_build_url(array('mod' => 'server')); - } + // depending on where the user came from, add the go back url: + if ($back_to == 'view' && $this->server_id > 0) { + $tpl_data['url_go_back'] = psm_build_url( + array('mod' => 'server', 'action' => 'view', 'id' => $this->server_id) + ); + } else { + $tpl_data['url_go_back'] = psm_build_url(array('mod' => 'server')); + } - $tpl_data['users'] = $this->db->select(PSM_DB_PREFIX.'users', null, array('user_id', 'name'), '', 'name'); + $tpl_data['users'] = $this->db->select(PSM_DB_PREFIX . 'users', null, array('user_id', 'name'), '', 'name'); - switch ($this->server_id) { - case 0: - // insert mode - $tpl_data['titlemode'] = psm_get_lang('system', 'insert'); - $tpl_data['edit_value_warning_threshold'] = '1'; + switch ($this->server_id) { + case 0: + // insert mode + $tpl_data['titlemode'] = psm_get_lang('system', 'insert'); + $tpl_data['edit_value_warning_threshold'] = '1'; - $edit_server = $_POST; - break; - default: - // edit mode - // get server entry - $edit_server = $this->getServers($this->server_id); - if (empty($edit_server)) { - $this->addMessage(psm_get_lang('servers', 'error_server_no_match'), 'error'); - return $this->runAction('index'); - } - $tpl_data['titlemode'] = psm_get_lang('system', 'edit').' '.$edit_server['label']; + $edit_server = $_POST; + break; + default: + // edit mode + // get server entry + $edit_server = $this->getServers($this->server_id); + if (empty($edit_server)) { + $this->addMessage(psm_get_lang('servers', 'error_server_no_match'), 'error'); + return $this->runAction('index'); + } + $tpl_data['titlemode'] = psm_get_lang('system', 'edit') . ' ' . $edit_server['label']; - $user_idc_selected = $this->getServerUsers($this->server_id); - foreach ($tpl_data['users'] as &$user) { - $user['id'] = $user['user_id']; - unset($user['user_id']); - $user['label'] = $user['name']; - unset($user['name']); - if (in_array($user['id'], $user_idc_selected)) { - $user['edit_selected'] = 'selected="selected"'; - } - } + $user_idc_selected = $this->getServerUsers($this->server_id); + foreach ($tpl_data['users'] as &$user) { + $user['id'] = $user['user_id']; + unset($user['user_id']); + $user['label'] = $user['name']; + unset($user['name']); + if (in_array($user['id'], $user_idc_selected)) { + $user['edit_selected'] = 'selected="selected"'; + } + } - break; - } + break; + } - if (!empty($edit_server)) { - // attempt to prefill previously posted fields - foreach ($edit_server as $key => $value) { - $edit_server[$key] = psm_POST($key, $value); - } + if (!empty($edit_server)) { + // attempt to prefill previously posted fields + foreach ($edit_server as $key => $value) { + $edit_server[$key] = psm_POST($key, $value); + } - $tpl_data = array_merge($tpl_data, array( - 'edit_value_label' => $edit_server['label'], - 'edit_value_ip' => $edit_server['ip'], - 'edit_value_port' => $edit_server['port'], - 'edit_value_request_method' => $edit_server['request_method'], - 'edit_value_post_field' => $edit_server['post_field'], - 'edit_value_timeout' => $edit_server['timeout'], - 'edit_value_pattern' => $edit_server['pattern'], - 'edit_pattern_selected_'.$edit_server['pattern_online'] => 'selected="selected"', - 'edit_redirect_check_selected_'.$edit_server['redirect_check'] => 'selected="selected"', - 'edit_value_allow_http_status' => $edit_server['allow_http_status'], - 'edit_value_header_name' => $edit_server['header_name'], - 'edit_value_header_value' => $edit_server['header_value'], - 'edit_value_warning_threshold' => $edit_server['warning_threshold'], - 'edit_value_website_username' => $edit_server['website_username'], - 'edit_value_website_password' => empty($edit_server['website_password']) ? '' : sha1($edit_server['website_password']), - 'edit_type_selected_'.$edit_server['type'] => 'selected="selected"', - 'edit_active_selected' => $edit_server['active'], - 'edit_email_selected' => $edit_server['email'], - 'edit_sms_selected' => $edit_server['sms'], - 'edit_pushover_selected' => $edit_server['pushover'], - 'edit_telegram_selected' => $edit_server['telegram'], - )); - } + $tpl_data = array_merge($tpl_data, array( + 'edit_value_label' => $edit_server['label'], + 'edit_value_ip' => $edit_server['ip'], + 'edit_value_port' => $edit_server['port'], + 'edit_value_request_method' => $edit_server['request_method'], + 'edit_value_post_field' => $edit_server['post_field'], + 'edit_value_timeout' => $edit_server['timeout'], + 'edit_value_pattern' => $edit_server['pattern'], + 'edit_pattern_selected_' . $edit_server['pattern_online'] => 'selected="selected"', + 'edit_redirect_check_selected_' . $edit_server['redirect_check'] => 'selected="selected"', + 'edit_value_allow_http_status' => $edit_server['allow_http_status'], + 'edit_value_header_name' => $edit_server['header_name'], + 'edit_value_header_value' => $edit_server['header_value'], + 'edit_value_warning_threshold' => $edit_server['warning_threshold'], + 'edit_value_website_username' => $edit_server['website_username'], + 'edit_value_website_password' => empty($edit_server['website_password']) ? '' : + sha1($edit_server['website_password']), + 'edit_type_selected_' . $edit_server['type'] => 'selected="selected"', + 'edit_active_selected' => $edit_server['active'], + 'edit_email_selected' => $edit_server['email'], + 'edit_sms_selected' => $edit_server['sms'], + 'edit_pushover_selected' => $edit_server['pushover'], + 'edit_telegram_selected' => $edit_server['telegram'], + )); + } - $notifications = array('email', 'sms', 'pushover', 'telegram'); - foreach ($notifications as $notification) { - if (psm_get_conf($notification.'_status') == 0) { - $tpl_data['warning_'.$notification] = true; - $tpl_data['label_warning_'.$notification] = psm_get_lang( - 'servers', 'warning_notifications_disabled_'.$notification - ); - } else { - $tpl_data['warning_'.$notification] = false; - } - } + $notifications = array('email', 'sms', 'pushover', 'telegram'); + foreach ($notifications as $notification) { + if (psm_get_conf($notification . '_status') == 0) { + $tpl_data['warning_' . $notification] = true; + $tpl_data['label_warning_' . $notification] = psm_get_lang( + 'servers', + 'warning_notifications_disabled_' . $notification + ); + } else { + $tpl_data['warning_' . $notification] = false; + } + } - return $this->twig->render('module/server/server/update.tpl.html', $tpl_data); - } + return $this->twig->render('module/server/server/update.tpl.html', $tpl_data); + } - /** - * Executes the saving of one of the servers - */ - protected function executeSave() { - if (empty($_POST)) { - // dont process anything if no data has been posted - return $this->executeIndex(); - } + /** + * Executes the saving of one of the servers + */ + protected function executeSave() + { + if (empty($_POST)) { + // dont process anything if no data has been posted + return $this->executeIndex(); + } - // We need the server id to encrypt the password. Encryption will be done after the server is added - $encrypted_password = ''; - - if (!empty($_POST['website_password'])) { - $new_password = psm_POST('website_password'); + // We need the server id to encrypt the password. Encryption will be done after the server is added + $encrypted_password = ''; + + if (!empty($_POST['website_password'])) { + $new_password = psm_POST('website_password'); - if ($this->server_id > 0) { - $edit_server = $this->getServers($this->server_id); - $hash = sha1($edit_server['website_password']); + if ($this->server_id > 0) { + $edit_server = $this->getServers($this->server_id); + $hash = sha1($edit_server['website_password']); - if ($new_password == $hash) { - $encrypted_password = $edit_server['website_password']; - } else { - $encrypted_password = psm_password_encrypt(strval($this->server_id).psm_get_conf('password_encrypt_key'), $new_password); - } - } - } + if ($new_password == $hash) { + $encrypted_password = $edit_server['website_password']; + } else { + $encrypted_password = psm_password_encrypt(strval($this->server_id) . + psm_get_conf('password_encrypt_key'), $new_password); + } + } + } - $clean = array( - 'label' => trim(strip_tags(psm_POST('label', ''))), - 'ip' => trim(strip_tags(psm_POST('ip', ''))), - 'timeout' => (isset($_POST['timeout']) && intval($_POST['timeout']) > 0) ? intval($_POST['timeout']) : 10, - 'website_username' => psm_POST('website_username'), - 'website_password' => $encrypted_password, - 'port' => intval(psm_POST('port', 0)), - 'request_method' => empty(psm_POST('request_method')) ? null : psm_POST('request_method'), - 'post_field' => empty(psm_POST('post_field')) ? null : psm_POST('post_field'), - 'type' => psm_POST('type', ''), - 'pattern' => psm_POST('pattern', ''), - 'pattern_online' => in_array($_POST['pattern_online'], array('yes', 'no')) ? $_POST['pattern_online'] : 'yes', - 'redirect_check' => in_array($_POST['redirect_check'], array('ok', 'bad')) ? $_POST['redirect_check'] : 'bad', - 'allow_http_status' => psm_POST('allow_http_status', ''), - 'header_name' => psm_POST('header_name', ''), - 'header_value' => psm_POST('header_value', ''), - 'warning_threshold' => intval(psm_POST('warning_threshold', 0)), - 'active' => in_array($_POST['active'], array('yes', 'no')) ? $_POST['active'] : 'no', - 'email' => in_array($_POST['email'], array('yes', 'no')) ? $_POST['email'] : 'no', - 'sms' => in_array($_POST['sms'], array('yes', 'no')) ? $_POST['sms'] : 'no', - 'pushover' => in_array($_POST['pushover'], array('yes', 'no')) ? $_POST['pushover'] : 'no', - 'telegram' => in_array($_POST['telegram'], array('yes', 'no')) ? $_POST['telegram'] : 'no', - ); - // make sure websites start with http:// - if ($clean['type'] == 'website' && substr($clean['ip'], 0, 4) != 'http' && substr($clean['ip'], 0, 3) != 'rdp') { - $clean['ip'] = 'http://'.$clean['ip']; - } + $clean = array( + 'label' => trim(strip_tags(psm_POST('label', ''))), + 'ip' => trim(strip_tags(psm_POST('ip', ''))), + 'timeout' => (isset($_POST['timeout']) && intval($_POST['timeout']) > 0) ? intval($_POST['timeout']) : 10, + 'website_username' => psm_POST('website_username'), + 'website_password' => $encrypted_password, + 'port' => intval(psm_POST('port', 0)), + 'request_method' => empty(psm_POST('request_method')) ? null : psm_POST('request_method'), + 'post_field' => empty(psm_POST('post_field')) ? null : psm_POST('post_field'), + 'type' => psm_POST('type', ''), + 'pattern' => psm_POST('pattern', ''), + 'pattern_online' => in_array($_POST['pattern_online'], array('yes', 'no')) ? + $_POST['pattern_online'] : 'yes', + 'redirect_check' => in_array($_POST['redirect_check'], array('ok', 'bad')) ? + $_POST['redirect_check'] : 'bad', + 'allow_http_status' => psm_POST('allow_http_status', ''), + 'header_name' => psm_POST('header_name', ''), + 'header_value' => psm_POST('header_value', ''), + 'warning_threshold' => intval(psm_POST('warning_threshold', 0)), + 'active' => in_array($_POST['active'], array('yes', 'no')) ? $_POST['active'] : 'no', + 'email' => in_array($_POST['email'], array('yes', 'no')) ? $_POST['email'] : 'no', + 'sms' => in_array($_POST['sms'], array('yes', 'no')) ? $_POST['sms'] : 'no', + 'pushover' => in_array($_POST['pushover'], array('yes', 'no')) ? $_POST['pushover'] : 'no', + 'telegram' => in_array($_POST['telegram'], array('yes', 'no')) ? $_POST['telegram'] : 'no', + ); + // make sure websites start with http:// + if ( + $clean['type'] == 'website' && + substr($clean['ip'], 0, 4) != 'http' && + substr($clean['ip'], 0, 3) != 'rdp' + ) { + $clean['ip'] = 'http://' . $clean['ip']; + } - if($clean['request_method'] == null) { + if ($clean['request_method'] == null) { $clean['post_field'] = null; } - // validate the lot - $server_validator = new \psm\Util\Server\ServerValidator($this->db); + // validate the lot + $server_validator = new \psm\Util\Server\ServerValidator($this->db); - // format port from http, https or rdp url - if ($clean['type'] == 'website') { - $tmp = parse_url($clean["ip"]); - if (isset($tmp["port"])) { - $clean["port"] = $tmp["port"]; - } elseif ($tmp["scheme"] === "https") { - $clean["port"] = 443; - } elseif ($tmp["scheme"] === "http") { - $clean["port"] = 80; - } elseif ($tmp["scheme"] === "rdp") { - $clean["port"] = 3389; - } - } + // format port from http, https or rdp url + if ($clean['type'] == 'website') { + $tmp = parse_url($clean["ip"]); + if (isset($tmp["port"])) { + $clean["port"] = $tmp["port"]; + } elseif ($tmp["scheme"] === "https") { + $clean["port"] = 443; + } elseif ($tmp["scheme"] === "http") { + $clean["port"] = 80; + } elseif ($tmp["scheme"] === "rdp") { + $clean["port"] = 3389; + } + } - try { - if ($this->server_id > 0) { - $server_validator->serverId($this->server_id); - } - $server_validator->label($clean['label']); - $server_validator->type($clean['type']); - $server_validator->ip($clean['ip'], $clean['type']); - $server_validator->warningThreshold($clean['warning_threshold']); - } catch (\InvalidArgumentException $ex) { - $this->addMessage(psm_get_lang('servers', 'error_'.$ex->getMessage()), 'error'); - return $this->executeEdit(); - } + try { + if ($this->server_id > 0) { + $server_validator->serverId($this->server_id); + } + $server_validator->label($clean['label']); + $server_validator->type($clean['type']); + $server_validator->ip($clean['ip'], $clean['type']); + $server_validator->warningThreshold($clean['warning_threshold']); + } catch (\InvalidArgumentException $ex) { + $this->addMessage(psm_get_lang('servers', 'error_' . $ex->getMessage()), 'error'); + return $this->executeEdit(); + } - // check for edit or add - if ($this->server_id > 0) { - // edit - $this->db->save( - PSM_DB_PREFIX.'servers', - $clean, - array('server_id' => $this->server_id) - ); - $this->addMessage(psm_get_lang('servers', 'updated'), 'success'); - } else { - // add - $clean['status'] = 'on'; - $this->server_id = $this->db->save(PSM_DB_PREFIX.'servers', $clean); + // check for edit or add + if ($this->server_id > 0) { + // edit + $this->db->save( + PSM_DB_PREFIX . 'servers', + $clean, + array('server_id' => $this->server_id) + ); + $this->addMessage(psm_get_lang('servers', 'updated'), 'success'); + } else { + // add + $clean['status'] = 'on'; + $this->server_id = $this->db->save(PSM_DB_PREFIX . 'servers', $clean); - // server has been added, re-encrypt - if (!empty($_POST['website_password'])) { - $cleanWebsitePassword = array( - 'website_password' => psm_password_encrypt( - strval($this->server_id).psm_get_conf('password_encrypt_key'), - psm_POST('website_password') - ), - ); + // server has been added, re-encrypt + if (!empty($_POST['website_password'])) { + $cleanWebsitePassword = array( + 'website_password' => psm_password_encrypt( + strval($this->server_id) . psm_get_conf('password_encrypt_key'), + psm_POST('website_password') + ), + ); - $this->db->save( - PSM_DB_PREFIX.'servers', - $cleanWebsitePassword, - array('server_id' => $this->server_id) - ); - } + $this->db->save( + PSM_DB_PREFIX . 'servers', + $cleanWebsitePassword, + array('server_id' => $this->server_id) + ); + } - $this->addMessage(psm_get_lang('servers', 'inserted'), 'success'); - } + $this->addMessage(psm_get_lang('servers', 'inserted'), 'success'); + } - // update users - $user_idc = psm_POST('user_id', array()); - $user_idc_save = array(); + // update users + $user_idc = psm_POST('user_id', array()); + $user_idc_save = array(); - foreach ($user_idc as $user_id) { - $user_idc_save[] = array( - 'user_id' => intval($user_id), - 'server_id' => intval($this->server_id), - ); - } - $this->db->delete(PSM_DB_PREFIX.'users_servers', array('server_id' => $this->server_id)); - if (!empty($user_idc_save)) { - // add all new users - $this->db->insertMultiple(PSM_DB_PREFIX.'users_servers', $user_idc_save); - } + foreach ($user_idc as $user_id) { + $user_idc_save[] = array( + 'user_id' => intval($user_id), + 'server_id' => intval($this->server_id), + ); + } + $this->db->delete(PSM_DB_PREFIX . 'users_servers', array('server_id' => $this->server_id)); + if (!empty($user_idc_save)) { + // add all new users + $this->db->insertMultiple(PSM_DB_PREFIX . 'users_servers', $user_idc_save); + } - $back_to = isset($_GET['back_to']) ? $_GET['back_to'] : 'index'; - if ($back_to == 'view') { - return $this->runAction('view'); - } else { - return $this->runAction('index'); - } - } + $back_to = isset($_GET['back_to']) ? $_GET['back_to'] : 'index'; + if ($back_to == 'view') { + return $this->runAction('view'); + } else { + return $this->runAction('index'); + } + } - /** - * Executes the deletion of one of the servers - */ - protected function executeDelete() { - if (isset($_GET['id'])) { - $id = intval($_GET['id']); - // do delete - $res = $this->db->delete(PSM_DB_PREFIX.'servers', array('server_id' => $id)); + /** + * Executes the deletion of one of the servers + */ + protected function executeDelete() + { + if (isset($_GET['id'])) { + $id = intval($_GET['id']); + // do delete + $res = $this->db->delete(PSM_DB_PREFIX . 'servers', array('server_id' => $id)); - if ($res === 1) { - $this->db->delete(PSM_DB_PREFIX.'log', array('server_id' => $id)); - $this->db->delete(PSM_DB_PREFIX.'users_servers', array('server_id' => $id)); - $this->db->delete(PSM_DB_PREFIX.'servers_uptime', array('server_id' => $id)); - $this->db->delete(PSM_DB_PREFIX.'servers_history', array('server_id' => $id)); - } - $this->addMessage(psm_get_lang('servers', 'deleted'), 'success'); - } - return $this->runAction('index'); - } + if ($res === 1) { + $this->db->delete(PSM_DB_PREFIX . 'log', array('server_id' => $id)); + $this->db->delete(PSM_DB_PREFIX . 'users_servers', array('server_id' => $id)); + $this->db->delete(PSM_DB_PREFIX . 'servers_uptime', array('server_id' => $id)); + $this->db->delete(PSM_DB_PREFIX . 'servers_history', array('server_id' => $id)); + } + $this->addMessage(psm_get_lang('servers', 'deleted'), 'success'); + } + return $this->runAction('index'); + } - /** - * Prepare the view template - */ - protected function executeView() { - if ($this->server_id == 0) { - return $this->runAction('index'); - } - $server = $this->getServers($this->server_id); + /** + * Prepare the view template + */ + protected function executeView() + { + if ($this->server_id == 0) { + return $this->runAction('index'); + } + $server = $this->getServers($this->server_id); - if (empty($server)) { - return $this->runAction('index'); - } + if (empty($server)) { + return $this->runAction('index'); + } - $tpl_data = $this->getLabels(); - $tpl_data = array_merge($tpl_data, $this->formatServer($server)); + $tpl_data = $this->getLabels(); + $tpl_data = array_merge($tpl_data, $this->formatServer($server)); - // create history HTML - $history = new \psm\Util\Server\HistoryGraph($this->db, $this->twig); - $tpl_data['html_history'] = $history->createHTML($this->server_id); + // create history HTML + $history = new \psm\Util\Server\HistoryGraph($this->db, $this->twig); + $tpl_data['html_history'] = $history->createHTML($this->server_id); - $sidebar = new \psm\Util\Module\Sidebar($this->twig); - $this->setSidebar($sidebar); + $sidebar = new \psm\Util\Module\Sidebar($this->twig); + $this->setSidebar($sidebar); - // check which module the user came from, and add a link accordingly - $back_to = isset($_GET['back_to']) && ($_GET['back_to'] == 'server_status' || $_GET['back_to'] == 'user') ? $_GET['back_to'] : 'server'; - $sidebar->addButton( - 'go_back', - psm_get_lang('system', 'go_back'), - psm_build_url(array('mod' => $back_to)), - 'angle-left', - 'link', - psm_get_lang('system', 'go_back') - ); + // check which module the user came from, and add a link accordingly + $back_to = isset($_GET['back_to']) && ($_GET['back_to'] == 'server_status' || $_GET['back_to'] == 'user') ? + $_GET['back_to'] : 'server'; + $sidebar->addButton( + 'go_back', + psm_get_lang('system', 'go_back'), + psm_build_url(array('mod' => $back_to)), + 'angle-left', + 'link', + psm_get_lang('system', 'go_back') + ); - // add edit/delete buttons for admins - if ($this->getUser()->getUserLevel() == PSM_USER_ADMIN) { - $tpl_data['has_admin_actions'] = true; - $tpl_data['url_edit'] = psm_build_url(array('mod' => 'server', 'action' => 'edit', 'id' => $this->server_id, 'back_to' => 'view')); + // add edit/delete buttons for admins + if ($this->getUser()->getUserLevel() == PSM_USER_ADMIN) { + $tpl_data['has_admin_actions'] = true; + $tpl_data['url_edit'] = psm_build_url( + array('mod' => 'server', 'action' => 'edit', 'id' => $this->server_id, 'back_to' => 'view') + ); - $modal = new \psm\Util\Module\Modal($this->twig, 'delete', \psm\Util\Module\Modal::MODAL_TYPE_DANGER); - $this->addModal($modal); - $modal->setTitle(psm_get_lang('servers', 'delete_title')); - $modal->setMessage(psm_get_lang('servers', 'delete_message')); - $modal->setOKButtonLabel(psm_get_lang('system', 'delete')); + $modal = new \psm\Util\Module\Modal($this->twig, 'delete', \psm\Util\Module\Modal::MODAL_TYPE_DANGER); + $this->addModal($modal); + $modal->setTitle(psm_get_lang('servers', 'delete_title')); + $modal->setMessage(psm_get_lang('servers', 'delete_message')); + $modal->setOKButtonLabel(psm_get_lang('system', 'delete')); - $sidebar->addButton( - 'edit', - psm_get_lang('system', 'edit'), - psm_build_url(array('mod' => 'server', 'action' => 'edit', 'id' => $this->server_id, 'back_to' => 'view')), - 'edit', - 'primary', - psm_get_lang('system', 'edit') - ); - } + $sidebar->addButton( + 'edit', + psm_get_lang('system', 'edit'), + psm_build_url( + array('mod' => 'server', 'action' => 'edit', 'id' => $this->server_id, 'back_to' => 'view') + ), + 'edit', + 'primary', + psm_get_lang('system', 'edit') + ); + } - // add all available servers to the menu - $servers = $this->getServers(); - $tpl_data['options'] = array(); - foreach ($servers as $i => $server_available) { - $tpl_data['options'][] = array( - 'class_active' => ($server_available['server_id'] == $this->server_id) ? 'active' : '', - 'url' => psm_build_url(array('mod' => 'server', 'action' => 'view', 'id' => $server_available['server_id'])), - 'label' => $server_available['label'], - ); - } + // add all available servers to the menu + $servers = $this->getServers(); + $tpl_data['options'] = array(); + foreach ($servers as $i => $server_available) { + $tpl_data['options'][] = array( + 'class_active' => ($server_available['server_id'] == $this->server_id) ? 'active' : '', + 'url' => psm_build_url( + array('mod' => 'server', 'action' => 'view', 'id' => $server_available['server_id']) + ), + 'label' => $server_available['label'], + ); + } - $tpl_data['last_output_truncated'] = $tpl_data['last_output']; - $tpl_data['last_error_output_truncated'] = $tpl_data['last_error_output']; + $tpl_data['last_output_truncated'] = $tpl_data['last_output']; + $tpl_data['last_error_output_truncated'] = $tpl_data['last_error_output']; - if (strlen($tpl_data['last_output']) > 255) { - $tpl_data['last_output_truncated'] = substr($tpl_data['last_output'], 0, 255) . '...'; - } + if (strlen($tpl_data['last_output']) > 255) { + $tpl_data['last_output_truncated'] = substr($tpl_data['last_output'], 0, 255) . '...'; + } - if (strlen($tpl_data['last_error_output']) > 255) { - $tpl_data['last_error_output_truncated'] = substr($tpl_data['last_error_output'], 0, 255) . '...'; - } + if (strlen($tpl_data['last_error_output']) > 255) { + $tpl_data['last_error_output_truncated'] = substr($tpl_data['last_error_output'], 0, 255) . '...'; + } - return $this->twig->render('module/server/server/view.tpl.html', $tpl_data); - } + return $this->twig->render('module/server/server/view.tpl.html', $tpl_data); + } - protected function getLabels() { - return array( - 'label_label' => psm_get_lang('servers', 'label'), - 'label_status' => psm_get_lang('servers', 'status'), - 'label_domain' => psm_get_lang('servers', 'domain'), - 'label_timeout' => psm_get_lang('servers', 'timeout'), - 'label_timeout_description' => psm_get_lang('servers', 'timeout_description'), - 'label_authentication_settings' => psm_get_lang('servers', 'authentication_settings'), - 'label_optional' => psm_get_lang('servers', 'optional'), - 'label_website_username' => psm_get_lang('servers', 'website_username'), - 'label_website_username_description' => psm_get_lang('servers', 'website_username_description'), - 'label_website_password' => psm_get_lang('servers', 'website_password'), - 'label_website_password_description' => psm_get_lang('servers', 'website_password_description'), - 'label_fieldset_monitoring' => psm_get_lang('servers', 'fieldset_monitoring'), - 'label_fieldset_permissions' => psm_get_lang('servers', 'fieldset_permissions'), - 'label_permissions' => psm_get_lang('servers', 'permissions'), - 'label_port' => psm_get_lang('servers', 'port'), - 'label_custom_port' => psm_get_lang('servers', 'custom_port'), - 'label_popular_ports' => psm_get_lang('servers', 'popular_ports'), - 'label_request_method' => psm_get_lang('servers', 'request_method'), - 'label_custom_request_method' => psm_get_lang('servers', 'custom_request_method'), - 'label_popular_request_methods' => psm_get_lang('servers', 'popular_request_methods'), - 'label_post_field' => psm_get_lang('servers', 'post_field'), - 'label_post_field_description' => psm_get_lang('servers', 'post_field_description'), - 'label_none' => psm_get_lang('system', 'none'), - 'label_please_select' => psm_get_lang('servers', 'please_select'), - 'label_type' => psm_get_lang('servers', 'type'), - 'label_website' => psm_get_lang('servers', 'type_website'), - 'label_service' => psm_get_lang('servers', 'type_service'), - 'label_ping' => psm_get_lang('servers', 'type_ping'), - 'label_pattern' => psm_get_lang('servers', 'pattern'), - 'label_pattern_description' => psm_get_lang('servers', 'pattern_description'), - 'label_pattern_online' => psm_get_lang('servers', 'pattern_online'), - 'label_pattern_online_description' => psm_get_lang('servers', 'pattern_online_description'), - 'label_redirect_check' => psm_get_lang('servers', 'redirect_check'), - 'label_redirect_check_description' => psm_get_lang('servers', 'redirect_check_description'), - 'label_allow_http_status' => psm_get_lang('servers', 'allow_http_status'), - 'label_allow_http_status_description' => psm_get_lang('servers', 'allow_http_status_description'), - 'label_header_name' => psm_get_lang('servers', 'header_name'), - 'label_header_value' => psm_get_lang('servers', 'header_value'), - 'label_header_name_description' => psm_get_lang('servers', 'header_name_description'), - 'label_header_value_description' => psm_get_lang('servers', 'header_value_description'), - 'label_last_check' => psm_get_lang('servers', 'last_check'), - 'label_rtime' => psm_get_lang('servers', 'latency'), - 'label_last_online' => psm_get_lang('servers', 'last_online'), - 'label_last_offline' => psm_get_lang('servers', 'last_offline'), - 'label_last_output' => psm_get_lang('servers', 'last_output'), - 'label_last_error' => psm_get_lang('servers', 'last_error'), - 'label_last_error_output' => psm_get_lang('servers', 'last_error_output'), - 'label_monitoring' => psm_get_lang('servers', 'monitoring'), - 'label_email' => psm_get_lang('servers', 'email'), - 'label_send_email' => psm_get_lang('servers', 'send_email'), - 'label_sms' => psm_get_lang('servers', 'sms'), - 'label_send_sms' => psm_get_lang('servers', 'send_sms'), - 'label_send_pushover' => psm_get_lang('servers', 'send_pushover'), - 'label_telegram' => psm_get_lang('servers', 'telegram'), - 'label_pushover' => psm_get_lang('servers', 'pushover'), - 'label_send_telegram' => psm_get_lang('servers', 'send_telegram'), - 'label_users' => psm_get_lang('servers', 'users'), - 'label_warning_threshold' => psm_get_lang('servers', 'warning_threshold'), - 'label_warning_threshold_description' => psm_get_lang('servers', 'warning_threshold_description'), - 'label_action' => psm_get_lang('system', 'action'), - 'label_save' => psm_get_lang('system', 'save'), - 'label_go_back' => psm_get_lang('system', 'go_back'), - 'label_edit' => psm_get_lang('system', 'edit'), - 'label_delete' => psm_get_lang('system', 'delete'), - 'label_view' => psm_get_lang('system', 'view'), - 'label_yes' => psm_get_lang('system', 'yes'), - 'label_no' => psm_get_lang('system', 'no'), - 'label_add_new' => psm_get_lang('system', 'add_new'), - 'label_seconds' => psm_get_lang('config', 'seconds'), - 'label_online' => psm_get_lang('servers', 'online'), - 'label_offline' => psm_get_lang('servers', 'offline'), - 'label_ok' => psm_get_lang('system', 'ok'), - 'label_bad' => psm_get_lang('system', 'bad'), - 'default_value_timeout' => PSM_CURL_TIMEOUT, - 'label_settings' => psm_get_lang('system', 'settings'), - 'label_output' => psm_get_lang('servers', 'output'), - 'label_search' => psm_get_lang('system', 'search'), - ); - } + protected function getLabels() + { + return array( + 'label_label' => psm_get_lang('servers', 'label'), + 'label_status' => psm_get_lang('servers', 'status'), + 'label_domain' => psm_get_lang('servers', 'domain'), + 'label_timeout' => psm_get_lang('servers', 'timeout'), + 'label_timeout_description' => psm_get_lang('servers', 'timeout_description'), + 'label_authentication_settings' => psm_get_lang('servers', 'authentication_settings'), + 'label_optional' => psm_get_lang('servers', 'optional'), + 'label_website_username' => psm_get_lang('servers', 'website_username'), + 'label_website_username_description' => psm_get_lang('servers', 'website_username_description'), + 'label_website_password' => psm_get_lang('servers', 'website_password'), + 'label_website_password_description' => psm_get_lang('servers', 'website_password_description'), + 'label_fieldset_monitoring' => psm_get_lang('servers', 'fieldset_monitoring'), + 'label_fieldset_permissions' => psm_get_lang('servers', 'fieldset_permissions'), + 'label_permissions' => psm_get_lang('servers', 'permissions'), + 'label_port' => psm_get_lang('servers', 'port'), + 'label_custom_port' => psm_get_lang('servers', 'custom_port'), + 'label_popular_ports' => psm_get_lang('servers', 'popular_ports'), + 'label_request_method' => psm_get_lang('servers', 'request_method'), + 'label_custom_request_method' => psm_get_lang('servers', 'custom_request_method'), + 'label_popular_request_methods' => psm_get_lang('servers', 'popular_request_methods'), + 'label_post_field' => psm_get_lang('servers', 'post_field'), + 'label_post_field_description' => psm_get_lang('servers', 'post_field_description'), + 'label_none' => psm_get_lang('system', 'none'), + 'label_please_select' => psm_get_lang('servers', 'please_select'), + 'label_type' => psm_get_lang('servers', 'type'), + 'label_website' => psm_get_lang('servers', 'type_website'), + 'label_service' => psm_get_lang('servers', 'type_service'), + 'label_ping' => psm_get_lang('servers', 'type_ping'), + 'label_pattern' => psm_get_lang('servers', 'pattern'), + 'label_pattern_description' => psm_get_lang('servers', 'pattern_description'), + 'label_pattern_online' => psm_get_lang('servers', 'pattern_online'), + 'label_pattern_online_description' => psm_get_lang('servers', 'pattern_online_description'), + 'label_redirect_check' => psm_get_lang('servers', 'redirect_check'), + 'label_redirect_check_description' => psm_get_lang('servers', 'redirect_check_description'), + 'label_allow_http_status' => psm_get_lang('servers', 'allow_http_status'), + 'label_allow_http_status_description' => psm_get_lang('servers', 'allow_http_status_description'), + 'label_header_name' => psm_get_lang('servers', 'header_name'), + 'label_header_value' => psm_get_lang('servers', 'header_value'), + 'label_header_name_description' => psm_get_lang('servers', 'header_name_description'), + 'label_header_value_description' => psm_get_lang('servers', 'header_value_description'), + 'label_last_check' => psm_get_lang('servers', 'last_check'), + 'label_rtime' => psm_get_lang('servers', 'latency'), + 'label_last_online' => psm_get_lang('servers', 'last_online'), + 'label_last_offline' => psm_get_lang('servers', 'last_offline'), + 'label_last_output' => psm_get_lang('servers', 'last_output'), + 'label_last_error' => psm_get_lang('servers', 'last_error'), + 'label_last_error_output' => psm_get_lang('servers', 'last_error_output'), + 'label_monitoring' => psm_get_lang('servers', 'monitoring'), + 'label_email' => psm_get_lang('servers', 'email'), + 'label_send_email' => psm_get_lang('servers', 'send_email'), + 'label_sms' => psm_get_lang('servers', 'sms'), + 'label_send_sms' => psm_get_lang('servers', 'send_sms'), + 'label_send_pushover' => psm_get_lang('servers', 'send_pushover'), + 'label_telegram' => psm_get_lang('servers', 'telegram'), + 'label_pushover' => psm_get_lang('servers', 'pushover'), + 'label_send_telegram' => psm_get_lang('servers', 'send_telegram'), + 'label_users' => psm_get_lang('servers', 'users'), + 'label_warning_threshold' => psm_get_lang('servers', 'warning_threshold'), + 'label_warning_threshold_description' => psm_get_lang('servers', 'warning_threshold_description'), + 'label_action' => psm_get_lang('system', 'action'), + 'label_save' => psm_get_lang('system', 'save'), + 'label_go_back' => psm_get_lang('system', 'go_back'), + 'label_edit' => psm_get_lang('system', 'edit'), + 'label_delete' => psm_get_lang('system', 'delete'), + 'label_view' => psm_get_lang('system', 'view'), + 'label_yes' => psm_get_lang('system', 'yes'), + 'label_no' => psm_get_lang('system', 'no'), + 'label_add_new' => psm_get_lang('system', 'add_new'), + 'label_seconds' => psm_get_lang('config', 'seconds'), + 'label_online' => psm_get_lang('servers', 'online'), + 'label_offline' => psm_get_lang('servers', 'offline'), + 'label_ok' => psm_get_lang('system', 'ok'), + 'label_bad' => psm_get_lang('system', 'bad'), + 'default_value_timeout' => PSM_CURL_TIMEOUT, + 'label_settings' => psm_get_lang('system', 'settings'), + 'label_output' => psm_get_lang('servers', 'output'), + 'label_search' => psm_get_lang('system', 'search'), + ); + } - /** - * Get all user ids for a server - * @param int $server_id - * @return array with ids only - */ - protected function getServerUsers($server_id) { - $users = $this->db->select( - PSM_DB_PREFIX.'users_servers', - array('server_id' => $server_id), - array('user_id') - ); - $result = array(); - foreach ($users as $user) { - $result[] = $user['user_id']; - } - return $result; - } + /** + * Get all user ids for a server + * @param int $server_id + * @return array with ids only + */ + protected function getServerUsers($server_id) + { + $users = $this->db->select( + PSM_DB_PREFIX . 'users_servers', + array('server_id' => $server_id), + array('user_id') + ); + $result = array(); + foreach ($users as $user) { + $result[] = $user['user_id']; + } + return $result; + } } diff --git a/src/psm/Module/Server/Controller/StatusController.php b/src/psm/Module/Server/Controller/StatusController.php index fcb8a642..efe840f3 100644 --- a/src/psm/Module/Server/Controller/StatusController.php +++ b/src/psm/Module/Server/Controller/StatusController.php @@ -1,4 +1,5 @@ setCSRFKey('status'); - $this->setActions(array('index', 'saveLayout'), 'index'); - } + $this->setCSRFKey('status'); + $this->setActions(array('index', 'saveLayout'), 'index'); + } - /** - * Prepare the template to show a list of all servers - */ - protected function executeIndex() { - // set background color to black - $this->black_background = true; - $this->twig->addGlobal('subtitle', psm_get_lang('menu', 'server_status')); + /** + * Prepare the template to show a list of all servers + */ + protected function executeIndex() + { + // set background color to black + $this->black_background = true; + $this->twig->addGlobal('subtitle', psm_get_lang('menu', 'server_status')); - // add header accessories - $layout = $this->getUser()->getUserPref('status_layout', 0); - $layout_data = array( - 'label_none' => psm_get_lang('system', 'none'), - 'label_last_check' => psm_get_lang('servers', 'last_check'), - 'label_last_online' => psm_get_lang('servers', 'last_online'), - 'label_last_offline' => psm_get_lang('servers', 'last_offline'), - 'label_online' => psm_get_lang('servers', 'online'), - 'label_offline' => psm_get_lang('servers', 'offline'), - 'label_rtime' => psm_get_lang('servers', 'latency'), - 'block_layout_active' => ($layout == 0) ? 'active' : '', - 'list_layout_active' => ($layout != 0) ? 'active' : '', - 'label_add_server' => psm_get_lang('system', 'add_new'), - 'layout' => $layout, - 'url_save' => psm_build_url(array('mod' => 'server', 'action' => 'edit')), - ); - $this->setHeaderAccessories($this->twig->render('module/server/status/header.tpl.html', $layout_data)); + // add header accessories + $layout = $this->getUser()->getUserPref('status_layout', 0); + $layout_data = array( + 'label_none' => psm_get_lang('system', 'none'), + 'label_last_check' => psm_get_lang('servers', 'last_check'), + 'label_last_online' => psm_get_lang('servers', 'last_online'), + 'label_last_offline' => psm_get_lang('servers', 'last_offline'), + 'label_online' => psm_get_lang('servers', 'online'), + 'label_offline' => psm_get_lang('servers', 'offline'), + 'label_rtime' => psm_get_lang('servers', 'latency'), + 'block_layout_active' => ($layout == 0) ? 'active' : '', + 'list_layout_active' => ($layout != 0) ? 'active' : '', + 'label_add_server' => psm_get_lang('system', 'add_new'), + 'layout' => $layout, + 'url_save' => psm_build_url(array('mod' => 'server', 'action' => 'edit')), + ); + $this->setHeaderAccessories($this->twig->render('module/server/status/header.tpl.html', $layout_data)); - $this->addFooter(false); + $this->addFooter(false); - // get the active servers from database - $servers = $this->getServers(); + // get the active servers from database + $servers = $this->getServers(); - $layout_data['servers_offline'] = array(); - $layout_data['servers_warning'] = array(); - $layout_data['servers_online'] = array(); + $layout_data['servers_offline'] = array(); + $layout_data['servers_warning'] = array(); + $layout_data['servers_online'] = array(); - foreach ($servers as $server) { - if ($server['active'] == 'no') { - continue; - } - $server['last_checked_nice'] = psm_timespan($server['last_check']); - $server['last_online_nice'] = psm_timespan($server['last_online']); - $server['last_offline_nice'] = psm_timespan($server['last_offline']); - $server['last_offline_duration_nice'] = ""; - if ($server['last_offline_nice'] != psm_get_lang('system', 'never')) { - $server['last_offline_duration_nice'] = "(".$server['last_offline_duration'].")"; - } - $server['url_view'] = psm_build_url(array('mod' => 'server', 'action' => 'view', 'id' => $server['server_id'], 'back_to' => 'server_status')); + foreach ($servers as $server) { + if ($server['active'] == 'no') { + continue; + } + $server['last_checked_nice'] = psm_timespan($server['last_check']); + $server['last_online_nice'] = psm_timespan($server['last_online']); + $server['last_offline_nice'] = psm_timespan($server['last_offline']); + $server['last_offline_duration_nice'] = ""; + if ($server['last_offline_nice'] != psm_get_lang('system', 'never')) { + $server['last_offline_duration_nice'] = "(" . $server['last_offline_duration'] . ")"; + } + $server['url_view'] = psm_build_url( + array('mod' => 'server', 'action' => 'view', 'id' => $server['server_id'], 'back_to' => 'server_status') + ); - if ($server['status'] == "off") { - $layout_data['servers_offline'][] = $server; - } elseif ($server['warning_threshold_counter'] > 0) { - $layout_data['servers_warning'][] = $server; - } else { - $layout_data['servers_online'][] = $server; - } - } + if ($server['status'] == "off") { + $layout_data['servers_offline'][] = $server; + } elseif ($server['warning_threshold_counter'] > 0) { + $layout_data['servers_warning'][] = $server; + } else { + $layout_data['servers_online'][] = $server; + } + } - $auto_refresh_seconds = psm_get_conf('auto_refresh_servers'); - if (intval($auto_refresh_seconds) > 0) { - $this->twig->addGlobal('auto_refresh', true); - $this->twig->addGlobal('auto_refresh_seconds', $auto_refresh_seconds); - } + $auto_refresh_seconds = psm_get_conf('auto_refresh_servers'); + if (intval($auto_refresh_seconds) > 0) { + $this->twig->addGlobal('auto_refresh', true); + $this->twig->addGlobal('auto_refresh_seconds', $auto_refresh_seconds); + } - if ($this->isXHR() || isset($_SERVER["HTTP_X_REQUESTED_WITH"])) { - $this->xhr = true; - //disable auto refresh in ajax return html - $layout_data["auto_refresh"] = 0; - } + if ($this->isXHR() || isset($_SERVER["HTTP_X_REQUESTED_WITH"])) { + $this->xhr = true; + //disable auto refresh in ajax return html + $layout_data["auto_refresh"] = 0; + } - return $this->twig->render('module/server/status/index.tpl.html', $layout_data); - } + return $this->twig->render('module/server/status/index.tpl.html', $layout_data); + } - protected function executeSaveLayout() { - if ($this->isXHR()) { - $layout = psm_POST('layout', 0); - $this->getUser()->setUserPref('status_layout', $layout); + protected function executeSaveLayout() + { + if ($this->isXHR()) { + $layout = psm_POST('layout', 0); + $this->getUser()->setUserPref('status_layout', $layout); - $response = new \Symfony\Component\HttpFoundation\JsonResponse(); - $response->setData(array( - 'layout' => $layout, - )); - return $response; - } - } + $response = new \Symfony\Component\HttpFoundation\JsonResponse(); + $response->setData(array( + 'layout' => $layout, + )); + return $response; + } + } } diff --git a/src/psm/Module/Server/Controller/UpdateController.php b/src/psm/Module/Server/Controller/UpdateController.php index 7b528b81..d2addcac 100644 --- a/src/psm/Module/Server/Controller/UpdateController.php +++ b/src/psm/Module/Server/Controller/UpdateController.php @@ -1,4 +1,5 @@ setActions('index', 'index'); - } + $this->setActions('index', 'index'); + } - protected function executeIndex() { - $autorun = $this->container->get('util.server.updatemanager'); - $autorun->run(); - - header('Location: '.psm_build_url(array( - 'mod' => 'server_status' - ), true, false)); - die(); - } + protected function executeIndex() + { + $autorun = $this->container->get('util.server.updatemanager'); + $autorun->run(); + header('Location: ' . psm_build_url(array( + 'mod' => 'server_status' + ), true, false)); + die(); + } } diff --git a/src/psm/Module/Server/ServerModule.php b/src/psm/Module/Server/ServerModule.php index 44a5b06e..a4cf1d76 100644 --- a/src/psm/Module/Server/ServerModule.php +++ b/src/psm/Module/Server/ServerModule.php @@ -1,4 +1,5 @@ __NAMESPACE__.'\Controller\ServerController', - 'log' => __NAMESPACE__.'\Controller\LogController', - 'status' => __NAMESPACE__.'\Controller\StatusController', - 'update' => __NAMESPACE__.'\Controller\UpdateController', - ); - - } + public function getControllers() + { + return array( + 'server' => __NAMESPACE__ . '\Controller\ServerController', + 'log' => __NAMESPACE__ . '\Controller\LogController', + 'status' => __NAMESPACE__ . '\Controller\StatusController', + 'update' => __NAMESPACE__ . '\Controller\UpdateController', + ); + } } diff --git a/src/psm/Module/User/Controller/LoginController.php b/src/psm/Module/User/Controller/LoginController.php index 09ceb4db..4c50272d 100644 --- a/src/psm/Module/User/Controller/LoginController.php +++ b/src/psm/Module/User/Controller/LoginController.php @@ -1,4 +1,5 @@ setMinUserLevelRequired(PSM_USER_ANONYMOUS); + $this->setMinUserLevelRequired(PSM_USER_ANONYMOUS); - $this->setActions(array( - 'login', 'forgot', 'reset', - ), 'login'); + $this->setActions(array( + 'login', 'forgot', 'reset', + ), 'login'); - $this->addMenu(false); - } + $this->addMenu(false); + } - protected function executeLogin() { - if (isset($_POST['user_name']) && isset($_POST['user_password'])) { - $rememberme = (isset($_POST['user_rememberme'])) ? true : false; - $result = $this->getUser()->loginWithPostData( - $_POST['user_name'], - $_POST['user_password'], - $rememberme - ); + protected function executeLogin() + { + if (isset($_POST['user_name']) && isset($_POST['user_password'])) { + $rememberme = (isset($_POST['user_rememberme'])) ? true : false; + $result = $this->getUser()->loginWithPostData( + $_POST['user_name'], + $_POST['user_password'], + $rememberme + ); - if ($result) { - // success login, redirect - header('Location: '. - psm_build_url( - empty($_SERVER["QUERY_STRING"]) ? null : $_SERVER["QUERY_STRING"] - ) - ); - die(); - } else { - $this->addMessage(psm_get_lang('login', 'error_login_incorrect'), 'error'); - } - } + if ($result) { + // success login, redirect + header('Location: ' . + psm_build_url( + empty($_SERVER["QUERY_STRING"]) ? null : $_SERVER["QUERY_STRING"] + )); + die(); + } else { + $this->addMessage(psm_get_lang('login', 'error_login_incorrect'), 'error'); + } + } - $tpl_data = array( - 'title_sign_in' => psm_get_lang('login', 'title_sign_in'), - 'label_username' => psm_get_lang('login', 'username'), - 'label_password' => psm_get_lang('login', 'password'), - 'label_remember_me' => psm_get_lang('login', 'remember_me'), - 'label_login' => psm_get_lang('login', 'login'), - 'label_password_forgot' => psm_get_lang('login', 'password_forgot'), - 'value_user_name' => (isset($_POST['user_name'])) ? $_POST['user_name'] : '', - 'value_rememberme' => (isset($rememberme) && $rememberme) ? 'checked="checked"' : '', - ); + $tpl_data = array( + 'title_sign_in' => psm_get_lang('login', 'title_sign_in'), + 'label_username' => psm_get_lang('login', 'username'), + 'label_password' => psm_get_lang('login', 'password'), + 'label_remember_me' => psm_get_lang('login', 'remember_me'), + 'label_login' => psm_get_lang('login', 'login'), + 'label_password_forgot' => psm_get_lang('login', 'password_forgot'), + 'value_user_name' => (isset($_POST['user_name'])) ? $_POST['user_name'] : '', + 'value_rememberme' => (isset($rememberme) && $rememberme) ? 'checked="checked"' : '', + ); - return $this->twig->render('module/user/login/login.tpl.html', $tpl_data); - } + return $this->twig->render('module/user/login/login.tpl.html', $tpl_data); + } - /** - * Show/process the password forgot form (before the mail) - * - * @return string - */ - protected function executeForgot() { - if (isset($_POST['user_name'])) { - $user = $this->getUser()->getUserByUsername($_POST['user_name']); + /** + * Show/process the password forgot form (before the mail) + * + * @return string + */ + protected function executeForgot() + { + if (isset($_POST['user_name'])) { + $user = $this->getUser()->getUserByUsername($_POST['user_name']); - if (!empty($user)) { - $token = $this->getUser()->generatePasswordResetToken($user->user_id); - // we have a token, send it along - $this->sendPasswordForgotMail( - $user->user_id, - $user->email, - $token - ); + if (!empty($user)) { + $token = $this->getUser()->generatePasswordResetToken($user->user_id); + // we have a token, send it along + $this->sendPasswordForgotMail( + $user->user_id, + $user->email, + $token + ); - $this->addMessage(psm_get_lang('login', 'success_password_forgot'), 'success'); - return $this->executeLogin(); - } else { - $this->addMessage(psm_get_lang('login', 'error_user_incorrect'), 'error'); - } - } + $this->addMessage(psm_get_lang('login', 'success_password_forgot'), 'success'); + return $this->executeLogin(); + } else { + $this->addMessage(psm_get_lang('login', 'error_user_incorrect'), 'error'); + } + } - $tpl_data = array( - 'title_forgot' => psm_get_lang('login', 'title_forgot'), - 'label_username' => psm_get_lang('login', 'username'), - 'label_submit' => psm_get_lang('login', 'submit'), - 'label_go_back' => psm_get_lang('system', 'go_back'), - ); - return $this->twig->render('module/user/login/forgot.tpl.html', $tpl_data); - } + $tpl_data = array( + 'title_forgot' => psm_get_lang('login', 'title_forgot'), + 'label_username' => psm_get_lang('login', 'username'), + 'label_submit' => psm_get_lang('login', 'submit'), + 'label_go_back' => psm_get_lang('system', 'go_back'), + ); + return $this->twig->render('module/user/login/forgot.tpl.html', $tpl_data); + } - /** - * Show/process the password reset form (after the mail) - */ - protected function executeReset() { - $service_user = $this->getUser(); - $user_id = (isset($_GET['user_id'])) ? intval($_GET['user_id']) : 0; - $token = (isset($_GET['token'])) ? $_GET['token'] : ''; + /** + * Show/process the password reset form (after the mail) + */ + protected function executeReset() + { + $service_user = $this->getUser(); + $user_id = (isset($_GET['user_id'])) ? intval($_GET['user_id']) : 0; + $token = (isset($_GET['token'])) ? $_GET['token'] : ''; - if (!$service_user->verifyPasswordResetToken($user_id, $token)) { - $this->addMessage(psm_get_lang('login', 'error_reset_invalid_link'), 'error'); - return $this->executeLogin(); - } + if (!$service_user->verifyPasswordResetToken($user_id, $token)) { + $this->addMessage(psm_get_lang('login', 'error_reset_invalid_link'), 'error'); + return $this->executeLogin(); + } - if (!empty($_POST['user_password_new']) && !empty($_POST['user_password_repeat'])) { - if ($_POST['user_password_new'] !== $_POST['user_password_repeat']) { - $this->addMessage(psm_get_lang('login', 'error_login_passwords_nomatch'), 'error'); - } else { - $result = $service_user->changePassword($user_id, $_POST['user_password_new']); + if (!empty($_POST['user_password_new']) && !empty($_POST['user_password_repeat'])) { + if ($_POST['user_password_new'] !== $_POST['user_password_repeat']) { + $this->addMessage(psm_get_lang('login', 'error_login_passwords_nomatch'), 'error'); + } else { + $result = $service_user->changePassword($user_id, $_POST['user_password_new']); - if ($result) { - $this->addMessage(psm_get_lang('login', 'success_password_reset'), 'success'); - return $this->executeLogin(); - } else { - $this->addMessage(psm_get_lang('login', 'error_login_incorrect'), 'error'); - } - } - } - $user = $service_user->getUser($user_id); + if ($result) { + $this->addMessage(psm_get_lang('login', 'success_password_reset'), 'success'); + return $this->executeLogin(); + } else { + $this->addMessage(psm_get_lang('login', 'error_login_incorrect'), 'error'); + } + } + } + $user = $service_user->getUser($user_id); - $tpl_data = array( - 'title_reset' => psm_get_lang('login', 'title_reset'), - 'label_username' => psm_get_lang('login', 'username'), - 'label_password' => psm_get_lang('login', 'password'), - 'label_password_repeat' => psm_get_lang('login', 'password_repeat'), - 'label_reset' => psm_get_lang('login', 'password_reset'), - 'label_go_back' => psm_get_lang('system', 'go_back'), - 'value_user_name' => $user->user_name, - ); - return $this->twig->render('module/user/login/reset.tpl.html', $tpl_data); - } + $tpl_data = array( + 'title_reset' => psm_get_lang('login', 'title_reset'), + 'label_username' => psm_get_lang('login', 'username'), + 'label_password' => psm_get_lang('login', 'password'), + 'label_password_repeat' => psm_get_lang('login', 'password_repeat'), + 'label_reset' => psm_get_lang('login', 'password_reset'), + 'label_go_back' => psm_get_lang('system', 'go_back'), + 'value_user_name' => $user->user_name, + ); + return $this->twig->render('module/user/login/reset.tpl.html', $tpl_data); + } - /** - * Sends the password-reset-email. - * @param int $user_id - * @param string $user_email - * @param string $user_password_reset_hash - */ - protected function sendPasswordForgotMail($user_id, $user_email, $user_password_reset_hash) { - $mail = psm_build_mail(); - $mail->Subject = psm_get_lang('login', 'password_reset_email_subject'); + /** + * Sends the password-reset-email. + * @param int $user_id + * @param string $user_email + * @param string $user_password_reset_hash + */ + protected function sendPasswordForgotMail($user_id, $user_email, $user_password_reset_hash) + { + $mail = psm_build_mail(); + $mail->Subject = psm_get_lang('login', 'password_reset_email_subject'); - $url = psm_build_url(array( - 'action' => 'reset', - 'user_id' => $user_id, - 'token' => $user_password_reset_hash, - ), true, false); - $body = psm_get_lang('login', 'password_reset_email_body'); - $body = str_replace('%link%', $url, $body); - $mail->Body = $body; - $mail->AltBody = str_replace('
    ', "\n", $body); + $url = psm_build_url(array( + 'action' => 'reset', + 'user_id' => $user_id, + 'token' => $user_password_reset_hash, + ), true, false); + $body = psm_get_lang('login', 'password_reset_email_body'); + $body = str_replace('%link%', $url, $body); + $mail->Body = $body; + $mail->AltBody = str_replace('
    ', "\n", $body); - $mail->AddAddress($user_email); - $mail->Send(); - } + $mail->AddAddress($user_email); + $mail->Send(); + } } diff --git a/src/psm/Module/User/Controller/ProfileController.php b/src/psm/Module/User/Controller/ProfileController.php index daeca3b6..bcd04c0f 100644 --- a/src/psm/Module/User/Controller/ProfileController.php +++ b/src/psm/Module/User/Controller/ProfileController.php @@ -1,4 +1,5 @@ setActions(array( - 'index', 'save', - ), 'index'); - $this->setCSRFKey('profile'); - } + $this->setActions(array( + 'index', 'save', + ), 'index'); + $this->setCSRFKey('profile'); + } - /** - * Show the profile page - * @return string - */ - protected function executeIndex() { - $this->twig->addGlobal('subtitle', psm_get_lang('users', 'profile')); - $user = $this->getUser()->getUser(null, true); + /** + * Show the profile page + * @return string + */ + protected function executeIndex() + { + $this->twig->addGlobal('subtitle', psm_get_lang('users', 'profile')); + $user = $this->getUser()->getUser(null, true); - $modal = new \psm\Util\Module\Modal($this->twig, 'activate' . ucfirst('telegram'), \psm\Util\Module\Modal::MODAL_TYPE_OKCANCEL); - $this->addModal($modal); - $modal->setTitle(psm_get_lang('users', 'activate_telegram')); - $modal->setMessage(psm_get_lang('users', 'activate_telegram_description')); - $modal->setOKButtonLabel(psm_get_lang('system', 'activate')); + $modal = new \psm\Util\Module\Modal( + $this->twig, + 'activate' . ucfirst('telegram'), + \psm\Util\Module\Modal::MODAL_TYPE_OKCANCEL + ); + $this->addModal($modal); + $modal->setTitle(psm_get_lang('users', 'activate_telegram')); + $modal->setMessage(psm_get_lang('users', 'activate_telegram_description')); + $modal->setOKButtonLabel(psm_get_lang('system', 'activate')); - $tpl_data = array( - 'label_general' => psm_get_lang('config', 'general'), - 'label_name' => psm_get_lang('users', 'name'), - 'label_user_name' => psm_get_lang('users', 'user_name'), - 'label_password' => psm_get_lang('users', 'password'), - 'label_password_repeat' => psm_get_lang('users', 'password_repeat'), - 'label_level' => psm_get_lang('users', 'level'), - 'label_mobile' => psm_get_lang('users', 'mobile'), - 'label_pushover' => psm_get_lang('users', 'pushover'), - 'label_pushover_description' => psm_get_lang('users', 'pushover_description'), - 'label_pushover_key' => psm_get_lang('users', 'pushover_key'), - 'label_pushover_device' => psm_get_lang('users', 'pushover_device'), - 'label_pushover_device_description' => psm_get_lang('users', 'pushover_device_description'), - 'label_telegram' => psm_get_lang('users', 'telegram'), - 'label_telegram_description' => psm_get_lang('users', 'telegram_description'), - 'label_telegram_chat_id' => psm_get_lang('users', 'telegram_chat_id'), - 'label_telegram_chat_id_description' => psm_get_lang('users', 'telegram_chat_id_description'), - 'label_activate_telegram' => psm_get_lang('users', 'activate_telegram'), - 'label_telegram_get_chat_id' => psm_get_lang('users', 'telegram_get_chat_id'), - 'telegram_get_chat_id_url' => PSM_TELEGRAM_GET_ID_URL, - 'label_email' => psm_get_lang('users', 'email'), - 'label_save' => psm_get_lang('system', 'save'), - 'form_action' => psm_build_url(array( - 'mod' => 'user_profile', - 'action' => 'save', - )), - 'level' => psm_get_lang('users', 'level_' . $user->level), - 'placeholder_password' => psm_get_lang('users', 'password_leave_blank'), - ); - foreach ($this->profile_fields as $field) { - $tpl_data[$field] = (isset($user->$field)) ? $user->$field : ''; - } - return $this->twig->render('module/user/profile.tpl.html', $tpl_data); - } + $tpl_data = array( + 'label_general' => psm_get_lang('config', 'general'), + 'label_name' => psm_get_lang('users', 'name'), + 'label_user_name' => psm_get_lang('users', 'user_name'), + 'label_password' => psm_get_lang('users', 'password'), + 'label_password_repeat' => psm_get_lang('users', 'password_repeat'), + 'label_level' => psm_get_lang('users', 'level'), + 'label_mobile' => psm_get_lang('users', 'mobile'), + 'label_pushover' => psm_get_lang('users', 'pushover'), + 'label_pushover_description' => psm_get_lang('users', 'pushover_description'), + 'label_pushover_key' => psm_get_lang('users', 'pushover_key'), + 'label_pushover_device' => psm_get_lang('users', 'pushover_device'), + 'label_pushover_device_description' => psm_get_lang('users', 'pushover_device_description'), + 'label_telegram' => psm_get_lang('users', 'telegram'), + 'label_telegram_description' => psm_get_lang('users', 'telegram_description'), + 'label_telegram_chat_id' => psm_get_lang('users', 'telegram_chat_id'), + 'label_telegram_chat_id_description' => psm_get_lang('users', 'telegram_chat_id_description'), + 'label_activate_telegram' => psm_get_lang('users', 'activate_telegram'), + 'label_telegram_get_chat_id' => psm_get_lang('users', 'telegram_get_chat_id'), + 'telegram_get_chat_id_url' => PSM_TELEGRAM_GET_ID_URL, + 'label_email' => psm_get_lang('users', 'email'), + 'label_save' => psm_get_lang('system', 'save'), + 'form_action' => psm_build_url(array( + 'mod' => 'user_profile', + 'action' => 'save', + )), + 'level' => psm_get_lang('users', 'level_' . $user->level), + 'placeholder_password' => psm_get_lang('users', 'password_leave_blank'), + ); + foreach ($this->profile_fields as $field) { + $tpl_data[$field] = (isset($user->$field)) ? $user->$field : ''; + } + return $this->twig->render('module/user/profile.tpl.html', $tpl_data); + } - /** - * Save the profile - */ - protected function executeSave() { - if (empty($_POST)) { - // dont process anything if no data has been posted - return $this->executeIndex(); - } - $validator = $this->container->get('util.user.validator'); - $fields = $this->profile_fields; - $fields[] = 'password'; - $fields[] = 'password_repeat'; + /** + * Save the profile + */ + protected function executeSave() + { + if (empty($_POST)) { + // dont process anything if no data has been posted + return $this->executeIndex(); + } + $validator = $this->container->get('util.user.validator'); + $fields = $this->profile_fields; + $fields[] = 'password'; + $fields[] = 'password_repeat'; - $clean = array(); - foreach ($fields as $field) { - if (isset($_POST[$field])) { - $clean[$field] = trim(strip_tags($_POST[$field])); - } else { - $clean[$field] = ''; - } - } + $clean = array(); + foreach ($fields as $field) { + if (isset($_POST[$field])) { + $clean[$field] = trim(strip_tags($_POST[$field])); + } else { + $clean[$field] = ''; + } + } - // validate the lot - try { - $validator->username($clean['user_name'], $this->getUser()->getUserId()); - $validator->email($clean['email']); + // validate the lot + try { + $validator->username($clean['user_name'], $this->getUser()->getUserId()); + $validator->email($clean['email']); - // always validate password for new users, - // but only validate it for existing users when they change it. - if ($clean['password'] != '') { - $validator->password($clean['password'], $clean['password_repeat']); - } - } catch (\InvalidArgumentException $e) { - $this->addMessage(psm_get_lang('users', 'error_' . $e->getMessage()), 'error'); - return $this->executeIndex(); - } - if (!empty($clean['password'])) { - $password = $clean['password']; - } - unset($clean['password']); - unset($clean['password_repeat']); + // always validate password for new users, + // but only validate it for existing users when they change it. + if ($clean['password'] != '') { + $validator->password($clean['password'], $clean['password_repeat']); + } + } catch (\InvalidArgumentException $e) { + $this->addMessage(psm_get_lang('users', 'error_' . $e->getMessage()), 'error'); + return $this->executeIndex(); + } + if (!empty($clean['password'])) { + $password = $clean['password']; + } + unset($clean['password']); + unset($clean['password_repeat']); - $this->db->save(PSM_DB_PREFIX . 'users', $clean, array('user_id' => $this->getUser()->getUserId())); - $this->container->get('event')->dispatch( - \psm\Module\User\UserEvents::USER_EDIT, - new \psm\Module\User\Event\UserEvent($this->getUser()->getUserId()) - ); - if (isset($password)) { - $this->getUser()->changePassword($this->getUser()->getUserId(), $password); - } - $this->addMessage(psm_get_lang('users', 'profile_updated'), 'success'); - if (!empty($_POST['activate_telegram'])) { - $this->activateTelegram(); - } - return $this->executeIndex(); - } + $this->db->save(PSM_DB_PREFIX . 'users', $clean, array('user_id' => $this->getUser()->getUserId())); + $this->container->get('event')->dispatch( + \psm\Module\User\UserEvents::USER_EDIT, + new \psm\Module\User\Event\UserEvent($this->getUser()->getUserId()) + ); + if (isset($password)) { + $this->getUser()->changePassword($this->getUser()->getUserId(), $password); + } + $this->addMessage(psm_get_lang('users', 'profile_updated'), 'success'); + if (!empty($_POST['activate_telegram'])) { + $this->activateTelegram(); + } + return $this->executeIndex(); + } - /** - * Allow the bot to send notifications to chat_id - * - */ - protected function activateTelegram() { - $telegram = psm_build_telegram(); - $apiToken = psm_get_conf('telegram_api_token'); + /** + * Allow the bot to send notifications to chat_id + * + */ + protected function activateTelegram() + { + $telegram = psm_build_telegram(); + $apiToken = psm_get_conf('telegram_api_token'); - if (empty($apiToken)) { - $this->addMessage(psm_get_lang('config', 'telegram_error_notoken'), 'error'); - return; - } + if (empty($apiToken)) { + $this->addMessage(psm_get_lang('config', 'telegram_error_notoken'), 'error'); + return; + } - $result = $telegram->getBotUsername(); + $result = $telegram->getBotUsername(); - if (isset($result['ok']) && $result['ok'] != false) { - $url = "https://t.me/" . $result["result"]["username"]; - $this->addMessage(sprintf(psm_get_lang('users', 'telegram_bot_username_found'), $url), 'success'); - return; - } + if (isset($result['ok']) && $result['ok'] != false) { + $url = "https://t.me/" . $result["result"]["username"]; + $this->addMessage(sprintf(psm_get_lang('users', 'telegram_bot_username_found'), $url), 'success'); + return; + } - if (isset($result['error_code']) && $result['error_code'] == 401) { - $error = psm_get_lang('users', 'telegram_bot_username_error_token'); - } elseif (isset($result['description'])) { - $error = $result['description']; - } else { - $error = 'Unknown'; - } - $this->addMessage(sprintf(psm_get_lang('users', 'telegram_bot_error'), $error), 'error'); - } + if (isset($result['error_code']) && $result['error_code'] == 401) { + $error = psm_get_lang('users', 'telegram_bot_username_error_token'); + } elseif (isset($result['description'])) { + $error = $result['description']; + } else { + $error = 'Unknown'; + } + $this->addMessage(sprintf(psm_get_lang('users', 'telegram_bot_error'), $error), 'error'); + } } diff --git a/src/psm/Module/User/Controller/UserController.php b/src/psm/Module/User/Controller/UserController.php index 2fdd788e..cbc3ff64 100644 --- a/src/psm/Module/User/Controller/UserController.php +++ b/src/psm/Module/User/Controller/UserController.php @@ -1,4 +1,5 @@ setMinUserLevelRequired(PSM_USER_ADMIN); - $this->setCSRFKey('user'); + $this->setMinUserLevelRequired(PSM_USER_ADMIN); + $this->setCSRFKey('user'); - $this->setActions(array( - 'index', 'edit', 'delete', 'save', - ), 'index'); - $this->twig->addGlobal('subtitle', psm_get_lang('menu', 'user')); - } + $this->setActions(array( + 'index', 'edit', 'delete', 'save', + ), 'index'); + $this->twig->addGlobal('subtitle', psm_get_lang('menu', 'user')); + } - public function run($action = NULL) { - $servers = $this->db->select(PSM_DB_PREFIX.'servers', null, array('server_id', 'label'), '', "ORDER BY `label` ASC"); - // change the indexes to reflect their server ids - foreach ($servers as $server) { - $this->servers[$server['server_id']] = $server; - } + public function run($action = null) + { + $servers = $this->db->select( + PSM_DB_PREFIX . 'servers', + null, + array('server_id', 'label'), + '', + "ORDER BY `label` ASC" + ); + // change the indexes to reflect their server ids + foreach ($servers as $server) { + $this->servers[$server['server_id']] = $server; + } - return parent::run($action); - } + return parent::run($action); + } - /** - * Create HTML to show a list of all users - * - * @return string - */ - protected function executeIndex() { - $sidebar = new \psm\Util\Module\Sidebar($this->twig); - $this->setSidebar($sidebar); + /** + * Create HTML to show a list of all users + * + * @return string + */ + protected function executeIndex() + { + $sidebar = new \psm\Util\Module\Sidebar($this->twig); + $this->setSidebar($sidebar); - $sidebar->addButton( - 'add_new', - psm_get_lang('system', 'add_new'), - psm_build_url(array('mod' => 'user', 'action' => 'edit')), - 'plus icon-white', - 'success', - psm_get_lang('system', 'add_new') - ); + $sidebar->addButton( + 'add_new', + psm_get_lang('system', 'add_new'), + psm_build_url(array('mod' => 'user', 'action' => 'edit')), + 'plus icon-white', + 'success', + psm_get_lang('system', 'add_new') + ); - $modal = new \psm\Util\Module\Modal($this->twig, 'delete', \psm\Util\Module\Modal::MODAL_TYPE_DANGER); - $this->addModal($modal); - $modal->setTitle(psm_get_lang('users', 'delete_title')); - $modal->setMessage(psm_get_lang('users', 'delete_message')); - $modal->setOKButtonLabel(psm_get_lang('system', 'delete')); + $modal = new \psm\Util\Module\Modal($this->twig, 'delete', \psm\Util\Module\Modal::MODAL_TYPE_DANGER); + $this->addModal($modal); + $modal->setTitle(psm_get_lang('users', 'delete_title')); + $modal->setMessage(psm_get_lang('users', 'delete_message')); + $modal->setOKButtonLabel(psm_get_lang('system', 'delete')); - // build label array for the next loop - $servers_labels = array(); - foreach ($this->servers as $server) { - $servers_labels[$server['server_id']] = $server['label']; - } + // build label array for the next loop + $servers_labels = array(); + foreach ($this->servers as $server) { + $servers_labels[$server['server_id']] = $server['label']; + } - $users = $this->db->select( - PSM_DB_PREFIX.'users', - null, - array('user_id', 'user_name', 'level', 'name', 'mobile', 'email'), - null, - array('name') - ); + $users = $this->db->select( + PSM_DB_PREFIX . 'users', + null, + array('user_id', 'user_name', 'level', 'name', 'mobile', 'email'), + null, + array('name') + ); - foreach ($users as $x => &$user) { - $user_servers = $this->getUserServers($user['user_id']); - $user['class'] = ($x & 1) ? 'odd' : 'even'; - $user['level_text'] = psm_get_lang('users', 'level_'.$user['level']); + foreach ($users as $x => &$user) { + $user_servers = $this->getUserServers($user['user_id']); + $user['class'] = ($x & 1) ? 'odd' : 'even'; + $user['level_text'] = psm_get_lang('users', 'level_' . $user['level']); - $user['emp_servers'] = array(); + $user['emp_servers'] = array(); - // fix server list - foreach ($user_servers as $server_id) { - if (!isset($servers_labels[$server_id])) { - continue; - } - $user['emp_servers'][] = array( - 'label' => $servers_labels[$server_id], - 'url' => psm_build_url(array('mod' => 'server', 'action' => 'view', 'id' => $server_id, 'back_to' => 'user')) - ); - } - sort($user['emp_servers']); + // fix server list + foreach ($user_servers as $server_id) { + if (!isset($servers_labels[$server_id])) { + continue; + } + $user['emp_servers'][] = array( + 'label' => $servers_labels[$server_id], + 'url' => psm_build_url( + array('mod' => 'server', 'action' => 'view', 'id' => $server_id, 'back_to' => 'user') + ) + ); + } + sort($user['emp_servers']); - $user['url_delete'] = psm_build_url(array( - 'mod' => 'user', - 'action' => 'delete', - 'id' => $user['user_id'], - )); - $user['url_edit'] = psm_build_url(array( - 'mod' => 'user', - 'action' => 'edit', - 'id' => $user['user_id'], - )); - } - $tpl_data = $this->getLabels(); - $tpl_data['users'] = $users; + $user['url_delete'] = psm_build_url(array( + 'mod' => 'user', + 'action' => 'delete', + 'id' => $user['user_id'], + )); + $user['url_edit'] = psm_build_url(array( + 'mod' => 'user', + 'action' => 'edit', + 'id' => $user['user_id'], + )); + } + $tpl_data = $this->getLabels(); + $tpl_data['users'] = $users; - return $this->twig->render('module/user/user/list.tpl.html', $tpl_data); - } + return $this->twig->render('module/user/user/list.tpl.html', $tpl_data); + } - /** - * Crate HTML for the update screen for a user - * - * @return string - */ - protected function executeEdit() { - $user_id = isset($_GET['id']) ? intval($_GET['id']) : 0; - $fields_prefill = array('name', 'user_name', 'mobile', 'pushover_key', 'pushover_device', 'telegram_id', 'email'); + /** + * Crate HTML for the update screen for a user + * + * @return string + */ + protected function executeEdit() + { + $user_id = isset($_GET['id']) ? intval($_GET['id']) : 0; + $fields_prefill = array( + 'name', + 'user_name', + 'mobile', + 'pushover_key', + 'pushover_device', + 'telegram_id', + 'email' + ); - if ($user_id == 0) { - // insert mode - $title = psm_get_lang('system', 'insert'); - $placeholder_password = ''; - $lvl_selected = PSM_USER_USER; // default level is regular user + if ($user_id == 0) { + // insert mode + $title = psm_get_lang('system', 'insert'); + $placeholder_password = ''; + $lvl_selected = PSM_USER_USER; // default level is regular user - // attempt to prefill previously posted fields - $edit_user = new \stdClass(); - foreach ($fields_prefill as $field) { - $edit_user->$field = (isset($_POST[$field])) ? $_POST[$field] : ''; - } + // attempt to prefill previously posted fields + $edit_user = new \stdClass(); + foreach ($fields_prefill as $field) { + $edit_user->$field = (isset($_POST[$field])) ? $_POST[$field] : ''; + } - // add inactive class to all servers - foreach ($this->servers as &$server) { - $server['class'] = 'inactive'; - } - } else { - // edit mode - try { - $this->container->get('util.user.validator')->userId($user_id); - } catch (\InvalidArgumentException $e) { - $this->addMessage(psm_get_lang('users', 'error_'.$e->getMessage()), 'error'); - return $this->executeIndex(); - } - $edit_user = $this->getUser()->getUser($user_id); - $title = psm_get_lang('system', 'edit').' '.$edit_user->name; - $placeholder_password = psm_get_lang('users', 'password_leave_blank'); - $lvl_selected = $edit_user->level; + // add inactive class to all servers + foreach ($this->servers as &$server) { + $server['class'] = 'inactive'; + } + } else { + // edit mode + try { + $this->container->get('util.user.validator')->userId($user_id); + } catch (\InvalidArgumentException $e) { + $this->addMessage(psm_get_lang('users', 'error_' . $e->getMessage()), 'error'); + return $this->executeIndex(); + } + $edit_user = $this->getUser()->getUser($user_id); + $title = psm_get_lang('system', 'edit') . ' ' . $edit_user->name; + $placeholder_password = psm_get_lang('users', 'password_leave_blank'); + $lvl_selected = $edit_user->level; - // select servers for this user - $user_servers = $this->getUserServers($user_id); + // select servers for this user + $user_servers = $this->getUserServers($user_id); - foreach ($this->servers as &$server) { - $this->servers[$server['server_id']]['id'] = $server['server_id']; - if (in_array($server['server_id'], $user_servers)) { - $server['edit_selected'] = 'selected="selected"'; - $server['class'] = 'active'; - } - } - } + foreach ($this->servers as &$server) { + $this->servers[$server['server_id']]['id'] = $server['server_id']; + if (in_array($server['server_id'], $user_servers)) { + $server['edit_selected'] = 'selected="selected"'; + $server['class'] = 'active'; + } + } + } - $tpl_data = array( - 'titlemode' => $title, - 'placeholder_password' => $placeholder_password, - 'edit_user_id' => $user_id, - 'url_save' => psm_build_url(array( - 'mod' => 'user', - 'action' => 'save', - 'id' => $user_id, - )), - 'servers' => $this->servers, - 'user_level' => $lvl_selected, - ); - foreach ($fields_prefill as $field) { - if (isset($edit_user->$field)) { - $tpl_data['edit_value_'.$field] = $edit_user->$field; - } - } + $tpl_data = array( + 'titlemode' => $title, + 'placeholder_password' => $placeholder_password, + 'edit_user_id' => $user_id, + 'url_save' => psm_build_url(array( + 'mod' => 'user', + 'action' => 'save', + 'id' => $user_id, + )), + 'servers' => $this->servers, + 'user_level' => $lvl_selected, + ); + foreach ($fields_prefill as $field) { + if (isset($edit_user->$field)) { + $tpl_data['edit_value_' . $field] = $edit_user->$field; + } + } - $tpl_data['levels'] = array(); - foreach ($this->container->get('util.user.validator')->getUserLevels() as $lvl) { - $tpl_data['levels'][] = array( - 'value' => $lvl, - 'label' => psm_get_lang('users', 'level_'.$lvl), - ); - } + $tpl_data['levels'] = array(); + foreach ($this->container->get('util.user.validator')->getUserLevels() as $lvl) { + $tpl_data['levels'][] = array( + 'value' => $lvl, + 'label' => psm_get_lang('users', 'level_' . $lvl), + ); + } - $tpl_data = array_merge($this->getLabels(), $tpl_data); + $tpl_data = array_merge($this->getLabels(), $tpl_data); - return $this->twig->render('module/user/user/update.tpl.html', $tpl_data); - } + return $this->twig->render('module/user/user/update.tpl.html', $tpl_data); + } - /** - * Executes the saving of a user - */ - protected function executeSave() { - if (empty($_POST)) { - // dont process anything if no data has been posted - return $this->executeIndex(); - } - $user_id = (isset($_GET['id'])) ? intval($_GET['id']) : 0; + /** + * Executes the saving of a user + */ + protected function executeSave() + { + if (empty($_POST)) { + // dont process anything if no data has been posted + return $this->executeIndex(); + } + $user_id = (isset($_GET['id'])) ? intval($_GET['id']) : 0; - $fields = array('name', 'user_name', 'password', 'password_repeat', 'level', 'mobile', 'pushover_key', 'pushover_device', 'telegram_id', 'email'); - $clean = array(); - foreach ($fields as $field) { - if (isset($_POST[$field])) { - $clean[$field] = trim(strip_tags($_POST[$field])); - } else { - $clean[$field] = ''; - } - } + $fields = array( + 'name', + 'user_name', + 'password', + 'password_repeat', + 'level', + 'mobile', + 'pushover_key', + 'pushover_device', + 'telegram_id', + 'email' + ); + $clean = array(); + foreach ($fields as $field) { + if (isset($_POST[$field])) { + $clean[$field] = trim(strip_tags($_POST[$field])); + } else { + $clean[$field] = ''; + } + } - $user_validator = $this->container->get('util.user.validator'); + $user_validator = $this->container->get('util.user.validator'); - try { - $user_validator->username($clean['user_name'], $user_id); - $user_validator->email($clean['email']); - $user_validator->level($clean['level']); - if(count($this->db->select(PSM_DB_PREFIX.'users', array('level' => PSM_USER_ADMIN))) == 1 && - $this->getUser()->getUserLevel() == PSM_USER_ADMIN) { - $this->addMessage(psm_get_lang('users', 'error_user_admin_cant_be_deleted'), 'warning'); - $clean['level'] = PSM_USER_ADMIN; - } + try { + $user_validator->username($clean['user_name'], $user_id); + $user_validator->email($clean['email']); + $user_validator->level($clean['level']); + if ( + count($this->db->select(PSM_DB_PREFIX . 'users', array('level' => PSM_USER_ADMIN))) == 1 && + $this->getUser()->getUserLevel() == PSM_USER_ADMIN + ) { + $this->addMessage(psm_get_lang('users', 'error_user_admin_cant_be_deleted'), 'warning'); + $clean['level'] = PSM_USER_ADMIN; + } - // always validate password for new users, - // but only validate it for existing users when they change it. - if ($user_id == 0 || ($user_id > 0 && $clean['password'] != '')) { - $user_validator->password($clean['password'], $clean['password_repeat']); - } - if ($user_id > 0) { - $user_validator->userId($user_id); - } - } catch (\InvalidArgumentException $e) { - $this->addMessage(psm_get_lang('users', 'error_'.$e->getMessage()), 'error'); - return $this->executeEdit(); - } - if (!empty($clean['password'])) { - $password = $clean['password']; - } - unset($clean['password_repeat']); + // always validate password for new users, + // but only validate it for existing users when they change it. + if ($user_id == 0 || ($user_id > 0 && $clean['password'] != '')) { + $user_validator->password($clean['password'], $clean['password_repeat']); + } + if ($user_id > 0) { + $user_validator->userId($user_id); + } + } catch (\InvalidArgumentException $e) { + $this->addMessage(psm_get_lang('users', 'error_' . $e->getMessage()), 'error'); + return $this->executeEdit(); + } + if (!empty($clean['password'])) { + $password = $clean['password']; + } + unset($clean['password_repeat']); - if ($user_id > 0) { - // edit user - unset($clean['password']); // password update is executed separately - $this->db->save(PSM_DB_PREFIX.'users', $clean, array('user_id' => $user_id)); - $this->addMessage(psm_get_lang('users', 'updated'), 'success'); + if ($user_id > 0) { + // edit user + unset($clean['password']); // password update is executed separately + $this->db->save(PSM_DB_PREFIX . 'users', $clean, array('user_id' => $user_id)); + $this->addMessage(psm_get_lang('users', 'updated'), 'success'); - $event = \psm\Module\User\UserEvents::USER_EDIT; - } else { - // add user - $clean['password'] = ''; // password update is executed separately - $user_id = $this->db->save(PSM_DB_PREFIX.'users', $clean); - $this->addMessage(psm_get_lang('users', 'inserted'), 'success'); + $event = \psm\Module\User\UserEvents::USER_EDIT; + } else { + // add user + $clean['password'] = ''; // password update is executed separately + $user_id = $this->db->save(PSM_DB_PREFIX . 'users', $clean); + $this->addMessage(psm_get_lang('users', 'inserted'), 'success'); - $event = \psm\Module\User\UserEvents::USER_ADD; - } - $this->container->get('event')->dispatch( - $event, - new \psm\Module\User\Event\UserEvent($user_id, $this->getUser()->getUserId()) - ); - if (isset($password)) { - $this->getUser()->changePassword($user_id, $password); - } + $event = \psm\Module\User\UserEvents::USER_ADD; + } + $this->container->get('event')->dispatch( + $event, + new \psm\Module\User\Event\UserEvent($user_id, $this->getUser()->getUserId()) + ); + if (isset($password)) { + $this->getUser()->changePassword($user_id, $password); + } - // update servers - $server_idc = psm_POST('server_id', array()); - $server_idc_save = array(); + // update servers + $server_idc = psm_POST('server_id', array()); + $server_idc_save = array(); - foreach ($server_idc as $server_id) { - $server_idc_save[] = array( - 'user_id' => $user_id, - 'server_id' => intval($server_id), - ); - } - // delete all existing records - $this->db->delete(PSM_DB_PREFIX.'users_servers', array('user_id' => $user_id)); - if (!empty($server_idc_save)) { - // add all new servers - $this->db->insertMultiple(PSM_DB_PREFIX.'users_servers', $server_idc_save); - } + foreach ($server_idc as $server_id) { + $server_idc_save[] = array( + 'user_id' => $user_id, + 'server_id' => intval($server_id), + ); + } + // delete all existing records + $this->db->delete(PSM_DB_PREFIX . 'users_servers', array('user_id' => $user_id)); + if (!empty($server_idc_save)) { + // add all new servers + $this->db->insertMultiple(PSM_DB_PREFIX . 'users_servers', $server_idc_save); + } - return $this->executeIndex(); - } + return $this->executeIndex(); + } - /** - * Executes the deletion of a user - */ - protected function executeDelete() { - $id = (isset($_GET['id'])) ? intval($_GET['id']) : 0; + /** + * Executes the deletion of a user + */ + protected function executeDelete() + { + $id = (isset($_GET['id'])) ? intval($_GET['id']) : 0; - try { - $this->container->get('util.user.validator')->userId($id); + try { + $this->container->get('util.user.validator')->userId($id); - if(count($this->db->select(PSM_DB_PREFIX.'users', array('level' => PSM_USER_ADMIN))) == 1) { - $this->addMessage(psm_get_lang('users', 'error_user_admin_cant_be_deleted'), 'error'); - } else { - $this->db->delete(PSM_DB_PREFIX.'users', array('user_id' => $id,)); - $this->db->delete(PSM_DB_PREFIX.'users_servers', array('user_id' => $id)); + if (count($this->db->select(PSM_DB_PREFIX . 'users', array('level' => PSM_USER_ADMIN))) == 1) { + $this->addMessage(psm_get_lang('users', 'error_user_admin_cant_be_deleted'), 'error'); + } else { + $this->db->delete(PSM_DB_PREFIX . 'users', array('user_id' => $id,)); + $this->db->delete(PSM_DB_PREFIX . 'users_servers', array('user_id' => $id)); - $this->container->get('event')->dispatch( - \psm\Module\User\UserEvents::USER_DELETE, - new \psm\Module\User\Event\UserEvent($id, $this->getUser()->getUserId()) - ); + $this->container->get('event')->dispatch( + \psm\Module\User\UserEvents::USER_DELETE, + new \psm\Module\User\Event\UserEvent($id, $this->getUser()->getUserId()) + ); - $this->addMessage(psm_get_lang('users', 'deleted'), 'success'); - } - } catch (\InvalidArgumentException $e) { - $this->addMessage(psm_get_lang('users', 'error_'.$e->getMessage()), 'error'); - } + $this->addMessage(psm_get_lang('users', 'deleted'), 'success'); + } + } catch (\InvalidArgumentException $e) { + $this->addMessage(psm_get_lang('users', 'error_' . $e->getMessage()), 'error'); + } - return $this->executeIndex(); - } + return $this->executeIndex(); + } - protected function getLabels() { - return array( - 'label_users' => psm_get_lang('menu', 'user'), - 'label_user' => psm_get_lang('users', 'user'), - 'label_name' => psm_get_lang('users', 'name'), - 'label_user_name' => psm_get_lang('users', 'user_name'), - 'label_password' => psm_get_lang('users', 'password'), - 'label_password_repeat' => psm_get_lang('users', 'password_repeat'), - 'label_level' => psm_get_lang('users', 'level'), - 'label_level_description' => psm_get_lang('users', 'level_description'), - 'label_mobile' => psm_get_lang('users', 'mobile'), - 'label_pushover' => psm_get_lang('users', 'pushover'), - 'label_pushover_description' => psm_get_lang('users', 'pushover_description'), - 'label_pushover_key' => psm_get_lang('users', 'pushover_key'), - 'label_pushover_device' => psm_get_lang('users', 'pushover_device'), - 'label_pushover_device_description' => psm_get_lang('users', 'pushover_device_description'), - 'label_telegram' => psm_get_lang('users', 'telegram'), - 'label_telegram_description' => psm_get_lang('users', 'telegram_description'), - 'label_telegram_id' => psm_get_lang('users', 'telegram_chat_id'), - 'label_telegram_id_description' => psm_get_lang('users', 'telegram_chat_id_description'), - 'label_email' => psm_get_lang('users', 'email'), - 'label_servers' => psm_get_lang('menu', 'server'), - 'label_save' => psm_get_lang('system', 'save'), - 'label_go_back' => psm_get_lang('system', 'go_back'), - 'label_edit' => psm_get_lang('system', 'edit'), - 'label_delete' => psm_get_lang('system', 'delete'), - 'label_add_new' => psm_get_lang('system', 'add_new'), - 'label_search' => psm_get_lang('system', 'search'), - ); - } + protected function getLabels() + { + return array( + 'label_users' => psm_get_lang('menu', 'user'), + 'label_user' => psm_get_lang('users', 'user'), + 'label_name' => psm_get_lang('users', 'name'), + 'label_user_name' => psm_get_lang('users', 'user_name'), + 'label_password' => psm_get_lang('users', 'password'), + 'label_password_repeat' => psm_get_lang('users', 'password_repeat'), + 'label_level' => psm_get_lang('users', 'level'), + 'label_level_description' => psm_get_lang('users', 'level_description'), + 'label_mobile' => psm_get_lang('users', 'mobile'), + 'label_pushover' => psm_get_lang('users', 'pushover'), + 'label_pushover_description' => psm_get_lang('users', 'pushover_description'), + 'label_pushover_key' => psm_get_lang('users', 'pushover_key'), + 'label_pushover_device' => psm_get_lang('users', 'pushover_device'), + 'label_pushover_device_description' => psm_get_lang('users', 'pushover_device_description'), + 'label_telegram' => psm_get_lang('users', 'telegram'), + 'label_telegram_description' => psm_get_lang('users', 'telegram_description'), + 'label_telegram_id' => psm_get_lang('users', 'telegram_chat_id'), + 'label_telegram_id_description' => psm_get_lang('users', 'telegram_chat_id_description'), + 'label_email' => psm_get_lang('users', 'email'), + 'label_servers' => psm_get_lang('menu', 'server'), + 'label_save' => psm_get_lang('system', 'save'), + 'label_go_back' => psm_get_lang('system', 'go_back'), + 'label_edit' => psm_get_lang('system', 'edit'), + 'label_delete' => psm_get_lang('system', 'delete'), + 'label_add_new' => psm_get_lang('system', 'add_new'), + 'label_search' => psm_get_lang('system', 'search'), + ); + } - /** - * Get all server ids for a user - * @param int $user_id - * @return array with ids only - * @todo we should probably find a central place for this kind of stuff - */ - protected function getUserServers($user_id) { - $servers = $this->db->select( - PSM_DB_PREFIX.'users_servers', - array('user_id' => $user_id), - array('server_id') - ); - $result = array(); - foreach ($servers as $server) { - $result[] = $server['server_id']; - } - return $result; - } + /** + * Get all server ids for a user + * @param int $user_id + * @return array with ids only + * @todo we should probably find a central place for this kind of stuff + */ + protected function getUserServers($user_id) + { + $servers = $this->db->select( + PSM_DB_PREFIX . 'users_servers', + array('user_id' => $user_id), + array('server_id') + ); + $result = array(); + foreach ($servers as $server) { + $result[] = $server['server_id']; + } + return $result; + } } diff --git a/src/psm/Module/User/Event/UserEvent.php b/src/psm/Module/User/Event/UserEvent.php index 44cdfee0..9bf14d1a 100644 --- a/src/psm/Module/User/Event/UserEvent.php +++ b/src/psm/Module/User/Event/UserEvent.php @@ -1,4 +1,5 @@ user_id = $user_id; - $this->user_id_by = $user_id_by; - } + public function __construct($user_id, $user_id_by = null) + { + $this->user_id = $user_id; + $this->user_id_by = $user_id_by; + } - public function getUserId() { - return $this->user_id; - } + public function getUserId() + { + return $this->user_id; + } - public function getUserIdBy() { - return $this->user_id_by; - } -} \ No newline at end of file + public function getUserIdBy() + { + return $this->user_id_by; + } +} diff --git a/src/psm/Module/User/EventListener/UserSubscriber.php b/src/psm/Module/User/EventListener/UserSubscriber.php index 34ec5183..080bfec3 100644 --- a/src/psm/Module/User/EventListener/UserSubscriber.php +++ b/src/psm/Module/User/EventListener/UserSubscriber.php @@ -1,4 +1,5 @@ array('onUserAdd', 0), - UserEvents::USER_EDIT => array('onUserEdit', 0), - UserEvents::USER_DELETE => array('onUserDelete', 0), - ); - } + public static function getSubscribedEvents() + { + return array( + UserEvents::USER_ADD => array('onUserAdd', 0), + UserEvents::USER_EDIT => array('onUserEdit', 0), + UserEvents::USER_DELETE => array('onUserDelete', 0), + ); + } - public function onUserAdd(UserEvent $event) { - } + public function onUserAdd(UserEvent $event) + { + } - public function onUserEdit(UserEvent $event) { - } + public function onUserEdit(UserEvent $event) + { + } - public function onUserDelete(UserEvent $event) { - } -} \ No newline at end of file + public function onUserDelete(UserEvent $event) + { + } +} diff --git a/src/psm/Module/User/UserEvents.php b/src/psm/Module/User/UserEvents.php index f0816551..33767928 100644 --- a/src/psm/Module/User/UserEvents.php +++ b/src/psm/Module/User/UserEvents.php @@ -1,4 +1,5 @@ get('event'); - $event->addSubscriber(new EventListener\UserSubscriber); - } + public function load(ContainerBuilder $container) + { + $event = $container->get('event'); + $event->addSubscriber(new EventListener\UserSubscriber()); + } - public function getControllers() { - return array( - 'user' => __NAMESPACE__.'\Controller\UserController', - 'login' => __NAMESPACE__.'\Controller\LoginController', - 'profile' => __NAMESPACE__.'\Controller\ProfileController', - ); - - } -} \ No newline at end of file + public function getControllers() + { + return array( + 'user' => __NAMESPACE__ . '\Controller\UserController', + 'login' => __NAMESPACE__ . '\Controller\LoginController', + 'profile' => __NAMESPACE__ . '\Controller\ProfileController', + ); + } +} diff --git a/src/psm/Router.php b/src/psm/Router.php index 140d95fb..41533989 100644 --- a/src/psm/Router.php +++ b/src/psm/Router.php @@ -1,4 +1,5 @@ container = $this->buildServiceContainer(); + public function __construct() + { + $this->container = $this->buildServiceContainer(); - $mods = $this->container->getParameter('modules'); + $mods = $this->container->getParameter('modules'); - foreach ($mods as $mod) { - $mod_loader = $this->container->get($mod); - $mod_loader->load($this->container); - } - } + foreach ($mods as $mod) { + $mod_loader = $this->container->get($mod); + $mod_loader->load($this->container); + } + } - /** - * Run a module. - * - * The $mod param is in the format $module_$controller. - * If the "_$controller" part is omitted, it will attempt to load - * the controller with the same name as the module. - * - * @param string $mod - * @throws \InvalidArgumentException - * @throws \LogicException - */ - public function run($mod) { - if (strpos($mod, '_') !== false) { - list($mod, $controller) = explode('_', $mod); - } else { - $controller = $mod; - } - $this->buildTwigEnvironment(); + /** + * Run a module. + * + * The $mod param is in the format $module_$controller. + * If the "_$controller" part is omitted, it will attempt to load + * the controller with the same name as the module. + * + * @param string $mod + * @throws \InvalidArgumentException + * @throws \LogicException + */ + public function run($mod) + { + if (strpos($mod, '_') !== false) { + list($mod, $controller) = explode('_', $mod); + } else { + $controller = $mod; + } + $this->buildTwigEnvironment(); - $controller = $this->getController($mod, $controller); - $action = null; + $controller = $this->getController($mod, $controller); + $action = null; - try { - $this->validateRequest($controller); - } catch (\InvalidArgumentException $ex) { - switch ($ex->getMessage()) { - case 'login_required': - $controller = $this->getController('user', 'login'); - break; - case 'invalid_csrf_token': - case 'invalid_user_level': - default: - $controller = $this->getController('error'); - $action = '401'; - break; - } - } + try { + $this->validateRequest($controller); + } catch (\InvalidArgumentException $ex) { + switch ($ex->getMessage()) { + case 'login_required': + $controller = $this->getController('user', 'login'); + break; + case 'invalid_csrf_token': + case 'invalid_user_level': + default: + $controller = $this->getController('error'); + $action = '401'; + break; + } + } - $response = $controller->run($action); + $response = $controller->run($action); - if (!($response instanceof Response)) { - throw new \LogicException('Controller did not return a Response object.'); - } - $response->send(); - } + if (!($response instanceof Response)) { + throw new \LogicException('Controller did not return a Response object.'); + } + $response->send(); + } - /** - * Get an instance of the requested controller. - * @param string $module_id - * @param string $controller_id if NULL, default controller will be used - * @return \psm\Module\ControllerInterface - * @throws \InvalidArgumentException - */ - public function getController($module_id, $controller_id = null) { - if ($controller_id === null) { - // by default, we use the controller with the same id as the module. - $controller_id = $module_id; - } + /** + * Get an instance of the requested controller. + * @param string $module_id + * @param string $controller_id if NULL, default controller will be used + * @return \psm\Module\ControllerInterface + * @throws \InvalidArgumentException + */ + public function getController($module_id, $controller_id = null) + { + if ($controller_id === null) { + // by default, we use the controller with the same id as the module. + $controller_id = $module_id; + } - $module = $this->container->get('module.'.$module_id); - $controllers = $module->getControllers(); - if (!isset($controllers[$controller_id]) || !class_exists($controllers[$controller_id])) { - throw new \InvalidArgumentException('Controller "'.$controller_id.'" is not registered or does not exist.'); - } - $controller = new $controllers[$controller_id]( - $this->container->get('db'), - $this->container->get('twig') - ); + $module = $this->container->get('module.' . $module_id); + $controllers = $module->getControllers(); + if (!isset($controllers[$controller_id]) || !class_exists($controllers[$controller_id])) { + throw new \InvalidArgumentException('Controller "' . $controller_id . '" + is not registered or does not exist.'); + } + $controller = new $controllers[$controller_id]( + $this->container->get('db'), + $this->container->get('twig') + ); - if (!$controller instanceof \psm\Module\ControllerInterface) { - throw new \Exception('Controller does not implement ControllerInterface'); - } - $controller->setContainer($this->container); + if (!$controller instanceof \psm\Module\ControllerInterface) { + throw new \Exception('Controller does not implement ControllerInterface'); + } + $controller->setContainer($this->container); - return $controller; - } + return $controller; + } - /** - * Get service from container - * @param string $id - * @return mixed FALSE on failure, service otherwise - * @throws \InvalidArgumentException - */ - public function getService($id) { - return $this->container->get($id); - } + /** + * Get service from container + * @param string $id + * @return mixed FALSE on failure, service otherwise + * @throws \InvalidArgumentException + */ + public function getService($id) + { + return $this->container->get($id); + } - /** - * Validate requets before heading to a controller - * @param \psm\Module\ControllerInterface $controller - * @throws \InvalidArgumentException - */ - protected function validateRequest(\psm\Module\ControllerInterface $controller) { - $request = Request::createFromGlobals(); + /** + * Validate requets before heading to a controller + * @param \psm\Module\ControllerInterface $controller + * @throws \InvalidArgumentException + */ + protected function validateRequest(\psm\Module\ControllerInterface $controller) + { + $request = Request::createFromGlobals(); - if ($request->getMethod() == 'POST') { - // require CSRF token for all POST calls - $session = $this->container->get('user')->getSession(); - $token_in = $request->request->get('csrf', ''); - $csrf_key = $controller->getCSRFKey(); + if ($request->getMethod() == 'POST') { + // require CSRF token for all POST calls + $session = $this->container->get('user')->getSession(); + $token_in = $request->request->get('csrf', ''); + $csrf_key = $controller->getCSRFKey(); - if (empty($csrf_key)) { - if (!hash_equals($session->get('csrf_token'), $token_in)) { - throw new \InvalidArgumentException('invalid_csrf_token'); - } - } else { - if (!hash_equals( - hash_hmac('sha256', $csrf_key, $session->get('csrf_token2')), - $token_in - )) { - throw new \InvalidArgumentException('invalid_csrf_token'); - } - } - } + if (empty($csrf_key)) { + if (!hash_equals($session->get('csrf_token'), $token_in)) { + throw new \InvalidArgumentException('invalid_csrf_token'); + } + } else { + if ( + !hash_equals( + hash_hmac('sha256', $csrf_key, $session->get('csrf_token2')), + $token_in + ) + ) { + throw new \InvalidArgumentException('invalid_csrf_token'); + } + } + } - // get min required level for this controller and make sure the user matches - $min_lvl = $controller->getMinUserLevelRequired(); + // get min required level for this controller and make sure the user matches + $min_lvl = $controller->getMinUserLevelRequired(); - if ($min_lvl < PSM_USER_ANONYMOUS) { - // if user is not logged in, load login module - if (!$this->container->get('user')->isUserLoggedIn()) { - throw new \InvalidArgumentException('login_required'); - } elseif ($this->container->get('user')->getUserLevel() > $min_lvl) { - throw new \InvalidArgumentException('invalid_user_level'); - } - } - } + if ($min_lvl < PSM_USER_ANONYMOUS) { + // if user is not logged in, load login module + if (!$this->container->get('user')->isUserLoggedIn()) { + throw new \InvalidArgumentException('login_required'); + } elseif ($this->container->get('user')->getUserLevel() > $min_lvl) { + throw new \InvalidArgumentException('invalid_user_level'); + } + } + } - /** - * Build a new service container - * @return \Symfony\Component\DependencyInjection\ContainerBuilder - * @throws \InvalidArgumentException - */ - protected function buildServiceContainer() { - $builder = new ContainerBuilder(); - $loader = new XmlFileLoader($builder, new FileLocator(PSM_PATH_CONFIG)); - $loader->load('services.xml'); + /** + * Build a new service container + * @return \Symfony\Component\DependencyInjection\ContainerBuilder + * @throws \InvalidArgumentException + */ + protected function buildServiceContainer() + { + $builder = new ContainerBuilder(); + $loader = new XmlFileLoader($builder, new FileLocator(PSM_PATH_CONFIG)); + $loader->load('services.xml'); - return $builder; - } + return $builder; + } - /** - * Prepare twig environment - * @return \Twig_Environment - */ - protected function buildTwigEnvironment() { - $twig = $this->container->get('twig'); - $session = $this->container->get('user')->getSession(); - if (!$session->has('csrf_token')) { - $session->set('csrf_token', bin2hex(random_bytes(32))); - } - if (!$session->has('csrf_token2')) { - $session->set('csrf_token2', random_bytes(32)); - } + /** + * Prepare twig environment + * @return \Twig_Environment + */ + protected function buildTwigEnvironment() + { + $twig = $this->container->get('twig'); + $session = $this->container->get('user')->getSession(); + if (!$session->has('csrf_token')) { + $session->set('csrf_token', bin2hex(random_bytes(32))); + } + if (!$session->has('csrf_token2')) { + $session->set('csrf_token2', random_bytes(32)); + } - $twig->addFunction( - new \Twig_SimpleFunction( - 'csrf_token', - function($lock_to = null) use ($session) { - if (empty($lock_to)) { - return $session->get('csrf_token'); - } - return hash_hmac('sha256', $lock_to, $session->get('csrf_token2')); - } - ) - ); - $twig->addGlobal('direction_current', psm_get_lang('locale_dir')); - $twig->addGlobal('language_current', psm_get_lang('locale_tag')); - $twig->addGlobal('language', psm_get_lang('locale')[1]); + $twig->addFunction( + new \Twig_SimpleFunction( + 'csrf_token', + function ($lock_to = null) use ($session) { + if (empty($lock_to)) { + return $session->get('csrf_token'); + } + return hash_hmac('sha256', $lock_to, $session->get('csrf_token2')); + } + ) + ); + $twig->addGlobal('direction_current', psm_get_lang('locale_dir')); + $twig->addGlobal('language_current', psm_get_lang('locale_tag')); + $twig->addGlobal('language', psm_get_lang('locale')[1]); - return $twig; - } -} \ No newline at end of file + return $twig; + } +} diff --git a/src/psm/Service/Database.php b/src/psm/Service/Database.php index 82aaca68..5d69dd55 100644 --- a/src/psm/Service/Database.php +++ b/src/psm/Service/Database.php @@ -1,4 +1,5 @@ db_host = $host; - $this->db_port = $port; - $this->db_name = $db; - $this->db_user = $user; - $this->db_pass = $pass; - $this->connect(); - } - } + /** + * Constructor + * + * @param string $host + * @param string $user + * @param string $pass + * @param string $db + * @param string|integer $port + */ + public function __construct($host = null, $user = null, $pass = null, $db = null, $port = '') + { + if ($host != null && $user != null && $pass !== null && $db != null) { + $this->db_host = $host; + $this->db_port = $port; + $this->db_name = $db; + $this->db_user = $user; + $this->db_pass = $pass; + $this->connect(); + } + } - /** - * Exectues query and fetches result. - * - * If you dont want to fetch a result, use exec(). - * @param string $query SQL query - * @param boolean $fetch automatically fetch results, or return PDOStatement? - * @return \PDOStatement|int|bool|array object - */ - public function query($query, $fetch = true) { - // Execute query and process results - try { - $this->last = $this->pdo()->query($query); - } catch (\PDOException $e) { - $this->error($e); - } + /** + * Exectues query and fetches result. + * + * If you dont want to fetch a result, use exec(). + * @param string $query SQL query + * @param boolean $fetch automatically fetch results, or return PDOStatement? + * @return \PDOStatement|int|bool|array object + */ + public function query($query, $fetch = true) + { + // Execute query and process results + try { + $this->last = $this->pdo()->query($query); + } catch (\PDOException $e) { + $this->error($e); + } - if ($fetch && $this->last != false) { - $cmd = strtolower(substr($query, 0, 6)); + if ($fetch && $this->last != false) { + $cmd = strtolower(substr($query, 0, 6)); - switch ($cmd) { - case 'insert': - // insert query, return insert id - $result = $this->getLastInsertedId(); - break; - case 'update': - case 'delete': - // update/delete, returns rowCount - $result = $this->getNumRows(); - break; - default: - $result = $this->last->fetchAll(\PDO::FETCH_ASSOC); - break; - } - } else { - $result = $this->last; - } - return $result; - } + switch ($cmd) { + case 'insert': + // insert query, return insert id + $result = $this->getLastInsertedId(); + break; + case 'update': + case 'delete': + // update/delete, returns rowCount + $result = $this->getNumRows(); + break; + default: + $result = $this->last->fetchAll(\PDO::FETCH_ASSOC); + break; + } + } else { + $result = $this->last; + } + return $result; + } - /** - * Execute SQL statement and return number of affected rows - * @param string $query - * @return int - */ - public function exec($query) { - try { - $this->last = $this->pdo()->exec($query); - } catch (\PDOException $e) { - $this->error($e); - } + /** + * Execute SQL statement and return number of affected rows + * @param string $query + * @return int + */ + public function exec($query) + { + try { + $this->last = $this->pdo()->exec($query); + } catch (\PDOException $e) { + $this->error($e); + } - return $this->last; - } + return $this->last; + } - /** - * Prepare and execute SQL statement with parameters - * @param string $query SQL statement - * @param array $parameters An array of values with as many elements as there are bound parameters in the SQL statement - * @param boolean $fetch automatically fetch results, or return PDOStatement? - * @return array|\PDOStatement if $fetch = true, array, otherwise \PDOStatement - */ - public function execute($query, $parameters, $fetch = true) { - try { - $this->last = $this->pdo()->prepare($query); - $this->last->execute($parameters); - } catch (\PDOException $e) { - $this->error($e); - } + /** + * Prepare and execute SQL statement with parameters + * @param string $query SQL statement + * @param array $parameters An array of values with as many elements as there are + * bound parameters in the SQL statement + * @param boolean $fetch automatically fetch results, or return PDOStatement? + * @return array|\PDOStatement if $fetch = true, array, otherwise \PDOStatement + */ + public function execute($query, $parameters, $fetch = true) + { + try { + $this->last = $this->pdo()->prepare($query); + $this->last->execute($parameters); + } catch (\PDOException $e) { + $this->error($e); + } - if ($fetch && $this->last != false) { - $result = $this->last->fetchAll(\PDO::FETCH_ASSOC); - } else { - $result = $this->last; - } - return $result; - } + if ($fetch && $this->last != false) { + $result = $this->last->fetchAll(\PDO::FETCH_ASSOC); + } else { + $result = $this->last; + } + return $result; + } - /** - * Performs a select on the given table and returns an multi dimensional associative array with results - * @param string $table tablename - * @param mixed $where string or array with where data - * @param array $fields array with fields to be retrieved. if empty all fields will be retrieved - * @param string $limit limit. for example: 0,30 - * @param array $orderby fields for the orderby clause - * @param string $direction ASC or DESC. Defaults to ASC - * @return \PDOStatement array multi dimensional array with results - */ - public function select($table, $where = null, $fields = null, $limit = '', $orderby = null, $direction = 'ASC') { - // build query - $query_parts = array(); - $query_parts[] = 'SELECT SQL_CALC_FOUND_ROWS'; + /** + * Performs a select on the given table and returns an multi dimensional associative array with results + * @param string $table tablename + * @param mixed $where string or array with where data + * @param array $fields array with fields to be retrieved. if empty all fields will be retrieved + * @param string $limit limit. for example: 0,30 + * @param array $orderby fields for the orderby clause + * @param string $direction ASC or DESC. Defaults to ASC + * @return \PDOStatement array multi dimensional array with results + */ + public function select($table, $where = null, $fields = null, $limit = '', $orderby = null, $direction = 'ASC') + { + // build query + $query_parts = array(); + $query_parts[] = 'SELECT SQL_CALC_FOUND_ROWS'; - // Fields - if ($fields !== null && !empty($fields)) { - $query_parts[] = "`".implode('`,`', $fields)."`"; - } else { - $query_parts[] = ' * '; - } + // Fields + if ($fields !== null && !empty($fields)) { + $query_parts[] = "`" . implode('`,`', $fields) . "`"; + } else { + $query_parts[] = ' * '; + } - // From - $query_parts[] = "FROM `{$table}`"; + // From + $query_parts[] = "FROM `{$table}`"; - // Where clause - $query_parts[] = $this->buildSQLClauseWhere($table, $where); + // Where clause + $query_parts[] = $this->buildSQLClauseWhere($table, $where); - // Order by - if ($orderby) { - $query_parts[] = $this->buildSQLClauseOrderBy($orderby, $direction); - } + // Order by + if ($orderby) { + $query_parts[] = $this->buildSQLClauseOrderBy($orderby, $direction); + } - // Limit - if ($limit != '') { - $query_parts[] = 'LIMIT '.$limit; - } + // Limit + if ($limit != '') { + $query_parts[] = 'LIMIT ' . $limit; + } - $query = implode(' ', $query_parts); + $query = implode(' ', $query_parts); - return $this->query($query); - } + return $this->query($query); + } - /** - * Alias to select() but uses limit = 1 to return only one row. - * @param string $table tablename - * @param mixed $where string or array with where data - * @param array $fields array with fields to be retrieved. if empty all fields will be retrieved - * @param array $orderby fields for the orderby clause - * @param string $direction ASC or DESC. Defaults to ASC - * @return array - */ - public function selectRow($table, $where = null, $fields = null, $orderby = null, $direction = 'ASC') { - $result = $this->select($table, $where, $fields, '1', $orderby, $direction); + /** + * Alias to select() but uses limit = 1 to return only one row. + * @param string $table tablename + * @param mixed $where string or array with where data + * @param array $fields array with fields to be retrieved. if empty all fields will be retrieved + * @param array $orderby fields for the orderby clause + * @param string $direction ASC or DESC. Defaults to ASC + * @return array + */ + public function selectRow($table, $where = null, $fields = null, $orderby = null, $direction = 'ASC') + { + $result = $this->select($table, $where, $fields, '1', $orderby, $direction); - if (isset($result[0])) { - $result = $result[0]; - } + if (isset($result[0])) { + $result = $result[0]; + } - return $result; - } + return $result; + } - /** - * Remove a record from database - * @param string $table tablename - * @param mixed $where Where clause array or primary Id (string) or where clause (string) - * @return int number of affected rows - */ - public function delete($table, $where = null) { - $sql = 'DELETE FROM `'.$table.'` '.$this->buildSQLClauseWhere($table, $where); + /** + * Remove a record from database + * @param string $table tablename + * @param mixed $where Where clause array or primary Id (string) or where clause (string) + * @return int number of affected rows + */ + public function delete($table, $where = null) + { + $sql = 'DELETE FROM `' . $table . '` ' . $this->buildSQLClauseWhere($table, $where); - return $this->exec($sql); - } + return $this->exec($sql); + } - /** - * Insert or update data to the database - * @param string $table table name - * @param array $data data to save or insert - * @param string|array $where either string ('user_id=2' or just '2' (works only with primary field)) or array with where clause (only when updating) - * @return int|array|\PDOStatement - */ - public function save($table, array $data, $where = null) { - if ($where === null) { - // insert mode - $query = "INSERT INTO "; - $exec = false; - } else { - $query = "UPDATE "; - $exec = true; - } + /** + * Insert or update data to the database + * @param string $table table name + * @param array $data data to save or insert + * @param string|array $where either string ('user_id=2' or just '2' (works only with primary field)) or + * array with where clause (only when updating) + * @return int|array|\PDOStatement + */ + public function save($table, array $data, $where = null) + { + if ($where === null) { + // insert mode + $query = "INSERT INTO "; + $exec = false; + } else { + $query = "UPDATE "; + $exec = true; + } - $query .= "`{$table}` SET "; + $query .= "`{$table}` SET "; - foreach ($data as $field => $value) { - if (is_null($value)) { - $value = 'NULL'; - } else { - $value = $this->quote($value); - } - $query .= "`{$table}`.`{$field}`={$value}, "; - } + foreach ($data as $field => $value) { + if (is_null($value)) { + $value = 'NULL'; + } else { + $value = $this->quote($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) { - return $this->exec($query); - } - return $this->query($query); - } + if ($exec) { + return $this->exec($query); + } + return $this->query($query); + } - /** - * Insert multiple rows into a single table - * - * This method is preferred over calling the insert() lots of times - * so it can be optimized to be inserted with 1 query. - * It can only be used if all inserts have the same fields, records - * that do not match the fields provided in the first record will be - * skipped. - * - * @param string $table - * @param array $data - * @return \PDOStatement - * @see insert() - */ - public function insertMultiple($table, array $data) { - if (empty($data)) { - return false; - } + /** + * Insert multiple rows into a single table + * + * This method is preferred over calling the insert() lots of times + * so it can be optimized to be inserted with 1 query. + * It can only be used if all inserts have the same fields, records + * that do not match the fields provided in the first record will be + * skipped. + * + * @param string $table + * @param array $data + * @return \PDOStatement + * @see insert() + */ + public function insertMultiple($table, array $data) + { + if (empty($data)) { + return false; + } - // prepare first part - $query = "INSERT INTO `{$table}` "; - $fields = array_keys($data[0]); - $query .= "(`".implode('`,`', $fields)."`) VALUES "; + // prepare first part + $query = "INSERT INTO `{$table}` "; + $fields = array_keys($data[0]); + $query .= "(`" . implode('`,`', $fields) . "`) VALUES "; - // prepare all rows to be inserted with placeholders for vars (\?) - $q_part = array_fill(0, count($fields), '?'); - $q_part = "(".implode(',', $q_part).")"; + // prepare all rows to be inserted with placeholders for vars (\?) + $q_part = array_fill(0, count($fields), '?'); + $q_part = "(" . implode(',', $q_part) . ")"; - $q_part = array_fill(0, count($data), $q_part); - $query .= implode(',', $q_part); + $q_part = array_fill(0, count($data), $q_part); + $query .= implode(',', $q_part); - $pst = $this->pdo()->prepare($query); + $pst = $this->pdo()->prepare($query); - $i = 1; - foreach ($data as $row) { - // make sure the fields of this row are identical to first row - $diff_keys = array_diff_key($fields, array_keys($row)); + $i = 1; + foreach ($data as $row) { + // make sure the fields of this row are identical to first row + $diff_keys = array_diff_key($fields, array_keys($row)); - if (!empty($diff_keys)) { - continue; - } - foreach ($fields as $field) { - $pst->bindParam($i++, $row[$field]); - } - } + if (!empty($diff_keys)) { + continue; + } + foreach ($fields as $field) { + $pst->bindParam($i++, $row[$field]); + } + } - try { - $this->last = $pst->execute(); - } catch (\PDOException $e) { - $this->error($e); - } - return $this->last; - } + try { + $this->last = $pst->execute(); + } catch (\PDOException $e) { + $this->error($e); + } + return $this->last; + } - /** - * Check if a certain table exists. - * @param string $table - * @return boolean - */ - public function ifTableExists($table) { - $table = $this->quote($table); - $db = $this->quote($this->getDbName()); + /** + * Check if a certain table exists. + * @param string $table + * @return boolean + */ + public function ifTableExists($table) + { + $table = $this->quote($table); + $db = $this->quote($this->getDbName()); - $if_exists = "SELECT COUNT(*) AS `cnt` + $if_exists = "SELECT COUNT(*) AS `cnt` FROM `information_schema`.`tables` WHERE `table_schema` = {$db} AND `table_name` = {$table}; "; - $if_exists = $this->query($if_exists); + $if_exists = $this->query($if_exists); - if (isset($if_exists[0]['cnt']) && $if_exists[0]['cnt'] == 1) { - return true; - } else { - false; - } - } + if (isset($if_exists[0]['cnt']) && $if_exists[0]['cnt'] == 1) { + return true; + } else { + false; + } + } - /** - * Quote a string - * @param string $value - * @return string - */ - public function quote($value) { - return $this->pdo()->quote($value); - } + /** + * Quote a string + * @param string $value + * @return string + */ + public function quote($value) + { + return $this->pdo()->quote($value); + } - /** - * Get the PDO object - * @return \PDO - */ - public function pdo() { - return $this->pdo; - } + /** + * Get the PDO object + * @return \PDO + */ + public function pdo() + { + return $this->pdo; + } - /** - * Get number of rows of last statement - * @return int number of rows - */ - public function getNumRows() { - return $this->last->rowCount(); - } + /** + * Get number of rows of last statement + * @return int number of rows + */ + public function getNumRows() + { + return $this->last->rowCount(); + } - /** - * Get the last inserted id after an insert - * @return int - */ - public function getLastInsertedId() { - return $this->pdo()->lastInsertId(); - } + /** + * Get the last inserted id after an insert + * @return int + */ + public function getLastInsertedId() + { + return $this->pdo()->lastInsertId(); + } - /** - * Build WHERE clause for query - * @param string $table table name - * @param mixed $where can be primary id (eg '2'), can be string (eg 'name=pepe') or can be array - * @return string sql where clause - * @see buildSQLClauseOrderBy() - */ - public function buildSQLClauseWhere($table, $where = null) { + /** + * Build WHERE clause for query + * @param string $table table name + * @param mixed $where can be primary id (eg '2'), can be string (eg 'name=pepe') or can be array + * @return string sql where clause + * @see buildSQLClauseOrderBy() + */ + public function buildSQLClauseWhere($table, $where = null) + { - $query = ''; + $query = ''; - if ($where !== null) { - if (is_array($where)) { - $query .= " WHERE "; + if ($where !== null) { + if (is_array($where)) { + $query .= " WHERE "; - foreach ($where as $field => $value) { - $query .= "`{$table}`.`{$field}`={$this->quote($value)} AND "; - } - $query = substr($query, 0, -5); - } else { - if (strpos($where, '=') === false) { - // no field given, use primary field - $primary = $this->getPrimary($table); - $query .= " WHERE `{$table}`.`{$primary}`={$this->quote($where)}"; - } elseif (strpos(strtolower(trim($where)), 'where') === false) { - $query .= " WHERE {$where}"; - } else { - $query .= ' '.$where; - } - } - } - return $query; - } + foreach ($where as $field => $value) { + $query .= "`{$table}`.`{$field}`={$this->quote($value)} AND "; + } + $query = substr($query, 0, -5); + } else { + if (strpos($where, '=') === false) { + // no field given, use primary field + $primary = $this->getPrimary($table); + $query .= " WHERE `{$table}`.`{$primary}`={$this->quote($where)}"; + } elseif (strpos(strtolower(trim($where)), 'where') === false) { + $query .= " WHERE {$where}"; + } else { + $query .= ' ' . $where; + } + } + } + return $query; + } - /** - * Build ORDER BY clause for a query - * @param mixed $order_by can be string (with or without order by) or array - * @param string $direction - * @return string sql order by clause - * @see buildSQLClauseWhere() - */ - public function buildSQLClauseOrderBy($order_by, $direction) { - $query = ''; + /** + * Build ORDER BY clause for a query + * @param mixed $order_by can be string (with or without order by) or array + * @param string $direction + * @return string sql order by clause + * @see buildSQLClauseWhere() + */ + public function buildSQLClauseOrderBy($order_by, $direction) + { + $query = ''; - if ($order_by !== null) { - if (is_array($order_by)) { - $query .= " ORDER BY "; + if ($order_by !== null) { + if (is_array($order_by)) { + $query .= " ORDER BY "; - foreach ($order_by as $field) { - $query .= "`{$field}`, "; - } - // remove trailing ", " - $query = substr($query, 0, -2); - } else { - if (strpos(strtolower(trim($order_by)), 'order by') === false) { - $query .= " ORDER BY {$order_by}"; - } else { - $query .= ' '.$order_by; - } - } - } - if (strlen($query) > 0) { - // check if "ASC" or "DESC" is already in the order by clause - if (strpos(strtolower(trim($query)), 'asc') === false && strpos(strtolower(trim($query)), 'desc') === false) { - $query .= ' '.$direction; - } - } + foreach ($order_by as $field) { + $query .= "`{$field}`, "; + } + // remove trailing ", " + $query = substr($query, 0, -2); + } else { + if (strpos(strtolower(trim($order_by)), 'order by') === false) { + $query .= " ORDER BY {$order_by}"; + } else { + $query .= ' ' . $order_by; + } + } + } + if (strlen($query) > 0) { + // check if "ASC" or "DESC" is already in the order by clause + if ( + strpos(strtolower(trim($query)), 'asc') === false && + strpos(strtolower(trim($query)), 'desc') === false + ) { + $query .= ' ' . $direction; + } + } - return $query; - } + return $query; + } - /** - * Get the host of the current connection - * @return string - */ - public function getDbHost() { - return $this->db_host; - } + /** + * Get the host of the current connection + * @return string + */ + public function getDbHost() + { + return $this->db_host; + } - /** - * Get the db name of the current connection - * @return string - */ - public function getDbName() { - return $this->db_name; - } + /** + * Get the db name of the current connection + * @return string + */ + public function getDbName() + { + return $this->db_name; + } - /** - * Get the db user of the current connection - * @return string - */ - public function getDbUser() { - return $this->db_user; - } + /** + * Get the db user of the current connection + * @return string + */ + public function getDbUser() + { + return $this->db_user; + } - /** - * Get status of the connection - * @return boolean - */ - public function status() { - return $this->status; - } + /** + * Get status of the connection + * @return boolean + */ + public function status() + { + return $this->status; + } - /** - * Connect to the database. - * - * @return resource mysql resource - */ - protected function connect() { - // Initizale connection - try { - $this->pdo = new \PDO( - 'mysql:host='.$this->db_host.';port='.$this->db_port.';dbname='.$this->db_name.';charset=utf8', - $this->db_user, - $this->db_pass - ); - $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); - $this->status = true; - } catch (\PDOException $e) { - $this->status = false; - return $this->onConnectFailure($e); - } - return $this->pdo; - } + /** + * Connect to the database. + * + * @return resource mysql resource + */ + protected function connect() + { + // Initizale connection + try { + $this->pdo = new \PDO( + 'mysql:host=' . $this->db_host . + ';port=' . $this->db_port . + ';dbname=' . $this->db_name . + ';charset=utf8', + $this->db_user, + $this->db_pass + ); + $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); + $this->status = true; + } catch (\PDOException $e) { + $this->status = false; + return $this->onConnectFailure($e); + } + return $this->pdo; + } - /** - * Is called after connection failure - */ - protected function onConnectFailure(\PDOException $e) { - trigger_error('MySQL connection failed: '.$e->getMessage(), E_USER_WARNING); - return false; - } + /** + * Is called after connection failure + */ + protected function onConnectFailure(\PDOException $e) + { + trigger_error('MySQL connection failed: ' . $e->getMessage(), E_USER_WARNING); + return false; + } - /** - * Disconnect from current link - */ - protected function disconnect() { - $this->pdo = null; - } + /** + * Disconnect from current link + */ + protected function disconnect() + { + $this->pdo = null; + } - /** - * Handle a PDOException - * @param \PDOException $e - */ - protected function error(\PDOException $e) { - trigger_error('SQL error: '.$e->getMessage(), E_USER_WARNING); - } + /** + * Handle a PDOException + * @param \PDOException $e + */ + protected function error(\PDOException $e) + { + trigger_error('SQL error: ' . $e->getMessage(), E_USER_WARNING); + } } diff --git a/src/psm/Service/User.php b/src/psm/Service/User.php index 6906fd93..fb50e475 100644 --- a/src/psm/Service/User.php +++ b/src/psm/Service/User.php @@ -1,4 +1,5 @@ db_connection = $db->pdo(); + /** + * Open a new user service + * + * @param \psm\Service\Database $db + * @param \Symfony\Component\HttpFoundation\Session\SessionInterface $session if NULL, one will be created + */ + public function __construct(Database $db, SessionInterface $session = null) + { + $this->db_connection = $db->pdo(); - if (!psm_is_cli()) { - if ($session == null) { - $session = new Session(); - $session->start(); - } - $this->session = $session; + if (!psm_is_cli()) { + if ($session == null) { + $session = new Session(); + $session->start(); + } + $this->session = $session; - if ((!defined('PSM_INSTALL') || !PSM_INSTALL)) { - // check the possible login actions: - // 1. login via session data (happens each time user opens a page on your php project AFTER he has successfully logged in via the login form) - // 2. login via cookie + if ((!defined('PSM_INSTALL') || !PSM_INSTALL)) { + // check the possible login actions: + // 1. login via session data (happens each time user opens a page on your php project AFTER + // he has successfully logged in via the login form) + // 2. login via cookie - // if user has an active session on the server - if (!$this->loginWithSessionData()) { - $this->loginWithCookieData(); - } - } - } - } + // if user has an active session on the server + if (!$this->loginWithSessionData()) { + $this->loginWithCookieData(); + } + } + } + } - /** - * Get user by id, or get current user. - * @param int $user_id if null it will attempt current user id - * @param boolean $flush if TRUE it will query db regardless of whether we already have the data - * @return object|boolean FALSE if user not found, object otherwise - */ - public function getUser($user_id = null, $flush = false) { - if ($user_id == null) { - if (!$this->isUserLoggedIn()) { - return false; - } else { - $user_id = $this->getUserId(); - } - } + /** + * Get user by id, or get current user. + * @param int $user_id if null it will attempt current user id + * @param boolean $flush if TRUE it will query db regardless of whether we already have the data + * @return object|boolean FALSE if user not found, object otherwise + */ + public function getUser($user_id = null, $flush = false) + { + if ($user_id == null) { + if (!$this->isUserLoggedIn()) { + return false; + } else { + $user_id = $this->getUserId(); + } + } - 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->bindValue(':user_id', $user_id, \PDO::PARAM_INT); - $query_user->execute(); - // get result row (as an object) - $this->user_data[$user_id] = $query_user->fetchObject(); - } - return $this->user_data[$user_id]; - } + 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->bindValue(':user_id', $user_id, \PDO::PARAM_INT); + $query_user->execute(); + // get result row (as an object) + $this->user_data[$user_id] = $query_user->fetchObject(); + } + return $this->user_data[$user_id]; + } - /** - * Search into database for the user data of user_name specified as parameter - * @return object|boolean user data as an object if existing user - */ - public function getUserByUsername($user_name) { - // database query, getting all the info of the selected user - $query_user = $this->db_connection->prepare('SELECT * FROM '.PSM_DB_PREFIX.'users WHERE user_name = :user_name'); - $query_user->bindValue(':user_name', $user_name, \PDO::PARAM_STR); - $query_user->execute(); - // get result row (as an object) - return $query_user->fetchObject(); - } + /** + * Search into database for the user data of user_name specified as parameter + * @return object|boolean user data as an object if existing user + */ + public function getUserByUsername($user_name) + { + // database query, getting all the info of the selected user + $query_user = $this->db_connection->prepare('SELECT * FROM ' . + PSM_DB_PREFIX . 'users WHERE user_name = :user_name'); + $query_user->bindValue(':user_name', $user_name, \PDO::PARAM_STR); + $query_user->execute(); + // get result row (as an object) + return $query_user->fetchObject(); + } - /** - * Logs in with SESSION data. - * - * @return boolean - */ - protected function loginWithSessionData() { - if (!$this->session->has('user_id')) { - return false; - } - $user = $this->getUser($this->session->get('user_id')); + /** + * Logs in with SESSION data. + * + * @return boolean + */ + protected function loginWithSessionData() + { + if (!$this->session->has('user_id')) { + return false; + } + $user = $this->getUser($this->session->get('user_id')); - if (!empty($user)) { - $this->setUserLoggedIn($user->user_id); - return true; - } else { - // user no longer exists in database - // call logout to clean up session vars - $this->doLogout(); - return false; - } - } + if (!empty($user)) { + $this->setUserLoggedIn($user->user_id); + return true; + } else { + // user no longer exists in database + // call logout to clean up session vars + $this->doLogout(); + return false; + } + } - /** - * Logs in via the Cookie - * @return bool success state of cookie login - */ - private function loginWithCookieData() { - if (isset($_COOKIE['rememberme'])) { - // extract data from the cookie - list ($user_id, $token, $hash) = explode(':', $_COOKIE['rememberme']); - // check cookie hash validity - if ($hash == hash('sha256', $user_id.':'.$token.PSM_LOGIN_COOKIE_SECRET_KEY) && !empty($token)) { - // cookie looks good, try to select corresponding user - // get real token from database (and all other data) - $user = $this->getUser($user_id); + /** + * Logs in via the Cookie + * @return bool success state of cookie login + */ + private function loginWithCookieData() + { + if (isset($_COOKIE['rememberme'])) { + // extract data from the cookie + list ($user_id, $token, $hash) = explode(':', $_COOKIE['rememberme']); + // check cookie hash validity + if ($hash == hash('sha256', $user_id . ':' . $token . PSM_LOGIN_COOKIE_SECRET_KEY) && !empty($token)) { + // cookie looks good, try to select corresponding user + // get real token from database (and all other data) + $user = $this->getUser($user_id); - if (!empty($user) && $token === $user->rememberme_token) { - $this->setUserLoggedIn($user->user_id, true); + if (!empty($user) && $token === $user->rememberme_token) { + $this->setUserLoggedIn($user->user_id, true); - // Cookie token usable only once - $this->newRememberMeCookie(); - return true; - } - } - // call logout to remove invalid cookie - $this->doLogout(); - } - return false; - } + // Cookie token usable only once + $this->newRememberMeCookie(); + return true; + } + } + // call logout to remove invalid cookie + $this->doLogout(); + } + return false; + } - /** - * Logs in with the data provided in $_POST, coming from the login form - * @param string $user_name - * @param string $user_password - * @param boolean $user_rememberme - * @return boolean - */ - public function loginWithPostData($user_name, $user_password, $user_rememberme = false) { - $user_name = trim($user_name); - $user_password = trim($user_password); + /** + * Logs in with the data provided in $_POST, coming from the login form + * @param string $user_name + * @param string $user_password + * @param boolean $user_rememberme + * @return boolean + */ + public function loginWithPostData($user_name, $user_password, $user_rememberme = false) + { + $user_name = trim($user_name); + $user_password = trim($user_password); - if (empty($user_name) && empty($user_password)) { - return false; - } - $user = $this->getUserByUsername($user_name); + if (empty($user_name) && empty($user_password)) { + return false; + } + $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 - if (!isset($user->user_id)) { - password_verify($user_password, 'dummy_call_against_timing'); - return false; - } else if (!password_verify($user_password, $user->password)) { - return false; - } + // using PHP 5.5's password_verify() function to check if the provided passwords + // fits to the hash of that user's password + if (!isset($user->user_id)) { + password_verify($user_password, 'dummy_call_against_timing'); + return false; + } elseif (!password_verify($user_password, $user->password)) { + 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_rememberme) { - $this->newRememberMeCookie(); - } + // if user has check the "remember me" checkbox, then generate token and write cookie + if ($user_rememberme) { + $this->newRememberMeCookie(); + } - // recalculate the user's password hash - // DELETE this if-block if you like, it only exists to recalculate users's hashes when you provide a cost factor, - // by default the script will use a cost factor of 10 and never change it. - // check if the have defined a cost factor in config/hashing.php - if (defined('PSM_LOGIN_HASH_COST_FACTOR')) { - // check if the hash needs to be rehashed - if (password_needs_rehash($user->password, PASSWORD_DEFAULT, array('cost' => PSM_LOGIN_HASH_COST_FACTOR))) { - $this->changePassword($user->user_id, $user_password); - } - } - return true; - } + // recalculate the user's password hash + // DELETE this if-block if you like, it only exists to recalculate + // users's hashes when you provide a cost factor, + // by default the script will use a cost factor of 10 and never change it. + // check if the have defined a cost factor in config/hashing.php + if (defined('PSM_LOGIN_HASH_COST_FACTOR')) { + // check if the hash needs to be rehashed + if (password_needs_rehash($user->password, PASSWORD_DEFAULT, array('cost' => PSM_LOGIN_HASH_COST_FACTOR))) { + $this->changePassword($user->user_id, $user_password); + } + } + return true; + } - /** - * Set the user logged in - * @param int $user_id - * @param boolean $regenerate regenerate session id against session fixation? - */ - protected function setUserLoggedIn($user_id, $regenerate = false) { - if ($regenerate) { - $this->session->invalidate(); - } - $this->session->set('user_id', $user_id); - $this->session->set('user_logged_in', 1); + /** + * Set the user logged in + * @param int $user_id + * @param boolean $regenerate regenerate session id against session fixation? + */ + protected function setUserLoggedIn($user_id, $regenerate = false) + { + if ($regenerate) { + $this->session->invalidate(); + } + $this->session->set('user_id', $user_id); + $this->session->set('user_logged_in', 1); - // declare user id, set the login status to true - $this->user_id = $user_id; - $this->user_is_logged_in = true; - } + // declare user id, set the login status to true + $this->user_id = $user_id; + $this->user_is_logged_in = true; + } - /** - * Create all data needed for remember me cookie connection on client and server side - */ - protected function newRememberMeCookie() { - // generate 64 char random string and store it in current user data - $random_token_string = hash('sha256', mt_rand()); - $sth = $this->db_connection->prepare('UPDATE '.PSM_DB_PREFIX.'users SET rememberme_token = :user_rememberme_token WHERE user_id = :user_id'); - $sth->execute(array(':user_rememberme_token' => $random_token_string, ':user_id' => $this->getUserId())); + /** + * Create all data needed for remember me cookie connection on client and server side + */ + protected function newRememberMeCookie() + { + // generate 64 char random string and store it in current user data + $random_token_string = hash('sha256', mt_rand()); + $sth = $this->db_connection->prepare('UPDATE ' . + PSM_DB_PREFIX . 'users SET rememberme_token = :user_rememberme_token WHERE user_id = :user_id'); + $sth->execute(array(':user_rememberme_token' => $random_token_string, ':user_id' => $this->getUserId())); - // generate cookie string that consists of userid, randomstring and combined hash of both - $cookie_string_first_part = $this->getUserId().':'.$random_token_string; - $cookie_string_hash = hash('sha256', $cookie_string_first_part.PSM_LOGIN_COOKIE_SECRET_KEY); - $cookie_string = $cookie_string_first_part.':'.$cookie_string_hash; + // generate cookie string that consists of userid, randomstring and combined hash of both + $cookie_string_first_part = $this->getUserId() . ':' . $random_token_string; + $cookie_string_hash = hash('sha256', $cookie_string_first_part . PSM_LOGIN_COOKIE_SECRET_KEY); + $cookie_string = $cookie_string_first_part . ':' . $cookie_string_hash; - // set cookie - setcookie('rememberme', $cookie_string, time() + PSM_LOGIN_COOKIE_RUNTIME, "/", PSM_LOGIN_COOKIE_DOMAIN); - } + // set cookie + setcookie('rememberme', $cookie_string, time() + PSM_LOGIN_COOKIE_RUNTIME, "/", PSM_LOGIN_COOKIE_DOMAIN); + } - /** - * Delete all data needed for remember me cookie connection on client and server side - */ - protected function deleteRememberMeCookie() { - // Reset rememberme token - if ($this->session->has('user_id')) { - $sth = $this->db_connection->prepare('UPDATE '.PSM_DB_PREFIX.'users SET rememberme_token = NULL WHERE user_id = :user_id'); - $sth->execute(array(':user_id' => $this->session->get('user_id'))); - } + /** + * Delete all data needed for remember me cookie connection on client and server side + */ + protected function deleteRememberMeCookie() + { + // Reset rememberme token + if ($this->session->has('user_id')) { + $sth = $this->db_connection->prepare('UPDATE ' . + PSM_DB_PREFIX . 'users SET rememberme_token = NULL WHERE user_id = :user_id'); + $sth->execute(array(':user_id' => $this->session->get('user_id'))); + } - // set the rememberme-cookie to ten years ago (3600sec * 365 days * 10). - // that's obivously the best practice to kill a cookie via php - // @see http://stackoverflow.com/a/686166/1114320 - setcookie('rememberme', false, time() - (3600 * 3650), '/', PSM_LOGIN_COOKIE_DOMAIN); - } + // set the rememberme-cookie to ten years ago (3600sec * 365 days * 10). + // that's obivously the best practice to kill a cookie via php + // @see http://stackoverflow.com/a/686166/1114320 + setcookie('rememberme', false, time() - (3600 * 3650), '/', PSM_LOGIN_COOKIE_DOMAIN); + } - /** - * Perform the logout, resetting the session - */ - public function doLogout() { - $this->deleteRememberMeCookie(); + /** + * Perform the logout, resetting the session + */ + public function doLogout() + { + $this->deleteRememberMeCookie(); - $this->session->clear(); - $this->session->invalidate(); + $this->session->clear(); + $this->session->invalidate(); - $this->user_is_logged_in = false; - } + $this->user_is_logged_in = false; + } - /** - * Simply return the current state of the user's login - * @return bool user's login status - */ - public function isUserLoggedIn() { - return $this->user_is_logged_in; - } + /** + * Simply return the current state of the user's login + * @return bool user's login status + */ + public function isUserLoggedIn() + { + return $this->user_is_logged_in; + } - /** - * Sets a random token into the database (that will verify the user when he/she comes back via the link - * in the email) and returns it - * @param int $user_id - * @return string|boolean FALSE on error, string otherwise - */ - public function generatePasswordResetToken($user_id) { - $user_id = intval($user_id); + /** + * Sets a random token into the database (that will verify the user when he/she comes back via the link + * in the email) and returns it + * @param int $user_id + * @return string|boolean FALSE on error, string otherwise + */ + public function generatePasswordResetToken($user_id) + { + $user_id = intval($user_id); - if ($user_id == 0) { - return false; - } - // generate timestamp (to see when exactly the user (or an attacker) requested the password reset mail) - $temporary_timestamp = time(); - // generate random hash for email password reset verification (40 char string) - $user_password_reset_hash = sha1(uniqid(mt_rand(), true)); + if ($user_id == 0) { + return false; + } + // generate timestamp (to see when exactly the user (or an attacker) requested the password reset mail) + $temporary_timestamp = time(); + // generate random hash for email password reset verification (40 char string) + $user_password_reset_hash = sha1(uniqid(mt_rand(), true)); - $query_update = $this->db_connection->prepare('UPDATE '.PSM_DB_PREFIX.'users SET password_reset_hash = :user_password_reset_hash, - password_reset_timestamp = :user_password_reset_timestamp - WHERE user_id = :user_id'); - $query_update->bindValue(':user_password_reset_hash', $user_password_reset_hash, \PDO::PARAM_STR); - $query_update->bindValue(':user_password_reset_timestamp', $temporary_timestamp, \PDO::PARAM_INT); - $query_update->bindValue(':user_id', $user_id, \PDO::PARAM_INT); - $query_update->execute(); + $query_update = $this->db_connection->prepare('UPDATE ' . + PSM_DB_PREFIX . 'users SET password_reset_hash = :user_password_reset_hash, + password_reset_timestamp = :user_password_reset_timestamp + WHERE user_id = :user_id'); + $query_update->bindValue(':user_password_reset_hash', $user_password_reset_hash, \PDO::PARAM_STR); + $query_update->bindValue(':user_password_reset_timestamp', $temporary_timestamp, \PDO::PARAM_INT); + $query_update->bindValue(':user_id', $user_id, \PDO::PARAM_INT); + $query_update->execute(); - // check if exactly one row was successfully changed: - if ($query_update->rowCount() == 1) { - return $user_password_reset_hash; - } else { - return false; - } - } + // check if exactly one row was successfully changed: + if ($query_update->rowCount() == 1) { + return $user_password_reset_hash; + } else { + return false; + } + } - /** - * Checks if the verification string in the account verification mail is valid and matches to the user. - * - * Please note it is valid for 1 hour. - * @param int $user_id - * @param string $token - * @return boolean - */ - public function verifyPasswordResetToken($user_id, $token) { - $user_id = intval($user_id); + /** + * Checks if the verification string in the account verification mail is valid and matches to the user. + * + * Please note it is valid for 1 hour. + * @param int $user_id + * @param string $token + * @return boolean + */ + public function verifyPasswordResetToken($user_id, $token) + { + $user_id = intval($user_id); - if (empty($user_id) || empty($token)) { - return false; - } - $user = $this->getUser($user_id); + if (empty($user_id) || empty($token)) { + return false; + } + $user = $this->getUser($user_id); - if (isset($user->user_id) && $user->password_reset_hash == $token) { - $runtime = (defined('PSM_LOGIN_RESET_RUNTIME')) ? PSM_LOGIN_RESET_RUNTIME : 3600; - $timestamp_max_interval = time() - $runtime; + if (isset($user->user_id) && $user->password_reset_hash == $token) { + $runtime = (defined('PSM_LOGIN_RESET_RUNTIME')) ? PSM_LOGIN_RESET_RUNTIME : 3600; + $timestamp_max_interval = time() - $runtime; - if ($user->password_reset_timestamp > $timestamp_max_interval) { - return true; - } - } - return false; - } + if ($user->password_reset_timestamp > $timestamp_max_interval) { + return true; + } + } + return false; + } - /** - * Change the password of a user - * @param int|\PDOStatement $user_id - * @param string $password - * @return boolean TRUE on success, FALSE on failure - */ - public function changePassword($user_id, $password) { - $user_id = intval($user_id); + /** + * Change the password of a user + * @param int|\PDOStatement $user_id + * @param string $password + * @return boolean TRUE on success, FALSE on failure + */ + public function changePassword($user_id, $password) + { + $user_id = intval($user_id); - if (empty($user_id) || empty($password)) { - return false; - } - // now it gets a little bit crazy: check if we have a constant PSM_LOGIN_HASH_COST_FACTOR defined (in src/includes/psmconfig.inc.php), - // if so: put the value into $hash_cost_factor, if not, make $hash_cost_factor = null - $hash_cost_factor = (defined('PSM_LOGIN_HASH_COST_FACTOR') ? PSM_LOGIN_HASH_COST_FACTOR : null); + if (empty($user_id) || empty($password)) { + return false; + } + // now it gets a little bit crazy: check if we have a constant + // PSM_LOGIN_HASH_COST_FACTOR defined (in src/includes/psmconfig.inc.php), + // if so: put the value into $hash_cost_factor, if not, make $hash_cost_factor = null + $hash_cost_factor = (defined('PSM_LOGIN_HASH_COST_FACTOR') ? PSM_LOGIN_HASH_COST_FACTOR : null); - // crypt the user's password with the PHP 5.5's password_hash() function, results in a 60 character hash string - // the PASSWORD_DEFAULT constant is defined by the PHP 5.5, or if you are using PHP 5.3/5.4, by the password hashing - // compatibility library. the third parameter looks a little bit shitty, but that's how those PHP 5.5 functions - // want the parameter: as an array with, currently only used with 'cost' => XX. - $user_password_hash = password_hash($password, PASSWORD_DEFAULT, array('cost' => $hash_cost_factor)); + // crypt the user's password with the PHP 5.5's password_hash() function, results in a 60 character hash string + // the PASSWORD_DEFAULT constant is defined by the PHP 5.5, + // or if you are using PHP 5.3/5.4, by the password hashing + // compatibility library. the third parameter looks a little bit shitty, but that's how those PHP 5.5 functions + // want the parameter: as an array with, currently only used with 'cost' => XX. + $user_password_hash = password_hash($password, PASSWORD_DEFAULT, array('cost' => $hash_cost_factor)); - // write users new hash into database - $query_update = $this->db_connection->prepare('UPDATE '.PSM_DB_PREFIX.'users SET password = :user_password_hash, - password_reset_hash = NULL, password_reset_timestamp = NULL - WHERE user_id = :user_id'); - $query_update->bindValue(':user_password_hash', $user_password_hash, \PDO::PARAM_STR); - $query_update->bindValue(':user_id', $user_id, \PDO::PARAM_STR); - $query_update->execute(); + // write users new hash into database + $query_update = $this->db_connection->prepare('UPDATE ' . + PSM_DB_PREFIX . 'users SET password = :user_password_hash, + password_reset_hash = NULL, password_reset_timestamp = NULL + WHERE user_id = :user_id'); + $query_update->bindValue(':user_password_hash', $user_password_hash, \PDO::PARAM_STR); + $query_update->bindValue(':user_id', $user_id, \PDO::PARAM_STR); + $query_update->execute(); - // check if exactly one row was successfully changed: - if ($query_update->rowCount() == 1) { - return true; - } else { - return false; - } - } + // check if exactly one row was successfully changed: + if ($query_update->rowCount() == 1) { + return true; + } else { + return false; + } + } - /** - * Gets the user id - * @return int - */ - public function getUserId() { - return $this->user_id; - } + /** + * Gets the user id + * @return int + */ + public function getUserId() + { + return $this->user_id; + } - /** - * Gets the username - * @return string - */ - public function getUsername() { - $user = $this->getUser(); - return (isset($user->user_name) ? $user->user_name : null); - } + /** + * Gets the username + * @return string + */ + public function getUsername() + { + $user = $this->getUser(); + return (isset($user->user_name) ? $user->user_name : null); + } - /** - * Gets the user level - * @return int - */ - public function getUserLevel() { - $user = $this->getUser(); + /** + * Gets the user level + * @return int + */ + public function getUserLevel() + { + $user = $this->getUser(); - if (isset($user->level)) { - return $user->level; - } else { - return PSM_USER_ANONYMOUS; - } - } + if (isset($user->level)) { + return $user->level; + } else { + return PSM_USER_ANONYMOUS; + } + } - /** - * read current user preferences from the database - * @return boolean return false is user not connected - */ - protected function loadPreferences() { - if ($this->user_preferences === null) { - if (!$this->getUser()) { - return false; - } + /** + * read current user preferences from the database + * @return boolean return false is user not connected + */ + protected function loadPreferences() + { + if ($this->user_preferences === null) { + if (!$this->getUser()) { + return false; + } - $this->user_preferences = array(); - foreach ($this->db_connection->query('SELECT `key`,`value` FROM `'.PSM_DB_PREFIX.'users_preferences` WHERE `user_id` = '.$this->user_id) as $row) { - $this->user_preferences[$row['key']] = $row['value']; - } - } - return true; - } + $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 + ) { + $this->user_preferences[$row['key']] = $row['value']; + } + } + return true; + } - /** - * Get a user preference value - * @param string $key - * @param mixed $default - * @return mixed - */ - public function getUserPref($key, $default = '') { - if (!$this->loadPreferences() || !isset($this->user_preferences[$key])) { - return $default; - } + /** + * Get a user preference value + * @param string $key + * @param mixed $default + * @return mixed + */ + public function getUserPref($key, $default = '') + { + if (!$this->loadPreferences() || !isset($this->user_preferences[$key])) { + return $default; + } - $value = $this->user_preferences[$key]; - settype($value, gettype($default)); - return $value; - } + $value = $this->user_preferences[$key]; + settype($value, gettype($default)); + return $value; + } - /** - * Set a user preference value - * @param string $key - * @param mixed $value - */ - public function setUserPref($key, $value) { - if ($this->loadPreferences()) { - if (isset($this->user_preferences[$key])) { - if ($this->user_preferences[$key] == $value) { - return; // no change - } - $sql = 'UPDATE `'.PSM_DB_PREFIX.'users_preferences` SET `key` = ?, `value` = ? WHERE `user_id` = ?'; - } else { - $sql = 'INSERT INTO `'.PSM_DB_PREFIX.'users_preferences` SET `key` = ?, `value` = ?, `user_id` = ?'; - } - $sth = $this->db_connection->prepare($sql); - $sth->execute(array($key, $value, $this->user_id)); - $this->user_preferences[$key] = $value; - } - } + /** + * Set a user preference value + * @param string $key + * @param mixed $value + */ + public function setUserPref($key, $value) + { + if ($this->loadPreferences()) { + if (isset($this->user_preferences[$key])) { + if ($this->user_preferences[$key] == $value) { + return; // no change + } + $sql = 'UPDATE `' . PSM_DB_PREFIX . 'users_preferences` SET `key` = ?, `value` = ? WHERE `user_id` = ?'; + } else { + $sql = 'INSERT INTO `' . PSM_DB_PREFIX . 'users_preferences` SET `key` = ?, `value` = ?, `user_id` = ?'; + } + $sth = $this->db_connection->prepare($sql); + $sth->execute(array($key, $value, $this->user_id)); + $this->user_preferences[$key] = $value; + } + } - /** - * Get session object - * @return \Symfony\Component\HttpFoundation\Session\SessionInterface - */ - public function getSession() { - return $this->session; - } + /** + * Get session object + * @return \Symfony\Component\HttpFoundation\Session\SessionInterface + */ + public function getSession() + { + return $this->session; + } } diff --git a/src/psm/Txtmsg/CMBulkSMS.php b/src/psm/Txtmsg/CMBulkSMS.php index 3ee1a83a..d0d3e0b1 100644 --- a/src/psm/Txtmsg/CMBulkSMS.php +++ b/src/psm/Txtmsg/CMBulkSMS.php @@ -1,4 +1,5 @@ . * - * @package phpservermon - * @author Axel Wehner - * @copyright Copyright (c) 2008-2017 Pepijn Over - * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 - * @version Release: @package_version@ - * @link http://www.phpservermonitor.org/ - * @since phpservermon 3.2.1 + * @package phpservermon + * @author Axel Wehner + * @copyright Copyright (c) 2008-2017 Pepijn Over + * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 + * @version Release: @package_version@ + * @link http://www.phpservermonitor.org/ + * @since phpservermon 3.2.1 **/ namespace psm\Txtmsg; @@ -36,195 +37,200 @@ namespace psm\Txtmsg; * * Requirements: cURL v7.18.1+ and OpenSSL 0.9.8j+ */ -class CMBulkSMS extends Core { - /** @var bool True when cURL request succeeded */ - public $result = true; +class CMBulkSMS extends Core +{ + /** @var bool True when cURL request succeeded */ + public $result = true; - /** @var string Contains error message if cURL request failed */ - public $error = ''; + /** @var string Contains error message if cURL request failed */ + public $error = ''; - /** @var bool Set to true for debug output/logging */ - protected $debug = false; + /** @var bool Set to true for debug output/logging */ + protected $debug = false; - /** @var bool Set to false if your operator isn't able to handle multipart messages */ - protected $multipartMessage = true; + /** @var bool Set to false if your operator isn't able to handle multipart messages */ + protected $multipartMessage = true; - /** @var string|null Gateway API URL uses const GATEWAY_URL_XML or GATEWAY_URL_JSON */ - protected $apiUrl; + /** @var string|null Gateway API URL uses const GATEWAY_URL_XML or GATEWAY_URL_JSON */ + protected $apiUrl; - /** @var string Gateway API Type: Use 'json' (default) or 'xml' */ - protected $apiType = 'json'; + /** @var string Gateway API Type: Use 'json' (default) or 'xml' */ + protected $apiType = 'json'; - /** @var string|null JSON or XML message for cURL request */ - protected $request; + /** @var string|null JSON or XML message for cURL request */ + protected $request; - /** @var string|null HTTP Content-Type for cURL request */ - protected $contentType; + /** @var string|null HTTP Content-Type for cURL request */ + protected $contentType; - /** @var string|null Raw sms text message */ - protected $messageBody; + /** @var string|null Raw sms text message */ + protected $messageBody; - /** @var string JSON Gateway API URL */ - const GATEWAY_URL_JSON = "https://gw.cmtelecom.com/v1.0/message"; + /** @var string JSON Gateway API URL */ + public const GATEWAY_URL_JSON = "https://gw.cmtelecom.com/v1.0/message"; - /** @var string XML Gateway API URL */ - const GATEWAY_URL_XML = "https://sgw01.cm.nl/gateway.ashx"; + /** @var string XML Gateway API URL */ + public const GATEWAY_URL_XML = "https://sgw01.cm.nl/gateway.ashx"; - /** - * Build the message and send cURL request to the sms gateway - * - * @see https://docs.cmtelecom.com/bulk-sms/v1.0#/send_a_message%7Csample_requests - * @param string $message Your text message - * @return bool|string true when cURL request was successful, otherwise string with error message - */ - public function sendSMS($message) { - // Check if recipient and text message are available - if (count($this->recipients) < 1 || empty($message)) { - return false; - } + /** + * Build the message and send cURL request to the sms gateway + * + * @see https://docs.cmtelecom.com/bulk-sms/v1.0#/send_a_message%7Csample_requests + * @param string $message Your text message + * @return bool|string true when cURL request was successful, otherwise string with error message + */ + public function sendSMS($message) + { + // Check if recipient and text message are available + if (count($this->recipients) < 1 || empty($message)) { + return false; + } - // Prepare the message in CM's XML or JSON format - switch ($this->apiType) { - case 'xml': - $this->request = $this->buildMessageXml(); - $this->contentType = 'Content-Type: application/xml'; - $this->apiUrl = self::GATEWAY_URL_XML; - break; + // Prepare the message in CM's XML or JSON format + switch ($this->apiType) { + case 'xml': + $this->request = $this->buildMessageXml(); + $this->contentType = 'Content-Type: application/xml'; + $this->apiUrl = self::GATEWAY_URL_XML; + break; - case 'json': - default: - $this->request = $this->buildMessageJson(); - $this->contentType = 'Content-Type: application/json'; - $this->apiUrl = self::GATEWAY_URL_JSON; - break; - } + case 'json': + default: + $this->request = $this->buildMessageJson(); + $this->contentType = 'Content-Type: application/json'; + $this->apiUrl = self::GATEWAY_URL_JSON; + break; + } - $request = $this->executeCurlRequest(); + $request = $this->executeCurlRequest(); - return $request; - } + return $request; + } - /** - * Create a JSON batch sms message using CM's format - * - * @see https://docs.cmtelecom.com/bulk-sms/v1.0#/send_a_message%7Cbatch_messages - * @see https://docs.cmtelecom.com/bulk-sms/v1.0#/send_a_message%7Csample_requests - * @see https://docs.cmtelecom.com/bulk-sms/v1.0#/send_a_message%7Cmultipart - * @return string JSON message object - */ - protected function buildMessageJson() { - // Prepare recipient array for batch message - $recipients = array(); - foreach ($this->recipients as $recipient) { - $recipients[] = array('number' => $recipient); - } + /** + * Create a JSON batch sms message using CM's format + * + * @see https://docs.cmtelecom.com/bulk-sms/v1.0#/send_a_message%7Cbatch_messages + * @see https://docs.cmtelecom.com/bulk-sms/v1.0#/send_a_message%7Csample_requests + * @see https://docs.cmtelecom.com/bulk-sms/v1.0#/send_a_message%7Cmultipart + * @return string JSON message object + */ + protected function buildMessageJson() + { + // Prepare recipient array for batch message + $recipients = array(); + foreach ($this->recipients as $recipient) { + $recipients[] = array('number' => $recipient); + } - // Build message array in CM's Bulk SMS format - $msgArray = array( - 'messages' => array( - 'authentication' => array( - 'producttoken' => $this->password - ), - 'msg' => array( - array( - 'from' => substr($this->originator, 0, 11), - 'to' => $recipients, - 'body' => array( - 'content' => $message - ) - ) - ) - ) - ); + // Build message array in CM's Bulk SMS format + $msgArray = array( + 'messages' => array( + 'authentication' => array( + 'producttoken' => $this->password + ), + 'msg' => array( + array( + 'from' => substr($this->originator, 0, 11), + 'to' => $recipients, + 'body' => array( + 'content' => $message + ) + ) + ) + ) + ); - // Multipart message - if ($this->multipartMessage) { - $msgArray['messages']['msg'][0]['minimumNumberOfMessageParts'] = 1; - $msgArray['messages']['msg'][0]['maximumNumberOfMessageParts'] = 8; - } + // Multipart message + if ($this->multipartMessage) { + $msgArray['messages']['msg'][0]['minimumNumberOfMessageParts'] = 1; + $msgArray['messages']['msg'][0]['maximumNumberOfMessageParts'] = 8; + } - // Convert array in JSON object - return json_encode($msgArray); - } + // Convert array in JSON object + return json_encode($msgArray); + } - /** - * Create a XML batch sms message in CM's format - * - * @see https://docs.cmtelecom.com/bulk-sms/v1.0#/send_a_message%7Cbatch_messages - * @see https://docs.cmtelecom.com/bulk-sms/v1.0#/send_a_message%7Csample_requests - * @see https://docs.cmtelecom.com/bulk-sms/v1.0#/send_a_message%7Cmultipart - * @return string XML message - */ - protected function buildMessageXml() { - // Create XML string - $xml = new \SimpleXMLElement(''); + /** + * Create a XML batch sms message in CM's format + * + * @see https://docs.cmtelecom.com/bulk-sms/v1.0#/send_a_message%7Cbatch_messages + * @see https://docs.cmtelecom.com/bulk-sms/v1.0#/send_a_message%7Csample_requests + * @see https://docs.cmtelecom.com/bulk-sms/v1.0#/send_a_message%7Cmultipart + * @return string XML message + */ + protected function buildMessageXml() + { + // Create XML string + $xml = new \SimpleXMLElement(''); - // API-Token - $auth = $xml->addChild('AUTHENTICATION'); - $auth->addChild('PRODUCTTOKEN', $this->password); + // API-Token + $auth = $xml->addChild('AUTHENTICATION'); + $auth->addChild('PRODUCTTOKEN', $this->password); - // Message - $msg = $xml->addChild('MSG'); + // Message + $msg = $xml->addChild('MSG'); - // From - $msg->addChild('FROM', substr($this->originator, 0, 11)); + // From + $msg->addChild('FROM', substr($this->originator, 0, 11)); - // Recipients - foreach ($this->recipients as $recipient) { - $msg->addChild('TO', $recipient); - } + // Recipients + foreach ($this->recipients as $recipient) { + $msg->addChild('TO', $recipient); + } - // Multipart message - if ($this->multipartMessage) { - $msg->addChild('MINIMUMNUMBEROFMESSAGEPARTS', 1); - $msg->addChild('MAXIMUMNUMBEROFMESSAGEPARTS', 8); - } + // Multipart message + if ($this->multipartMessage) { + $msg->addChild('MINIMUMNUMBEROFMESSAGEPARTS', 1); + $msg->addChild('MAXIMUMNUMBEROFMESSAGEPARTS', 8); + } - // Add body text - $msg->addChild('BODY', $message); + // Add body text + $msg->addChild('BODY', $message); - return $xml->asXML(); - } + return $xml->asXML(); + } - /** - * Create and execute the curl request - * - * @return boolean|string boolean if message is sent, else string - */ + /** + * Create and execute the curl request + * + * @return boolean|string boolean if message is sent, else string + */ - protected function executeCurlRequest() { - $cr = curl_init(); - curl_setopt_array($cr, array( - CURLOPT_URL => $this->apiUrl, - CURLOPT_HTTPHEADER => array($this->contentType), - CURLOPT_POST => true, - CURLOPT_POSTFIELDS => $this->request, - CURLOPT_RETURNTRANSFER => true, - CURLOPT_FAILONERROR => true - ) - ); + protected function executeCurlRequest() + { + $cr = curl_init(); + curl_setopt_array($cr, array( + CURLOPT_URL => $this->apiUrl, + CURLOPT_HTTPHEADER => array($this->contentType), + CURLOPT_POST => true, + CURLOPT_POSTFIELDS => $this->request, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_FAILONERROR => true + )); - // execute curl request and fetch the response/error - $cResponse = curl_exec($cr); - $cError = curl_error($cr); - $cErrorCode = curl_errno($cr); - curl_close($cr); + // execute curl request and fetch the response/error + $cResponse = curl_exec($cr); + $cError = curl_error($cr); + $cErrorCode = curl_errno($cr); + curl_close($cr); - // set result and log error if needed - if ($cError) { - $this->error = 'Response: CM SMS API:'.$cResponse.' cURL Error Code: '.$cErrorCode.'"'.$cError.'"'; - error_log($this->error, E_USER_ERROR); - $this->result = false; - } + // set result and log error if needed + if ($cError) { + $this->error = 'Response: CM SMS API:' . $cResponse . ' cURL Error Code: ' . + $cErrorCode . '"' . $cError . '"'; + error_log($this->error, E_USER_ERROR); + $this->result = false; + } - // Debug output - // Note: CM's XML gateway gives no response when message is sent successfully :/ - if ($this->debug || PSM_DEBUG) { - $debug = '
    Request: '.$this->request.'
    Response: '.$cResponse.'
    '; - error_log("Request: $this->request\r\nResponse: $cResponse", E_USER_NOTICE); - echo $debug; - } + // Debug output + // Note: CM's XML gateway gives no response when message is sent successfully :/ + if ($this->debug || PSM_DEBUG) { + $debug = '
    Request: ' . $this->request . '
    Response: ' . $cResponse . '
    '; + error_log("Request: $this->request\r\nResponse: $cResponse", E_USER_NOTICE); + echo $debug; + } - return $this->result ? $this->result : $this->error; - } + return $this->result ? $this->result : $this->error; + } } diff --git a/src/psm/Txtmsg/Callr.php b/src/psm/Txtmsg/Callr.php index 71311e48..524d62d2 100644 --- a/src/psm/Txtmsg/Callr.php +++ b/src/psm/Txtmsg/Callr.php @@ -1,4 +1,5 @@ . * - * @package phpservermon - * @author Ward Pieters - * @author Tim Zandbergen - * @copyright Copyright (c) 2008-2017 Pepijn Over - * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 - * @version Release: @package_version@ - * @link http://www.phpservermonitor.org/ - * @since phpservermon 3.3.0 + * @package phpservermon + * @author Ward Pieters + * @author Tim Zandbergen + * @copyright Copyright (c) 2008-2017 Pepijn Over + * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 + * @version Release: @package_version@ + * @link http://www.phpservermonitor.org/ + * @since phpservermon 3.3.0 **/ namespace psm\Txtmsg; -class Callr extends Core { +class Callr extends Core +{ - /** - * Send sms using the Callr API - * - * @var string $message - * @var string $this->password - * @var array $this->recipients - * @var array $this->originator - * @var string $recipient - * - * @var mixed $result - * @var array $headers - * - * @var resource $curl - * @var string $err - * - * @var int $success - * @var string $error - * - * @return bool|string - */ - - public function sendSMS($message) { - $error = ""; - $success = 1; - - foreach ($this->recipients as $recipient) { - $curl = curl_init(); - curl_setopt_array($curl, array( - CURLOPT_URL => "https://api.callr.com/rest/v1.1/sms", - CURLOPT_RETURNTRANSFER => true, - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => json_encode( - array( - "to" => $recipient, - "from" => $this->originator, - "body" => urlencode($message), - "options" => null, - ) - ), - CURLOPT_HTTPHEADER => array( - "authorization: Basic ".base64_encode($this->username.":".$this->password), - "content-type: application/json" - ), - )); - - $result = json_decode(curl_exec($curl), true); - $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); - $err = curl_errno($curl); + /** + * Send sms using the Callr API + * + * @var string $message + * @var string $this->password + * @var array $this->recipients + * @var array $this->originator + * @var string $recipient + * + * @var mixed $result + * @var array $headers + * + * @var resource $curl + * @var string $err + * + * @var int $success + * @var string $error + * + * @return bool|string + */ + + public function sendSMS($message) + { + $error = ""; + $success = 1; + + foreach ($this->recipients as $recipient) { + $curl = curl_init(); + curl_setopt_array($curl, array( + CURLOPT_URL => "https://api.callr.com/rest/v1.1/sms", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "POST", + CURLOPT_POSTFIELDS => json_encode( + array( + "to" => $recipient, + "from" => $this->originator, + "body" => urlencode($message), + "options" => null, + ) + ), + CURLOPT_HTTPHEADER => array( + "authorization: Basic " . base64_encode($this->username . ":" . $this->password), + "content-type: application/json" + ), + )); + + $result = json_decode(curl_exec($curl), true); + $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); + $err = curl_errno($curl); - if ($err != 0 || $httpcode != 200 || $result['status'] == "error") { - $success = 0; - $error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". Result: ".$result['data']['code']." - ".$result['data']['message']; - } - curl_close($curl); - } - if ($success) { - return 1; - } - return $error; - } -} \ No newline at end of file + if ($err != 0 || $httpcode != 200 || $result['status'] == "error") { + $success = 0; + $error = "HTTP_code: " . $httpcode . ".\ncURL error (" . $err . "): " . curl_strerror($err) . + ". Result: " . $result['data']['code'] . " - " . $result['data']['message']; + } + curl_close($curl); + } + if ($success) { + return 1; + } + return $error; + } +} diff --git a/src/psm/Txtmsg/ClickSend.php b/src/psm/Txtmsg/ClickSend.php index fe116a30..d0176ce7 100644 --- a/src/psm/Txtmsg/ClickSend.php +++ b/src/psm/Txtmsg/ClickSend.php @@ -1,4 +1,5 @@ password - * @var array $this->recipients - * @var array $this->originator - * @var string $recipients - * - * @var resource $curl - * @var string $err - * @var mixed $result - * - * @var int $success - * @var string $error - * - * @return bool|string - */ - - public function sendSMS($message) { - $error = ""; - $success = 1; - - if (empty($this->recipients)) { - return false; - } - - $data = array('messages' => array()); - foreach ($this->recipients as $recipient) { - $data['messages'][] = array( - 'source' => 'phpservermon', - 'from' => substr($this->originator, 0, 11), - 'to' => $recipient, - 'body' => $message, - ); - } - - $curl = curl_init(); - curl_setopt_array($curl, array( - CURLOPT_URL => "https://rest.clicksend.com/v3/sms/send", - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => json_encode($data), - CURLOPT_HTTPHEADER => array( - "authorization: Basic ".base64_encode($this->username.":".$this->password), - "content-type: application/json" - ), - )); - - $result = json_decode(curl_exec($curl), true); - $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); - $err = curl_errno($curl); - - if ($err != 0 || ($httpcode != '200' && $httpcode != '201' && $httpcode != '202' && $result['response_code'] != "SUCCESS")) { - $success = 0; - $error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". Result: ".$result.""; - } - curl_close($curl); - - if ($success) { - return 1; - } - return $error; - } -} \ No newline at end of file +class ClickSend extends Core +{ + + /** + * Send sms using the SMSgw.NET API + * + * @var string $message + * @var string $this->password + * @var array $this->recipients + * @var array $this->originator + * @var string $recipients + * + * @var resource $curl + * @var string $err + * @var mixed $result + * + * @var int $success + * @var string $error + * + * @return bool|string + */ + + public function sendSMS($message) + { + $error = ""; + $success = 1; + + if (empty($this->recipients)) { + return false; + } + + $data = array('messages' => array()); + foreach ($this->recipients as $recipient) { + $data['messages'][] = array( + 'source' => 'phpservermon', + 'from' => substr($this->originator, 0, 11), + 'to' => $recipient, + 'body' => $message, + ); + } + + $curl = curl_init(); + curl_setopt_array($curl, array( + CURLOPT_URL => "https://rest.clicksend.com/v3/sms/send", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "POST", + CURLOPT_POSTFIELDS => json_encode($data), + CURLOPT_HTTPHEADER => array( + "authorization: Basic " . base64_encode($this->username . ":" . $this->password), + "content-type: application/json" + ), + )); + + $result = json_decode(curl_exec($curl), true); + $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); + $err = curl_errno($curl); + + if ( + $err != 0 || + ($httpcode != '200' && $httpcode != '201' && $httpcode != '202' && $result['response_code'] != "SUCCESS") + ) { + $success = 0; + $error = "HTTP_code: " . $httpcode . ".\ncURL error (" . $err . "): " . + curl_strerror($err) . ". Result: " . $result . ""; + } + curl_close($curl); + + if ($success) { + return 1; + } + return $error; + } +} diff --git a/src/psm/Txtmsg/Clickatell.php b/src/psm/Txtmsg/Clickatell.php index 8d26ca8f..655a7a24 100644 --- a/src/psm/Txtmsg/Clickatell.php +++ b/src/psm/Txtmsg/Clickatell.php @@ -1,4 +1,5 @@ . * - * @package phpservermon - * @author Pepijn Over - * @author Tim Zandbergen - * @copyright Copyright (c) 2008-2018 Pepijn Over - * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 - * @version Release: @package_version@ - * @link https://www.phpservermonitor.org/ + * @package phpservermon + * @author Pepijn Over + * @author Tim Zandbergen + * @copyright Copyright (c) 2008-2018 Pepijn Over + * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 + * @version Release: @package_version@ + * @link https://www.phpservermonitor.org/ **/ namespace psm\Txtmsg; -class Clickatell extends Core { +class Clickatell extends Core +{ - /** - * Send sms using the Clickatell API - * @var string $message - * @var array $this->recipients - * @var string $recipient - * @var string $this->password - * @var string $this->originator - * - * @var int $success - * @var string $error - * - * @return bool|string - */ - - public function sendSMS($message) { - $success = 1; - $error = ''; - foreach ($this->recipients as $recipient) { - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, "https://platform.clickatell.com/messages/http/send?apiKey=".urlencode($this->password)."&to=".urlencode($recipient)."&content=".urlencode($message)); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - $headers = array(); - $headers[] = "Content-Type: application/x-www-form-urlencoded"; - curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); - $result = curl_exec($ch); - curl_close($ch); + /** + * Send sms using the Clickatell API + * @var string $message + * @var array $this->recipients + * @var string $recipient + * @var string $this->password + * @var string $this->originator + * + * @var int $success + * @var string $error + * + * @return bool|string + */ + + public function sendSMS($message) + { + $success = 1; + $error = ''; + foreach ($this->recipients as $recipient) { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, "https://platform.clickatell.com/messages/http/send?apiKey=" . + urlencode($this->password) . "&to=" . urlencode($recipient) . "&content=" . urlencode($message)); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + $headers = array(); + $headers[] = "Content-Type: application/x-www-form-urlencoded"; + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); + $result = curl_exec($ch); + curl_close($ch); - // Check on error - if (strpos($result, ",\"errorCode\":null,\"error\":null,\"errorDescription\":null") === False) { - $error = $result; - $success = 0; - } - } - if ($success) { - return 1; - } - return $error; - } + // Check on error + if (strpos($result, ",\"errorCode\":null,\"error\":null,\"errorDescription\":null") === false) { + $error = $result; + $success = 0; + } + } + if ($success) { + return 1; + } + return $error; + } } diff --git a/src/psm/Txtmsg/Core.php b/src/psm/Txtmsg/Core.php index b14fe1de..de49dd25 100644 --- a/src/psm/Txtmsg/Core.php +++ b/src/psm/Txtmsg/Core.php @@ -1,4 +1,5 @@ username = $username; - $this->password = $password; - } + /** + * Define login information for the gateway + * + * @param string $username + * @param string $password + */ + public function setLogin($username, $password) + { + $this->username = $username; + $this->password = $password; + } - /** - * Set the mobile number the text message will be send from - * - * @param string $originator - */ - public function setOriginator($originator) { - $this->originator = $originator; - } + /** + * Set the mobile number the text message will be send from + * + * @param string $originator + */ + public function setOriginator($originator) + { + $this->originator = $originator; + } - /** - * Add new recipient to the list - * - * @param string|int $recipient - */ - public function addRecipients($recipient) { - array_push($this->recipients, $recipient); - } + /** + * Add new recipient to the list + * + * @param string|int $recipient + */ + public function addRecipients($recipient) + { + array_push($this->recipients, $recipient); + } } diff --git a/src/psm/Txtmsg/FreeMobileSMS.php b/src/psm/Txtmsg/FreeMobileSMS.php index ea008012..43a7d2c0 100644 --- a/src/psm/Txtmsg/FreeMobileSMS.php +++ b/src/psm/Txtmsg/FreeMobileSMS.php @@ -1,4 +1,5 @@ password - * @var string $this->username - * - * @var resource $curl - * @var string $err - * @var int $success - * @var string $error - * @var string $http_code - * - * @return bool|string - */ - - public function sendSMS($message) { - $success = 1; - $error = ""; - - $curl = curl_init(); - curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - curl_setopt($curl, CURLOPT_URL, "https://smsapi.free-mobile.fr/sendmsg?".http_build_query( - array( - "user" => $this->username, - "pass" => $this->password, - "msg" => urlencode($message), - ) - ) - ); +class FreeMobileSMS extends Core +{ + + /** + * Send sms using the FreeMobileSMS API + * + * @var string $message + * @var string $this->password + * @var string $this->username + * + * @var resource $curl + * @var string $err + * @var int $success + * @var string $error + * @var string $http_code + * + * @return bool|string + */ + + public function sendSMS($message) + { + $success = 1; + $error = ""; + + $curl = curl_init(); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curl, CURLOPT_URL, "https://smsapi.free-mobile.fr/sendmsg?" . http_build_query( + array( + "user" => $this->username, + "pass" => $this->password, + "msg" => urlencode($message), + ) + )); - $result = curl_exec($curl); - $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); - $err = curl_errno($curl); - - if ($err != 0 || $httpcode != 200) { - $success = 0; - $error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err); - } - curl_close($curl); - - if ($success) { - return 1; - } - return $error; - } + $result = curl_exec($curl); + $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); + $err = curl_errno($curl); + + if ($err != 0 || $httpcode != 200) { + $success = 0; + $error = "HTTP_code: " . $httpcode . ".\ncURL error (" . $err . "): " . curl_strerror($err); + } + curl_close($curl); + + if ($success) { + return 1; + } + return $error; + } } diff --git a/src/psm/Txtmsg/FreeVoipDeal.php b/src/psm/Txtmsg/FreeVoipDeal.php index 1bd6e559..234e6bd0 100755 --- a/src/psm/Txtmsg/FreeVoipDeal.php +++ b/src/psm/Txtmsg/FreeVoipDeal.php @@ -1,4 +1,5 @@ . * - * @package phpservermon - * @author Ward Pieters - * @copyright Copyright (c) 2008-2017 Pepijn Over - * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 - * @version Release: @package_version@ - * @link http://www.phpservermonitor.org/ - * @since phpservermon 3.1 + * @package phpservermon + * @author Ward Pieters + * @copyright Copyright (c) 2008-2017 Pepijn Over + * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 + * @version Release: @package_version@ + * @link http://www.phpservermonitor.org/ + * @since phpservermon 3.1 **/ namespace psm\Txtmsg; -class FreeVoipDeal extends Core { - - /** - * Send sms using the FreeVoipDeal API - * @var string $message - * @var string $this->password - * @var array $this->recipients - * @var array $this->originator - * - * @var resource $curl - * @var string $err - * @var string $recipient - * @var string $from - * @var mixed $result - * @var int $success - * @var string $error - * - * @return bool|string - */ - - public function sendSMS($message) { - $error = ""; - $success = 1; - - $message = rawurlencode($message); - - foreach ($this->recipients as $recipient) { - - $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, "https://www.freevoipdeal.com/myaccount/sendsms.php?".http_build_query( - array( - "username" => $this->username, - "password" => $this->password, - "from" => substr($this->originator, 0, 11), - "to" => $recipient, - "text" => $message, - ) - ) - ); - curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - - $result = curl_exec($curl); - $err = curl_errno($curl); - curl_close($curl); - - if ($err != 0 || is_numeric(strpos($result, "failure"))) { - $success = 0; - $error = $result; - } - } - - if ($success) { - return 1; - } - return $error; - } +class FreeVoipDeal extends Core +{ + + /** + * Send sms using the FreeVoipDeal API + * @var string $message + * @var string $this->password + * @var array $this->recipients + * @var array $this->originator + * + * @var resource $curl + * @var string $err + * @var string $recipient + * @var string $from + * @var mixed $result + * @var int $success + * @var string $error + * + * @return bool|string + */ + + public function sendSMS($message) + { + $error = ""; + $success = 1; + + $message = rawurlencode($message); + + foreach ($this->recipients as $recipient) { + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, "https://www.freevoipdeal.com/myaccount/sendsms.php?" . http_build_query( + array( + "username" => $this->username, + "password" => $this->password, + "from" => substr($this->originator, 0, 11), + "to" => $recipient, + "text" => $message, + ) + )); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + + $result = curl_exec($curl); + $err = curl_errno($curl); + curl_close($curl); + + if ($err != 0 || is_numeric(strpos($result, "failure"))) { + $success = 0; + $error = $result; + } + } + + if ($success) { + return 1; + } + return $error; + } } diff --git a/src/psm/Txtmsg/GatewayAPI.php b/src/psm/Txtmsg/GatewayAPI.php index a07a527d..4ea2ef39 100644 --- a/src/psm/Txtmsg/GatewayAPI.php +++ b/src/psm/Txtmsg/GatewayAPI.php @@ -1,4 +1,5 @@ . * - * @package phpservermon - * @author Ward Pieters - * @author Tim Zandbergen - * @copyright Copyright (c) 2008-2017 Pepijn Over - * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 - * @version Release: @package_version@ - * @link http://www.phpservermonitor.org/ - * @since phpservermon 3.3.0 + * @package phpservermon + * @author Ward Pieters + * @author Tim Zandbergen + * @copyright Copyright (c) 2008-2017 Pepijn Over + * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 + * @version Release: @package_version@ + * @link http://www.phpservermonitor.org/ + * @since phpservermon 3.3.0 **/ namespace psm\Txtmsg; -class GatewayAPI extends Core { +class GatewayAPI extends Core +{ - /** - * Send sms using the GatewayAPI API - * - * @var string $message - * @var string $this->password - * @var array $this->recipients - * @var array $this->originator - * @var string $recipient - * @var mixed $result - * - * @var resource $curl - * @var string $err - * @var int $success - * @var string $error - * - * @return bool|string - */ + /** + * Send sms using the GatewayAPI API + * + * @var string $message + * @var string $this->password + * @var array $this->recipients + * @var array $this->originator + * @var string $recipient + * @var mixed $result + * + * @var resource $curl + * @var string $err + * @var int $success + * @var string $error + * + * @return bool|string + */ - public function sendSMS($message) { - $error = ""; - $success = 1; + public function sendSMS($message) + { + $error = ""; + $success = 1; - if (empty($this->recipients)) { - return false; - } + if (empty($this->recipients)) { + return false; + } - $json = [ - 'sender' => isset($this->originator) ? $this->originator : "PHPServerMon", - 'message' => $message, - 'recipients' => [], - ]; + $json = [ + 'sender' => isset($this->originator) ? $this->originator : "PHPServerMon", + 'message' => $message, + 'recipients' => [], + ]; - foreach ($this->recipients as $recipient) { - $json['recipients'][] = ['msisdn' => $recipient]; - } + foreach ($this->recipients as $recipient) { + $json['recipients'][] = ['msisdn' => $recipient]; + } - $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, "https://gatewayapi.com/rest/mtsms"); - curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json")); - curl_setopt($curl, CURLOPT_USERPWD, $this->password.":"); - curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($json)); - curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, "https://gatewayapi.com/rest/mtsms"); + curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json")); + curl_setopt($curl, CURLOPT_USERPWD, $this->password . ":"); + curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($json)); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - $result = json_decode(curl_exec($curl), true); - $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); - $err = curl_errno($curl); - curl_close($curl); + $result = json_decode(curl_exec($curl), true); + $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); + $err = curl_errno($curl); + curl_close($curl); - if ($err != 0 || $httpcode != 200) { - $success = 0; - $error = $result['code']." - ".$result['message']; - } + if ($err != 0 || $httpcode != 200) { + $success = 0; + $error = $result['code'] . " - " . $result['message']; + } - if ($success) { - return 1; - } - return $error; - } -} \ No newline at end of file + if ($success) { + return 1; + } + return $error; + } +} diff --git a/src/psm/Txtmsg/Inetworx.php b/src/psm/Txtmsg/Inetworx.php index 7a09a921..21fde105 100644 --- a/src/psm/Txtmsg/Inetworx.php +++ b/src/psm/Txtmsg/Inetworx.php @@ -1,4 +1,5 @@ . * - * @package phpservermon - * @author Ward Pieters - * @author Tim Zandbergen - * @copyright Copyright (c) 2008-2017 Pepijn Over - * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 - * @version Release: @package_version@ - * @link http://www.phpservermonitor.org/ + * @package phpservermon + * @author Ward Pieters + * @author Tim Zandbergen + * @copyright Copyright (c) 2008-2017 Pepijn Over + * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 + * @version Release: @package_version@ + * @link http://www.phpservermonitor.org/ **/ namespace psm\Txtmsg; -class Inetworx extends Core { +class Inetworx extends Core +{ - /** - * Send sms using the Inetworx API - * - * @var string $message - * @var string $this->password - * @var array $this->recipients - * @var array $this->originator - * - * @var resource $curl - * @var string $err - * @var string $recipient - * @var mixed $result - * - * @var int $success - * @var string $error - * - * @return bool|string - */ + /** + * Send sms using the Inetworx API + * + * @var string $message + * @var string $this->password + * @var array $this->recipients + * @var array $this->originator + * + * @var resource $curl + * @var string $err + * @var string $recipient + * @var mixed $result + * + * @var int $success + * @var string $error + * + * @return bool|string + */ - public function sendSMS($message) { - $error = ""; - $success = 1; + public function sendSMS($message) + { + $error = ""; + $success = 1; - foreach ($this->recipients as $recipient) { - $curl = curl_init(); + foreach ($this->recipients as $recipient) { + $curl = curl_init(); - curl_setopt_array($curl, array( - CURLOPT_URL => "https://sms.inetworx.ch/smsapp/sendsms.php", - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => http_build_query( - array( - "user" => $this->username, - "pass" => $this->password, - "sender" => $this->originator, - "rcpt" => $recipient, - "msgbody" => $message, - ) - ), - CURLOPT_HTTPHEADER => array( - "authorization: Basic ".base64_encode("inetworxag:conn2smsapp"), - "content-type: application/x-www-form-urlencoded" - ), - )); + curl_setopt_array($curl, array( + CURLOPT_URL => "https://sms.inetworx.ch/smsapp/sendsms.php", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "POST", + CURLOPT_POSTFIELDS => http_build_query( + array( + "user" => $this->username, + "pass" => $this->password, + "sender" => $this->originator, + "rcpt" => $recipient, + "msgbody" => $message, + ) + ), + CURLOPT_HTTPHEADER => array( + "authorization: Basic " . base64_encode("inetworxag:conn2smsapp"), + "content-type: application/x-www-form-urlencoded" + ), + )); - $result = curl_exec($curl); - $err = curl_errno($curl); + $result = curl_exec($curl); + $err = curl_errno($curl); - $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); - if ($err != 0 || $httpcode != 200 || strpos($result, "200") === false) { - $success = 0; - $error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". \nResult: ".$result; - } - curl_close($curl); - } + $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); + if ($err != 0 || $httpcode != 200 || strpos($result, "200") === false) { + $success = 0; + $error = "HTTP_code: " . $httpcode . ".\ncURL error (" . $err . "): " . + curl_strerror($err) . ". \nResult: " . $result; + } + curl_close($curl); + } - if ($success) { - return 1; - } - return $error; - } -} \ No newline at end of file + if ($success) { + return 1; + } + return $error; + } +} diff --git a/src/psm/Txtmsg/Messagebird.php b/src/psm/Txtmsg/Messagebird.php index 3463c7d2..76f1d737 100644 --- a/src/psm/Txtmsg/Messagebird.php +++ b/src/psm/Txtmsg/Messagebird.php @@ -1,4 +1,5 @@ recipients - * @var array $this->originator (Max 11 characters) - * @var array $recipients_chunk - * @var string $this->password - * - * @var mixed $result - * @var array $headers - * - * @var int $success - * @var string $error - * - * @return bool|string - */ - - public function sendSMS($message) { - $success = 1; - $error = ''; + /** + * Send sms using the Messagebird API + * @var string $message + * @var array $this->recipients + * @var array $this->originator (Max 11 characters) + * @var array $recipients_chunk + * @var string $this->password + * + * @var mixed $result + * @var array $headers + * + * @var int $success + * @var string $error + * + * @return bool|string + */ + + public function sendSMS($message) + { + $success = 1; + $error = ''; - // Maximum of 50 users a time. - $recipients_chunk = array_chunk($this->recipients, ceil(count($this->recipients) / 50)); + // Maximum of 50 users a time. + $recipients_chunk = array_chunk($this->recipients, ceil(count($this->recipients) / 50)); - foreach ($recipients_chunk as $recipients) { - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, "https://rest.messagebird.com/messages"); - curl_setopt($ch, CURLOPT_POSTFIELDS, - "originator=".urlencode($this->originator == '' ? 'PSM' : $this->originator). - "&body=".urlencode($message). - "&recipients=".implode(",", $recipients)); - curl_setopt($ch, CURLOPT_POST, 1); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - $headers = array(); - $headers[] = "Authorization: AccessKey ".$this->password; - $headers[] = "Content-Type: application/x-www-form-urlencoded"; - curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); - $result = curl_exec($ch); - curl_close($ch); + foreach ($recipients_chunk as $recipients) { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, "https://rest.messagebird.com/messages"); + curl_setopt( + $ch, + CURLOPT_POSTFIELDS, + "originator=" . urlencode($this->originator == '' ? 'PSM' : $this->originator) . + "&body=" . urlencode($message) . + "&recipients=" . implode(",", $recipients) + ); + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + $headers = array(); + $headers[] = "Authorization: AccessKey " . $this->password; + $headers[] = "Content-Type: application/x-www-form-urlencoded"; + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); + $result = curl_exec($ch); + curl_close($ch); - // Check on error - if (is_numeric(strpos($result, "{\"errors\":"))) { - $error = $result; - $success = 0; - } - } - if ($success) { - return 1; - } - return $error; - } -} \ No newline at end of file + // Check on error + if (is_numeric(strpos($result, "{\"errors\":"))) { + $error = $result; + $success = 0; + } + } + if ($success) { + return 1; + } + return $error; + } +} diff --git a/src/psm/Txtmsg/Mosms.php b/src/psm/Txtmsg/Mosms.php index 28420d5d..98381579 100644 --- a/src/psm/Txtmsg/Mosms.php +++ b/src/psm/Txtmsg/Mosms.php @@ -1,4 +1,5 @@ . * - * @package phpservermon - * @author Ward Pieters - * @copyright Copyright (c) 2008-2017 Pepijn Over - * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 - * @version Release: @package_version@ - * @link http://www.phpservermonitor.org/ - * @since phpservermon 2.1 + * @package phpservermon + * @author Ward Pieters + * @copyright Copyright (c) 2008-2017 Pepijn Over + * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 + * @version Release: @package_version@ + * @link http://www.phpservermonitor.org/ + * @since phpservermon 2.1 **/ namespace psm\Txtmsg; -class Mosms extends Core { +class Mosms extends Core +{ - /** - * Send sms using the Mosms API - * - * @var string $message - * @var array $this->username - * @var string $this->password - * @var array $this->recipients - * @var string $recipient - * @var array $this->originator (Max 11 characters) - * - * @var resource $curl - * @var string $err - * @var int $success - * @var string $error - * - * @return bool|string - */ - - public function sendSMS($message) { - $error = ""; - $success = 1; - - $message = rawurlencode($message); - - foreach ($this->recipients as $recipient) { - - $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, "https://www.mosms.com/se/sms-send.php?".http_build_query( - array( - "username" => $this->username, - "password" => $this->password, - "customsender" => substr($this->originator, 0, 11), - "nr" => $recipient, - "type" => "text", - "data" => $message, - ) - ) - ); - curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); - - $result = curl_exec($curl); - $err = curl_errno($curl); - - if ($err != 0 || $httpcode != 200 || $result == 2 || $result == 5) { - $success = 0; - $error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".$err.". \nResult: ".$result; - } - curl_close($curl); - - } - - if ($success) { - return 1; - } - return $error; - } -} \ No newline at end of file + /** + * Send sms using the Mosms API + * + * @var string $message + * @var array $this->username + * @var string $this->password + * @var array $this->recipients + * @var string $recipient + * @var array $this->originator (Max 11 characters) + * + * @var resource $curl + * @var string $err + * @var int $success + * @var string $error + * + * @return bool|string + */ + + public function sendSMS($message) + { + $error = ""; + $success = 1; + + $message = rawurlencode($message); + + foreach ($this->recipients as $recipient) { + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, "https://www.mosms.com/se/sms-send.php?" . http_build_query( + array( + "username" => $this->username, + "password" => $this->password, + "customsender" => substr($this->originator, 0, 11), + "nr" => $recipient, + "type" => "text", + "data" => $message, + ) + )); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); + + $result = curl_exec($curl); + $err = curl_errno($curl); + + if ($err != 0 || $httpcode != 200 || $result == 2 || $result == 5) { + $success = 0; + $error = "HTTP_code: " . $httpcode . ".\ncURL error (" . $err . "): " . $err . ". \nResult: " . $result; + } + curl_close($curl); + } + + if ($success) { + return 1; + } + return $error; + } +} diff --git a/src/psm/Txtmsg/Nexmo.php b/src/psm/Txtmsg/Nexmo.php index a4bf51ff..2d185574 100644 --- a/src/psm/Txtmsg/Nexmo.php +++ b/src/psm/Txtmsg/Nexmo.php @@ -1,4 +1,5 @@ . * - * @package phpservermon - * @author Ward Pieters - * @copyright Copyright (c) 2008-2017 Pepijn Over - * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 - * @version Release: @package_version@ - * @link http://www.phpservermonitor.org/ - * @since phpservermon 3.1.1 + * @package phpservermon + * @author Ward Pieters + * @copyright Copyright (c) 2008-2017 Pepijn Over + * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 + * @version Release: @package_version@ + * @link http://www.phpservermonitor.org/ + * @since phpservermon 3.1.1 **/ namespace psm\Txtmsg; -class Nexmo extends Core { - - - /** - * Send sms using the GatewayAPI API - * - * @var string $message - * @var string $this->password - * @var array $this->recipients - * @var array $this->originator - * @var string $recipient - * - * @var resource $curl - * @var string $err - * @var mixed $result - * - * @var int $success - * @var string $error - * - * @return bool|string - */ - - public function sendSMS($message) { - $success = 1; - $error = ""; +class Nexmo extends Core +{ + + + /** + * Send sms using the GatewayAPI API + * + * @var string $message + * @var string $this->password + * @var array $this->recipients + * @var array $this->originator + * @var string $recipient + * + * @var resource $curl + * @var string $err + * @var mixed $result + * + * @var int $success + * @var string $error + * + * @return bool|string + */ + + public function sendSMS($message) + { + $success = 1; + $error = ""; - foreach ($this->recipients as $recipient) { - - $curl = curl_init(); - curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - curl_setopt($curl, CURLOPT_URL, "https://rest.nexmo.com/sms/json?".http_build_query( - array( - "api_key" => $this->username, - "api_secret" => $this->password, - "from" => $this->originator, - "to" => $recipient, - "text" => $message, - ) - ) - ); - - $result = json_decode(curl_exec($curl), true); - $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); - $err = curl_errno($curl); - - if ($err != 0 || $httpcode != 200 || $result['messages'][0]['status'] != "0") { - $success = 0; - $error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". \nResult: ".$result['messages'][0]['error-text']; - } - curl_close($curl); - - } - - if ($success) { - return 1; - } - return $error; - } -} \ No newline at end of file + foreach ($this->recipients as $recipient) { + $curl = curl_init(); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curl, CURLOPT_URL, "https://rest.nexmo.com/sms/json?" . http_build_query( + array( + "api_key" => $this->username, + "api_secret" => $this->password, + "from" => $this->originator, + "to" => $recipient, + "text" => $message, + ) + )); + + $result = json_decode(curl_exec($curl), true); + $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); + $err = curl_errno($curl); + + if ($err != 0 || $httpcode != 200 || $result['messages'][0]['status'] != "0") { + $success = 0; + $error = "HTTP_code: " . $httpcode . ".\ncURL error (" . $err . "): " . curl_strerror($err) . + ". \nResult: " . $result['messages'][0]['error-text']; + } + curl_close($curl); + } + + if ($success) { + return 1; + } + return $error; + } +} diff --git a/src/psm/Txtmsg/Octopush.php b/src/psm/Txtmsg/Octopush.php index b515f7c2..4ce98de1 100644 --- a/src/psm/Txtmsg/Octopush.php +++ b/src/psm/Txtmsg/Octopush.php @@ -1,4 +1,5 @@ . * - * @package phpservermon - * @author Alexis Urien - * @Author Tim Zandbergen - * @author Ward Pieters - * @copyright Copyright (c) 2016 Alexis Urien - * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 - * @version Release: @package_version@ - * @link http://www.phpservermonitor.org/ - * @since phpservermon 2.1 + * @package phpservermon + * @author Alexis Urien + * @Author Tim Zandbergen + * @author Ward Pieters + * @copyright Copyright (c) 2016 Alexis Urien + * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 + * @version Release: @package_version@ + * @link http://www.phpservermonitor.org/ + * @since phpservermon 2.1 **/ namespace psm\Txtmsg; -class Octopush extends Core { - - /** - * Send sms using the Octopush API - * @var string $message - * @var string $this->username - * @var string $this->password - * @var array $this->recipients - * @var array $this->originator - * - * @var resource $curl - * @var SimpleXMLElement $xmlResults - * @var string $err - * @var string $recipient - * @var string $smsType - * @var mixed $result - * - * @var int $success - * @var string $error - * - * @return bool|string - */ - - public function sendSMS($message) { - $error = ""; - $success = 1; - $smsType = "XXX"; //FR = premium, WWW = world, XXX = Low cost - - $recipients = join(',', $this->recipients); - - $message = ($smsType == "FR") ? urlencode($message." STOP au XXXX") : urlencode($message); +class Octopush extends Core +{ + + /** + * Send sms using the Octopush API + * @var string $message + * @var string $this->username + * @var string $this->password + * @var array $this->recipients + * @var array $this->originator + * + * @var resource $curl + * @var SimpleXMLElement $xmlResults + * @var string $err + * @var string $recipient + * @var string $smsType + * @var mixed $result + * + * @var int $success + * @var string $error + * + * @return bool|string + */ + + public function sendSMS($message) + { + $error = ""; + $success = 1; + $smsType = "XXX"; //FR = premium, WWW = world, XXX = Low cost + + $recipients = join(',', $this->recipients); + + $message = ($smsType == "FR") ? urlencode($message . " STOP au XXXX") : urlencode($message); - $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, "http://www.octopush-dm.com/api/sms/?".http_build_query( - array( - "user_login" => $this->username, - "api_key" => $this->password, - "sms_recipients" => $recipients, - "sms_type" => $smsType, - "sms_sender" => substr($this->originator, 0, 11), - "sms_text" => $message, - ) - ) - ); - curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - - $result = curl_exec($curl); - $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); - $xmlResults = simplexml_load_string($result); - $err = curl_errno($curl); + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, "http://www.octopush-dm.com/api/sms/?" . http_build_query( + array( + "user_login" => $this->username, + "api_key" => $this->password, + "sms_recipients" => $recipients, + "sms_type" => $smsType, + "sms_sender" => substr($this->originator, 0, 11), + "sms_text" => $message, + ) + )); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + + $result = curl_exec($curl); + $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); + $xmlResults = simplexml_load_string($result); + $err = curl_errno($curl); - if ($err != 0 || $httpcode != 200 || $xmlResults === false || $xmlResults->error_code != '000') { - $success = 0; - $error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". \nResult: ".$xmlResults->error_code.". Look at http://www.octopush-dm.com/en/errors for the error description."; - } - curl_close($curl); - - if ($success) { - return 1; - } - return $error; - } -} \ No newline at end of file + if ($err != 0 || $httpcode != 200 || $xmlResults === false || $xmlResults->error_code != '000') { + $success = 0; + $error = "HTTP_code: " . $httpcode . ".\ncURL error (" . $err . "): " . curl_strerror($err) . + ". \nResult: " . $xmlResults->error_code . + ". Look at http://www.octopush-dm.com/en/errors for the error description."; + } + curl_close($curl); + + if ($success) { + return 1; + } + return $error; + } +} diff --git a/src/psm/Txtmsg/Plivo.php b/src/psm/Txtmsg/Plivo.php index f4790cf1..e2eec00f 100644 --- a/src/psm/Txtmsg/Plivo.php +++ b/src/psm/Txtmsg/Plivo.php @@ -1,4 +1,5 @@ . * - * @package phpservermon - * @author Tim Zandbergen - * @author Ward Pieters - * @copyright Copyright (c) 2008-2017 Pepijn Over - * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 - * @version Release: @package_version@ - * @link http://www.phpservermonitor.org/ - * @since phpservermon 3.3.0 + * @package phpservermon + * @author Tim Zandbergen + * @author Ward Pieters + * @copyright Copyright (c) 2008-2017 Pepijn Over + * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 + * @version Release: @package_version@ + * @link http://www.phpservermonitor.org/ + * @since phpservermon 3.3.0 **/ namespace psm\Txtmsg; -class Plivo extends Core { - - /** - * Send sms using the Plivo API - * - * @var string $message - * @var string $this->password - * @var array $this->recipients - * @var array $this->originator - * @var string $recipients - * - * @var resource $curl - * @var string $err - * @var int $success - * @var string $error - * - * @return bool|string - */ - - public function sendSMS($message) { - $error = ""; - $success = 1; - - if (empty($this->recipients)) { - return false; - } - - $recipients = join('<', $this->recipients); - - $curl = curl_init(); - curl_setopt_array($curl, array( - CURLOPT_URL => "https://api.plivo.com/v1/Account/".$this->username."/Message/", - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => json_encode( - array( - "src" => $this->originator, - "dst" => $recipients, - "text" => urlencode($message) - ) - ), - CURLOPT_HTTPHEADER => array( - "authorization: Basic ".base64_encode($this->username.":".$this->password), - "content-type: application/json" - ), - )); - - $result = curl_exec($curl); - $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); - $err = curl_errno($curl); - - if ($err != 0 || ($httpcode != '200' && $httpcode != '201' && $httpcode != '202')) { - $success = 0; - $error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". Result: ".$result.""; - } - curl_close($curl); - - if ($success) { - return 1; - } - return $error; - } -} \ No newline at end of file +class Plivo extends Core +{ + + /** + * Send sms using the Plivo API + * + * @var string $message + * @var string $this->password + * @var array $this->recipients + * @var array $this->originator + * @var string $recipients + * + * @var resource $curl + * @var string $err + * @var int $success + * @var string $error + * + * @return bool|string + */ + + public function sendSMS($message) + { + $error = ""; + $success = 1; + + if (empty($this->recipients)) { + return false; + } + + $recipients = join('<', $this->recipients); + + $curl = curl_init(); + curl_setopt_array($curl, array( + CURLOPT_URL => "https://api.plivo.com/v1/Account/" . $this->username . "/Message/", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "POST", + CURLOPT_POSTFIELDS => json_encode( + array( + "src" => $this->originator, + "dst" => $recipients, + "text" => urlencode($message) + ) + ), + CURLOPT_HTTPHEADER => array( + "authorization: Basic " . base64_encode($this->username . ":" . $this->password), + "content-type: application/json" + ), + )); + + $result = curl_exec($curl); + $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); + $err = curl_errno($curl); + + if ($err != 0 || ($httpcode != '200' && $httpcode != '201' && $httpcode != '202')) { + $success = 0; + $error = "HTTP_code: " . $httpcode . ".\ncURL error (" . $err . "): " . + curl_strerror($err) . ". Result: " . $result . ""; + } + curl_close($curl); + + if ($success) { + return 1; + } + return $error; + } +} diff --git a/src/psm/Txtmsg/Smsglobal.php b/src/psm/Txtmsg/Smsglobal.php index 7cd3da47..9947b05a 100644 --- a/src/psm/Txtmsg/Smsglobal.php +++ b/src/psm/Txtmsg/Smsglobal.php @@ -1,4 +1,5 @@ . * - * @package phpservermon - * @author Ward Pieters - * @copyright Copyright (c) 2008-2017 Pepijn Over - * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 - * @version Release: @package_version@ - * @link http://www.phpservermonitor.org/ - * @since phpservermon 3.1 + * @package phpservermon + * @author Ward Pieters + * @copyright Copyright (c) 2008-2017 Pepijn Over + * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 + * @version Release: @package_version@ + * @link http://www.phpservermonitor.org/ + * @since phpservermon 3.1 **/ namespace psm\Txtmsg; -class Smsglobal extends Core { +class Smsglobal extends Core +{ - /** - * Send sms using the Smsglobal API - * @var string $message - * @var string $this->password - * @var array $this->recipients - * @var array $this->originator - * - * @var resource $curl - * @var string $err - * @var string $recipient - * @var string $from - * @var mixed $result - * - * @var int $success - * @var string $error - * - * @return bool|string - */ - - public function sendSMS($message) { - $error = ""; - $success = 1; - - $recipients = join(',', $this->recipients); - - $from = substr($this->originator, 0, 11); // Max 11 Characters - $message = substr(rawurlencode($message), 0, 153); - - $curl = curl_init(); - curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - curl_setopt($curl, CURLOPT_TIMEOUT, 30); - curl_setopt($curl, CURLOPT_URL, "https://www.smsglobal.com/http-api.php?".http_build_query( - array( - "action" => "sendsms", - "user" => $this->username, - "password" => $this->password, - "from" => $from, - "to" => $recipients, - "clientcharset" => "ISO-8859-1", - "text" => $message, - ) - )); - - $result = curl_exec($curl); - $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); - - $err = curl_errno($curl); - - if ($err != 0 || substr($result, 0, 5) != "OK: 0") { - $success = 0; - $result = ($result == '') ? 'Wrong input, please check if all values are correct!' : $result; - $error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". \nResult: ".$result; - } - curl_close($curl); - - if ($success) { - return 1; - } - return $error; - } -} \ No newline at end of file + /** + * Send sms using the Smsglobal API + * @var string $message + * @var string $this->password + * @var array $this->recipients + * @var array $this->originator + * + * @var resource $curl + * @var string $err + * @var string $recipient + * @var string $from + * @var mixed $result + * + * @var int $success + * @var string $error + * + * @return bool|string + */ + + public function sendSMS($message) + { + $error = ""; + $success = 1; + + $recipients = join(',', $this->recipients); + + $from = substr($this->originator, 0, 11); // Max 11 Characters + $message = substr(rawurlencode($message), 0, 153); + + $curl = curl_init(); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curl, CURLOPT_TIMEOUT, 30); + curl_setopt($curl, CURLOPT_URL, "https://www.smsglobal.com/http-api.php?" . http_build_query( + array( + "action" => "sendsms", + "user" => $this->username, + "password" => $this->password, + "from" => $from, + "to" => $recipients, + "clientcharset" => "ISO-8859-1", + "text" => $message, + ) + )); + + $result = curl_exec($curl); + $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); + + $err = curl_errno($curl); + + if ($err != 0 || substr($result, 0, 5) != "OK: 0") { + $success = 0; + $result = ($result == '') ? 'Wrong input, please check if all values are correct!' : $result; + $error = "HTTP_code: " . $httpcode . ".\ncURL error (" . $err . "): " . + curl_strerror($err) . ". \nResult: " . $result; + } + curl_close($curl); + + if ($success) { + return 1; + } + return $error; + } +} diff --git a/src/psm/Txtmsg/Smsgw.php b/src/psm/Txtmsg/Smsgw.php index 67fb22d9..2267a54d 100644 --- a/src/psm/Txtmsg/Smsgw.php +++ b/src/psm/Txtmsg/Smsgw.php @@ -1,4 +1,5 @@ password - * @var array $this->recipients - * @var array $this->originator - * @var string $recipients - * - * @var resource $curl - * @var string $err - * @var int $success - * @var string $error - * - * @return bool|string - */ + /** + * Send sms using the SMSgw.NET API + * + * @var string $message + * @var string $this->password + * @var array $this->recipients + * @var array $this->originator + * @var string $recipients + * + * @var resource $curl + * @var string $err + * @var int $success + * @var string $error + * + * @return bool|string + */ - public function sendSMS($message) { - $error = ""; - $success = 1; + public function sendSMS($message) + { + $error = ""; + $success = 1; - $recipients = join(';', $this->recipients); + $recipients = join(';', $this->recipients); - $curl = curl_init(); - curl_setopt_array($curl, array( - CURLOPT_URL => "https://api.smsgw.net/SendBulkSMS", - CURLOPT_RETURNTRANSFER => true, - CURLOPT_ENCODING => "", - CURLOPT_MAXREDIRS => 10, - CURLOPT_TIMEOUT => 30, - CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, - CURLOPT_CUSTOMREQUEST => "POST", - CURLOPT_POSTFIELDS => array( - 'strUserName' => $this->username, - 'strPassword' => $this->password, - "strTagName" => $this->originator, - "strRecepientNumbers" => $recipients, - "strMessage" => urlencode($message), - ), - )); + $curl = curl_init(); + curl_setopt_array($curl, array( + CURLOPT_URL => "https://api.smsgw.net/SendBulkSMS", + CURLOPT_RETURNTRANSFER => true, + CURLOPT_ENCODING => "", + CURLOPT_MAXREDIRS => 10, + CURLOPT_TIMEOUT => 30, + CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, + CURLOPT_CUSTOMREQUEST => "POST", + CURLOPT_POSTFIELDS => array( + 'strUserName' => $this->username, + 'strPassword' => $this->password, + "strTagName" => $this->originator, + "strRecepientNumbers" => $recipients, + "strMessage" => urlencode($message), + ), + )); - $result = curl_exec($curl); - $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); - $err = curl_errno($curl); - - if ($err != 0 || ($httpcode != '200' && $httpcode != '201' && $httpcode != '202' && $result != "1")) { - $success = 0; - $error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". Result: ".$result.""; - } - curl_close($curl); + $result = curl_exec($curl); + $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); + $err = curl_errno($curl); + + if ($err != 0 || ($httpcode != '200' && $httpcode != '201' && $httpcode != '202' && $result != "1")) { + $success = 0; + $error = "HTTP_code: " . $httpcode . ".\ncURL error (" . $err . "): " . + curl_strerror($err) . ". Result: " . $result . ""; + } + curl_close($curl); - if ($success) { - return 1; - } - return $error; - } -} \ No newline at end of file + if ($success) { + return 1; + } + return $error; + } +} diff --git a/src/psm/Txtmsg/Smsit.php b/src/psm/Txtmsg/Smsit.php index 5b8f61b8..964ff5eb 100644 --- a/src/psm/Txtmsg/Smsit.php +++ b/src/psm/Txtmsg/Smsit.php @@ -1,4 +1,5 @@ . * - * @package phpservermon - * @author Ward Pieters - * @copyright Copyright (c) 2008-2017 Pepijn Over - * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 - * @version Release: @package_version@ - * @link http://www.phpservermonitor.org/ - * @since phpservermon 3.1 + * @package phpservermon + * @author Ward Pieters + * @copyright Copyright (c) 2008-2017 Pepijn Over + * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 + * @version Release: @package_version@ + * @link http://www.phpservermonitor.org/ + * @since phpservermon 3.1 **/ namespace psm\Txtmsg; -class Smsit extends Core { - - /** - * Send sms using the Smsit API - * - * @var string $message - * @var string $this->password - * @var array $this->recipients - * @var array $this->originator - * - * @var resource $curl - * @var string $err - * @var String $recipient - * @var mixed $result - * - * @var int $success - * @var string $error - * - * @return bool|string - */ - - public function sendSMS($message) { - $success = 1; - $error = ""; - - foreach ($this->recipients as $recipient) { - - $curl = curl_init(); - curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - curl_setopt($curl, CURLOPT_URL, "https://www.smsit.dk/api/v2?".http_build_query( - array( - "apiKey" => $this->password, - "mobile" => $recipient, - "message" => urlencode($message), - "senderId" => substr($this->originator, 0, 11), - ) - ) - ); - - $result = curl_exec($curl); - $err = curl_errno($curl); - curl_close($curl); - - if ($err != 0 || is_numeric(strpos($result, "{\"errors\":[{\"code\":"))) { - $success = 0; - $error = $result; - } - } - - if ($success) { - return 1; - } - return $error; - } -} \ No newline at end of file +class Smsit extends Core +{ + + /** + * Send sms using the Smsit API + * + * @var string $message + * @var string $this->password + * @var array $this->recipients + * @var array $this->originator + * + * @var resource $curl + * @var string $err + * @var String $recipient + * @var mixed $result + * + * @var int $success + * @var string $error + * + * @return bool|string + */ + + public function sendSMS($message) + { + $success = 1; + $error = ""; + + foreach ($this->recipients as $recipient) { + $curl = curl_init(); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curl, CURLOPT_URL, "https://www.smsit.dk/api/v2?" . http_build_query( + array( + "apiKey" => $this->password, + "mobile" => $recipient, + "message" => urlencode($message), + "senderId" => substr($this->originator, 0, 11), + ) + )); + + $result = curl_exec($curl); + $err = curl_errno($curl); + curl_close($curl); + + if ($err != 0 || is_numeric(strpos($result, "{\"errors\":[{\"code\":"))) { + $success = 0; + $error = $result; + } + } + + if ($success) { + return 1; + } + return $error; + } +} diff --git a/src/psm/Txtmsg/SolutionsInfini.php b/src/psm/Txtmsg/SolutionsInfini.php index 46091dd8..a21d1479 100644 --- a/src/psm/Txtmsg/SolutionsInfini.php +++ b/src/psm/Txtmsg/SolutionsInfini.php @@ -1,4 +1,5 @@ . * - * @package phpservermon - * @author Ward Pieters - * @author Tim Zandbergen - * @copyright Copyright (c) 2008-2017 Pepijn Over - * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 - * @version Release: @package_version@ - * @link http://www.phpservermonitor.org/ - * @since phpservermon 3.3.0 + * @package phpservermon + * @author Ward Pieters + * @author Tim Zandbergen + * @copyright Copyright (c) 2008-2017 Pepijn Over + * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 + * @version Release: @package_version@ + * @link http://www.phpservermonitor.org/ + * @since phpservermon 3.3.0 **/ namespace psm\Txtmsg; -class SolutionsInfini extends Core { +class SolutionsInfini extends Core +{ - /** - * Send sms using the SolutionsInfini API - * - * @var string $message - * @var string $this->password - * @var array $this->recipients - * @var string $recipients - * @var array $this->originator (Max 11 characters) - * - * @var resource $curl - * @var string $err - * - * @var int $success - * @var string $error - * - * @return bool|string - */ - - public function sendSMS($message) { - $error = ""; - $success = 1; + /** + * Send sms using the SolutionsInfini API + * + * @var string $message + * @var string $this->password + * @var array $this->recipients + * @var string $recipients + * @var array $this->originator (Max 11 characters) + * + * @var resource $curl + * @var string $err + * + * @var int $success + * @var string $error + * + * @return bool|string + */ + + public function sendSMS($message) + { + $error = ""; + $success = 1; - $message = urlencode($message); + $message = urlencode($message); - $recipients = join(',', $this->recipients); + $recipients = join(',', $this->recipients); - $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL, "https://api-alerts.solutionsinfini.com/v4/?".http_build_query( - array( - "api_key" => $this->password, - "method" => "sms", - "to" => $recipients, - "sender" => substr($this->originator, 0, 11), - "message" => $message, - ) - ) - ); - curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, "https://api-alerts.solutionsinfini.com/v4/?" . http_build_query( + array( + "api_key" => $this->password, + "method" => "sms", + "to" => $recipients, + "sender" => substr($this->originator, 0, 11), + "message" => $message, + ) + )); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - $result = json_decode(curl_exec($curl), true); - $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); - $err = curl_errno($curl); + $result = json_decode(curl_exec($curl), true); + $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); + $err = curl_errno($curl); - if ($err != 0 || $httpcode != 200 || $result['status'] != "OK") { - $success = 0; - $error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". Result: ".$result['status']." - ".$result['message']."."; - } - curl_close($curl); - if ($success) { - return 1; - } - return $error; - } -} \ No newline at end of file + if ($err != 0 || $httpcode != 200 || $result['status'] != "OK") { + $success = 0; + $error = "HTTP_code: " . $httpcode . ".\ncURL error (" . $err . "): " . + curl_strerror($err) . ". Result: " . $result['status'] . " - " . $result['message'] . "."; + } + curl_close($curl); + if ($success) { + return 1; + } + return $error; + } +} diff --git a/src/psm/Txtmsg/Spryng.php b/src/psm/Txtmsg/Spryng.php index df3eddb1..de148eab 100644 --- a/src/psm/Txtmsg/Spryng.php +++ b/src/psm/Txtmsg/Spryng.php @@ -1,4 +1,5 @@ . * - * @package phpservermon - * @author Pepijn Over - * @copyright Copyright (c) 2008-2017 Pepijn Over - * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 - * @version Release: @package_version@ - * @link http://www.phpservermonitor.org/ + * @package phpservermon + * @author Pepijn Over + * @copyright Copyright (c) 2008-2017 Pepijn Over + * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 + * @version Release: @package_version@ + * @link http://www.phpservermonitor.org/ **/ namespace psm\Txtmsg; -class Spryng extends Core { +class Spryng extends Core +{ - /** - * Send sms using the Spryngsms API - * @var string $message - * @var array $this->recipients - * @var string $this->username - * @var string $this->password - * @var string $this->originator - * @var mixed $result - * @var array $headers - * - * @var int $success - * @var string $error - * - * @return bool|string - */ + /** + * Send sms using the Spryngsms API + * @var string $message + * @var array $this->recipients + * @var string $this->username + * @var string $this->password + * @var string $this->originator + * @var mixed $result + * @var array $headers + * + * @var int $success + * @var string $error + * + * @return bool|string + */ - public function sendSMS($message) { - $recipients = implode(",", $this->recipients); + public function sendSMS($message) + { + $recipients = implode(",", $this->recipients); - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, "https://api.spryngsms.com/api/send.php?OPERATION=send&USERNAME=".urlencode($this->username)."&PASSWORD=".urlencode($this->password)."&DESTINATION=".urlencode($recipients)."&SENDER=".urlencode($this->originator)."&BODY=".urlencode($message)."&SMSTYPE=BUSINESS"); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - $headers = array(); - $headers[] = "Content-Type: application/x-www-form-urlencoded"; - curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); - $result = curl_exec($ch); - curl_close($ch); + $ch = curl_init(); + curl_setopt( + $ch, + CURLOPT_URL, + "https://api.spryngsms.com/api/send.php?OPERATION=send&USERNAME=" . + urlencode($this->username) . + "&PASSWORD=" . urlencode($this->password) . + "&DESTINATION=" . urlencode($recipients) . + "&SENDER=" . urlencode($this->originator) . + "&BODY=" . urlencode($message) . "&SMSTYPE=BUSINESS" + ); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + $headers = array(); + $headers[] = "Content-Type: application/x-www-form-urlencoded"; + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); + $result = curl_exec($ch); + curl_close($ch); - // Check on error - if ($result != 1) { - return "Error ".$result.": see http://www.spryng.nl/en/developers/http-api/ for the description."; - } - return 1; - } + // Check on error + if ($result != 1) { + return "Error " . $result . ": see http://www.spryng.nl/en/developers/http-api/ for the description."; + } + return 1; + } } diff --git a/src/psm/Txtmsg/Textmarketer.php b/src/psm/Txtmsg/Textmarketer.php index 5efbf621..94bb4a2f 100644 --- a/src/psm/Txtmsg/Textmarketer.php +++ b/src/psm/Txtmsg/Textmarketer.php @@ -1,4 +1,5 @@ . * - * @package phpservermon - * @author Perri Vardy-Mason - * @author Tim Zandbergen - * @copyright Copyright (c) 2008-2017 Pepijn Over - * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 - * @version Release: @package_version@ - * @link http://www.phpservermonitor.org/ - * @since phpservermon 2.1 + * @package phpservermon + * @author Perri Vardy-Mason + * @author Tim Zandbergen + * @copyright Copyright (c) 2008-2017 Pepijn Over + * @license http://www.gnu.org/licenses/gpl.txt GNU GPL v3 + * @version Release: @package_version@ + * @link http://www.phpservermonitor.org/ + * @since phpservermon 2.1 **/ namespace psm\Txtmsg; -class Textmarketer extends Core { +class Textmarketer extends Core +{ - /** - * Send sms using the Textmarketer API - * @var string $message - * @var array $this->recipients - * @var string $recipient - * @var string $this->username - * @var string $this->password - * @var mixed $result - * @var array $headers - * - * @var int $success - * @var string $error - * - * @return bool|string - */ + /** + * Send sms using the Textmarketer API + * @var string $message + * @var array $this->recipients + * @var string $recipient + * @var string $this->username + * @var string $this->password + * @var mixed $result + * @var array $headers + * + * @var int $success + * @var string $error + * + * @return bool|string + */ - public function sendSMS($message) { - $success = 1; - $error = ''; - foreach ($this->recipients as $recipient) { + public function sendSMS($message) + { + $success = 1; + $error = ''; + foreach ($this->recipients as $recipient) { + $ch = curl_init(); + curl_setopt( + $ch, + CURLOPT_URL, + "https://api.textmarketer.co.uk/gateway/?username=" . $this->username . + "&password=" . $this->password . + "&to=" . $recipient . + "&message=" . urlencode($message) . + "&orig=SERVERALERT" + ); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + $headers = array(); + $headers[] = "Content-Type: application/x-www-form-urlencoded"; + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); + $result = curl_exec($ch); + curl_close($ch); - $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_RETURNTRANSFER, 1); - $headers = array(); - $headers[] = "Content-Type: application/x-www-form-urlencoded"; - curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); - $result = curl_exec($ch); - curl_close($ch); - - // Check on error - if (is_numeric(strpos($result, "FAILED"))) { - $error = $result; - $success = 0; - } - } - if ($success == 1) { - return 1; - } - return $error; - } + // Check on error + if (is_numeric(strpos($result, "FAILED"))) { + $error = $result; + $success = 0; + } + } + if ($success == 1) { + return 1; + } + return $error; + } } diff --git a/src/psm/Txtmsg/Twilio.php b/src/psm/Txtmsg/Twilio.php index 1d37c220..34490366 100644 --- a/src/psm/Txtmsg/Twilio.php +++ b/src/psm/Txtmsg/Twilio.php @@ -1,4 +1,5 @@ recipients - * @var string $recipient - * @var string $this->username - * @var string $this->password - * @var string $this->originator - * @var mixed $result - * @var array $headers - * - * @var int $success - * @var string $error - * - * @return bool|string - */ - - public function sendSMS($message) { - $success = 1; - $error = ''; + /** + * Send sms using the Twilio API + * https://www.twilio.com/docs/sms/api#send-an-sms-with-the-sms-api + * @var string $message + * @var array $this->recipients + * @var string $recipient + * @var string $this->username + * @var string $this->password + * @var string $this->originator + * @var mixed $result + * @var array $headers + * + * @var int $success + * @var string $error + * + * @return bool|string + */ + + public function sendSMS($message) + { + $success = 1; + $error = ''; - foreach ($this->recipients as $recipient) { - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, "https://api.twilio.com/2010-04-01/Accounts/".$this->username."/Messages.json"); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_POSTFIELDS, "From=".urlencode($this->originator)."&Body=".urlencode($message)."&To=".urlencode($recipient)); - curl_setopt($ch, CURLOPT_POST, 1); - curl_setopt($ch, CURLOPT_USERPWD, $this->username.":".$this->password); + foreach ($this->recipients as $recipient) { + $ch = curl_init(); + curl_setopt( + $ch, + CURLOPT_URL, + "https://api.twilio.com/2010-04-01/Accounts/" . $this->username . "/Messages.json" + ); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt( + $ch, + CURLOPT_POSTFIELDS, + "From=" . urlencode($this->originator) . + "&Body=" . urlencode($message) . + "&To=" . urlencode($recipient) + ); + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_USERPWD, $this->username . ":" . $this->password); - $headers = array(); - $headers[] = "Content-Type: application/x-www-form-urlencoded"; - curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); + $headers = array(); + $headers[] = "Content-Type: application/x-www-form-urlencoded"; + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); - $result = curl_exec($ch); - curl_close($ch); + $result = curl_exec($ch); + curl_close($ch); - // When the result string starts with {"code": there is a problem - if (strpos($result, "{\"code\":") === 0) { - $error = $result; - $success = 0; - } - } - if ($success) { - return 1; - } - return $error; - } -} \ No newline at end of file + // When the result string starts with {"code": there is a problem + if (strpos($result, "{\"code\":") === 0) { + $error = $result; + $success = 0; + } + } + if ($success) { + return 1; + } + return $error; + } +} diff --git a/src/psm/Txtmsg/TxtmsgInterface.php b/src/psm/Txtmsg/TxtmsgInterface.php index eed3441a..e96e74af 100644 --- a/src/psm/Txtmsg/TxtmsgInterface.php +++ b/src/psm/Txtmsg/TxtmsgInterface.php @@ -1,4 +1,5 @@ db = $db; - $this->logger = $logger; - } + /** + * Open a new installer instance + * @param \psm\Service\Database $db + * @param callable $logger + */ + public function __construct(\psm\Service\Database $db, $logger = null) + { + $this->db = $db; + $this->logger = $logger; + } - /** - * Check if an upgrade is required for the current version. - * @return boolean - * @see upgrade() - */ - public function isUpgradeRequired() { - $version_db = psm_get_conf('version'); + /** + * Check if an upgrade is required for the current version. + * @return boolean + * @see upgrade() + */ + public function isUpgradeRequired() + { + $version_db = psm_get_conf('version'); - if (version_compare(PSM_VERSION, $version_db, '==')) { - // version is up to date - return false; - } + if (version_compare(PSM_VERSION, $version_db, '==')) { + // version is up to date + return false; + } - // different DB version, check if the version requires any changes - if (version_compare($version_db, PSM_VERSION, '<')) { - return true; - } else { - // change database version to current version so this check won't be required next time - psm_update_conf('version', PSM_VERSION); - } - return false; - } + // different DB version, check if the version requires any changes + if (version_compare($version_db, PSM_VERSION, '<')) { + return true; + } else { + // change database version to current version so this check won't be required next time + psm_update_conf('version', PSM_VERSION); + } + return false; + } - /** - * Log a message to the logger callable (if any) - * @param string|array $msg - * @return \psm\Util\Install\Installer - */ - protected function log($msg) { - if (is_callable($this->logger)) { - $msg = (!is_array($msg)) ? array($msg) : $msg; + /** + * Log a message to the logger callable (if any) + * @param string|array $msg + * @return \psm\Util\Install\Installer + */ + protected function log($msg) + { + if (is_callable($this->logger)) { + $msg = (!is_array($msg)) ? array($msg) : $msg; - foreach ($msg as $m) { - call_user_func($this->logger, $m); - } - } - return $this; - } + foreach ($msg as $m) { + call_user_func($this->logger, $m); + } + } + return $this; + } - /** - * Execute one or more queries. Does no fetching or anything, so execute only. - * @param string|array $query - * @return \psm\Util\Install\Installer - */ - protected function execSQL($query) { - $query = (!is_array($query)) ? array($query) : $query; + /** + * Execute one or more queries. Does no fetching or anything, so execute only. + * @param string|array $query + * @return \psm\Util\Install\Installer + */ + protected function execSQL($query) + { + $query = (!is_array($query)) ? array($query) : $query; - foreach ($query as $q) { - $this->queries[] = $q; - $this->db->exec($q); - } - return $this; - } + foreach ($query as $q) { + $this->queries[] = $q; + $this->db->exec($q); + } + return $this; + } - /** - * Retrieve table queries for install - */ - public function install() { - $this->installTables(); + /** + * Retrieve table queries for install + */ + public function install() + { + $this->installTables(); - $this->log('Populating database...'); - $queries = array(); - $queries[] = "INSERT INTO `".PSM_DB_PREFIX."servers` (`ip`, `port`, `label`, `type`, `pattern`, `pattern_online`, `redirect_check`, `status`, `rtime`, `active`, `email`, `sms`, `pushover`, `telegram`) VALUES ('http://sourceforge.net/index.php', 80, 'SourceForge', 'website', '', 'yes', 'bad', 'on', '0.0000000', 'yes', 'yes', 'yes', 'yes', 'yes'), ('smtp.gmail.com', 465, 'Gmail SMTP', 'service', '', 'yes', 'bad','on', '0.0000000', 'yes', 'yes', 'yes', 'yes', 'yes')"; - $queries[] = "INSERT INTO `".PSM_DB_PREFIX."users_servers` (`user_id`,`server_id`) VALUES (1, 1), (1, 2);"; - $queries[] = "INSERT INTO `".PSM_DB_PREFIX."config` (`key`, `value`) VALUE + $this->log('Populating database...'); + $queries = array(); + $queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "servers` ( + `ip`, `port`, `label`, `type`, `pattern`, `pattern_online`, `redirect_check`, + `status`, `rtime`, `active`, `email`, `sms`, `pushover`, `telegram`) + VALUES ('http://sourceforge.net/index.php', 80, 'SourceForge', 'website', '', + 'yes', 'bad', 'on', '0.0000000', 'yes', 'yes', 'yes', 'yes', 'yes'), + ('smtp.gmail.com', 465, 'Gmail SMTP', 'service', '', + 'yes', 'bad','on', '0.0000000', 'yes', 'yes', 'yes', 'yes', 'yes')"; + $queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "users_servers` (`user_id`,`server_id`) VALUES (1, 1), (1, 2);"; + $queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`) VALUE ('language', 'en_US'), ('proxy', '0'), ('proxy_url', ''), @@ -151,7 +164,7 @@ class Installer { ('pushover_api_token', ''), ('telegram_status', '0'), ('telegram_api_token', ''), - ('password_encrypt_key', '".sha1(microtime())."'), + ('password_encrypt_key', '" . sha1(microtime()) . "'), ('alert_type', 'status'), ('log_status', '1'), ('log_email', '1'), @@ -159,240 +172,265 @@ class Installer { ('log_pushover', '1'), ('log_telegram', '1'), ('log_retention_period', '365'), - ('version', '".PSM_VERSION."'), - ('version_update_check', '".PSM_VERSION."'), + ('version', '" . PSM_VERSION . "'), + ('version_update_check', '" . PSM_VERSION . "'), ('auto_refresh_servers', '0'), ('show_update', '1'), ('last_update_check', '0'), ('cron_running', '0'), ('cron_running_time', '0');"; - $this->execSQL($queries); - } + $this->execSQL($queries); + } - /** - * Install the tables for the monitor - */ - protected function installTables() { - $tables = array( - PSM_DB_PREFIX.'config' => "CREATE TABLE `".PSM_DB_PREFIX."config` ( - `key` varchar(255) NOT NULL, - `value` varchar(255) NOT NULL, - PRIMARY KEY (`key`) - ) ENGINE=MyISAM DEFAULT CHARSET=utf8;", - PSM_DB_PREFIX.'users' => "CREATE TABLE IF NOT EXISTS `".PSM_DB_PREFIX."users` ( - `user_id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `user_name` varchar(64) NOT NULL COMMENT 'user''s name, unique', - `password` varchar(255) NOT NULL COMMENT 'user''s password in salted and hashed format', - `password_reset_hash` char(40) DEFAULT NULL COMMENT 'user''s password reset code', - `password_reset_timestamp` bigint(20) DEFAULT NULL COMMENT 'timestamp of the password reset request', - `rememberme_token` varchar(64) DEFAULT NULL COMMENT 'user''s remember-me cookie token', - `level` tinyint(2) unsigned NOT NULL DEFAULT '20', - `name` varchar(255) NOT NULL, - `mobile` varchar(15) NOT NULL, - `pushover_key` varchar(255) NOT NULL, - `pushover_device` varchar(255) NOT NULL, - `telegram_id` varchar(255) NOT NULL, - `email` varchar(255) NOT NULL, - PRIMARY KEY (`user_id`), - UNIQUE KEY `unique_username` (`user_name`) - ) ENGINE=MyISAM DEFAULT CHARSET=utf8;", - PSM_DB_PREFIX.'users_preferences' => "CREATE TABLE IF NOT EXISTS `".PSM_DB_PREFIX."users_preferences` ( - `user_id` int(11) unsigned NOT NULL, - `key` varchar(255) NOT NULL, - `value` varchar(255) NOT NULL, - PRIMARY KEY (`user_id`, `key`) - ) ENGINE=MyISAM DEFAULT CHARSET=utf8;", - PSM_DB_PREFIX.'users_servers' => "CREATE TABLE `".PSM_DB_PREFIX."users_servers` ( - `user_id` INT( 11 ) UNSIGNED NOT NULL , - `server_id` INT( 11 ) UNSIGNED NOT NULL , - PRIMARY KEY ( `user_id` , `server_id` ) - ) ENGINE = MyISAM DEFAULT CHARSET=utf8;", - PSM_DB_PREFIX.'log' => "CREATE TABLE `".PSM_DB_PREFIX."log` ( - `log_id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `server_id` int(11) unsigned NOT NULL, - `type` enum('status','email','sms','pushover','telegram') NOT NULL, - `message` TEXT NOT NULL, - `datetime` timestamp NOT NULL default CURRENT_TIMESTAMP, - PRIMARY KEY (`log_id`) - ) ENGINE=MyISAM DEFAULT CHARSET=utf8;", - PSM_DB_PREFIX.'log_users' => "CREATE TABLE `".PSM_DB_PREFIX."log_users` ( - `log_id` int(11) UNSIGNED NOT NULL , - `user_id` int(11) UNSIGNED NOT NULL , - PRIMARY KEY (`log_id`, `user_id`) - ) ENGINE=MyISAM DEFAULT CHARSET=utf8;", - PSM_DB_PREFIX.'servers' => "CREATE TABLE `".PSM_DB_PREFIX."servers` ( - `server_id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `ip` varchar(500) NOT NULL, - `port` int(5) NOT NULL, - `request_method` varchar(50) NULL, - `label` varchar(255) NOT NULL, - `type` enum('ping','service','website') NOT NULL default 'service', - `pattern` varchar(255) NOT NULL default '', - `pattern_online` enum('yes','no') NOT NULL default 'yes', - `post_field` varchar(255) NULL, - `redirect_check` enum('ok','bad') NOT NULL default 'bad', - `allow_http_status` varchar(255) NOT NULL default '', - `header_name` varchar(255) NOT NULL default '', - `header_value` varchar(255) NOT NULL default '', - `status` enum('on','off') NOT NULL default 'on', - `error` varchar(255) NULL, - `rtime` FLOAT(9, 7) NULL, - `last_online` datetime NULL, - `last_offline` datetime NULL, - `last_offline_duration` varchar(255) NULL, - `last_check` datetime NULL, - `active` enum('yes','no') NOT NULL default 'yes', - `email` enum('yes','no') NOT NULL default 'yes', - `sms` enum('yes','no') NOT NULL default 'no', - `pushover` enum('yes','no') NOT NULL default 'yes', - `telegram` enum('yes','no') NOT NULL default 'yes', - `warning_threshold` mediumint(1) unsigned NOT NULL DEFAULT '1', - `warning_threshold_counter` mediumint(1) unsigned NOT NULL DEFAULT '0', - `timeout` smallint(1) unsigned NULL DEFAULT NULL, - `website_username` varchar(255) DEFAULT NULL, - `website_password` varchar(255) DEFAULT NULL, - `last_error` varchar(255) DEFAULT NULL, - `last_error_output` TEXT, - `last_output` TEXT, - PRIMARY KEY (`server_id`) - ) ENGINE=MyISAM DEFAULT CHARSET=utf8;", - PSM_DB_PREFIX.'servers_uptime' => "CREATE TABLE IF NOT EXISTS `".PSM_DB_PREFIX."servers_uptime` ( - `servers_uptime_id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `server_id` int(11) unsigned NOT NULL, - `date` datetime NOT NULL, - `status` tinyint(1) unsigned NOT NULL, - `latency` float(9,7) DEFAULT NULL, - PRIMARY KEY (`servers_uptime_id`), - KEY `server_id` (`server_id`) - ) ENGINE=MyISAM DEFAULT CHARSET=utf8;", - PSM_DB_PREFIX.'servers_history' => "CREATE TABLE IF NOT EXISTS `".PSM_DB_PREFIX."servers_history` ( - `servers_history_id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `server_id` int(11) unsigned NOT NULL, - `date` date NOT NULL, - `latency_min` float(9,7) NOT NULL, - `latency_avg` float(9,7) NOT NULL, - `latency_max` float(9,7) NOT NULL, - `checks_total` int(11) unsigned NOT NULL, - `checks_failed` int(11) unsigned NOT NULL, - PRIMARY KEY (`servers_history_id`), - UNIQUE KEY `server_id_date` (`server_id`,`date`) - ) ENGINE=MyISAM DEFAULT CHARSET=utf8;", - ); + /** + * Install the tables for the monitor + */ + protected function installTables() + { + $tables = array( + PSM_DB_PREFIX . 'config' => "CREATE TABLE `" . PSM_DB_PREFIX . "config` ( + `key` varchar(255) NOT NULL, + `value` varchar(255) NOT NULL, + PRIMARY KEY (`key`) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8;", + PSM_DB_PREFIX . 'users' => "CREATE TABLE IF NOT EXISTS `" . PSM_DB_PREFIX . "users` ( + `user_id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `user_name` varchar(64) NOT NULL COMMENT 'user''s name, unique', + `password` varchar(255) NOT NULL COMMENT 'user''s password in salted and hashed format', + `password_reset_hash` char(40) DEFAULT NULL COMMENT 'user''s password reset code', + `password_reset_timestamp` bigint(20) DEFAULT NULL COMMENT 'timestamp of the password reset request', + `rememberme_token` varchar(64) DEFAULT NULL COMMENT 'user''s remember-me cookie token', + `level` tinyint(2) unsigned NOT NULL DEFAULT '20', + `name` varchar(255) NOT NULL, + `mobile` varchar(15) NOT NULL, + `pushover_key` varchar(255) NOT NULL, + `pushover_device` varchar(255) NOT NULL, + `telegram_id` varchar(255) NOT NULL, + `email` varchar(255) NOT NULL, + PRIMARY KEY (`user_id`), + UNIQUE KEY `unique_username` (`user_name`) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8;", + PSM_DB_PREFIX . + 'users_preferences' => "CREATE TABLE IF NOT EXISTS `" . PSM_DB_PREFIX . "users_preferences` ( + `user_id` int(11) unsigned NOT NULL, + `key` varchar(255) NOT NULL, + `value` varchar(255) NOT NULL, + PRIMARY KEY (`user_id`, `key`) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8;", + PSM_DB_PREFIX . 'users_servers' => "CREATE TABLE `" . PSM_DB_PREFIX . "users_servers` ( + `user_id` INT( 11 ) UNSIGNED NOT NULL , + `server_id` INT( 11 ) UNSIGNED NOT NULL , + PRIMARY KEY ( `user_id` , `server_id` ) + ) ENGINE = MyISAM DEFAULT CHARSET=utf8;", + PSM_DB_PREFIX . 'log' => "CREATE TABLE `" . PSM_DB_PREFIX . "log` ( + `log_id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `server_id` int(11) unsigned NOT NULL, + `type` enum('status','email','sms','pushover','telegram') NOT NULL, + `message` TEXT NOT NULL, + `datetime` timestamp NOT NULL default CURRENT_TIMESTAMP, + PRIMARY KEY (`log_id`) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8;", + PSM_DB_PREFIX . 'log_users' => "CREATE TABLE `" . PSM_DB_PREFIX . "log_users` ( + `log_id` int(11) UNSIGNED NOT NULL , + `user_id` int(11) UNSIGNED NOT NULL , + PRIMARY KEY (`log_id`, `user_id`) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8;", + PSM_DB_PREFIX . 'servers' => "CREATE TABLE `" . PSM_DB_PREFIX . "servers` ( + `server_id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `ip` varchar(500) NOT NULL, + `port` int(5) NOT NULL, + `request_method` varchar(50) NULL, + `label` varchar(255) NOT NULL, + `type` enum('ping','service','website') NOT NULL default 'service', + `pattern` varchar(255) NOT NULL default '', + `pattern_online` enum('yes','no') NOT NULL default 'yes', + `post_field` varchar(255) NULL, + `redirect_check` enum('ok','bad') NOT NULL default 'bad', + `allow_http_status` varchar(255) NOT NULL default '', + `header_name` varchar(255) NOT NULL default '', + `header_value` varchar(255) NOT NULL default '', + `status` enum('on','off') NOT NULL default 'on', + `error` varchar(255) NULL, + `rtime` FLOAT(9, 7) NULL, + `last_online` datetime NULL, + `last_offline` datetime NULL, + `last_offline_duration` varchar(255) NULL, + `last_check` datetime NULL, + `active` enum('yes','no') NOT NULL default 'yes', + `email` enum('yes','no') NOT NULL default 'yes', + `sms` enum('yes','no') NOT NULL default 'no', + `pushover` enum('yes','no') NOT NULL default 'yes', + `telegram` enum('yes','no') NOT NULL default 'yes', + `warning_threshold` mediumint(1) unsigned NOT NULL DEFAULT '1', + `warning_threshold_counter` mediumint(1) unsigned NOT NULL DEFAULT '0', + `timeout` smallint(1) unsigned NULL DEFAULT NULL, + `website_username` varchar(255) DEFAULT NULL, + `website_password` varchar(255) DEFAULT NULL, + `last_error` varchar(255) DEFAULT NULL, + `last_error_output` TEXT, + `last_output` TEXT, + PRIMARY KEY (`server_id`) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8;", + PSM_DB_PREFIX . 'servers_uptime' => "CREATE TABLE IF NOT EXISTS `" . PSM_DB_PREFIX . "servers_uptime` ( + `servers_uptime_id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `server_id` int(11) unsigned NOT NULL, + `date` datetime NOT NULL, + `status` tinyint(1) unsigned NOT NULL, + `latency` float(9,7) DEFAULT NULL, + PRIMARY KEY (`servers_uptime_id`), + KEY `server_id` (`server_id`) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8;", + PSM_DB_PREFIX . 'servers_history' => "CREATE TABLE IF NOT EXISTS `" . PSM_DB_PREFIX . "servers_history` ( + `servers_history_id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `server_id` int(11) unsigned NOT NULL, + `date` date NOT NULL, + `latency_min` float(9,7) NOT NULL, + `latency_avg` float(9,7) NOT NULL, + `latency_max` float(9,7) NOT NULL, + `checks_total` int(11) unsigned NOT NULL, + `checks_failed` int(11) unsigned NOT NULL, + PRIMARY KEY (`servers_history_id`), + UNIQUE KEY `server_id_date` (`server_id`,`date`) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8;", + ); - foreach ($tables as $name => $sql) { - $if_table_exists = $this->db->query("SHOW TABLES LIKE '{$name}'"); + foreach ($tables as $name => $sql) { + $if_table_exists = $this->db->query("SHOW TABLES LIKE '{$name}'"); - if (!empty($if_table_exists)) { - $this->log('Table '.$name.' already exists in your database!'); - } else { - $this->execSQL($sql); - $this->log('Table '.$name.' added.'); - } - } - } + if (!empty($if_table_exists)) { + $this->log('Table ' . $name . ' already exists in your database!'); + } else { + $this->execSQL($sql); + $this->log('Table ' . $name . ' added.'); + } + } + } - /** - * Populate the tables and perform upgrades if necessary - * @param string $version_from - * @param string $version_to - * @see isUpgradeRequired() - */ - public function upgrade($version_from, $version_to) { - if (version_compare($version_from, '2.1.0', '<')) { - $this->upgrade210(); - } - if (version_compare($version_from, '3.0.0', '<')) { - $this->upgrade300(); - } - if (version_compare($version_from, '3.1.0', '<')) { - $this->upgrade310(); - } - if (version_compare($version_from, '3.2.0', '<')) { - $this->upgrade320(); - } - if (version_compare($version_from, '3.2.1', '<')) { - $this->upgrade321(); - } - if (version_compare($version_from, '3.2.2', '<')) { - $this->upgrade322(); - } - if (version_compare($version_from, '3.3.0', '<')) { - $this->upgrade330(); - } - if (version_compare($version_from, '3.4.0', '<')) { - $this->upgrade340(); - } - if (version_compare($version_from, '3.4.2', '<')) { - $this->upgrade342(); - } - psm_update_conf('version', $version_to); - } + /** + * Populate the tables and perform upgrades if necessary + * @param string $version_from + * @param string $version_to + * @see isUpgradeRequired() + */ + public function upgrade($version_from, $version_to) + { + if (version_compare($version_from, '2.1.0', '<')) { + $this->upgrade210(); + } + if (version_compare($version_from, '3.0.0', '<')) { + $this->upgrade300(); + } + if (version_compare($version_from, '3.1.0', '<')) { + $this->upgrade310(); + } + if (version_compare($version_from, '3.2.0', '<')) { + $this->upgrade320(); + } + if (version_compare($version_from, '3.2.1', '<')) { + $this->upgrade321(); + } + if (version_compare($version_from, '3.2.2', '<')) { + $this->upgrade322(); + } + if (version_compare($version_from, '3.3.0', '<')) { + $this->upgrade330(); + } + if (version_compare($version_from, '3.4.0', '<')) { + $this->upgrade340(); + } + if (version_compare($version_from, '3.4.2', '<')) { + $this->upgrade342(); + } + psm_update_conf('version', $version_to); + } - /** - * Upgrade for v2.1.0 release - */ - protected function upgrade210() { - $queries = array(); - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."config` DROP `config_id`;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."config` ADD PRIMARY KEY ( `key` );"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."config` DROP INDEX `key`;"; - $queries[] = "INSERT INTO `".PSM_DB_PREFIX."config` (`key`, `value`) VALUES ('cron_running', '0');"; - $queries[] = "INSERT INTO `".PSM_DB_PREFIX."config` (`key`, `value`) VALUES ('cron_running_time', '0');"; + /** + * Upgrade for v2.1.0 release + */ + protected function upgrade210() + { + $queries = array(); + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "config` DROP `config_id`;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "config` ADD PRIMARY KEY ( `key` );"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "config` DROP INDEX `key`;"; + $queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`) VALUES ('cron_running', '0');"; + $queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`) VALUES ('cron_running_time', '0');"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` CHANGE `error` `error` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` CHANGE `rtime` `rtime` FLOAT( 9, 7 ) NULL;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` CHANGE `last_online` `last_online` DATETIME NULL;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` CHANGE `last_check` `last_check` DATETIME NULL;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `pattern` VARCHAR( 255 ) NOT NULL AFTER `type`;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `last_offline` DATETIME NULL;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `last_offline_duration` varchar(255) NULL;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` CHANGE `error` `error` VARCHAR( 255 ) + CHARACTER SET utf8 COLLATE utf8_general_ci NULL;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` CHANGE `rtime` `rtime` FLOAT( 9, 7 ) NULL;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` CHANGE `last_online` `last_online` DATETIME NULL;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` CHANGE `last_check` `last_check` DATETIME NULL;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `pattern` VARCHAR( 255 ) NOT NULL AFTER `type`;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `last_offline` DATETIME NULL;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `last_offline_duration` varchar(255) NULL;"; - $this->execSQL($queries); - } + $this->execSQL($queries); + } - /** - * Upgrade for v3.0.0 release - */ - protected function upgrade300() { - $queries = array(); - // language is now stored as language code (ISO 639-1) + country code (ISO 3166-1) - $queries[] = "UPDATE `".PSM_DB_PREFIX."config` SET `value`='bg_BG' WHERE `key`='language' AND `value`='bg';"; - $queries[] = "UPDATE `".PSM_DB_PREFIX."config` SET `value`='de_DE' WHERE `key`='language' AND `value`='de';"; - $queries[] = "UPDATE `".PSM_DB_PREFIX."config` SET `value`='en_US' WHERE `key`='language' AND `value`='en';"; - $queries[] = "UPDATE `".PSM_DB_PREFIX."config` SET `value`='fr_FR' WHERE `key`='language' AND `value`='fr';"; - $queries[] = "UPDATE `".PSM_DB_PREFIX."config` SET `value`='ko_KR' WHERE `key`='language' AND `value`='kr';"; - $queries[] = "UPDATE `".PSM_DB_PREFIX."config` SET `value`='nl_NL' WHERE `key`='language' AND `value`='nl';"; - $queries[] = "UPDATE `".PSM_DB_PREFIX."config` SET `value`='pt_BR' WHERE `key`='language' AND `value`='br';"; + /** + * Upgrade for v3.0.0 release + */ + protected function upgrade300() + { + $queries = array(); + // language is now stored as language code (ISO 639-1) + country code (ISO 3166-1) + $queries[] = "UPDATE `" . PSM_DB_PREFIX . "config` SET `value`='bg_BG' + WHERE `key`='language' AND `value`='bg';"; + $queries[] = "UPDATE `" . PSM_DB_PREFIX . "config` SET `value`='de_DE' + WHERE `key`='language' AND `value`='de';"; + $queries[] = "UPDATE `" . PSM_DB_PREFIX . "config` SET `value`='en_US' + WHERE `key`='language' AND `value`='en';"; + $queries[] = "UPDATE `" . PSM_DB_PREFIX . "config` SET `value`='fr_FR' + WHERE `key`='language' AND `value`='fr';"; + $queries[] = "UPDATE `" . PSM_DB_PREFIX . "config` SET `value`='ko_KR' + WHERE `key`='language' AND `value`='kr';"; + $queries[] = "UPDATE `" . PSM_DB_PREFIX . "config` SET `value`='nl_NL' + WHERE `key`='language' AND `value`='nl';"; + $queries[] = "UPDATE `" . PSM_DB_PREFIX . "config` SET `value`='pt_BR' + WHERE `key`='language' AND `value`='br';"; - $queries[] = "INSERT INTO `".PSM_DB_PREFIX."config` (`key`, `value`) VALUES ('version_update_check', '".PSM_VERSION."');"; - $queries[] = "INSERT INTO `".PSM_DB_PREFIX."config` (`key`, `value`) VALUES ('email_smtp', '');"; - $queries[] = "INSERT INTO `".PSM_DB_PREFIX."config` (`key`, `value`) VALUES ('email_smtp_host', '');"; - $queries[] = "INSERT INTO `".PSM_DB_PREFIX."config` (`key`, `value`) VALUES ('email_smtp_port', '');"; - $queries[] = "INSERT INTO `".PSM_DB_PREFIX."config` (`key`, `value`) VALUES ('email_smtp_username', '');"; - $queries[] = "INSERT INTO `".PSM_DB_PREFIX."config` (`key`, `value`) VALUES ('email_smtp_password', '');"; + $queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`) VALUES + ('version_update_check', '" . PSM_VERSION . "');"; + $queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`) VALUES ('email_smtp', '');"; + $queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`) VALUES ('email_smtp_host', '');"; + $queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`) VALUES ('email_smtp_port', '');"; + $queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`) VALUES ('email_smtp_username', '');"; + $queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`) VALUES ('email_smtp_password', '');"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."log` CHANGE `log_id` `log_id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."log` CHANGE `server_id` `server_id` INT( 11 ) UNSIGNED NOT NULL;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "log` CHANGE `log_id` `log_id` INT( 11 ) + UNSIGNED NOT NULL AUTO_INCREMENT;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "log` CHANGE `server_id` `server_id` INT( 11 ) + UNSIGNED NOT NULL;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` CHANGE `server_id` `server_id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `warning_threshold` MEDIUMINT( 1 ) UNSIGNED NOT NULL DEFAULT '1';"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `warning_threshold_counter` MEDIUMINT( 1 ) UNSIGNED NOT NULL DEFAULT '0';"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `last_offline` DATETIME NULL;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `last_offline_duration` varchar(255) NULL;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` CHANGE `server_id` `server_id` INT( 11 ) + UNSIGNED NOT NULL AUTO_INCREMENT;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `warning_threshold` MEDIUMINT( 1 ) + UNSIGNED NOT NULL DEFAULT '1';"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `warning_threshold_counter` MEDIUMINT( 1 ) + UNSIGNED NOT NULL DEFAULT '0';"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `last_offline` DATETIME NULL;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `last_offline_duration` varchar(255) NULL;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."users` CHANGE `user_id` `user_id` INT( 11 ) UNSIGNED NOT NULL AUTO_INCREMENT;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."users` - ADD `user_name` varchar(64) COLLATE utf8_general_ci NOT NULL COMMENT 'user\'s name, unique' AFTER `user_id`, - ADD `password` varchar(255) COLLATE utf8_general_ci NOT NULL COMMENT 'user\'s password in salted and hashed format' AFTER `user_name`, - ADD `password_reset_hash` char(40) COLLATE utf8_general_ci DEFAULT NULL COMMENT 'user\'s password reset code' AFTER `password`, - ADD `password_reset_timestamp` bigint(20) DEFAULT NULL COMMENT 'timestamp of the password reset request' AFTER `password_reset_hash`, - ADD `rememberme_token` varchar(64) COLLATE utf8_general_ci DEFAULT NULL COMMENT 'user\'s remember-me cookie token' AFTER `password_reset_timestamp`, + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "users` CHANGE `user_id` `user_id` INT( 11 ) + UNSIGNED NOT NULL AUTO_INCREMENT;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "users` + ADD `user_name` varchar(64) COLLATE utf8_general_ci NOT NULL + COMMENT 'user\'s name, unique' AFTER `user_id`, + ADD `password` varchar(255) COLLATE utf8_general_ci NOT NULL + COMMENT 'user\'s password in salted and hashed format' AFTER `user_name`, + ADD `password_reset_hash` char(40) COLLATE utf8_general_ci DEFAULT NULL + COMMENT 'user\'s password reset code' AFTER `password`, + ADD `password_reset_timestamp` bigint(20) DEFAULT NULL + COMMENT 'timestamp of the password reset request' AFTER `password_reset_hash`, + ADD `rememberme_token` varchar(64) COLLATE utf8_general_ci DEFAULT NULL + COMMENT 'user\'s remember-me cookie token' AFTER `password_reset_timestamp`, ADD `level` TINYINT( 2 ) UNSIGNED NOT NULL DEFAULT '20' AFTER `rememberme_token`;"; - // make sure all current users are admins (previously we didnt have non-admins): - $queries[] = "UPDATE `".PSM_DB_PREFIX."users` SET `user_name`=`email`, `level`=10;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."users` ADD UNIQUE `unique_username` ( `user_name` );"; + // make sure all current users are admins (previously we didnt have non-admins): + $queries[] = "UPDATE `" . PSM_DB_PREFIX . "users` SET `user_name`=`email`, `level`=10;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "users` ADD UNIQUE `unique_username` ( `user_name` );"; - $queries[] = "CREATE TABLE IF NOT EXISTS `".PSM_DB_PREFIX."servers_uptime` ( + $queries[] = "CREATE TABLE IF NOT EXISTS `" . PSM_DB_PREFIX . "servers_uptime` ( `servers_uptime_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `server_id` int(11) unsigned NOT NULL, `date` datetime NOT NULL, @@ -402,189 +440,219 @@ class Installer { KEY `server_id` (`server_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;"; - $queries[] = "CREATE TABLE IF NOT EXISTS `".PSM_DB_PREFIX."servers_history` ( - `servers_history_id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `server_id` int(11) unsigned NOT NULL, - `date` date NOT NULL, - `latency_min` float(9,7) NOT NULL, - `latency_avg` float(9,7) NOT NULL, - `latency_max` float(9,7) NOT NULL, - `checks_total` int(11) unsigned NOT NULL, - `checks_failed` int(11) unsigned NOT NULL, + $queries[] = "CREATE TABLE IF NOT EXISTS `" . PSM_DB_PREFIX . "servers_history` ( + `servers_history_id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `server_id` int(11) unsigned NOT NULL, + `date` date NOT NULL, + `latency_min` float(9,7) NOT NULL, + `latency_avg` float(9,7) NOT NULL, + `latency_max` float(9,7) NOT NULL, + `checks_total` int(11) unsigned NOT NULL, + `checks_failed` int(11) unsigned NOT NULL, PRIMARY KEY (`servers_history_id`), UNIQUE KEY `server_id_date` (`server_id`,`date`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;"; - $queries[] = "CREATE TABLE `".PSM_DB_PREFIX."users_servers` ( + $queries[] = "CREATE TABLE `" . PSM_DB_PREFIX . "users_servers` ( `user_id` INT( 11 ) UNSIGNED NOT NULL , `server_id` INT( 11 ) UNSIGNED NOT NULL , PRIMARY KEY ( `user_id` , `server_id` ) ) ENGINE = MYISAM ;"; - $this->execSQL($queries); + $this->execSQL($queries); - // from 3.0 all user-server relations are in a separate table - $users = $this->db->select(PSM_DB_PREFIX.'users', null, array('user_id', 'server_id')); - foreach ($users as $user) { - $idc = array(); - if ($user['server_id'] == '') { - continue; - } - if (strpos($user['server_id'], ',') === false) { - $idc[] = $user['server_id']; - } else { - $idc = explode(',', $user['server_id']); - } - foreach ($idc as $id) { - $this->db->save(PSM_DB_PREFIX.'users_servers', array( - 'user_id' => $user['user_id'], - 'server_id' => $id, - )); - } - } - $this->execSQL("ALTER TABLE `".PSM_DB_PREFIX."users` DROP `server_id`;"); - } + // 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')); + foreach ($users as $user) { + $idc = array(); + if ($user['server_id'] == '') { + continue; + } + if (strpos($user['server_id'], ',') === false) { + $idc[] = $user['server_id']; + } else { + $idc = explode(',', $user['server_id']); + } + foreach ($idc as $id) { + $this->db->save(PSM_DB_PREFIX . 'users_servers', array( + 'user_id' => $user['user_id'], + 'server_id' => $id, + )); + } + } + $this->execSQL("ALTER TABLE `" . PSM_DB_PREFIX . "users` DROP `server_id`;"); + } - /** - * Upgrade for v3.1.0 release - */ - protected function upgrade310() { - $queries = array(); - psm_update_conf('log_retention_period', '365'); + /** + * Upgrade for v3.1.0 release + */ + protected function upgrade310() + { + $queries = array(); + psm_update_conf('log_retention_period', '365'); - psm_update_conf('pushover_status', 0); - psm_update_conf('log_pushover', 1); - psm_update_conf('pushover_api_token', ''); - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."users` ADD `pushover_key` VARCHAR( 255 ) NOT NULL AFTER `mobile`;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."users` ADD `pushover_device` VARCHAR( 255 ) NOT NULL AFTER `pushover_key`;"; + psm_update_conf('pushover_status', 0); + psm_update_conf('log_pushover', 1); + psm_update_conf('pushover_api_token', ''); + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "users` ADD `pushover_key` VARCHAR( 255 ) + NOT NULL AFTER `mobile`;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "users` ADD `pushover_device` VARCHAR( 255 ) + NOT NULL AFTER `pushover_key`;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `pushover` ENUM( 'yes','no' ) NOT NULL DEFAULT 'yes' AFTER `sms`;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."log` CHANGE `type` `type` ENUM( 'status', 'email', 'sms', 'pushover' ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `pushover` ENUM( 'yes','no' ) + NOT NULL DEFAULT 'yes' AFTER `sms`;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . + "log` CHANGE `type` `type` ENUM( 'status', 'email', 'sms', 'pushover' ) + CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `timeout` smallint(1) unsigned NULL DEFAULT NULL;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `last_offline` DATETIME NULL;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `last_offline_duration` varchar(255) NULL;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `timeout` smallint(1) unsigned NULL DEFAULT NULL;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `last_offline` DATETIME NULL;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `last_offline_duration` varchar(255) NULL;"; - $queries[] = "CREATE TABLE IF NOT EXISTS `".PSM_DB_PREFIX."users_preferences` ( + $queries[] = "CREATE TABLE IF NOT EXISTS `" . PSM_DB_PREFIX . "users_preferences` ( `user_id` int(11) unsigned NOT NULL, `key` varchar(255) NOT NULL, `value` varchar(255) NOT NULL, PRIMARY KEY (`user_id`, `key`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;"; - $this->execSQL($queries); - } + $this->execSQL($queries); + } - /** - * Upgrade for v3.2.0 release - */ - protected function upgrade320() { - $queries = array(); + /** + * Upgrade for v3.2.0 release + */ + protected function upgrade320() + { + $queries = array(); - psm_update_conf('password_encrypt_key', sha1(microtime())); - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` CHANGE `ip` `ip` VARCHAR(500) NOT NULL;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `website_username` varchar(255) NULL, ADD `website_password` varchar(255) NULL AFTER `website_username`;"; - $queries[] = "INSERT INTO `".PSM_DB_PREFIX."config` (`key`, `value`) VALUE + psm_update_conf('password_encrypt_key', sha1(microtime())); + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` CHANGE `ip` `ip` VARCHAR(500) NOT NULL;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `website_username` varchar(255) NULL, + ADD `website_password` varchar(255) NULL AFTER `website_username`;"; + $queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`) VALUE ('proxy', '0'), ('proxy_url', ''), ('proxy_user', ''), ('proxy_password', '');"; - $this->execSQL($queries); + $this->execSQL($queries); - // Create log_users table - $this->execSQL("CREATE TABLE `".PSM_DB_PREFIX."log_users` ( + // Create log_users table + $this->execSQL("CREATE TABLE `" . PSM_DB_PREFIX . "log_users` ( `log_id` int(11) UNSIGNED NOT NULL , `user_id` int(11) UNSIGNED NOT NULL , PRIMARY KEY (`log_id`, `user_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;"); - // Migrate the data - $logs = $this->db->select(PSM_DB_PREFIX.'log', null, array('log_id', 'user_id')); - foreach ($logs as $log) { - // Validation - if (empty($log['user_id']) || trim($log['user_id']) == '') { - continue; - } + // Migrate the data + $logs = $this->db->select(PSM_DB_PREFIX . 'log', null, array('log_id', 'user_id')); + foreach ($logs as $log) { + // Validation + if (empty($log['user_id']) || trim($log['user_id']) == '') { + continue; + } - // Insert into new table - foreach (explode(',', $log['user_id']) as $user_id) { - psm_add_log_user($log['log_id'], $user_id); - } - } + // Insert into new table + foreach (explode(',', $log['user_id']) as $user_id) { + psm_add_log_user($log['log_id'], $user_id); + } + } - // Drop old user_id('s) column - $this->execSQL("ALTER TABLE `".PSM_DB_PREFIX."log` DROP COLUMN `user_id`;"); - } + // Drop old user_id('s) column + $this->execSQL("ALTER TABLE `" . PSM_DB_PREFIX . "log` DROP COLUMN `user_id`;"); + } - /** - * Upgrade for v3.2.1 release - */ - protected function upgrade321() { - $queries = array(); - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD COLUMN `header_name` VARCHAR(255) AFTER `pattern`, ADD COLUMN `header_value` VARCHAR(255) AFTER `header_name`"; - $this->execSQL($queries); - } + /** + * Upgrade for v3.2.1 release + */ + protected function upgrade321() + { + $queries = array(); + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD COLUMN `header_name` VARCHAR(255) AFTER `pattern`, + ADD COLUMN `header_value` VARCHAR(255) AFTER `header_name`"; + $this->execSQL($queries); + } - /** - * Upgrade for v3.2.2 release - */ - protected function upgrade322() { - $queries = array(); - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."users` ADD `telegram_id` VARCHAR( 255 ) NOT NULL AFTER `pushover_device`;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `telegram` ENUM( 'yes','no' ) NOT NULL DEFAULT 'yes' AFTER `pushover`;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."log` CHANGE `type` `type` ENUM( 'status', 'email', 'sms', 'pushover', 'telegram' ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;"; - $queries[] = "INSERT INTO `".PSM_DB_PREFIX."config` (`key`, `value`) VALUE + /** + * Upgrade for v3.2.2 release + */ + protected function upgrade322() + { + $queries = array(); + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "users` ADD `telegram_id` VARCHAR( 255 ) + NOT NULL AFTER `pushover_device`;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `telegram` ENUM( 'yes','no' ) + NOT NULL DEFAULT 'yes' AFTER `pushover`;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . + "log` CHANGE `type` `type` ENUM( 'status', 'email', 'sms', 'pushover', 'telegram' ) + CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;"; + $queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`) VALUE ('telegram_status', '0'), ('log_telegram', '1'), ('telegram_api_token', '');"; - $this->execSQL($queries); - } + $this->execSQL($queries); + } - /** - * Upgrade for v3.3.0 release - */ - protected function upgrade330() { - $queries = array(); - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD COLUMN `last_offline` DATETIME NULL AFTER `last_online`, ADD COLUMN `last_offline_duration` varchar(255) NULL AFTER `last_offline`;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `pattern_online` ENUM( 'yes','no' ) NOT NULL DEFAULT 'yes' AFTER `pattern`;"; - $this->execSQL($queries); - if (psm_get_conf('sms_gateway') == 'mollie') { - psm_update_conf('sms_gateway', 'messagebird'); - } - } + /** + * Upgrade for v3.3.0 release + */ + protected function upgrade330() + { + $queries = array(); + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD COLUMN `last_offline` DATETIME + NULL AFTER `last_online`, ADD COLUMN `last_offline_duration` varchar(255) NULL AFTER `last_offline`;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` ADD `pattern_online` ENUM( 'yes','no' ) + NOT NULL DEFAULT 'yes' AFTER `pattern`;"; + $this->execSQL($queries); + if (psm_get_conf('sms_gateway') == 'mollie') { + psm_update_conf('sms_gateway', 'messagebird'); + } + } - /** - * Upgrade for v3.4.0 release - */ - protected function upgrade340() { - $queries = array(); - /** - * Redirect_check is first set to default ok. - * If you have a lot of server that are redirecting, - * this will make sure you're servers stay online. - */ - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD COLUMN `allow_http_status` VARCHAR(255) NOT NULL DEFAULT '' AFTER `pattern_online`;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD `redirect_check` ENUM( 'ok','bad' ) NOT NULL DEFAULT 'ok' AFTER `allow_http_status`;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` CHANGE `redirect_check` `redirect_check` ENUM('ok','bad') NOT NULL DEFAULT 'bad';"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD COLUMN `last_error` VARCHAR(255) NULL AFTER `website_password`;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD COLUMN `last_error_output` TEXT AFTER `last_error`;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD COLUMN `last_output` TEXT AFTER `last_error_output`;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD COLUMN `request_method` varchar(50) NULL AFTER `port`;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` ADD COLUMN `post_field` varchar(255) NULL AFTER `pattern_online`;"; - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."log` CHANGE `message` `message` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;"; - $queries[] = "INSERT INTO `".PSM_DB_PREFIX."config` (`key`, `value`) VALUES ('combine_notifications', '1');"; - $this->execSQL($queries); - $this->log('Combined notifications enabled. Check out the config page for more info.'); - } - - /** - * Patch for v3.4.2 release - * Version_compare was forgotten in v3.4.1 and query failed. - * Fixed in v3.4.2, 3.4.1 has been removed. - */ - protected function upgrade342() { - $queries = array(); - $queries[] = "ALTER TABLE `".PSM_DB_PREFIX."servers` CHANGE `last_output` `last_output` TEXT;"; - $this->execSQL($queries); - } + /** + * Upgrade for v3.4.0 release + */ + protected function upgrade340() + { + $queries = array(); + /** + * Redirect_check is first set to default ok. + * If you have a lot of server that are redirecting, + * this will make sure you're servers stay online. + */ + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` + ADD COLUMN `allow_http_status` VARCHAR(255) NOT NULL DEFAULT '' AFTER `pattern_online`;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` + ADD `redirect_check` ENUM( 'ok','bad' ) NOT NULL DEFAULT 'ok' AFTER `allow_http_status`;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` + CHANGE `redirect_check` `redirect_check` ENUM('ok','bad') NOT NULL DEFAULT 'bad';"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` + ADD COLUMN `last_error` VARCHAR(255) NULL AFTER `website_password`;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` + ADD COLUMN `last_error_output` TEXT AFTER `last_error`;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` + ADD COLUMN `last_output` TEXT AFTER `last_error_output`;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` + ADD COLUMN `request_method` varchar(50) NULL AFTER `port`;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` + ADD COLUMN `post_field` varchar(255) NULL AFTER `pattern_online`;"; + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "log` + CHANGE `message` `message` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;"; + $queries[] = "INSERT INTO `" . PSM_DB_PREFIX . "config` (`key`, `value`) + VALUES ('combine_notifications', '1');"; + $this->execSQL($queries); + $this->log('Combined notifications enabled. Check out the config page for more info.'); + } + + /** + * Patch for v3.4.2 release + * Version_compare was forgotten in v3.4.1 and query failed. + * Fixed in v3.4.2, 3.4.1 has been removed. + */ + protected function upgrade342() + { + $queries = array(); + $queries[] = "ALTER TABLE `" . PSM_DB_PREFIX . "servers` CHANGE `last_output` `last_output` TEXT;"; + $this->execSQL($queries); + } } diff --git a/src/psm/Util/Module/Modal.php b/src/psm/Util/Module/Modal.php index 014b6325..76d27ee6 100644 --- a/src/psm/Util/Module/Modal.php +++ b/src/psm/Util/Module/Modal.php @@ -1,4 +1,5 @@ modal_id = $modal_id; - $this->twig = $twig; - $this->type = $type; - } + public function __construct(\Twig_Environment $twig, $modal_id = 'main', $type = self::MODAL_TYPE_OK) + { + $this->modal_id = $modal_id; + $this->twig = $twig; + $this->type = $type; + } - /** - * get the modal dialog box element prefix - * @return string - */ - public function getModalID() { - return $this->modal_id; - } + /** + * get the modal dialog box element prefix + * @return string + */ + public function getModalID() + { + return $this->modal_id; + } - /** - * Set the modal dialog type - * @param int $type - * @return \psm\Util\Module\Modal - */ - public function setType($type) { - if (in_array($type, array(self::MODAL_TYPE_OK, self::MODAL_TYPE_OKCANCEL, self::MODAL_TYPE_DANGER))) { - $this->type = $type; - } - return $this; - } + /** + * Set the modal dialog type + * @param int $type + * @return \psm\Util\Module\Modal + */ + public function setType($type) + { + if (in_array($type, array(self::MODAL_TYPE_OK, self::MODAL_TYPE_OKCANCEL, self::MODAL_TYPE_DANGER))) { + $this->type = $type; + } + return $this; + } - /** - * Set the modal dialog title - * @param string $title - * @return \psm\Util\Module\Modal - */ - public function setTitle($title) { - $this->title = $title; - return $this; - } + /** + * Set the modal dialog title + * @param string $title + * @return \psm\Util\Module\Modal + */ + public function setTitle($title) + { + $this->title = $title; + return $this; + } - /** - * Set the modal dialog message - * @param string $message - * @return \psm\Util\Module\Modal - */ - public function setMessage($message) { - $this->message = $message; - return $this; - } + /** + * Set the modal dialog message + * @param string $message + * @return \psm\Util\Module\Modal + */ + public function setMessage($message) + { + $this->message = $message; + return $this; + } - public function setOKButtonLabel($label) { - $this->ok_label = $label; - return $this; - } + public function setOKButtonLabel($label) + { + $this->ok_label = $label; + return $this; + } - public function createHTML() { - $has_cancel = ($this->type == self::MODAL_TYPE_OK) ? false : true; - $button_type = ($this->type == self::MODAL_TYPE_DANGER) ? 'danger' : 'primary'; - $button_label = empty($this->ok_label) ? psm_get_lang('system', 'ok') : $this->ok_label; - $message = !empty($this->message) ? $this->message : ''; + public function createHTML() + { + $has_cancel = ($this->type == self::MODAL_TYPE_OK) ? false : true; + $button_type = ($this->type == self::MODAL_TYPE_DANGER) ? 'danger' : 'primary'; + $button_label = empty($this->ok_label) ? psm_get_lang('system', 'ok') : $this->ok_label; + $message = !empty($this->message) ? $this->message : ''; - $matches = array(); - if (preg_match_all('/%(\d)/', $message, $matches, PREG_SET_ORDER)) { - foreach ($matches as $match) { - $message = str_replace($match[0], '', $message); - } - } + $matches = array(); + if (preg_match_all('/%(\d)/', $message, $matches, PREG_SET_ORDER)) { + foreach ($matches as $match) { + $message = str_replace($match[0], '', $message); + } + } - $tpl = $this->twig->loadTemplate('util/module/modal.tpl.html'); - $html = $tpl->render(array( - 'modal_id' => $this->modal_id, - 'modal_title' => !empty($this->title) ? $this->title : psm_get_lang('system', 'title'), - 'modal_body' => $message, - 'has_cancel' => $has_cancel, - 'label_cancel' => psm_get_lang('system', 'cancel'), - 'modal_button_type' => $button_type, - 'modal_button_label'=> $button_label, - )); + $tpl = $this->twig->loadTemplate('util/module/modal.tpl.html'); + $html = $tpl->render(array( + 'modal_id' => $this->modal_id, + 'modal_title' => !empty($this->title) ? $this->title : psm_get_lang('system', 'title'), + 'modal_body' => $message, + 'has_cancel' => $has_cancel, + 'label_cancel' => psm_get_lang('system', 'cancel'), + 'modal_button_type' => $button_type, + 'modal_button_label' => $button_label, + )); - return $html; - } + return $html; + } } diff --git a/src/psm/Util/Module/ModalInterface.php b/src/psm/Util/Module/ModalInterface.php index d4cd0576..a7d79bb3 100644 --- a/src/psm/Util/Module/ModalInterface.php +++ b/src/psm/Util/Module/ModalInterface.php @@ -1,4 +1,5 @@ twig = $twig; - } + public function __construct(\Twig_Environment $twig) + { + $this->twig = $twig; + } - /** - * Set active item - * @param string $id - * @return \psm\Util\Module\Sidebar - */ - public function setActiveItem($id) { - $this->active_id = $id; - return $this; - } + /** + * Set active item + * @param string $id + * @return \psm\Util\Module\Sidebar + */ + public function setActiveItem($id) + { + $this->active_id = $id; + return $this; + } - /** - * Set a custom subtitle (default is module subitle) - * @param string $title - * @return \psm\Util\Module\Sidebar - */ - public function setSubtitle($title) { - $this->subtitle = $title; - return $this; - } + /** + * Set a custom subtitle (default is module subitle) + * @param string $title + * @return \psm\Util\Module\Sidebar + */ + public function setSubtitle($title) + { + $this->subtitle = $title; + return $this; + } - /** - * Add new link to sidebar - * @param string $id - * @param string $label - * @param string $url - * @param string $icon - * @return \psm\Util\Module\Sidebar - */ - public function addLink($id, $label, $url, $icon = null) { - if (!isset($this->items['link'])) { - $this->items['link'] = array(); - } + /** + * Add new link to sidebar + * @param string $id + * @param string $label + * @param string $url + * @param string $icon + * @return \psm\Util\Module\Sidebar + */ + public function addLink($id, $label, $url, $icon = null) + { + if (!isset($this->items['link'])) { + $this->items['link'] = array(); + } - $this->items['link'][$id] = array( - 'id' => $id, - 'label' => $label, - 'url' => str_replace('"', '\"', $url), - 'icon' => $icon, - ); - return $this; - } + $this->items['link'][$id] = array( + 'id' => $id, + 'label' => $label, + 'url' => str_replace('"', '\"', $url), + 'icon' => $icon, + ); + return $this; + } - /** - * Add a new button to the sidebar - * @param string $id - * @param string $label - * @param string $url - * @param string $icon - * @param string $btn_class - * @param boolean $url_is_onclick if you want onclick rather than url, change this to true - * @return \psm\Util\Module\Sidebar - */ - public function addButton($id, $label, $url, $icon = null, $btn_class = 'link', $title = '', $modal_id = null) { - if (!isset($this->items['button'])) { - $this->items['button'] = array(); - } + /** + * Add a new button to the sidebar + * @param string $id + * @param string $label + * @param string $url + * @param string $icon + * @param string $btn_class + * @param boolean $url_is_onclick if you want onclick rather than url, change this to true + * @return \psm\Util\Module\Sidebar + */ + public function addButton($id, $label, $url, $icon = null, $btn_class = 'link', $title = '', $modal_id = null) + { + if (!isset($this->items['button'])) { + $this->items['button'] = array(); + } - $this->items['button'][$id] = array( - 'id' => $id, - 'label' => $label, - 'url' => str_replace('"', '\"', $url), - 'icon' => $icon, - 'btn_class'=> $btn_class, - 'title'=> $title, - 'modal_id'=> $modal_id - ); - return $this; - } + $this->items['button'][$id] = array( + 'id' => $id, + 'label' => $label, + 'url' => str_replace('"', '\"', $url), + 'icon' => $icon, + 'btn_class' => $btn_class, + 'title' => $title, + 'modal_id' => $modal_id + ); + return $this; + } - /** - * Add dropdown button - * @param string $id - * @param string $label - * @param array $options - * @param string $icon - * @param string $btn_class - * @return \psm\Util\Module\Sidebar - */ - public function addDropdown($id, $label, $options, $icon = null, $btn_class = null) { - if (!isset($this->items['dropdown'])) { - $this->items['dropdown'] = array(); - } - $this->items['dropdown'][$id] = array( - 'id' => $id, - 'label' => $label, - 'options' => $options, - 'icon' => $icon, - 'btn_class' => $btn_class, - ); - return $this; - } + /** + * Add dropdown button + * @param string $id + * @param string $label + * @param array $options + * @param string $icon + * @param string $btn_class + * @return \psm\Util\Module\Sidebar + */ + public function addDropdown($id, $label, $options, $icon = null, $btn_class = null) + { + if (!isset($this->items['dropdown'])) { + $this->items['dropdown'] = array(); + } + $this->items['dropdown'][$id] = array( + 'id' => $id, + 'label' => $label, + 'options' => $options, + 'icon' => $icon, + 'btn_class' => $btn_class, + ); + return $this; + } - public function createHTML() { - $tpl_data = array( - 'subtitle' => $this->subtitle, - ); - $types = array('dropdown', 'button', 'link'); - $tpl_data['items'] = array(); + public function createHTML() + { + $tpl_data = array( + 'subtitle' => $this->subtitle, + ); + $types = array('dropdown', 'button', 'link'); + $tpl_data['items'] = array(); - // loop through all types and build their html - foreach ($types as $type) { - if (empty($this->items[$type])) { - // no items for this type - continue; - } + // loop through all types and build their html + foreach ($types as $type) { + if (empty($this->items[$type])) { + // no items for this type + continue; + } - // build html for each individual item - foreach ($this->items[$type] as $id => $item) { - $item['type'] = $type; - $item['class_active'] = ($id === $this->active_id) ? 'active' : ''; - $tpl_data['items'][] = $item; - } - } + // build html for each individual item + foreach ($this->items[$type] as $id => $item) { + $item['type'] = $type; + $item['class_active'] = ($id === $this->active_id) ? 'active' : ''; + $tpl_data['items'][] = $item; + } + } - $tpl = $this->twig->loadTemplate('util/module/sidebar.tpl.html'); - $html = $tpl->render($tpl_data); + $tpl = $this->twig->loadTemplate('util/module/sidebar.tpl.html'); + $html = $tpl->render($tpl_data); - return $html; - } -} \ No newline at end of file + return $html; + } +} diff --git a/src/psm/Util/Module/SidebarInterface.php b/src/psm/Util/Module/SidebarInterface.php index 9102bfaf..f99775a7 100644 --- a/src/psm/Util/Module/SidebarInterface.php +++ b/src/psm/Util/Module/SidebarInterface.php @@ -1,4 +1,5 @@ db = $db; + public function __construct(\psm\Service\Database $db) + { + $this->db = $db; - $this->setRetentionPeriod(psm_get_conf('log_retention_period', 365)); + $this->setRetentionPeriod(psm_get_conf('log_retention_period', 365)); - $this->archivers[] = new Archiver\UptimeArchiver($db); - $this->archivers[] = new Archiver\LogsArchiver($db); - } + $this->archivers[] = new Archiver\UptimeArchiver($db); + $this->archivers[] = new Archiver\LogsArchiver($db); + } - /** - * Archive one or more servers. - * @param int $server_id - * @return boolean - */ - public function archive($server_id = null) { - $result = true; - foreach ($this->archivers as $archiver) { - if (!$archiver->archive($server_id)) { - $result = false; - } - } - return $result; - } + /** + * Archive one or more servers. + * @param int $server_id + * @return boolean + */ + public function archive($server_id = null) + { + $result = true; + foreach ($this->archivers as $archiver) { + if (!$archiver->archive($server_id)) { + $result = false; + } + } + return $result; + } - /** - * Cleanup old records for one or more servers - * @param int $server_id - * @return boolean - */ - public function cleanup($server_id = null) { - $result = true; - if (!$this->retention_period) { - // cleanup is disabled - return $result; - } - $retdate = new \DateTime(); - $retdate->sub($this->retention_period); + /** + * Cleanup old records for one or more servers + * @param int $server_id + * @return boolean + */ + public function cleanup($server_id = null) + { + $result = true; + if (!$this->retention_period) { + // cleanup is disabled + return $result; + } + $retdate = new \DateTime(); + $retdate->sub($this->retention_period); - foreach ($this->archivers as $archiver) { - if (!$archiver->cleanup($retdate, $server_id)) { - $result = false; - } - } - return $result; - } + foreach ($this->archivers as $archiver) { + if (!$archiver->cleanup($retdate, $server_id)) { + $result = false; + } + } + return $result; + } - /** - * Set retention period for this archive run. - * - * Set period to 0 to disable cleanup altogether. - * @param \DateInterval|int $period \DateInterval object or number of days (int) - * @return \psm\Util\Server\ArchiveManager - */ - public function setRetentionPeriod($period) { - if (is_object($period) && $period instanceof \DateInterval) { - $this->retention_period = $period; - } elseif (intval($period) == 0) { - // cleanup disabled - $this->retention_period = false; - } else { - $this->retention_period = new \DateInterval('P'.intval($period).'D'); - } - return $this; - } -} \ No newline at end of file + /** + * Set retention period for this archive run. + * + * Set period to 0 to disable cleanup altogether. + * @param \DateInterval|int $period \DateInterval object or number of days (int) + * @return \psm\Util\Server\ArchiveManager + */ + public function setRetentionPeriod($period) + { + if (is_object($period) && $period instanceof \DateInterval) { + $this->retention_period = $period; + } elseif (intval($period) == 0) { + // cleanup disabled + $this->retention_period = false; + } else { + $this->retention_period = new \DateInterval('P' . intval($period) . 'D'); + } + return $this; + } +} diff --git a/src/psm/Util/Server/Archiver/ArchiverInterface.php b/src/psm/Util/Server/Archiver/ArchiverInterface.php index 6007e1ad..8c46433e 100644 --- a/src/psm/Util/Server/Archiver/ArchiverInterface.php +++ b/src/psm/Util/Server/Archiver/ArchiverInterface.php @@ -1,4 +1,5 @@ db = $db; - } + public function __construct(Database $db) + { + $this->db = $db; + } - /** - * Currently there is not really a log archive. - * - * It stays in the log table until cleaned up. - * @param int $server_id - */ - public function archive($server_id = null) { - return true; - } + /** + * Currently there is not really a log archive. + * + * It stays in the log table until cleaned up. + * @param int $server_id + */ + public function archive($server_id = null) + { + return true; + } - public function cleanup(\DateTime $retention_date, $server_id = null) { - $sql_where_server = ($server_id !== null) - // this is obviously not the cleanest way to implement this when using paramter binding.. sorry. - ? ' `server_id` = '.intval($server_id).' AND ' - : ''; + public function cleanup(\DateTime $retention_date, $server_id = null) + { + $sql_where_server = ($server_id !== null) + // this is obviously not the cleanest way to implement this when using paramter binding.. sorry. + ? ' `server_id` = ' . intval($server_id) . ' AND ' + : ''; - $this->db->execute( - "DELETE FROM `".PSM_DB_PREFIX."log` WHERE {$sql_where_server} `datetime` < :latest_date", - array('latest_date' => $retention_date->format('Y-m-d 00:00:00')), - false - ); - return true; - } + $this->db->execute( + "DELETE FROM `" . PSM_DB_PREFIX . "log` WHERE {$sql_where_server} `datetime` < :latest_date", + array('latest_date' => $retention_date->format('Y-m-d 00:00:00')), + false + ); + return true; + } - /** - * Empty tables log and log_users - */ - public function cleanupall() { - $this->db->delete(PSM_DB_PREFIX."log"); - $this->db->delete(PSM_DB_PREFIX."log_users"); - return true; - } + /** + * Empty tables log and log_users + */ + public function cleanupall() + { + $this->db->delete(PSM_DB_PREFIX . "log"); + $this->db->delete(PSM_DB_PREFIX . "log_users"); + return true; + } } diff --git a/src/psm/Util/Server/Archiver/UptimeArchiver.php b/src/psm/Util/Server/Archiver/UptimeArchiver.php index d8ee9e2c..e7db3183 100644 --- a/src/psm/Util/Server/Archiver/UptimeArchiver.php +++ b/src/psm/Util/Server/Archiver/UptimeArchiver.php @@ -1,4 +1,5 @@ db = $db; - } + public function __construct(Database $db) + { + $this->db = $db; + } - /** - * Archive all server status records older than 1 week. - * - * Archiving means calculating averages per day, and storing 1 single - * history row for each day for each server. - * - * @param int $server_id - */ - public function archive($server_id = null) { - $latest_date = new \DateTime('-1 week 0:0:0'); + /** + * Archive all server status records older than 1 week. + * + * Archiving means calculating averages per day, and storing 1 single + * history row for each day for each server. + * + * @param int $server_id + */ + public function archive($server_id = null) + { + $latest_date = new \DateTime('-1 week 0:0:0'); - // Lock tables to prevent simultaneous archiving (by other sessions or the cron job) - try { - $this->db->pdo()->exec('LOCK TABLES '.PSM_DB_PREFIX.'servers_uptime WRITE, '.PSM_DB_PREFIX.'servers_history WRITE'); - $locked = true; - } catch (\PDOException $e) { - // user does not have lock rights, ignore - $locked = false; - } + // Lock tables to prevent simultaneous archiving (by other sessions or the cron job) + try { + $this->db->pdo()->exec('LOCK TABLES ' . PSM_DB_PREFIX . + 'servers_uptime WRITE, ' . PSM_DB_PREFIX . 'servers_history WRITE'); + $locked = true; + } catch (\PDOException $e) { + // user does not have lock rights, ignore + $locked = false; + } - $latest_date_str = $latest_date->format('Y-m-d 00:00:00'); + $latest_date_str = $latest_date->format('Y-m-d 00:00:00'); - $sql_where_server = $this->createSQLWhereServer($server_id); + $sql_where_server = $this->createSQLWhereServer($server_id); - $records = $this->db->execute( - "SELECT `server_id`,`date`,`status`,`latency` - FROM `".PSM_DB_PREFIX."servers_uptime` + $records = $this->db->execute( + "SELECT `server_id`,`date`,`status`,`latency` + FROM `" . PSM_DB_PREFIX . "servers_uptime` WHERE {$sql_where_server} `date` < :latest_date", - array('latest_date' => $latest_date_str)); + array('latest_date' => $latest_date_str) + ); - if (!empty($records)) { - // first group all records by day and server_id - $data_by_day = array(); - foreach ($records as $record) { - $server_id = (int) $record['server_id']; - $day = date('Y-m-d', strtotime($record['date'])); - if (!isset($data_by_day[$day][$server_id])) { - $data_by_day[$day][$server_id] = array(); - } - $data_by_day[$day][$server_id][] = $record; - } + if (!empty($records)) { + // first group all records by day and server_id + $data_by_day = array(); + foreach ($records as $record) { + $server_id = (int) $record['server_id']; + $day = date('Y-m-d', strtotime($record['date'])); + if (!isset($data_by_day[$day][$server_id])) { + $data_by_day[$day][$server_id] = array(); + } + $data_by_day[$day][$server_id][] = $record; + } - // now get history data day by day - $histories = array(); - foreach ($data_by_day as $day => $day_records) { - foreach ($day_records as $server_id => $server_day_records) { - $histories[] = $this->getHistoryForDay($day, $server_id, $server_day_records); - } - } + // now get history data day by day + $histories = array(); + foreach ($data_by_day as $day => $day_records) { + foreach ($day_records as $server_id => $server_day_records) { + $histories[] = $this->getHistoryForDay($day, $server_id, $server_day_records); + } + } - // Save all - $this->db->insertMultiple(PSM_DB_PREFIX.'servers_history', $histories); + // Save all + $this->db->insertMultiple(PSM_DB_PREFIX . 'servers_history', $histories); - // now remove all records from the uptime table - $this->db->execute( - "DELETE FROM `".PSM_DB_PREFIX."servers_uptime` WHERE {$sql_where_server} `date` < :latest_date", - array('latest_date' => $latest_date_str), - false - ); - } + // now remove all records from the uptime table + $this->db->execute( + "DELETE FROM `" . PSM_DB_PREFIX . "servers_uptime` WHERE {$sql_where_server} `date` < :latest_date", + array('latest_date' => $latest_date_str), + false + ); + } - if ($locked) { - $this->db->exec('UNLOCK TABLES'); - } + if ($locked) { + $this->db->exec('UNLOCK TABLES'); + } - return true; - } + return true; + } - public function cleanup(\DateTime $retention_date, $server_id = null) { - $sql_where_server = $this->createSQLWhereServer($server_id); - $this->db->execute( - "DELETE FROM `".PSM_DB_PREFIX."servers_history` WHERE {$sql_where_server} `date` < :latest_date", - array('latest_date' => $retention_date->format('Y-m-d 00:00:00')), - false - ); - return true; - } + public function cleanup(\DateTime $retention_date, $server_id = null) + { + $sql_where_server = $this->createSQLWhereServer($server_id); + $this->db->execute( + "DELETE FROM `" . PSM_DB_PREFIX . "servers_history` WHERE {$sql_where_server} `date` < :latest_date", + array('latest_date' => $retention_date->format('Y-m-d 00:00:00')), + false + ); + return true; + } - /** - * Build a history array for a day records - * @param string $day - * @param int $server_id - * @param array $day_records - * @return array - */ - protected function getHistoryForDay($day, $server_id, $day_records) { - $latencies = array(); - $checks_failed = 0; + /** + * Build a history array for a day records + * @param string $day + * @param int $server_id + * @param array $day_records + * @return array + */ + protected function getHistoryForDay($day, $server_id, $day_records) + { + $latencies = array(); + $checks_failed = 0; - foreach ($day_records as $day_record) { - $latencies[] = $day_record['latency']; + foreach ($day_records as $day_record) { + $latencies[] = $day_record['latency']; - if ($day_record['status'] == 0) { - $checks_failed++; - } - } - sort($latencies, SORT_NUMERIC); + if ($day_record['status'] == 0) { + $checks_failed++; + } + } + sort($latencies, SORT_NUMERIC); - $history = array( - 'date' => $day, - 'server_id' => $server_id, - 'latency_min' => min($latencies), - 'latency_avg' => array_sum($latencies) / count($latencies), - 'latency_max' => max($latencies), - 'checks_total' => count($day_records), - 'checks_failed' => $checks_failed, - ); - return $history; - } + $history = array( + 'date' => $day, + 'server_id' => $server_id, + 'latency_min' => min($latencies), + 'latency_avg' => array_sum($latencies) / count($latencies), + 'latency_max' => max($latencies), + 'checks_total' => count($day_records), + 'checks_failed' => $checks_failed, + ); + return $history; + } - protected function createSQLWhereServer($server_id) { - $sql_where_server = ($server_id !== null) - // this is obviously not the cleanest way to implement this when using paramter binding.. sorry. - ? ' `server_id` = '.intval($server_id).' AND ' - : ''; + protected function createSQLWhereServer($server_id) + { + $sql_where_server = ($server_id !== null) + // this is obviously not the cleanest way to implement this when using paramter binding.. sorry. + ? ' `server_id` = ' . intval($server_id) . ' AND ' + : ''; - return $sql_where_server; - } -} \ No newline at end of file + return $sql_where_server; + } +} diff --git a/src/psm/Util/Server/HistoryGraph.php b/src/psm/Util/Server/HistoryGraph.php index 42c0b052..8b5b8e38 100644 --- a/src/psm/Util/Server/HistoryGraph.php +++ b/src/psm/Util/Server/HistoryGraph.php @@ -1,4 +1,5 @@ db = $db; - $this->twig = $twig; - } + public function __construct(Database $db, \Twig_Environment $twig) + { + $this->db = $db; + $this->twig = $twig; + } - /** - * Prepare the HTML for the graph - * @return string - */ - public function createHTML($server_id) { - // Archive all records for this server to make sure we have up-to-date stats - $archive = new ArchiveManager($this->db); - $archive->archive($server_id); + /** + * Prepare the HTML for the graph + * @return string + */ + public function createHTML($server_id) + { + // Archive all records for this server to make sure we have up-to-date stats + $archive = new ArchiveManager($this->db); + $archive->archive($server_id); - $now = new \DateTime(); - $last_week = new \DateTime('-1 week 0:0:0'); - $last_year = new \DateTime('-1 year -1 week 0:0:0'); + $now = new \DateTime(); + $last_week = new \DateTime('-1 week 0:0:0'); + $last_year = new \DateTime('-1 year -1 week 0:0:0'); - $graphs = array( - 0 => $this->generateGraphUptime($server_id, $last_week, $now), - 1 => $this->generateGraphHistory($server_id, $last_year, $last_week), - ); - $info_fields = array( - 'latency_avg' => '%01.4f', - 'uptime' => '%01.3f%%', - ); + $graphs = array( + 0 => $this->generateGraphUptime($server_id, $last_week, $now), + 1 => $this->generateGraphHistory($server_id, $last_year, $last_week), + ); + $info_fields = array( + 'latency_avg' => '%01.4f', + 'uptime' => '%01.3f%%', + ); - foreach ($graphs as $i => &$graph) { - // add subarray for info fields - $graph['info'] = array(); + foreach ($graphs as $i => &$graph) { + // add subarray for info fields + $graph['info'] = array(); - foreach ($info_fields as $field => $format) { - if (!isset($graph[$field])) { - continue; - } - $graph['info'][] = array( - 'label' => psm_get_lang('servers', $field), - 'value' => sprintf($format, $graph[$field]), - ); - } - } - $tpl_data = array( - 'graphs' => $graphs, - ); - return $this->twig->render('module/server/history.tpl.html', $tpl_data); - } + foreach ($info_fields as $field => $format) { + if (!isset($graph[$field])) { + continue; + } + $graph['info'][] = array( + 'label' => psm_get_lang('servers', $field), + 'value' => sprintf($format, $graph[$field]), + ); + } + } + $tpl_data = array( + 'graphs' => $graphs, + ); + return $this->twig->render('module/server/history.tpl.html', $tpl_data); + } - /** - * Generate data for uptime graph - * @param int $server_id - * @param \DateTime $start_time Lowest DateTime of the graph - * @param \DateTime $end_time Highest DateTime of the graph - * @return array - */ - public function generateGraphUptime($server_id, $start_time, $end_time) { + /** + * Generate data for uptime graph + * @param int $server_id + * @param \DateTime $start_time Lowest DateTime of the graph + * @param \DateTime $end_time Highest DateTime of the graph + * @return array + */ + public function generateGraphUptime($server_id, $start_time, $end_time) + { - $lines = array( - 'latency' => array(), - ); + $lines = array( + 'latency' => array(), + ); - $hour = new \DateTime('-1 hour'); - $day = new \DateTime('-1 day'); - $week = new \DateTime('-1 week'); - - $records = $this->getRecords('uptime', $server_id, $start_time, $end_time); + $hour = new \DateTime('-1 hour'); + $day = new \DateTime('-1 day'); + $week = new \DateTime('-1 week'); + + $records = $this->getRecords('uptime', $server_id, $start_time, $end_time); - $data = $this->generateGraphLines($records, $lines, 'latency', $hour, $end_time, true); + $data = $this->generateGraphLines($records, $lines, 'latency', $hour, $end_time, true); - $data['title'] = psm_get_lang('servers', 'chart_last_week'); - $data['id'] = 'history_short'; - $data['unit'] = 'minute'; - $data['buttons'] = array(); - $data['button_name'] = 'timeframe_short'; - $data['buttons'][] = array('unit' => 'minute', 'time' => $hour->getTimestamp()*1000, 'label' => psm_get_lang('servers', 'hour'), 'class_active' => 'active'); - $data['buttons'][] = array('unit' => 'hour', 'time' => $day->getTimestamp()*1000, 'label' => psm_get_lang('servers', 'day')); - $data['buttons'][] = array('unit' => 'day', 'time' => $week->getTimestamp()*1000, 'label' => psm_get_lang('servers', 'week')); + $data['title'] = psm_get_lang('servers', 'chart_last_week'); + $data['id'] = 'history_short'; + $data['unit'] = 'minute'; + $data['buttons'] = array(); + $data['button_name'] = 'timeframe_short'; + $data['buttons'][] = array( + 'unit' => 'minute', + 'time' => $hour->getTimestamp() * 1000, + 'label' => psm_get_lang('servers', 'hour'), + 'class_active' => 'active' + ); + $data['buttons'][] = array( + 'unit' => 'hour', + 'time' => $day->getTimestamp() * 1000, + 'label' => psm_get_lang('servers', 'day') + ); + $data['buttons'][] = array( + 'unit' => 'day', + 'time' => $week->getTimestamp() * 1000, + 'label' => psm_get_lang('servers', 'week') + ); - return $data; - } + return $data; + } - /** - * Generate data for history graph - * @param int $server_id - * @param \DateTime $start_time Lowest DateTime of the graph - * @param \DateTime $end_time Highest DateTime of the graph - * @return array - */ - public function generateGraphHistory($server_id, $start_time, $end_time) { - $lines = array( - 'latency_min' => array(), - 'latency_avg' => array(), - 'latency_max' => array(), - ); + /** + * Generate data for history graph + * @param int $server_id + * @param \DateTime $start_time Lowest DateTime of the graph + * @param \DateTime $end_time Highest DateTime of the graph + * @return array + */ + public function generateGraphHistory($server_id, $start_time, $end_time) + { + $lines = array( + 'latency_min' => array(), + 'latency_avg' => array(), + 'latency_max' => array(), + ); - $week = new \DateTime('-2 week 0:0:0'); - $month = new \DateTime('-1 month -1 week 0:0:0'); - $year = new \DateTime('-1 year -1 week 0:0:0'); + $week = new \DateTime('-2 week 0:0:0'); + $month = new \DateTime('-1 month -1 week 0:0:0'); + $year = new \DateTime('-1 year -1 week 0:0:0'); - $records = $this->getRecords('history', $server_id, $year, $end_time); + $records = $this->getRecords('history', $server_id, $year, $end_time); - // dont add uptime for now because we have no way to calculate accurate uptimes for archived records - $data = $this->generateGraphLines($records, $lines, 'latency_avg', $start_time, $end_time, false); - $data['title'] = psm_get_lang('servers', 'chart_history'); - $data['id'] = 'history_long'; - $data['unit'] = 'week'; - $data['buttons'] = array(); - $data['button_name'] = 'timeframe_long'; - $data['buttons'][] = array('unit' => 'day', 'time' => $week->getTimestamp()*1000, 'label' => psm_get_lang('servers', 'week')); - $data['buttons'][] = array('unit' => 'week', 'time' => $month->getTimestamp()*1000, 'label' => psm_get_lang('servers', 'month'), 'class_active' => 'active'); - $data['buttons'][] = array('unit' => 'month', 'time' => $year->getTimestamp()*1000, 'label' => psm_get_lang('servers', 'year')); + // dont add uptime for now because we have no way to calculate accurate uptimes for archived records + $data = $this->generateGraphLines($records, $lines, 'latency_avg', $start_time, $end_time, false); + $data['title'] = psm_get_lang('servers', 'chart_history'); + $data['id'] = 'history_long'; + $data['unit'] = 'week'; + $data['buttons'] = array(); + $data['button_name'] = 'timeframe_long'; + $data['buttons'][] = array( + 'unit' => 'day', + 'time' => $week->getTimestamp() * 1000, + 'label' => psm_get_lang('servers', 'week') + ); + $data['buttons'][] = array( + 'unit' => 'week', + 'time' => $month->getTimestamp() * 1000, + 'label' => psm_get_lang('servers', 'month'), + 'class_active' => 'active' + ); + $data['buttons'][] = array( + 'unit' => 'month', + 'time' => $year->getTimestamp() * 1000, + 'label' => psm_get_lang('servers', 'year') + ); - return $data; - } + return $data; + } - /** - * Get all uptime/history records for a server - * @param string $type - * @param int $server_id - * @param \DateTime $start_time Lowest DateTime of the graph - * @param \DateTime $end_time Highest DateTime of the graph - * @return array - */ - protected function getRecords($type, $server_id, $start_time, $end_time) { - if (!in_array($type, array('history', 'uptime'))) { - return array(); - } + /** + * Get all uptime/history records for a server + * @param string $type + * @param int $server_id + * @param \DateTime $start_time Lowest DateTime of the graph + * @param \DateTime $end_time Highest DateTime of the graph + * @return array + */ + protected function getRecords($type, $server_id, $start_time, $end_time) + { + if (!in_array($type, array('history', 'uptime'))) { + return array(); + } - $records = $this->db->execute( - "SELECT * - FROM `".PSM_DB_PREFIX."servers_$type` + $records = $this->db->execute( + "SELECT * + FROM `" . PSM_DB_PREFIX . "servers_$type` WHERE `server_id` = :server_id AND `date` BETWEEN :start_time AND :end_time ORDER BY `date` ASC", - array( - 'server_id' => $server_id, - 'start_time' => $start_time->format('Y-m-d H:i:s'), - 'end_time' => $end_time->format('Y-m-d H:i:s'), - )); - return $records; - } + array( + 'server_id' => $server_id, + 'start_time' => $start_time->format('Y-m-d H:i:s'), + 'end_time' => $end_time->format('Y-m-d H:i:s'), + ) + ); + return $records; + } - /** - * Generate data arrays for graphs - * @param array $records All uptime records to parse, MUST BE SORTED BY DATE IN ASCENDING ORDER - * @param array $lines Array with keys as line ids to prepare (key must be available in uptime records) - * @param string $latency_avg_key which key from uptime records to use for calculating averages - * @param \DateTime $start_time Lowest DateTime of the graph - * @param \DateTime $end_time Highest DateTime of the graph - * @param boolean $add_uptime Add uptime calculation? - * @param array $prev Previous result - * @param int $downtime Total downtime - * @param int $prev_downtime Timestamp from last offline record. 0 when last record is uptime - * @return array - */ - protected function generateGraphLines($records, $lines, $latency_avg_key, $start_time, $end_time, $add_uptime = false) { - $now = new \DateTime(); - $data = array(); + /** + * Generate data arrays for graphs + * @param array $records All uptime records to parse, MUST BE SORTED BY DATE IN ASCENDING ORDER + * @param array $lines Array with keys as line ids to prepare (key must be available in uptime records) + * @param string $latency_avg_key which key from uptime records to use for calculating averages + * @param \DateTime $start_time Lowest DateTime of the graph + * @param \DateTime $end_time Highest DateTime of the graph + * @param boolean $add_uptime Add uptime calculation? + * @param array $prev Previous result + * @param int $downtime Total downtime + * @param int $prev_downtime Timestamp from last offline record. 0 when last record is uptime + * @return array + */ + protected function generateGraphLines( + $records, + $lines, + $latency_avg_key, + $start_time, + $end_time, + $add_uptime = false + ) { + $now = new \DateTime(); + $data = array(); - // PLEASE NOTE: all times are in microseconds! because of javascript. - $latency_avg = 0; + // PLEASE NOTE: all times are in microseconds! because of javascript. + $latency_avg = 0; - $prev = reset($records); + $prev = reset($records); - $prev_downtime = 0; - $downtime = 0; + $prev_downtime = 0; + $downtime = 0; - // Create the list of points and server down zones - foreach ($records as $record) { - $time = strtotime($record['date']); - // use the first line to calculate average latency - $latency_avg += (float) $record[$latency_avg_key]; + // Create the list of points and server down zones + foreach ($records as $record) { + $time = strtotime($record['date']); + // use the first line to calculate average latency + $latency_avg += (float) $record[$latency_avg_key]; - foreach ($lines as $key => $value) { - // add the value for each of the different lines - if (isset($record[$key])) { - if (isset($record['status'])){ - // down - if ($record['status'] == 0){ - $lines['online'][] = $prev['status'] - // Previous datapoint was online - ? '{ x: '.($time*1000).', y: '.$prev['latency'].'}' - // Previous datapoint was offline - : '{ x: '.($time*1000).', y: null}'; - // new outage start - $lines['offline'][] = '{ x: '.($time*1000).', y:0.1}'; + foreach ($lines as $key => $value) { + // add the value for each of the different lines + if (isset($record[$key])) { + if (isset($record['status'])) { + // down + if ($record['status'] == 0) { + $lines['online'][] = $prev['status'] + // Previous datapoint was online + ? '{ x: ' . ($time * 1000) . ', y: ' . $prev['latency'] . '}' + // Previous datapoint was offline + : '{ x: ' . ($time * 1000) . ', y: null}'; + // new outage start + $lines['offline'][] = '{ x: ' . ($time * 1000) . ', y:0.1}'; - $prev_downtime != 0 ?: $prev_downtime = $time; - } - // up - else { - // outage ends - $lines['offline'][] = $prev['status'] - // Previous datapoint was online - ? '{ x: '.($time*1000).', y:null}' - // Previous datapoint was offline - : '{ x: '.($time*1000).', y:0.1}'; - $lines['online'][] = '{ x: '.($time*1000).', y: '.round((float) $record[$key], 4).'}'; + $prev_downtime != 0 ?: $prev_downtime = $time; + } else { + // up + // outage ends + $lines['offline'][] = $prev['status'] + // Previous datapoint was online + ? '{ x: ' . ($time * 1000) . ', y:null}' + // Previous datapoint was offline + : '{ x: ' . ($time * 1000) . ', y:0.1}'; + $lines['online'][] = '{ x: ' . ($time * 1000) . ', y: ' . + round((float) $record[$key], 4) . '}'; - $prev_downtime == 0 ?: $downtime += ($time - $prev_downtime); - $prev_downtime = 0; - } - } - else { - $lines[$key][] = '{ x: \''.$record['date'].'\', y: '.$record[$key].'}'; - } - $prev = $record; - } - } - } - // Was down before. - // Record the first and last date as a string in the down array - $prev_downtime == 0 ?: $downtime += ($now->getTimestamp()-$prev_downtime); - if ($add_uptime) { - $prev['status'] ?: $lines['offline'][] = '{ x: '.($now->getTimestamp()*1000).', y:0.1}'; - $data['uptime'] = 100 - ($downtime / ($end_time->getTimestamp() - $start_time->getTimestamp())); - } + $prev_downtime == 0 ?: $downtime += ($time - $prev_downtime); + $prev_downtime = 0; + } + } else { + $lines[$key][] = '{ x: \'' . $record['date'] . '\', y: ' . $record[$key] . '}'; + } + $prev = $record; + } + } + } + // Was down before. + // Record the first and last date as a string in the down array + $prev_downtime == 0 ?: $downtime += ($now->getTimestamp() - $prev_downtime); + if ($add_uptime) { + $prev['status'] ?: $lines['offline'][] = '{ x: ' . ($now->getTimestamp() * 1000) . ', y:0.1}'; + $data['uptime'] = 100 - ($downtime / ($end_time->getTimestamp() - $start_time->getTimestamp())); + } - $lines_merged = array(); - foreach ($lines as $line_key => $line_value) { - - if (empty($line_value)) { - continue; - } - $lines_merged[$line_key]['value'] = implode(', ', $line_value); - $lines_merged[$line_key]['name'] = psm_get_lang('servers', $line_key); - } + $lines_merged = array(); + foreach ($lines as $line_key => $line_value) { + if (empty($line_value)) { + continue; + } + $lines_merged[$line_key]['value'] = implode(', ', $line_value); + $lines_merged[$line_key]['name'] = psm_get_lang('servers', $line_key); + } - $data['latency_avg'] = count($records) > 0 ? ($latency_avg / count($records)) : 0; - $data['lines'] = sizeof($lines_merged) ? $lines_merged : ''; - $data['end_timestamp'] = number_format($end_time->getTimestamp(), 0, '', '')*1000; - $data['start_timestamp'] = number_format($start_time->getTimestamp(), 0, '', '')*1000; - return $data; - } + $data['latency_avg'] = count($records) > 0 ? ($latency_avg / count($records)) : 0; + $data['lines'] = sizeof($lines_merged) ? $lines_merged : ''; + $data['end_timestamp'] = number_format($end_time->getTimestamp(), 0, '', '') * 1000; + $data['start_timestamp'] = number_format($start_time->getTimestamp(), 0, '', '') * 1000; + return $data; + } } diff --git a/src/psm/Util/Server/ServerValidator.php b/src/psm/Util/Server/ServerValidator.php index a7ac57e5..63e5688b 100644 --- a/src/psm/Util/Server/ServerValidator.php +++ b/src/psm/Util/Server/ServerValidator.php @@ -1,4 +1,5 @@ db = $db; - } + public function __construct(\psm\Service\Database $db) + { + $this->db = $db; + } - /** - * Check if the server id exists - * @param int|\PDOStatement $server_id - * @return boolean - * @throws \InvalidArgumentException - */ - public function serverId($server_id) { - $server = $this->db->selectRow(PSM_DB_PREFIX.'servers', array('server_id' => $server_id), array('server_id')); + /** + * Check if the server id exists + * @param int|\PDOStatement $server_id + * @return boolean + * @throws \InvalidArgumentException + */ + public function serverId($server_id) + { + $server = $this->db->selectRow(PSM_DB_PREFIX . 'servers', array('server_id' => $server_id), array('server_id')); - if (empty($server)) { - throw new \InvalidArgumentException('server_no_match'); - } - return true; - } + if (empty($server)) { + throw new \InvalidArgumentException('server_no_match'); + } + return true; + } - /** - * Check label - * @param string $label - * @return boolean - * @throws \InvalidArgumentException - */ - public function label($label) { - $label = trim($label); - if (empty($label) || strlen($label) > 255) { - throw new \InvalidArgumentException('server_label_bad_length'); - } - return true; - } + /** + * Check label + * @param string $label + * @return boolean + * @throws \InvalidArgumentException + */ + public function label($label) + { + $label = trim($label); + if (empty($label) || strlen($label) > 255) { + throw new \InvalidArgumentException('server_label_bad_length'); + } + return true; + } - /** - * Check server domain/ip - * @param string $value - * @param string $type if given, it can be checked for "website"/"ip" - * @return boolean - * @throws \InvalidArgumentException - */ - public function ip($value, $type = null) { - $value = trim($value); + /** + * Check server domain/ip + * @param string $value + * @param string $type if given, it can be checked for "website"/"ip" + * @return boolean + * @throws \InvalidArgumentException + */ + public function ip($value, $type = null) + { + $value = trim($value); - if (empty($value) || strlen($value) > 255) { - throw new \InvalidArgumentException('server_ip_bad_length'); - } + if (empty($value) || strlen($value) > 255) { + throw new \InvalidArgumentException('server_ip_bad_length'); + } - switch ($type) { - case 'website': - // url regex as per https://stackoverflow.com/a/3809435 - if (!preg_match_all("/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,12}\b([-a-zA-Z0-9@:%_\+.~#?&\/\/=]*)/", $value)) { - throw new \InvalidArgumentException('server_ip_bad_website'); - } - break; - case 'service': - case 'ping': - if (!filter_var($value, FILTER_VALIDATE_IP) - // domain regex as per http://stackoverflow.com/questions/106179/regular-expression-to-match-hostname-or-ip-address : - && !preg_match("/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/", $value) - ) {throw new \InvalidArgumentException('server_ip_bad_service'); } - break; - } + switch ($type) { + case 'website': + // url regex as per https://stackoverflow.com/a/3809435 + // Regex looks a bit weird, but otherwise it's more then 120 characters + if ( + !preg_match_all( + "/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\." . + "[a-z]{2,12}\b([-a-zA-Z0-9@:%_\+.~#?&\/\/=]*)/", + $value + ) + ) { + throw new \InvalidArgumentException('server_ip_bad_website'); + } + break; + case 'service': + case 'ping': + if ( + !filter_var($value, FILTER_VALIDATE_IP) + // domain regex as per + // http://stackoverflow.com/questions/106179/regular-expression-to-match-hostname-or-ip-address + // Regex looks a bit weird, but otherwise it's more then 120 characters + && !preg_match( + "/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*" . + "([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/", + $value + ) + ) { + throw new \InvalidArgumentException('server_ip_bad_service'); + } + break; + } - return true; - } + return true; + } - /** - * Check server type - * @param string $type - * @return boolean - * @throws \InvalidArgumentException - */ - public function type($type) { - if (!in_array($type, array('ping', 'service', 'website'))) { - throw new \InvalidArgumentException('server_type_invalid'); - } - return true; - } + /** + * Check server type + * @param string $type + * @return boolean + * @throws \InvalidArgumentException + */ + public function type($type) + { + if (!in_array($type, array('ping', 'service', 'website'))) { + throw new \InvalidArgumentException('server_type_invalid'); + } + return true; + } - /** - * Check warning threshold - * @param int $value - * @return boolean - * @throws \InvalidArgumentException - */ - public function warningThreshold($value) { - if (!is_numeric($value) || intval($value) == 0) { - throw new \InvalidArgumentException('server_warning_threshold_invalid'); - } - return true; - } + /** + * Check warning threshold + * @param int $value + * @return boolean + * @throws \InvalidArgumentException + */ + public function warningThreshold($value) + { + if (!is_numeric($value) || intval($value) == 0) { + throw new \InvalidArgumentException('server_warning_threshold_invalid'); + } + return true; + } } diff --git a/src/psm/Util/Server/UpdateManager.php b/src/psm/Util/Server/UpdateManager.php index fe335f09..29a397cd 100644 --- a/src/psm/Util/Server/UpdateManager.php +++ b/src/psm/Util/Server/UpdateManager.php @@ -1,4 +1,5 @@ container = $container; + } - function __construct(ContainerInterface $container) { - $this->container = $container; - } + /** + * Go :-) + * + * @param boolean $skip_perms if TRUE, no user permissions will be taken in account and all servers will be updated + */ + public function run($skip_perms = false) + { + // check if we need to restrict the servers to a certain user + $sql_join = ''; - /** - * Go :-) - * - * @param boolean $skip_perms if TRUE, no user permissions will be taken in account and all servers will be updated - */ - public function run($skip_perms = false) { - // check if we need to restrict the servers to a certain user - $sql_join = ''; - - if (!$skip_perms && $this->container->get('user')->getUserLevel() > PSM_USER_ADMIN) { - // restrict by user_id - $sql_join = "JOIN `".PSM_DB_PREFIX."users_servers` AS `us` ON ( + if (!$skip_perms && $this->container->get('user')->getUserLevel() > PSM_USER_ADMIN) { + // restrict by user_id + $sql_join = "JOIN `" . PSM_DB_PREFIX . "users_servers` AS `us` ON ( `us`.`user_id`={$this->container->get('user')->getUserId()} AND `us`.`server_id`=`s`.`server_id` )"; - } + } - $sql = "SELECT `s`.`server_id`,`s`.`ip`,`s`.`port`,`s`.`label`,`s`.`type`,`s`.`pattern`,`s`.`header_name`,`s`.`header_value`,`s`.`status`,`s`.`active`,`s`.`email`,`s`.`sms`,`s`.`pushover`,`s`.`telegram` - FROM `".PSM_DB_PREFIX."servers` AS `s` + $sql = "SELECT `s`.`server_id`,`s`.`ip`,`s`.`port`,`s`.`label`,`s`.`type`,`s`.`pattern`,`s`.`header_name`, + `s`.`header_value`,`s`.`status`,`s`.`active`,`s`.`email`,`s`.`sms`,`s`.`pushover`,`s`.`telegram` + FROM `" . PSM_DB_PREFIX . "servers` AS `s` {$sql_join} WHERE `active`='yes' "; - $servers = $this->container->get('db')->query($sql); + $servers = $this->container->get('db')->query($sql); - $updater = new Updater\StatusUpdater($this->container->get('db')); - $notifier = new Updater\StatusNotifier($this->container->get('db')); + $updater = new Updater\StatusUpdater($this->container->get('db')); + $notifier = new Updater\StatusNotifier($this->container->get('db')); - foreach ($servers as $server) { - $status_old = ($server['status'] == 'on') ? true : false; - $status_new = $updater->update($server['server_id']); - // notify the nerds if applicable - $notifier->notify($server['server_id'], $status_old, $status_new); - // clean-up time!! archive all records - $archive = new ArchiveManager($this->container->get('db')); - $archive->archive($server['server_id']); - $archive->cleanup($server['server_id']); - } - if($notifier->combine){ - $notifier->notifyCombined(); - } - } + foreach ($servers as $server) { + $status_old = ($server['status'] == 'on') ? true : false; + $status_new = $updater->update($server['server_id']); + // notify the nerds if applicable + $notifier->notify($server['server_id'], $status_old, $status_new); + // clean-up time!! archive all records + $archive = new ArchiveManager($this->container->get('db')); + $archive->archive($server['server_id']); + $archive->cleanup($server['server_id']); + } + if ($notifier->combine) { + $notifier->notifyCombined(); + } + } } diff --git a/src/psm/Util/Server/Updater/StatusNotifier.php b/src/psm/Util/Server/Updater/StatusNotifier.php index 443a5cbc..4b8a8d3c 100644 --- a/src/psm/Util/Server/Updater/StatusNotifier.php +++ b/src/psm/Util/Server/Updater/StatusNotifier.php @@ -1,4 +1,5 @@ array(), - 'users' => array(), - 'notifications' => array(), - 'userNotifications' => array() - ); + /** + * Notification list + * @var array $combiNotification + */ + protected $combiNotification = array( + 'count' => array(), + 'users' => array(), + 'notifications' => array(), + 'userNotifications' => array() + ); - /** - * Server id - * @var int $server_id - */ - protected $server_id; + /** + * Server id + * @var int $server_id + */ + protected $server_id; - /** - * Server information - * @var array $server - */ - protected $server; + /** + * Server information + * @var array $server + */ + protected $server; - /** - * Old status - * @var boolean $status_old - */ - protected $status_old; + /** + * Old status + * @var boolean $status_old + */ + protected $status_old; - /** - * New status - * @var boolean $status_new - */ - protected $status_new; + /** + * New status + * @var boolean $status_new + */ + protected $status_new; - function __construct(Database $db) { - $this->db = $db; + public function __construct(Database $db) + { + $this->db = $db; - $this->send_emails = psm_get_conf('email_status'); - $this->send_sms = psm_get_conf('sms_status'); - $this->send_pushover = psm_get_conf('pushover_status'); - $this->send_telegram = psm_get_conf('telegram_status'); - $this->save_logs = psm_get_conf('log_status'); - $this->combine = psm_get_conf('combine_notifications'); - } + $this->send_emails = psm_get_conf('email_status'); + $this->send_sms = psm_get_conf('sms_status'); + $this->send_pushover = psm_get_conf('pushover_status'); + $this->send_telegram = psm_get_conf('telegram_status'); + $this->save_logs = psm_get_conf('log_status'); + $this->combine = psm_get_conf('combine_notifications'); + } /** * This function initializes the sending (text msg, email, Pushover and Telegram) and logging @@ -133,107 +136,119 @@ class StatusNotifier { * @return boolean * @throws \PHPMailer\PHPMailer\Exception */ - public function notify($server_id, $status_old, $status_new) { - if ( - !$this->send_emails && - !$this->send_sms && - !$this->send_pushover && - !$this->send_telegram && - !$this->save_logs - ) { - // seems like we have nothing to do. skip the rest - return false; - } - - $this->server_id = $server_id; - $this->status_old = $status_old; - $this->status_new = $status_new; - - // get server info from db - // only get info that will be put into the notification - // or is needed to check if a notification need to be send - $this->server = $this->db->selectRow(PSM_DB_PREFIX.'servers', array( - 'server_id' => $server_id, - ), array( - 'server_id', 'ip', 'port', 'label', 'error', 'email', 'sms', 'pushover', 'telegram', 'last_online', 'last_offline', 'last_offline_duration', - )); - if (empty($this->server)) { - return false; - } - - $notify = false; - - // check which type of alert the user wants - switch (psm_get_conf('alert_type')) { - case 'always': - if ($status_new == false) { - // server is offline. we are in error state. - $notify = true; - } - break; - case 'offline': - // only send a notification if the server goes down for the first time! - if ($status_new == false && $status_old == true) { - $notify = true; - } - break; - case 'status': - if ($status_new != $status_old) { - // status has been changed! - $notify = true; - } - break; - } - - if (!$notify) { - return false; - } - - // first add to log (we use the same text as the SMS message because its short..) - if ($this->save_logs) { - psm_add_log( - $this->server_id, - 'status', - psm_parse_msg($status_new, 'sms', $this->server) - ); - } - - $users = $this->getUsers($this->server_id); - - if (empty($users)) { - return $notify; - } - - if($this->combine){ - $this->setCombi('init', $users); + public function notify($server_id, $status_old, $status_new) + { + if ( + !$this->send_emails && + !$this->send_sms && + !$this->send_pushover && + !$this->send_telegram && + !$this->save_logs + ) { + // seems like we have nothing to do. skip the rest + return false; } - // check if email is enabled for this server - if ($this->send_emails && $this->server['email'] == 'yes') { - // send email - $this->combine ? $this->setCombi('email') : $this->notifyByEmail($users); - } + $this->server_id = $server_id; + $this->status_old = $status_old; + $this->status_new = $status_new; - // check if sms is enabled for this server - if ($this->send_sms && $this->server['sms'] == 'yes') { - // sms will not be send combined as some gateways don't support long sms / charge extra - // yay lets wake those nerds up! - $this->notifyByTxtMsg($users); - } + // get server info from db + // only get info that will be put into the notification + // or is needed to check if a notification need to be send + $this->server = $this->db->selectRow(PSM_DB_PREFIX . 'servers', array( + 'server_id' => $server_id, + ), array( + 'server_id', + 'ip', + 'port', + 'label', + 'error', + 'email', + 'sms', + 'pushover', + 'telegram', + 'last_online', + 'last_offline', + 'last_offline_duration', + )); + if (empty($this->server)) { + return false; + } - // check if pushover is enabled for this server - if ($this->send_pushover && $this->server['pushover'] == 'yes') { - // yay lets wake those nerds up! - $this->combine ? $this->setCombi('pushover') : $this->notifyByPushover($users); - } + $notify = false; - // check if telegram is enabled for this server - if ($this->send_telegram && $this->server['telegram'] == 'yes') { - $this->combine ? $this->setCombi('telegram') : $this->notifyByTelegram($users); - } + // check which type of alert the user wants + switch (psm_get_conf('alert_type')) { + case 'always': + if ($status_new == false) { + // server is offline. we are in error state. + $notify = true; + } + break; + case 'offline': + // only send a notification if the server goes down for the first time! + if ($status_new == false && $status_old == true) { + $notify = true; + } + break; + case 'status': + if ($status_new != $status_old) { + // status has been changed! + $notify = true; + } + break; + } - return $notify; - } + if (!$notify) { + return false; + } + + // first add to log (we use the same text as the SMS message because its short..) + if ($this->save_logs) { + psm_add_log( + $this->server_id, + 'status', + psm_parse_msg($status_new, 'sms', $this->server) + ); + } + + $users = $this->getUsers($this->server_id); + + if (empty($users)) { + return $notify; + } + + if ($this->combine) { + $this->setCombi('init', $users); + } + + // check if email is enabled for this server + if ($this->send_emails && $this->server['email'] == 'yes') { + // send email + $this->combine ? $this->setCombi('email') : $this->notifyByEmail($users); + } + + // check if sms is enabled for this server + if ($this->send_sms && $this->server['sms'] == 'yes') { + // sms will not be send combined as some gateways don't support long sms / charge extra + // yay lets wake those nerds up! + $this->notifyByTxtMsg($users); + } + + // check if pushover is enabled for this server + if ($this->send_pushover && $this->server['pushover'] == 'yes') { + // yay lets wake those nerds up! + $this->combine ? $this->setCombi('pushover') : $this->notifyByPushover($users); + } + + // check if telegram is enabled for this server + if ($this->send_telegram && $this->server['telegram'] == 'yes') { + $this->combine ? $this->setCombi('telegram') : $this->notifyByTelegram($users); + } + + return $notify; + } /** * This functions collects all of the notifications @@ -242,71 +257,75 @@ class StatusNotifier { * @param array $users Users * @return void */ - public function setCombi($method, $users = array()) { - $status = $this->status_new ? 'on' : 'off'; + public function setCombi($method, $users = array()) + { + $status = $this->status_new ? 'on' : 'off'; - if ($method == 'init' && !empty($users)){ - foreach($users as $user) { - if(!isset($this->combiNotification['count'][$user['user_id']])){ + if ($method == 'init' && !empty($users)) { + foreach ($users as $user) { + if (!isset($this->combiNotification['count'][$user['user_id']])) { $this->combiNotification['count'][$user['user_id']] = array('on' => 0, 'off' => 0); } $this->combiNotification['userNotifications'][$user['user_id']][] = $this->server_id; $this->combiNotification['users'][$user['user_id']] = $user; $this->combiNotification['count'][$user['user_id']][$status] += 1; - } - return; - } - - $this->combiNotification['notifications'][$method][$status][$this->server_id] = - psm_parse_msg($this->status_new, $method.'_message', $this->server, true); - return; - } + } + return; + } + + $this->combiNotification['notifications'][$method][$status][$this->server_id] = + psm_parse_msg($this->status_new, $method . '_message', $this->server, true); + return; + } /** * This functions returns the subject for a combined notification * * @return void */ - public function notifyCombined() { - if(empty($this->combiNotification['userNotifications'])){ - return; - } - // Get the servers the user will get notified of + public function notifyCombined() + { + if (empty($this->combiNotification['userNotifications'])) { + return; + } + // Get the servers the user will get notified of $this->status_new = true; - foreach ($this->combiNotification['userNotifications'] as $user => $servers) { - $notifications = array(); - // Combine all of the messages belonging to the server the user will get notification of - foreach ($servers as $server) { - foreach ($this->combiNotification['notifications'] as $method => $status){ + foreach ($this->combiNotification['userNotifications'] as $user => $servers) { + $notifications = array(); + // Combine all of the messages belonging to the server the user will get notification of + foreach ($servers as $server) { + foreach ($this->combiNotification['notifications'] as $method => $status) { foreach ($status as $the_status => $value) { - if(!key_exists($method, $notifications)){ + if (!key_exists($method, $notifications)) { $notifications[$method] = array('on' => '', 'off' => ''); - } - if(key_exists($server, $status[$the_status])){ - $notifications[$method][$the_status] .= $status[$the_status][$server]; - } - // Set $this->status_new to false if a server is down. + } + if (key_exists($server, $status[$the_status])) { + $notifications[$method][$the_status] .= $status[$the_status][$server]; + } + // Set $this->status_new to false if a server is down. // This is used by Pushover to determine the priority. - if(!empty($notifications[$method]['off'])){ + if (!empty($notifications[$method]['off'])) { $this->status_new = false; } } - } - } - // Send combined notification per user - foreach ($notifications as $method => $notification){ + } + } + // Send combined notification per user + foreach ($notifications as $method => $notification) { $finalNotification['message'] = $this->createCombiMessage($method, $notification); $subject = $this->createCombiSubject($method, $user); - if(!is_null($subject)){ + if (!is_null($subject)) { $finalNotification['subject'] = $subject; } - $this->{'notifyBy' . ucwords($method)} - (array($this->combiNotification['users'][$user]), $finalNotification); + $this->{'notifyBy' . ucwords($method)}( + array($this->combiNotification['users'][$user]), + $finalNotification + ); } - } - unset($notifications); - return; - } + } + unset($notifications); + return; + } /** * This functions returns the message for a combined notification @@ -315,15 +334,16 @@ class StatusNotifier { * @param array $notification Notification * @return string */ - protected function createCombiMessage($method, $notification){ - if(empty($notification['off'])){ - $notification['off'] = "
    • ".psm_get_lang('system', 'none')."
    "; + protected function createCombiMessage($method, $notification) + { + if (empty($notification['off'])) { + $notification['off'] = "
    • " . psm_get_lang('system', 'none') . "
    "; } - if(empty($notification['on'])){ - $notification['on'] = "
    • ".psm_get_lang('system', 'none')."
    "; + if (empty($notification['on'])) { + $notification['on'] = "
    • " . psm_get_lang('system', 'none') . "
    "; } - $vars = array('DOWN_SERVERS' => $notification['off'], 'UP_SERVERS' => $notification['on']); - return psm_parse_msg(null, $method.'_message', $vars, true); + $vars = array('DOWN_SERVERS' => $notification['off'], 'UP_SERVERS' => $notification['on']); + return psm_parse_msg(null, $method . '_message', $vars, true); } /** @@ -333,10 +353,14 @@ class StatusNotifier { * @param integer $user_id User id * @return string|null */ - protected function createCombiSubject($method, $user_id){ - $vars = array('DOWN' => $this->combiNotification['count'][$user_id]['off'], 'UP' => $this->combiNotification['count'][$user_id]['on']); - $translation = isset($GLOBALS['sm_lang_default']['notifications']['combi_'.$method.'_subject']) ? - psm_parse_msg(null, $method.'_subject', $vars, true) : + protected function createCombiSubject($method, $user_id) + { + $vars = array( + 'DOWN' => $this->combiNotification['count'][$user_id]['off'], + 'UP' => $this->combiNotification['count'][$user_id]['on'] + ); + $translation = isset($GLOBALS['sm_lang_default']['notifications']['combi_' . $method . '_subject']) ? + psm_parse_msg(null, $method . '_subject', $vars, true) : null; return $translation; } @@ -349,143 +373,150 @@ class StatusNotifier { * @return void * @throws \PHPMailer\PHPMailer\Exception */ - protected function notifyByEmail($users, $combi = array()) { - // build mail object with some default values - $mail = psm_build_mail(); - $mail->Subject = key_exists('subject', $combi) ? - $combi['subject'] : - psm_parse_msg($this->status_new, 'email_subject', $this->server); - $mail->Priority = 1; + protected function notifyByEmail($users, $combi = array()) + { + // build mail object with some default values + $mail = psm_build_mail(); + $mail->Subject = key_exists('subject', $combi) ? + $combi['subject'] : + psm_parse_msg($this->status_new, 'email_subject', $this->server); + $mail->Priority = 1; - $body = key_exists('message', $combi) ? - $combi['message'] : - psm_parse_msg($this->status_new, 'email_body', $this->server); - $mail->Body = $body; - $mail->AltBody = str_replace('
    ', "\n", $body); + $body = key_exists('message', $combi) ? + $combi['message'] : + psm_parse_msg($this->status_new, 'email_body', $this->server); + $mail->Body = $body; + $mail->AltBody = str_replace('
    ', "\n", $body); - if (psm_get_conf('log_email')) { - $log_id = psm_add_log($this->server_id, 'email', $body); - } + if (psm_get_conf('log_email')) { + $log_id = psm_add_log($this->server_id, 'email', $body); + } - // go through empl - foreach ($users as $user) { - if (!empty($log_id)) { - psm_add_log_user($log_id, $user['user_id']); - } + // go through empl + foreach ($users as $user) { + if (!empty($log_id)) { + psm_add_log_user($log_id, $user['user_id']); + } - // we sent a separate email to every single user. - $mail->AddAddress($user['email'], $user['name']); - $mail->Send(); - $mail->ClearAddresses(); - } - return; - } + // we sent a separate email to every single user. + $mail->AddAddress($user['email'], $user['name']); + $mail->Send(); + $mail->ClearAddresses(); + } + return; + } - /** - * This functions performs the pushover notifications - * - * @param \PDOStatement $users + /** + * This functions performs the pushover notifications + * + * @param \PDOStatement $users * @param array $combi contains message and subject (optional) - * @return void - */ - protected function notifyByPushover($users, $combi = array()) { - // Remove users that have no pushover_key - foreach ($users as $k => $user) { - if (trim($user['pushover_key']) == '') { - unset($users[$k]); - } - } + * @return void + */ + protected function notifyByPushover($users, $combi = array()) + { + // Remove users that have no pushover_key + foreach ($users as $k => $user) { + if (trim($user['pushover_key']) == '') { + unset($users[$k]); + } + } - // Validation - if (empty($users)) { - return; - } + // Validation + if (empty($users)) { + return; + } - // Pushover - $message = key_exists('message', $combi) ? - $combi['message'] : - psm_parse_msg($this->status_new, 'pushover_message', $this->server); + // Pushover + $message = key_exists('message', $combi) ? + $combi['message'] : + psm_parse_msg($this->status_new, 'pushover_message', $this->server); - $pushover = psm_build_pushover(); - if ($this->status_new === true) { - $pushover->setPriority(0); - } else { - $pushover->setPriority(2); - $pushover->setRetry(300); //Used with Priority = 2; Pushover will resend the notification every 60 seconds until the user accepts. - $pushover->setExpire(3600); //Used with Priority = 2; Pushover will resend the notification every 60 seconds for 3600 seconds. After that point, it stops sending notifications. - } - $title = key_exists('subject', $combi) ? - $combi['subject'] : - psm_parse_msg($this->status_new, 'pushover_title', $this->server); - $pushover->setHtml(1); - $pushover->setTitle($title); - $pushover->setMessage(str_replace('
    ', "\n", $message)); - $pushover->setUrl(psm_build_url()); - $pushover->setUrlTitle(psm_get_lang('system', 'title')); + $pushover = psm_build_pushover(); + if ($this->status_new === true) { + $pushover->setPriority(0); + } else { + $pushover->setPriority(2); + //Used with Priority = 2; Pushover will resend the notification every 60 seconds until the user accepts. + $pushover->setRetry(300); + // Used with Priority = 2; Pushover will resend the notification every 60 seconds for 3600 seconds. + // After that point, it stops sending notifications. + $pushover->setExpire(3600); + } + $title = key_exists('subject', $combi) ? + $combi['subject'] : + psm_parse_msg($this->status_new, 'pushover_title', $this->server); + $pushover->setHtml(1); + $pushover->setTitle($title); + $pushover->setMessage(str_replace('
    ', "\n", $message)); + $pushover->setUrl(psm_build_url()); + $pushover->setUrlTitle(psm_get_lang('system', 'title')); - // Log - if (psm_get_conf('log_pushover')) { - $log_id = psm_add_log($this->server_id, 'pushover', $message); - } + // Log + if (psm_get_conf('log_pushover')) { + $log_id = psm_add_log($this->server_id, 'pushover', $message); + } - foreach ($users as $user) { - // Log - if (!empty($log_id)) { - psm_add_log_user($log_id, $user['user_id']); - } + foreach ($users as $user) { + // Log + if (!empty($log_id)) { + psm_add_log_user($log_id, $user['user_id']); + } - // Set recipient + send - $pushover->setUser($user['pushover_key']); - if ($user['pushover_device'] != '') { - $pushover->setDevice($user['pushover_device']); - } - $pushover->send(); - } - } + // Set recipient + send + $pushover->setUser($user['pushover_key']); + if ($user['pushover_device'] != '') { + $pushover->setDevice($user['pushover_device']); + } + $pushover->send(); + } + } - /** - * This functions performs the text message notifications - * - * @param \PDOStatement $users - * @return boolean - */ - protected function notifyByTxtMsg($users) { - $sms = psm_build_sms(); - if (!$sms) { - return false; - } + /** + * This functions performs the text message notifications + * + * @param \PDOStatement $users + * @return boolean + */ + protected function notifyByTxtMsg($users) + { + $sms = psm_build_sms(); + if (!$sms) { + return false; + } - $message = psm_parse_msg($this->status_new, 'sms', $this->server); + $message = psm_parse_msg($this->status_new, 'sms', $this->server); - // Log - if (psm_get_conf('log_sms')) { - $log_id = psm_add_log($this->server_id, 'sms', $message); - } + // Log + if (psm_get_conf('log_sms')) { + $log_id = psm_add_log($this->server_id, 'sms', $message); + } - // add all users to the recipients list - foreach ($users as $user) { - // Log - if (!empty($log_id)) { - psm_add_log_user($log_id, $user['user_id']); - } + // add all users to the recipients list + foreach ($users as $user) { + // Log + if (!empty($log_id)) { + psm_add_log_user($log_id, $user['user_id']); + } - $sms->addRecipients($user['mobile']); - } + $sms->addRecipients($user['mobile']); + } - // Send sms - $result = $sms->sendSMS($message); + // Send sms + $result = $sms->sendSMS($message); - return $result; - } + return $result; + } - /** - * This functions performs the telegram notifications - * - * @param \PDOStatement $users + /** + * This functions performs the telegram notifications + * + * @param \PDOStatement $users * @param array $combi contains message and subject (optional) - * @return void - */ - protected function notifyByTelegram($users, $combi = array()) { + * @return void + */ + protected function notifyByTelegram($users, $combi = array()) + { // Remove users that have no telegram_id foreach ($users as $k => $user) { if (trim($user['telegram_id']) == '') { @@ -500,16 +531,16 @@ class StatusNotifier { // Telegram $message = key_exists('message', $combi) ? - $combi['message'] : - psm_parse_msg($this->status_new, 'telegram_message', $this->server); + $combi['message'] : + psm_parse_msg($this->status_new, 'telegram_message', $this->server); $telegram = psm_build_telegram(); - $telegram->setMessage($message); - + $telegram->setMessage($message); + // Log if (psm_get_conf('log_telegram')) { $log_id = psm_add_log($this->server_id, 'telegram', $message); - } - + } + foreach ($users as $user) { // Log if (!empty($log_id)) { @@ -520,21 +551,23 @@ class StatusNotifier { } } - /** - * Get all users for the provided server id - * @param int $server_id - * @return \PDOStatement array - */ - public function getUsers($server_id) { - // find all the users with this server listed - $users = $this->db->query(" - SELECT `u`.`user_id`, `u`.`name`,`u`.`email`, `u`.`mobile`, `u`.`pushover_key`, `u`.`pushover_device`, `u`.`telegram_id` - FROM `".PSM_DB_PREFIX."users` AS `u` - JOIN `".PSM_DB_PREFIX."users_servers` AS `us` ON ( + /** + * Get all users for the provided server id + * @param int $server_id + * @return \PDOStatement array + */ + public function getUsers($server_id) + { + // find all the users with this server listed + $users = $this->db->query(" + SELECT `u`.`user_id`, `u`.`name`,`u`.`email`, `u`.`mobile`, `u`.`pushover_key`, + `u`.`pushover_device`, `u`.`telegram_id` + FROM `" . PSM_DB_PREFIX . "users` AS `u` + JOIN `" . PSM_DB_PREFIX . "users_servers` AS `us` ON ( `us`.`user_id`=`u`.`user_id` AND `us`.`server_id` = {$server_id} ) "); - return $users; - } + return $users; + } } diff --git a/src/psm/Util/Server/Updater/StatusUpdater.php b/src/psm/Util/Server/Updater/StatusUpdater.php index 2b1f26b8..24bdf209 100644 --- a/src/psm/Util/Server/Updater/StatusUpdater.php +++ b/src/psm/Util/Server/Updater/StatusUpdater.php @@ -1,4 +1,5 @@ db = $db; - } + public function __construct(Database $db) + { + $this->db = $db; + } - /** - * The function its all about. This one checks whether the given ip and port are up and running! - * If the server check fails it will try one more time, depending on the $max_runs. - * - * Please note: if the server is down but has not met the warning threshold, this will return true - * to avoid any "we are down" events. - * - * @todo Get last_output when there is a HTTP 50x error. - * - * @param int $server_id - * @param int $max_runs how many times should the script recheck the server if unavailable. default is 2 - * @return boolean TRUE if server is up, FALSE otherwise - */ - public function update($server_id, $max_runs = 2) { - $this->server_id = $server_id; - $this->error = ''; - $this->header = ''; - $this->rtime = ''; + /** + * The function its all about. This one checks whether the given ip and port are up and running! + * If the server check fails it will try one more time, depending on the $max_runs. + * + * Please note: if the server is down but has not met the warning threshold, this will return true + * to avoid any "we are down" events. + * + * @todo Get last_output when there is a HTTP 50x error. + * + * @param int $server_id + * @param int $max_runs how many times should the script recheck the server if unavailable. default is 2 + * @return boolean TRUE if server is up, FALSE otherwise + */ + public function update($server_id, $max_runs = 2) + { + $this->server_id = $server_id; + $this->error = ''; + $this->header = ''; + $this->rtime = ''; - // get server info from db - $this->server = $this->db->selectRow(PSM_DB_PREFIX.'servers', array( - 'server_id' => $server_id, - ), array( - 'server_id', 'ip', 'port', 'request_method', 'label', 'type', 'pattern', 'pattern_online', 'post_field', - 'allow_http_status', 'redirect_check', 'header_name', 'header_value', 'status', 'active', 'warning_threshold', - 'warning_threshold_counter', 'timeout', 'website_username', 'website_password', 'last_offline' - )); - if (empty($this->server)) { - return false; - } + // get server info from db + $this->server = $this->db->selectRow(PSM_DB_PREFIX . 'servers', array( + 'server_id' => $server_id, + ), array( + 'server_id', 'ip', 'port', 'request_method', 'label', + 'type', 'pattern', 'pattern_online', 'post_field', + 'allow_http_status', 'redirect_check', 'header_name', + 'header_value', 'status', 'active', 'warning_threshold', + 'warning_threshold_counter', 'timeout', 'website_username', + 'website_password', 'last_offline' + )); + if (empty($this->server)) { + return false; + } - switch ($this->server['type']) { - case 'ping': - $this->status_new = $this->updatePing($max_runs); - break; - case 'service': - $this->status_new = $this->updateService($max_runs); - break; - case 'website': - $this->status_new = $this->updateWebsite($max_runs); - break; - } + switch ($this->server['type']) { + case 'ping': + $this->status_new = $this->updatePing($max_runs); + break; + case 'service': + $this->status_new = $this->updateService($max_runs); + break; + case 'website': + $this->status_new = $this->updateWebsite($max_runs); + break; + } - // update server status - $save = array( - 'last_check' => date('Y-m-d H:i:s'), - 'error' => $this->error, - 'rtime' => $this->rtime - ); - if(!empty($this->error)){ - $save['last_error'] = $this->error; - } + // update server status + $save = array( + 'last_check' => date('Y-m-d H:i:s'), + 'error' => $this->error, + 'rtime' => $this->rtime + ); + if (!empty($this->error)) { + $save['last_error'] = $this->error; + } - // log the uptime before checking the warning threshold, - // so that the warnings can still be reviewed in the server history. - psm_log_uptime($this->server_id, (int) $this->status_new, $this->rtime); + // log the uptime before checking the warning threshold, + // so that the warnings can still be reviewed in the server history. + psm_log_uptime($this->server_id, (int) $this->status_new, $this->rtime); - if ($this->status_new == true) { - // if the server is on, add the last_online value and reset the error threshold counter - $save['status'] = 'on'; - $save['last_online'] = date('Y-m-d H:i:s'); - $save['last_output'] = substr($this->header,0,5000); - $save['warning_threshold_counter'] = 0; - if ($this->server['status'] == 'off') { - $online_date = new \DateTime($save['last_online']); - $offline_date = new \DateTime($this->server['last_offline']); - $difference = $online_date->diff($offline_date); - $save['last_offline_duration'] = trim(psm_format_interval($difference)); - } - } else { - // server is offline, increase the error counter and set last offline - $save['warning_threshold_counter'] = $this->server['warning_threshold_counter'] + 1; - $save['last_offline'] = date('Y-m-d H:i:s'); - $save['last_error_output'] = empty($this->header) ? "Could not get headers. probably HTTP 50x error." : $this->header; + if ($this->status_new == true) { + // if the server is on, add the last_online value and reset the error threshold counter + $save['status'] = 'on'; + $save['last_online'] = date('Y-m-d H:i:s'); + $save['last_output'] = substr($this->header, 0, 5000); + $save['warning_threshold_counter'] = 0; + if ($this->server['status'] == 'off') { + $online_date = new \DateTime($save['last_online']); + $offline_date = new \DateTime($this->server['last_offline']); + $difference = $online_date->diff($offline_date); + $save['last_offline_duration'] = trim(psm_format_interval($difference)); + } + } else { + // server is offline, increase the error counter and set last offline + $save['warning_threshold_counter'] = $this->server['warning_threshold_counter'] + 1; + $save['last_offline'] = date('Y-m-d H:i:s'); + $save['last_error_output'] = empty($this->header) ? + "Could not get headers. probably HTTP 50x error." : $this->header; - if ($save['warning_threshold_counter'] < $this->server['warning_threshold']) { - // the server is offline but the error threshold has not been met yet. - // so we are going to leave the status "on" for now while we are in a sort of warning state.. - $save['status'] = 'on'; - $this->status_new = true; - } else { - $save['status'] = 'off'; - if ($this->server['status'] == 'on') { - $save['last_offline'] = $save['last_check']; - } - } - } - $this->db->save(PSM_DB_PREFIX.'servers', $save, array('server_id' => $this->server_id)); + if ($save['warning_threshold_counter'] < $this->server['warning_threshold']) { + // the server is offline but the error threshold has not been met yet. + // so we are going to leave the status "on" for now while we are in a sort of warning state.. + $save['status'] = 'on'; + $this->status_new = true; + } else { + $save['status'] = 'off'; + if ($this->server['status'] == 'on') { + $save['last_offline'] = $save['last_check']; + } + } + } + $this->db->save(PSM_DB_PREFIX . 'servers', $save, array('server_id' => $this->server_id)); - return $this->status_new; + return $this->status_new; + } - } + /** + * Check the current servers ping status - Code from http://stackoverflow.com/a/20467492 + * @param int $max_runs + * @param int $run + * @return boolean + */ + protected function updatePing($max_runs, $run = 1) + { + // save response time + $starttime = microtime(true); + // set ping payload + $package = "\x08\x00\x7d\x4b\x00\x00\x00\x00PingHost"; - /** - * Check the current servers ping status - Code from http://stackoverflow.com/a/20467492 - * @param int $max_runs - * @param int $run - * @return boolean - */ - protected function updatePing($max_runs, $run = 1) { - // save response time - $starttime = microtime(true); - // set ping payload - $package = "\x08\x00\x7d\x4b\x00\x00\x00\x00PingHost"; + $socket = socket_create(AF_INET, SOCK_RAW, 1); + socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 10, 'usec' => 0)); + socket_connect($socket, $this->server['ip'], null); - $socket = socket_create(AF_INET, SOCK_RAW, 1); - socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 10, 'usec' => 0)); - socket_connect($socket, $this->server['ip'], null); + socket_send($socket, $package, strLen($package), 0); + if (socket_read($socket, 255)) { + $status = true; + } else { + $status = false; - socket_send($socket, $package, strLen($package), 0); - if (socket_read($socket, 255)) { - $status = true; - } else { - $status = false; + // set error message + $errorcode = socket_last_error(); + $this->error = "Couldn't create socket [" . $errorcode . "]: " . socket_strerror($errorcode); + } + $this->rtime = microtime(true) - $starttime; + socket_close($socket); - // set error message - $errorcode = socket_last_error(); - $this->error = "Couldn't create socket [".$errorcode."]: ".socket_strerror($errorcode); - } - $this->rtime = microtime(true) - $starttime; - socket_close($socket); + // check if server is available and rerun if asked. + if (!$status && $run < $max_runs) { + return $this->updatePing($max_runs, $run + 1); + } - // check if server is available and rerun if asked. - if (!$status && $run < $max_runs) { - return $this->updatePing($max_runs, $run + 1); - } + return $status; + } - return $status; - } + /** + * Check the current server as a service + * @param int $max_runs + * @param int $run + * @return boolean + */ + protected function updateService($max_runs, $run = 1) + { + $timeout = ($this->server['timeout'] === null || $this->server['timeout'] > 0) ? + PSM_CURL_TIMEOUT : intval($this->server['timeout']); + $errno = 0; + // save response time + $starttime = microtime(true); - /** - * Check the current server as a service - * @param int $max_runs - * @param int $run - * @return boolean - */ - protected function updateService($max_runs, $run = 1) { - $timeout = ($this->server['timeout'] === null || $this->server['timeout'] > 0) ? PSM_CURL_TIMEOUT : intval($this->server['timeout']); - $errno = 0; - // save response time - $starttime = microtime(true); + $fp = @fsockopen($this->server['ip'], $this->server['port'], $errno, $this->error, $timeout); - $fp = @fsockopen($this->server['ip'], $this->server['port'], $errno, $this->error, $timeout); + $status = ($fp === false) ? false : true; + $this->rtime = (microtime(true) - $starttime); - $status = ($fp === false) ? false : true; - $this->rtime = (microtime(true) - $starttime); + if (is_resource($fp)) { + fclose($fp); + } - if (is_resource($fp)) { - fclose($fp); - } + // check if server is available and rerun if asked. + if (!$status && $run < $max_runs) { + return $this->updateService($max_runs, $run + 1); + } - // check if server is available and rerun if asked. - if (!$status && $run < $max_runs) { - return $this->updateService($max_runs, $run + 1); - } + return $status; + } - return $status; - } + /** + * Check the current server as a website + * @param int $max_runs + * @param int $run + * @return boolean + */ + protected function updateWebsite($max_runs, $run = 1) + { + $starttime = microtime(true); - /** - * Check the current server as a website - * @param int $max_runs - * @param int $run - * @return boolean - */ - protected function updateWebsite($max_runs, $run = 1) { - $starttime = microtime(true); + // We're only interested in the header, because that should tell us plenty! + // unless we have a pattern to search for! + $curl_result = psm_curl_get( + $this->server['ip'], + true, + ($this->server['pattern'] == '' ? false : true), + $this->server['timeout'], + true, + $this->server['website_username'], + psm_password_decrypt($this->server['server_id'] . + psm_get_conf('password_encrypt_key'), $this->server['website_password']), + $this->server['request_method'], + $this->server['post_field'] + ); + $this->header = $curl_result; - // We're only interested in the header, because that should tell us plenty! - // unless we have a pattern to search for! - $curl_result = psm_curl_get( - $this->server['ip'], - true, - ($this->server['pattern'] == '' ? false : true), - $this->server['timeout'], - true, - $this->server['website_username'], - psm_password_decrypt($this->server['server_id'].psm_get_conf('password_encrypt_key'), $this->server['website_password']), - $this->server['request_method'], - $this->server['post_field'] - ); - $this->header = $curl_result; + $this->rtime = (microtime(true) - $starttime); - $this->rtime = (microtime(true) - $starttime); + // the first line would be the status code.. + $status_code = strtok($curl_result, "\r\n"); + // keep it general + // $code[2][0] = status code + // $code[3][0] = name of status code + $code_matches = array(); + preg_match_all("/[A-Z]{2,5}\/\d(\.\d)?\s(\d{3})\s?(.*)/", $status_code, $code_matches); - // the first line would be the status code.. - $status_code = strtok($curl_result, "\r\n"); - // keep it general - // $code[2][0] = status code - // $code[3][0] = name of status code - $code_matches = array(); - preg_match_all("/[A-Z]{2,5}\/\d(\.\d)?\s(\d{3})\s?(.*)/", $status_code, $code_matches); + if (empty($code_matches[0])) { + // somehow we dont have a proper response. + $this->error = 'TIMEOUT ERROR: no response from server'; + $result = false; + } else { + $code = $code_matches[2][0]; + $msg = $code_matches[3][0]; - if(empty($code_matches[0])) { - // somehow we dont have a proper response. - $this->error = 'TIMEOUT ERROR: no response from server'; - $result = false; - } else { - $code = $code_matches[2][0]; - $msg = $code_matches[3][0]; + $allow_http_status = explode("|", $this->server['allow_http_status']); + // All status codes starting with a 4 or higher mean trouble! + if (substr($code, 0, 1) >= '4' && !in_array($code, $allow_http_status)) { + $this->error = "HTTP STATUS ERROR: " . $code . ' ' . $msg; + $result = false; + } else { + $result = true; - $allow_http_status = explode("|", $this->server['allow_http_status']); - // All status codes starting with a 4 or higher mean trouble! - if (substr($code, 0, 1) >= '4' && !in_array($code ,$allow_http_status)) { - $this->error = "HTTP STATUS ERROR: ".$code.' '.$msg; - $result = false; - } else { - $result = true; + // Okay, the HTTP status is good : 2xx or 3xx. Now we have to test the pattern if it's set up + if ($this->server['pattern'] != '') { + // Check to see if the body should not contain specified pattern + // Check to see if the pattern was [not] found. + if ( + ($this->server['pattern_online'] == 'yes') == + !preg_match( + "/{$this->server['pattern']}/i", + $curl_result + ) + ) { + $this->error = "TEXT ERROR : Pattern '{$this->server['pattern']}' " . + ($this->server['pattern_online'] == 'yes' ? 'not' : 'was') . + ' found.'; + $result = false; + } + } - // Okay, the HTTP status is good : 2xx or 3xx. Now we have to test the pattern if it's set up - if ($this->server['pattern'] != '') { - // Check to see if the body should not contain specified pattern - // Check to see if the pattern was [not] found. - if (($this->server['pattern_online'] == 'yes') == !preg_match("/{$this->server['pattern']}/i", $curl_result)) { - $this->error = "TEXT ERROR : Pattern '{$this->server['pattern']}' ". - ($this->server['pattern_online'] == 'yes' ? 'not' : 'was'). - ' found.'; - $result = false; - } - } - - // Check if the website redirects to another domain - if ($this->server['redirect_check'] == 'bad'){ - $location_matches = array(); - preg_match('/([Ll]ocation: )(https*:\/\/)(www.)?([a-zA-Z.:0-9]*)([\/][[:alnum:][:punct:]]*)/', $curl_result, $location_matches); - if(!empty($location_matches)) { + // Check if the website redirects to another domain + if ($this->server['redirect_check'] == 'bad') { + $location_matches = array(); + preg_match( + '/([Ll]ocation: )(https*:\/\/)(www.)?([a-zA-Z.:0-9]*)([\/][[:alnum:][:punct:]]*)/', + $curl_result, + $location_matches + ); + if (!empty($location_matches)) { $ip_matches = array(); - preg_match('/(https*:\/\/)(www.)?([a-zA-Z.:0-9]*)([\/][[:alnum:][:punct:]]*)?/', $this->server['ip'], $ip_matches); + preg_match( + '/(https*:\/\/)(www.)?([a-zA-Z.:0-9]*)([\/][[:alnum:][:punct:]]*)?/', + $this->server['ip'], + $ip_matches + ); if (strtolower($location_matches[4]) !== strtolower($ip_matches[3])) { $this->error = "The IP/URL redirects to another domain."; $result = false; } } - } + } - // Should we check a header ? - if ($this->server['header_name'] != '' && $this->server['header_value'] != '') { - $header_flag = false; - $header_text = substr($curl_result, 0, strpos($curl_result, "\r\n\r\n")); // Only get the header text if the result also includes the body - foreach (explode("\r\n", $header_text) as $i => $line) { - if ($i === 0 || strpos($line, ':') == false) { - continue; // We skip the status code & other non-header lines. Needed for proxy or redirects - } else { - list ($key, $value) = explode(': ', $line); - if (strcasecmp($key, $this->server['header_name']) == 0) { // Header found (case-insensitive) - if (!preg_match("/{$this->server['header_value']}/i", $value)) { // The value doesn't match what we needed - $result = false; - } else { - $header_flag = true; - break; // No need to go further - } - } - } - } + // Should we check a header ? + if ($this->server['header_name'] != '' && $this->server['header_value'] != '') { + $header_flag = false; + // Only get the header text if the result also includes the body + $header_text = substr($curl_result, 0, strpos($curl_result, "\r\n\r\n")); + foreach (explode("\r\n", $header_text) as $i => $line) { + if ($i === 0 || strpos($line, ':') == false) { + continue; // We skip the status code & other non-header lines. Needed for proxy or redirects + } else { + list ($key, $value) = explode(': ', $line); + // Header found (case-insensitive) + if (strcasecmp($key, $this->server['header_name']) == 0) { + // The value doesn't match what we needed + if (!preg_match("/{$this->server['header_value']}/i", $value)) { + $result = false; + } else { + $header_flag = true; + break; // No need to go further + } + } + } + } - if (!$header_flag) { - // Header was not present - $result = false; - } - } - } - } + if (!$header_flag) { + // Header was not present + $result = false; + } + } + } + } - // check if server is available and rerun if asked. - if (!$result && $run < $max_runs) { - return $this->updateWebsite($max_runs, $run + 1); - } + // check if server is available and rerun if asked. + if (!$result && $run < $max_runs) { + return $this->updateWebsite($max_runs, $run + 1); + } - return $result; - } + return $result; + } - /** - * Get the error returned by the update function - * - * @return string - */ - public function getError() { - return $this->error; - } + /** + * Get the error returned by the update function + * + * @return string + */ + public function getError() + { + return $this->error; + } - /** - * Get the response time of the server - * - * @return string - */ - public function getRtime() { - return $this->rtime; - } + /** + * Get the response time of the server + * + * @return string + */ + public function getRtime() + { + return $this->rtime; + } } diff --git a/src/psm/Util/User/UserValidator.php b/src/psm/Util/User/UserValidator.php index 67c12ac0..65f322e0 100644 --- a/src/psm/Util/User/UserValidator.php +++ b/src/psm/Util/User/UserValidator.php @@ -1,4 +1,5 @@ user = $user; - } + public function __construct(\psm\Service\User $user) + { + $this->user = $user; + } - /** - * Check if the user id exists - * @param int $user_id - * @return boolean - * @throws \InvalidArgumentException - */ - public function userId($user_id) { - $user = $this->user->getUser($user_id); - if (empty($user)) { - throw new \InvalidArgumentException('user_no_match'); - } - return true; - } + /** + * Check if the user id exists + * @param int $user_id + * @return boolean + * @throws \InvalidArgumentException + */ + public function userId($user_id) + { + $user = $this->user->getUser($user_id); + if (empty($user)) { + throw new \InvalidArgumentException('user_no_match'); + } + return true; + } - /** - * Check username on: - * - * - Length (2-64 chars) - * - Contents (alphabetic chars and digits only) - * - Unique - * @param string $username - * @param int $user_id to check whether the username is unique - * @return boolean - * @throws \InvalidArgumentException - */ - public function username($username, $user_id = 0) { - if (strlen($username) > 64 || strlen($username) < 2) { - throw new \InvalidArgumentException('user_name_bad_length'); - } - if (!preg_match('/^[a-zA-Z\d_\.]{2,64}$/i', $username)) { - throw new \InvalidArgumentException('user_name_invalid'); - } - $user_exists = $this->user->getUserByUsername($username); + /** + * Check username on: + * + * - Length (2-64 chars) + * - Contents (alphabetic chars and digits only) + * - Unique + * @param string $username + * @param int $user_id to check whether the username is unique + * @return boolean + * @throws \InvalidArgumentException + */ + public function username($username, $user_id = 0) + { + if (strlen($username) > 64 || strlen($username) < 2) { + throw new \InvalidArgumentException('user_name_bad_length'); + } + if (!preg_match('/^[a-zA-Z\d_\.]{2,64}$/i', $username)) { + throw new \InvalidArgumentException('user_name_invalid'); + } + $user_exists = $this->user->getUserByUsername($username); - if (!empty($user_exists) && ($user_id == 0 || $user_id != $user_exists->user_id)) { - throw new \InvalidArgumentException('user_name_exists'); - } - return true; - } + if (!empty($user_exists) && ($user_id == 0 || $user_id != $user_exists->user_id)) { + throw new \InvalidArgumentException('user_name_exists'); + } + return true; + } - /** - * Check user password - * @param string $password - * @param string $password_repeat - * @return boolean - * @throws \InvalidArgumentException - */ - public function password($password, $password_repeat) { - if (empty($password) || empty($password_repeat)) { - throw new \InvalidArgumentException('user_password_invalid'); - } - if ($password !== $password_repeat) { - throw new \InvalidArgumentException('user_password_no_match'); - } - return true; - } + /** + * Check user password + * @param string $password + * @param string $password_repeat + * @return boolean + * @throws \InvalidArgumentException + */ + public function password($password, $password_repeat) + { + if (empty($password) || empty($password_repeat)) { + throw new \InvalidArgumentException('user_password_invalid'); + } + if ($password !== $password_repeat) { + throw new \InvalidArgumentException('user_password_no_match'); + } + return true; + } - /** - * Install only; Check username on: - * - * - Length (2-64 chars) - * - Contents (alphabetic chars and digits only) - * @param string $username - * @return boolean - * @throws \InvalidArgumentException - */ - public function username_new($username) { - if (strlen($username) > 64 || strlen($username) < 2) { - throw new \InvalidArgumentException('user_name_bad_length'); - } - if (!preg_match('/^[a-zA-Z\d_\.]{2,64}$/i', $username)) { - throw new \InvalidArgumentException('user_name_invalid'); - } - return true; - } + /** + * Install only; Check username on: + * + * - Length (2-64 chars) + * - Contents (alphabetic chars and digits only) + * @param string $username + * @return boolean + * @throws \InvalidArgumentException + */ + public function usernameNew($username) + { + if (strlen($username) > 64 || strlen($username) < 2) { + throw new \InvalidArgumentException('user_name_bad_length'); + } + if (!preg_match('/^[a-zA-Z\d_\.]{2,64}$/i', $username)) { + throw new \InvalidArgumentException('user_name_invalid'); + } + return true; + } - /** - * Check email - * @param string $email - * @return boolean - * @throws \InvalidArgumentException - */ - public function email($email) { - if (strlen($email) > 255 || strlen($email) < 5) { - throw new \InvalidArgumentException('user_email_bad_length'); - } - if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { - throw new \InvalidArgumentException('user_email_invalid'); - } - return true; - } + /** + * Check email + * @param string $email + * @return boolean + * @throws \InvalidArgumentException + */ + public function email($email) + { + if (strlen($email) > 255 || strlen($email) < 5) { + throw new \InvalidArgumentException('user_email_bad_length'); + } + if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { + throw new \InvalidArgumentException('user_email_invalid'); + } + return true; + } - /** - * Check user level - * @param int $level - * @return boolean - * @throws \InvalidArgumentException - */ - public function level($level) { - if (!in_array($level, $this->user_levels)) { - throw new \InvalidArgumentException('user_level_invalid'); - } - return true; - } + /** + * Check user level + * @param int $level + * @return boolean + * @throws \InvalidArgumentException + */ + public function level($level) + { + if (!in_array($level, $this->user_levels)) { + throw new \InvalidArgumentException('user_level_invalid'); + } + return true; + } - /** - * Get list of all available user levels - * @return array - */ - public function getUserLevels() { - return $this->user_levels; - } + /** + * Get list of all available user levels + * @return array + */ + public function getUserLevels() + { + return $this->user_levels; + } }