Spacing, indentation and braces

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

View File

@ -26,11 +26,11 @@
**/ **/
// include main configuration and functionality // include main configuration and functionality
require_once __DIR__ . '/../src/bootstrap.php'; require_once __DIR__.'/../src/bootstrap.php';
if(!psm_is_cli()) { if (!psm_is_cli()) {
// check if it's an allowed host // check if it's an allowed host
if(!isset($_SERVER["HTTP_X_FORWARDED_FOR"])){ if (!isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
$_SERVER["HTTP_X_FORWARDED_FOR"] = ""; $_SERVER["HTTP_X_FORWARDED_FOR"] = "";
} }
@ -39,7 +39,7 @@ if(!psm_is_cli()) {
$data = @unserialize(PSM_CRON_ALLOW); $data = @unserialize(PSM_CRON_ALLOW);
$allow = $data === false ? PSM_CRON_ALLOW : $data; $allow = $data === false ? PSM_CRON_ALLOW : $data;
if(!in_array($_SERVER['REMOTE_ADDR'], $allow) && !in_array($_SERVER["HTTP_X_FORWARDED_FOR"], $allow)) { if (!in_array($_SERVER['REMOTE_ADDR'], $allow) && !in_array($_SERVER["HTTP_X_FORWARDED_FOR"], $allow)) {
header('HTTP/1.0 403 Forbidden'); header('HTTP/1.0 403 Forbidden');
die('<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><html><head><title>403 Forbidden</title></head><body><h1>Forbidden</h1><p>IP address not allowed. See the <a href="http://docs.phpservermonitor.org/en/latest/install.html#cronjob-over-web">documentation</a> for more info.</p></body></html>'); die('<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><html><head><title>403 Forbidden</title></head><body><h1>Forbidden</h1><p>IP address not allowed. See the <a href="http://docs.phpservermonitor.org/en/latest/install.html#cronjob-over-web">documentation</a> for more info.</p></body></html>');
} }
@ -48,15 +48,15 @@ if(!psm_is_cli()) {
$cron_timeout = PSM_CRON_TIMEOUT; $cron_timeout = PSM_CRON_TIMEOUT;
// parse a couple of arguments // parse a couple of arguments
if(!empty($_SERVER['argv'])) { if (!empty($_SERVER['argv'])) {
foreach ($_SERVER['argv'] as $argv) { foreach ($_SERVER['argv'] as $argv) {
$argi = explode('=', ltrim($argv, '--')); $argi = explode('=', ltrim($argv, '--'));
if(count($argi) !== 2) { if (count($argi) !== 2) {
continue; continue;
} }
switch($argi[0]) { switch ($argi[0]) {
case 'uri': case 'uri':
if(!defined('PSM_BASE_URL')){ if (!defined('PSM_BASE_URL')) {
define('PSM_BASE_URL', $argi[1]); define('PSM_BASE_URL', $argi[1]);
} }
break; break;
@ -72,14 +72,14 @@ if(!empty($_SERVER['argv'])) {
// if you want to change PSM_CRON_TIMEOUT, have a look in src/includes/psmconfig.inc.php. // if you want to change PSM_CRON_TIMEOUT, have a look in src/includes/psmconfig.inc.php.
// or you can provide the --timeout=x argument // or you can provide the --timeout=x argument
$time = time(); $time = time();
if( if (
psm_get_conf('cron_running') == 1 psm_get_conf('cron_running') == 1
&& $cron_timeout > 0 && $cron_timeout > 0
&& ($time - psm_get_conf('cron_running_time') < $cron_timeout) && ($time - psm_get_conf('cron_running_time') < $cron_timeout)
) { ) {
die('Cron is already running. Exiting.'); die('Cron is already running. Exiting.');
} }
if(!defined('PSM_DEBUG') || !PSM_DEBUG) { if (!defined('PSM_DEBUG') || !PSM_DEBUG) {
psm_update_conf('cron_running', 1); psm_update_conf('cron_running', 1);
} }
psm_update_conf('cron_running_time', $time); psm_update_conf('cron_running_time', $time);

View File

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

View File

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

View File

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

View File

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

View File

@ -36,211 +36,211 @@
if (!defined('PASSWORD_DEFAULT')) { if (!defined('PASSWORD_DEFAULT')) {
define('PASSWORD_BCRYPT', 1); define('PASSWORD_BCRYPT', 1);
define('PASSWORD_DEFAULT', PASSWORD_BCRYPT); define('PASSWORD_DEFAULT', PASSWORD_BCRYPT);
/** /**
* Hash the password using the specified algorithm * Hash the password using the specified algorithm
* *
* @param string $password The password to hash * @param string $password The password to hash
* @param int $algo The algorithm to use (Defined by PASSWORD_* constants) * @param int $algo The algorithm to use (Defined by PASSWORD_* constants)
* @param array $options The options for the algorithm to use * @param array $options The options for the algorithm to use
* *
* @return string|false The hashed password, or false on error. * @return string|false The hashed password, or false on error.
*/ */
function password_hash($password, $algo, array $options = array()) { function password_hash($password, $algo, array $options = array()) {
if (!function_exists('crypt')) { if (!function_exists('crypt')) {
trigger_error("Crypt must be loaded for password_hash to function", E_USER_WARNING); trigger_error("Crypt must be loaded for password_hash to function", E_USER_WARNING);
return null; return null;
} }
if (!is_string($password)) { if (!is_string($password)) {
trigger_error("password_hash(): Password must be a string", E_USER_WARNING); trigger_error("password_hash(): Password must be a string", E_USER_WARNING);
return null; return null;
} }
if (!is_int($algo)) { if (!is_int($algo)) {
trigger_error("password_hash() expects parameter 2 to be long, " . gettype($algo) . " given", E_USER_WARNING); trigger_error("password_hash() expects parameter 2 to be long, ".gettype($algo)." given", E_USER_WARNING);
return null; return null;
} }
switch ($algo) { switch ($algo) {
case PASSWORD_BCRYPT: case PASSWORD_BCRYPT:
// Note that this is a C constant, but not exposed to PHP, so we don't define it here. // Note that this is a C constant, but not exposed to PHP, so we don't define it here.
$cost = 10; $cost = 10;
if (isset($options['cost'])) { if (isset($options['cost'])) {
$cost = $options['cost']; $cost = $options['cost'];
if ($cost < 4 || $cost > 31) { if ($cost < 4 || $cost > 31) {
trigger_error(sprintf("password_hash(): Invalid bcrypt cost parameter specified: %d", $cost), E_USER_WARNING); trigger_error(sprintf("password_hash(): Invalid bcrypt cost parameter specified: %d", $cost), E_USER_WARNING);
return null; return null;
} }
} }
// The length of salt to generate // The length of salt to generate
$raw_salt_len = 16; $raw_salt_len = 16;
// The length required in the final serialization // The length required in the final serialization
$required_salt_len = 22; $required_salt_len = 22;
$hash_format = sprintf("$2y$%02d$", $cost); $hash_format = sprintf("$2y$%02d$", $cost);
break; break;
default: default:
trigger_error(sprintf("password_hash(): Unknown password hashing algorithm: %s", $algo), E_USER_WARNING); trigger_error(sprintf("password_hash(): Unknown password hashing algorithm: %s", $algo), E_USER_WARNING);
return null; return null;
} }
if (isset($options['salt'])) { if (isset($options['salt'])) {
switch (gettype($options['salt'])) { switch (gettype($options['salt'])) {
case 'NULL': case 'NULL':
case 'boolean': case 'boolean':
case 'integer': case 'integer':
case 'double': case 'double':
case 'string': case 'string':
$salt = (string) $options['salt']; $salt = (string) $options['salt'];
break; break;
case 'object': case 'object':
if (method_exists($options['salt'], '__tostring')) { if (method_exists($options['salt'], '__tostring')) {
$salt = (string) $options['salt']; $salt = (string) $options['salt'];
break; break;
} }
case 'array': case 'array':
case 'resource': case 'resource':
default: default:
trigger_error('password_hash(): Non-string salt parameter supplied', E_USER_WARNING); trigger_error('password_hash(): Non-string salt parameter supplied', E_USER_WARNING);
return null; return null;
} }
if (strlen($salt) < $required_salt_len) { if (strlen($salt) < $required_salt_len) {
trigger_error(sprintf("password_hash(): Provided salt is too short: %d expecting %d", strlen($salt), $required_salt_len), E_USER_WARNING); trigger_error(sprintf("password_hash(): Provided salt is too short: %d expecting %d", strlen($salt), $required_salt_len), E_USER_WARNING);
return null; return null;
} elseif (0 == preg_match('#^[a-zA-Z0-9./]+$#D', $salt)) { } elseif (0 == preg_match('#^[a-zA-Z0-9./]+$#D', $salt)) {
$salt = str_replace('+', '.', base64_encode($salt)); $salt = str_replace('+', '.', base64_encode($salt));
} }
} else { } else {
$buffer = ''; $buffer = '';
$buffer_valid = false; $buffer_valid = false;
if (function_exists('mcrypt_create_iv') && !defined('PHALANGER')) { if (function_exists('mcrypt_create_iv') && !defined('PHALANGER')) {
$buffer = mcrypt_create_iv($raw_salt_len, MCRYPT_DEV_URANDOM); $buffer = mcrypt_create_iv($raw_salt_len, MCRYPT_DEV_URANDOM);
if ($buffer) { if ($buffer) {
$buffer_valid = true; $buffer_valid = true;
} }
} }
if (!$buffer_valid && function_exists('openssl_random_pseudo_bytes')) { if (!$buffer_valid && function_exists('openssl_random_pseudo_bytes')) {
$buffer = openssl_random_pseudo_bytes($raw_salt_len); $buffer = openssl_random_pseudo_bytes($raw_salt_len);
if ($buffer) { if ($buffer) {
$buffer_valid = true; $buffer_valid = true;
} }
} }
if (!$buffer_valid && is_readable('/dev/urandom')) { if (!$buffer_valid && is_readable('/dev/urandom')) {
$f = fopen('/dev/urandom', 'r'); $f = fopen('/dev/urandom', 'r');
$read = strlen($buffer); $read = strlen($buffer);
while ($read < $raw_salt_len) { while ($read < $raw_salt_len) {
$buffer .= fread($f, $raw_salt_len - $read); $buffer .= fread($f, $raw_salt_len - $read);
$read = strlen($buffer); $read = strlen($buffer);
} }
fclose($f); fclose($f);
if ($read >= $raw_salt_len) { if ($read >= $raw_salt_len) {
$buffer_valid = true; $buffer_valid = true;
} }
} }
if (!$buffer_valid || strlen($buffer) < $raw_salt_len) { if (!$buffer_valid || strlen($buffer) < $raw_salt_len) {
$bl = strlen($buffer); $bl = strlen($buffer);
for ($i = 0; $i < $raw_salt_len; $i++) { for ($i = 0; $i < $raw_salt_len; $i++) {
if ($i < $bl) { if ($i < $bl) {
$buffer[$i] = $buffer[$i] ^ chr(mt_rand(0, 255)); $buffer[$i] = $buffer[$i] ^ chr(mt_rand(0, 255));
} else { } else {
$buffer .= chr(mt_rand(0, 255)); $buffer .= chr(mt_rand(0, 255));
} }
} }
} }
$salt = str_replace('+', '.', base64_encode($buffer)); $salt = str_replace('+', '.', base64_encode($buffer));
} }
$salt = substr($salt, 0, $required_salt_len); $salt = substr($salt, 0, $required_salt_len);
$hash = $hash_format . $salt; $hash = $hash_format.$salt;
$ret = crypt($password, $hash); $ret = crypt($password, $hash);
if (!is_string($ret) || strlen($ret) <= 13) { if (!is_string($ret) || strlen($ret) <= 13) {
return false; return false;
} }
return $ret; return $ret;
} }
/** /**
* Get information about the password hash. Returns an array of the information * Get information about the password hash. Returns an array of the information
* that was used to generate the password hash. * that was used to generate the password hash.
* *
* array( * array(
* 'algo' => 1, * 'algo' => 1,
* 'algoName' => 'bcrypt', * 'algoName' => 'bcrypt',
* 'options' => array( * 'options' => array(
* 'cost' => 10, * 'cost' => 10,
* ), * ),
* ) * )
* *
* @param string $hash The password hash to extract info from * @param string $hash The password hash to extract info from
* *
* @return array The array of information about the hash. * @return array The array of information about the hash.
*/ */
function password_get_info($hash) { function password_get_info($hash) {
$return = array( $return = array(
'algo' => 0, 'algo' => 0,
'algoName' => 'unknown', 'algoName' => 'unknown',
'options' => array(), 'options' => array(),
); );
if (substr($hash, 0, 4) == '$2y$' && strlen($hash) == 60) { if (substr($hash, 0, 4) == '$2y$' && strlen($hash) == 60) {
$return['algo'] = PASSWORD_BCRYPT; $return['algo'] = PASSWORD_BCRYPT;
$return['algoName'] = 'bcrypt'; $return['algoName'] = 'bcrypt';
list($cost) = sscanf($hash, "$2y$%d$"); list($cost) = sscanf($hash, "$2y$%d$");
$return['options']['cost'] = $cost; $return['options']['cost'] = $cost;
} }
return $return; return $return;
} }
/** /**
* Determine if the password hash needs to be rehashed according to the options provided * 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. * If the answer is true, after validating the password using password_verify, rehash it.
* *
* @param string $hash The hash to test * @param string $hash The hash to test
* @param int $algo The algorithm used for new password hashes * @param int $algo The algorithm used for new password hashes
* @param array $options The options array passed to password_hash * @param array $options The options array passed to password_hash
* *
* @return boolean True if the password needs to be rehashed. * @return boolean True if the password needs to be rehashed.
*/ */
function password_needs_rehash($hash, $algo, array $options = array()) { function password_needs_rehash($hash, $algo, array $options = array()) {
$info = password_get_info($hash); $info = password_get_info($hash);
if ($info['algo'] != $algo) { if ($info['algo'] != $algo) {
return true; return true;
} }
switch ($algo) { switch ($algo) {
case PASSWORD_BCRYPT: case PASSWORD_BCRYPT:
$cost = isset($options['cost']) ? $options['cost'] : 10; $cost = isset($options['cost']) ? $options['cost'] : 10;
if ($cost != $info['options']['cost']) { if ($cost != $info['options']['cost']) {
return true; return true;
} }
break; break;
} }
return false; return false;
} }
/** /**
* Verify a password against a hash using a timing attack resistant approach * Verify a password against a hash using a timing attack resistant approach
* *
* @param string $password The password to verify * @param string $password The password to verify
* @param string $hash The hash to verify against * @param string $hash The hash to verify against
* *
* @return boolean If the password matches the hash * @return boolean If the password matches the hash
*/ */
function password_verify($password, $hash) { function password_verify($password, $hash) {
if (!function_exists('crypt')) { if (!function_exists('crypt')) {
trigger_error("Crypt must be loaded for password_verify to function", E_USER_WARNING); trigger_error("Crypt must be loaded for password_verify to function", E_USER_WARNING);
return false; return false;
} }
$ret = crypt($password, $hash); $ret = crypt($password, $hash);
if (!is_string($ret) || strlen($ret) != strlen($hash) || strlen($ret) <= 13) { if (!is_string($ret) || strlen($ret) != strlen($hash) || strlen($ret) <= 13) {
return false; return false;
} }
$status = 0; $status = 0;
for ($i = 0; $i < strlen($ret); $i++) { for ($i = 0; $i < strlen($ret); $i++) {
$status |= (ord($ret[$i]) ^ ord($hash[$i])); $status |= (ord($ret[$i]) ^ ord($hash[$i]));
} }
return $status === 0; return $status === 0;
} }
} }

View File

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

View File

@ -227,12 +227,12 @@ $sm_lang = array(
'pushover_api_token' => 'Pushover App API Token', 'pushover_api_token' => 'Pushover App API Token',
'pushover_api_token_description' => 'Pře použitím Pushoveru se musíte <a href="%1$s" target="_blank">registrovat</a> a získat API Token.', 'pushover_api_token_description' => 'Pře použitím Pushoveru se musíte <a href="%1$s" target="_blank">registrovat</a> a získat API Token.',
'alert_type' => 'Zvolte kdy si přejete být upozorněni.', 'alert_type' => 'Zvolte kdy si přejete být upozorněni.',
'alert_type_description' => '<b>Změna stavu:</b> '. 'alert_type_description' => '<b>Změna stavu:</b> '.
'Obdržíte upozornění při změně stavu, tedy:online -> offline nebo offline -> online.<br/>'. 'Obdržíte upozornění při změně stavu, tedy:online -> offline nebo offline -> online.<br/>'.
'<br /><b>Offline:</b> '. '<br /><b>Offline:</b> '.
'Obdržíte upozornění, kdy server přejde poprvé do offline stavu. Například, pokud je cron nastaven na 15 minut a sledovaný server bude offline mezi 01:00 a 06:00. Obdržíte upozornění pouze v 01:00. <br/>'. 'Obdržíte upozornění, kdy server přejde poprvé do offline stavu. Například, pokud je cron nastaven na 15 minut a sledovaný server bude offline mezi 01:00 a 06:00. Obdržíte upozornění pouze v 01:00. <br/>'.
'<br><b>Vždy:</b> '. '<br><b>Vždy:</b> '.
'Obdržíte upozornění při každém spuštění kontroly, tedy i pokud bude server offline několik hodin.', 'Obdržíte upozornění při každém spuštění kontroly, tedy i pokud bude server offline několik hodin.',
'alert_type_status' => 'Změna stavu', 'alert_type_status' => 'Změna stavu',
'alert_type_offline' => 'Offline', 'alert_type_offline' => 'Offline',
'alert_type_always' => 'Vždy', 'alert_type_always' => 'Vždy',

View File

@ -213,13 +213,13 @@ $sm_lang = array(
'pushover_api_token_description' => 'Før du kan benytte Pushover, skal du <a href="%1$s" target="_blank">registrere en app</a> på deres website og indtaste en App API Token her.', 'pushover_api_token_description' => 'Før du kan benytte Pushover, skal du <a href="%1$s" target="_blank">registrere en app</a> på deres website og indtaste en App API Token her.',
'alert_type' => 'Vælg hvornår du vil modtage beskeden', 'alert_type' => 'Vælg hvornår du vil modtage beskeden',
'alert_type_description' => '<b>Status ændring:</b> '. 'alert_type_description' => '<b>Status ændring:</b> '.
'Du vil modtage en notifkation når en server har en ændring i status. Fra online -> offline eller offline -> online.<br/>'. 'Du vil modtage en notifkation når en server har en ændring i status. Fra online -> offline eller offline -> online.<br/>'.
'<br /><b>Offline:</b> '. '<br /><b>Offline:</b> '.
'Du vil modtage en meddelelse, når en server går offline for første gang. Eksempelvis '. '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, '. 'hvis dit cronjob kører hvert kvarter, og din server går ned kl 01 og kommer først op kl 06, '.
' vil du kun modtage en mail kl 01.<br/>'. ' vil du kun modtage en mail kl 01.<br/>'.
'<br><b>Altid:</b> '. '<br><b>Altid:</b> '.
'Du vil modtage en besked, hver gang scriptet kører og et websted er nede, selvom site har været offline i flere timer.', '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_status' => 'Status ændret',
'alert_type_offline' => 'Offline', 'alert_type_offline' => 'Offline',
'alert_type_always' => 'Altid', 'alert_type_always' => 'Altid',

View File

@ -258,14 +258,14 @@ $sm_lang = array(
'telegram_api_token' => 'Telegram API Token', 'telegram_api_token' => 'Telegram API Token',
'telegram_api_token_description' => 'Before you can use Telegram, you need to get a API token. Visit the <a href="http://docs.phpservermonitor.org/">documentation</a> for help.', 'telegram_api_token_description' => 'Before you can use Telegram, you need to get a API token. Visit the <a href="http://docs.phpservermonitor.org/">documentation</a> for help.',
'alert_type' => 'Select when you\'d like to be notified.', 'alert_type' => 'Select when you\'d like to be notified.',
'alert_type_description' => '<b>Status change:</b> '. 'alert_type_description' => '<b>Status change:</b> '.
'You will receive a notifcation when a server has a change in status. So from online -> offline or offline -> online.<br/>'. 'You will receive a notifcation when a server has a change in status. So from online -> offline or offline -> online.<br/>'.
'<br /><b>Offline:</b> '. '<br /><b>Offline:</b> '.
'You will receive a notification when a server goes offline for the *FIRST TIME ONLY*. For example, '. 'You will receive a notification when a server goes offline for the *FIRST TIME ONLY*. For example, '.
'your cronjob is every 15 mins and your server goes down at 1 am and stays down till 6 am. '. 'your cronjob is every 15 mins and your server goes down at 1 am and stays down till 6 am. '.
'You will get 1 notification at 1 am and thats it.<br/>'. 'You will get 1 notification at 1 am and thats it.<br/>'.
'<br><b>Always:</b> '. '<br><b>Always:</b> '.
'You will receive a notification every time the script runs and a site is down, even if the site has been offline for hours.', 'You will receive a notification every time the script runs and a site is down, even if the site has been offline for hours.',
'alert_type_status' => 'Status change', 'alert_type_status' => 'Status change',
'alert_type_offline' => 'Offline', 'alert_type_offline' => 'Offline',
'alert_type_always' => 'Always', 'alert_type_always' => 'Always',

View File

@ -216,14 +216,14 @@ $sm_lang = array(
'pushover_api_token' => 'Token API de Pushover', 'pushover_api_token' => 'Token API de Pushover',
'pushover_api_token_description' => 'Antes de poder utilizar Pushover, necesita <a href="%1$s" target="_blank"> registrar </a> su aplicación en la página web e ingresar el token API.', 'pushover_api_token_description' => 'Antes de poder utilizar Pushover, necesita <a href="%1$s" target="_blank"> registrar </a> su aplicación en la página web e ingresar el token API.',
'alert_type' => '¿Cuándo desea recibir notificaciones ?', 'alert_type' => '¿Cuándo desea recibir notificaciones ?',
'alert_type_description' => '<b>... Al cambiar el estado:</b> '. 'alert_type_description' => '<b>... Al cambiar el estado:</b> '.
'p.ej. en línea -> fuera de línea o fuera de línea -> en línea.<br/>'. 'p.ej. en línea -> fuera de línea o fuera de línea -> en línea.<br/>'.
'<br /><b>Fuera de Línea:</b> '. '<br /><b>Fuera de Línea:</b> '.
'Recibirá una notificación cuando el servidor esté fuera de línea.'. 'Recibirá una notificación cuando el servidor esté fuera de línea.'.
'Se envia un sólo mensaje cuando se detecte la caída por primera vez.<br/>'. 'Se envia un sólo mensaje cuando se detecte la caída por primera vez.<br/>'.
'<br><b>Siempre:</b> '. '<br><b>Siempre:</b> '.
'Se le enviará una notificación cada vez que se ejecuta el script '. 'Se le enviará una notificación cada vez que se ejecuta el script '.
'aunqué el servicio puede haber estado fuera de línea por varias horas.', 'aunqué el servicio puede haber estado fuera de línea por varias horas.',
'alert_type_status' => 'Cambio de estado', 'alert_type_status' => 'Cambio de estado',
'alert_type_offline' => 'Fuera de Línea', 'alert_type_offline' => 'Fuera de Línea',
'alert_type_always' => 'Siempre', 'alert_type_always' => 'Siempre',

View File

@ -201,14 +201,14 @@ $sm_lang = array(
'pushover_api_token' => 'Pushover Äppi API Žetoon', 'pushover_api_token' => 'Pushover Äppi API Žetoon',
'pushover_api_token_description' => 'Enne, kui saad Pushoverida pead sa <a href="%1$s" target="_blank">regristreerima äpi</a> nende kodulehel ja sisestama API žetooni siia.', 'pushover_api_token_description' => 'Enne, kui saad Pushoverida pead sa <a href="%1$s" target="_blank">regristreerima äpi</a> nende kodulehel ja sisestama API žetooni siia.',
'alert_type' => 'Vali, millal sa sooviksid olla teavitatud.', 'alert_type' => 'Vali, millal sa sooviksid olla teavitatud.',
'alert_type_description' => '<b>Staatuse muutus:</b> '. 'alert_type_description' => '<b>Staatuse muutus:</b> '.
'Saate teavituse kui serveri staatuses toimub muudatusi. Seega kättesaadav -> võrgust väljas või võrgust väljas -> kättesaadav.<br/>'. 'Saate teavituse kui serveri staatuses toimub muudatusi. Seega kättesaadav -> võrgust väljas või võrgust väljas -> kättesaadav.<br/>'.
'<br /><b>Võrgust väljas:</b> '. '<br /><b>Võrgust väljas:</b> '.
'Saate teavituse kui server läheb võrgust välja *ESIMEST KORDA*. Näiteks, '. 'Saate teavituse kui server läheb võrgust välja *ESIMEST KORDA*. Näiteks, '.
'sinu cronjob on iga 15 minuti tagant ja sulgub kell 1 öösel kuni kella 6ni hommikul. '. 'sinu cronjob on iga 15 minuti tagant ja sulgub kell 1 öösel kuni kella 6ni hommikul. '.
'Saate 1 teavituse kell 1 öösel ja see on kõik.<br/>'. 'Saate 1 teavituse kell 1 öösel ja see on kõik.<br/>'.
'<br><b>Alati:</b> '. '<br><b>Alati:</b> '.
'Saate teavituse iga kord kui staatust uuendatakse, isegi kui leht on olnud maas juba tunde.', 'Saate teavituse iga kord kui staatust uuendatakse, isegi kui leht on olnud maas juba tunde.',
'alert_type_status' => 'Staatuse muutus', 'alert_type_status' => 'Staatuse muutus',
'alert_type_offline' => 'Võrgust väljas', 'alert_type_offline' => 'Võrgust väljas',
'alert_type_always' => 'Alati', 'alert_type_always' => 'Alati',

View File

@ -201,14 +201,14 @@ $sm_lang = array(
'pushover_api_token' => 'رمز API برنامه پوش آور', 'pushover_api_token' => 'رمز API برنامه پوش آور',
'pushover_api_token_description' => 'قبل از استفاده از پوش آور، شما باید در سایت آن ها <a href="%1$s" target="_blank">یک برنامه ثبت نام کنید</a> و رمز API برنامه پوش آور را اینجا وارد کنید.', 'pushover_api_token_description' => 'قبل از استفاده از پوش آور، شما باید در سایت آن ها <a href="%1$s" target="_blank">یک برنامه ثبت نام کنید</a> و رمز API برنامه پوش آور را اینجا وارد کنید.',
'alert_type' => 'زمان دلخواه خورد برای دریافت اطلاعیه ها را انتخاب کنید.', 'alert_type' => 'زمان دلخواه خورد برای دریافت اطلاعیه ها را انتخاب کنید.',
'alert_type_description' => '<b>تغییر وضعیت:</b> '. 'alert_type_description' => '<b>تغییر وضعیت:</b> '.
'زمانی که وضعیت سرور تغییر کرد شما یک اطلاعیته دریافت خواهید کرد. از آنلاین -> آفلاین یا آفلاین -> آنلاین.<br/>'. 'زمانی که وضعیت سرور تغییر کرد شما یک اطلاعیته دریافت خواهید کرد. از آنلاین -> آفلاین یا آفلاین -> آنلاین.<br/>'.
'<br /><b>آفلاین:</b> '. '<br /><b>آفلاین:</b> '.
'زمانی که یک سرور *فقط برای اولین بار* آفلاین شد شما یک اطلاعیه دریافت خواهید کرد. به عنوان مثال،'. 'زمانی که یک سرور *فقط برای اولین بار* آفلاین شد شما یک اطلاعیه دریافت خواهید کرد. به عنوان مثال،'.
'cronjob شما هر 15 دقیقه است و سرور شما در ساعت 1 صبح دان می شود و تا ساعت 6 صبح دان می ماند.'. 'cronjob شما هر 15 دقیقه است و سرور شما در ساعت 1 صبح دان می شود و تا ساعت 6 صبح دان می ماند.'.
'شما 1 اطلاعیه در ساعت 1 صبح دریافت خواهید کرد. همین و بس!'. 'شما 1 اطلاعیه در ساعت 1 صبح دریافت خواهید کرد. همین و بس!'.
'<br><b>همیشه:</b> '. '<br><b>همیشه:</b> '.
'هر بار که اسکریپت اجرا شود و یک سایت دان شود شما یک اطلاعیه دریافت خواهید کرد، حتی اگر سایت چند ساعت آفلاین باشد.', 'هر بار که اسکریپت اجرا شود و یک سایت دان شود شما یک اطلاعیه دریافت خواهید کرد، حتی اگر سایت چند ساعت آفلاین باشد.',
'alert_type_status' => 'تغییر وضعیت', 'alert_type_status' => 'تغییر وضعیت',
'alert_type_offline' => 'آفلاین', 'alert_type_offline' => 'آفلاین',
'alert_type_always' => 'همیشه', 'alert_type_always' => 'همیشه',

View File

@ -201,14 +201,14 @@ $sm_lang = array(
'pushover_api_token' => 'Pushover API-avain', 'pushover_api_token' => 'Pushover API-avain',
'pushover_api_token_description' => 'Ennen kuin voit käyttää Pushoveria, sinun täytyy <a href="%1$s" target="_blank">rekisteröidä sovellus</a> heidän nettisivuillaan, ja kopioida API-avain tänne.', 'pushover_api_token_description' => 'Ennen kuin voit käyttää Pushoveria, sinun täytyy <a href="%1$s" target="_blank">rekisteröidä sovellus</a> heidän nettisivuillaan, ja kopioida API-avain tänne.',
'alert_type' => 'Valitse milloin haluat ilmoituksia.', 'alert_type' => 'Valitse milloin haluat ilmoituksia.',
'alert_type_description' => '<b>Tilan muutos:</b> '. 'alert_type_description' => '<b>Tilan muutos:</b> '.
'Saat ilmoituksen kun palvelimen tila vaihtuu. Eli tilasta päällä -> sammunut tai sammunut -> päällä.<br/>'. 'Saat ilmoituksen kun palvelimen tila vaihtuu. Eli tilasta päällä -> sammunut tai sammunut -> päällä.<br/>'.
'<br /><b>Sammunut:</b> '. '<br /><b>Sammunut:</b> '.
'Saat yhden ilmoituksen kun palvelimen tila vaihtuu sammuneeksi, mutta *VAIN ENSIMMÄISEN KERRAN*. Esimerkiksi, '. 'Saat yhden ilmoituksen kun palvelimen tila vaihtuu sammuneeksi, mutta *VAIN ENSIMMÄISEN KERRAN*. Esimerkiksi, '.
'jos tarkistus tehdään joka 15 minuutti, ja palvelin sammuu klo 1 ja pysyy sammuneena klo 6 asti. '. 'jos tarkistus tehdään joka 15 minuutti, ja palvelin sammuu klo 1 ja pysyy sammuneena klo 6 asti. '.
'Saat vain yhden ilmoituksen klo 1, ei muuta.<br/>'. 'Saat vain yhden ilmoituksen klo 1, ei muuta.<br/>'.
'<br><b>Aina:</b> '. '<br><b>Aina:</b> '.
'Saat ilmoituksen joka kerta kun palvelin tarkistetaan, vaikka palvelin olisi ollut sammuneena tunteja.', 'Saat ilmoituksen joka kerta kun palvelin tarkistetaan, vaikka palvelin olisi ollut sammuneena tunteja.',
'alert_type_status' => 'Tilan muutos', 'alert_type_status' => 'Tilan muutos',
'alert_type_offline' => 'Sammunut', 'alert_type_offline' => 'Sammunut',
'alert_type_always' => 'Aina', 'alert_type_always' => 'Aina',

View File

@ -214,14 +214,14 @@ $sm_lang = array(
'pushover_api_token' => 'Pushover App API Token', 'pushover_api_token' => 'Pushover App API Token',
'pushover_api_token_description' => 'Prima di poter usare Pushover, devi <a href="%1$s" target="_blank">registrare un\'App</a> nel loro sito web ed inserire la \'App API Token\' qui.', 'pushover_api_token_description' => 'Prima di poter usare Pushover, devi <a href="%1$s" target="_blank">registrare un\'App</a> nel loro sito web ed inserire la \'App API Token\' qui.',
'alert_type' => 'Seleziona quando vuoi essere notificato', 'alert_type' => 'Seleziona quando vuoi essere notificato',
'alert_type_description' => '<b>Cambio di Stato:</b> '. 'alert_type_description' => '<b>Cambio di Stato:</b> '.
'Riceverai una notifica solo quando un server cambierà stato. Quindi da online -> offline oppure da offline -> online.<br/>'. 'Riceverai una notifica solo quando un server cambierà stato. Quindi da online -> offline oppure da offline -> online.<br/>'.
'<br /><b>Fuori linea:</b> '. '<br /><b>Fuori linea:</b> '.
'Riceverai una notifica solo quando un server andrà offline *SOLO LA PRIMA VOLTA*. Per esempio, '. 'Riceverai una notifica solo quando un server andrà offline *SOLO LA PRIMA VOLTA*. Per esempio, '.
'Se il tuo cronjob è impostato per controllare ogni 15 min e il tuo server andrà offline dalle 2AM alle 6AM. '. 'Se il tuo cronjob è impostato per controllare ogni 15 min e il tuo server andrà offline dalle 2AM alle 6AM. '.
'Riceverai una sola notifica alle 2AM e nient\'altro.<br/>'. 'Riceverai una sola notifica alle 2AM e nient\'altro.<br/>'.
'<br><b>Sempre:</b> '. '<br><b>Sempre:</b> '.
'Riceverai una notifica ogni volta che lo script troverà un server down anche se è stato offline per ore.', 'Riceverai una notifica ogni volta che lo script troverà un server down anche se è stato offline per ore.',
'alert_type_status' => 'Cambio di Stato', 'alert_type_status' => 'Cambio di Stato',
'alert_type_offline' => 'Fuori linea', 'alert_type_offline' => 'Fuori linea',
'alert_type_always' => 'Sempre', 'alert_type_always' => 'Sempre',

View File

@ -218,14 +218,14 @@ $sm_lang = array(
'pushover_api_token' => 'プッシュオーバーアプリケーションのAPIトークン', 'pushover_api_token' => 'プッシュオーバーアプリケーションのAPIトークン',
'pushover_api_token_description' => 'プッシュオーバーを使用するには、事前にウェブサイトで<a href="%1$s" target="_blank">アプリを登録</a>してApp APIトークンを入力する必要があります。', 'pushover_api_token_description' => 'プッシュオーバーを使用するには、事前にウェブサイトで<a href="%1$s" target="_blank">アプリを登録</a>してApp APIトークンを入力する必要があります。',
'alert_type' => '通知するタイミングを選択', 'alert_type' => '通知するタイミングを選択',
'alert_type_description' => '<b>状態の変化:</b> '. 'alert_type_description' => '<b>状態の変化:</b> '.
'サーバーのステータスが変更されたときに通知を受け取ります。 だからオンライン -> オフラインまたはオフライン -> オンライン。<br/>'. 'サーバーのステータスが変更されたときに通知を受け取ります。 だからオンライン -> オフラインまたはオフライン -> オンライン。<br/>'.
'<br /><b>オフライン:</b> '. '<br /><b>オフライン:</b> '.
'サーバーが*初めての間*オフラインになったときに通知を受け取ります。 例えば、'. 'サーバーが*初めての間*オフラインになったときに通知を受け取ります。 例えば、'.
'あなたのcronの仕事は15分ごとです。あなたのサーバーは午前1時にダウンし、午前6時まで停止します。 '. 'あなたのcronの仕事は15分ごとです。あなたのサーバーは午前1時にダウンし、午前6時まで停止します。 '.
'午前1時に1つの通知が届きます。<br/>'. '午前1時に1つの通知が届きます。<br/>'.
'<br><b>常に:</b> '. '<br><b>常に:</b> '.
'サイトが数時間にわたってオフラインになっていても、スクリプトが実行され、サイトが停止するたびに通知を受け取ります。', 'サイトが数時間にわたってオフラインになっていても、スクリプトが実行され、サイトが停止するたびに通知を受け取ります。',
'alert_type_status' => '状況の変化', 'alert_type_status' => '状況の変化',
'alert_type_offline' => 'オフライン', 'alert_type_offline' => 'オフライン',
'alert_type_always' => '常に', 'alert_type_always' => '常に',

View File

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

View File

@ -214,14 +214,14 @@ $sm_lang = array(
'pushover_api_token' => 'Pushover App API Token', 'pushover_api_token' => 'Pushover App API Token',
'pushover_api_token_description' => 'Zanim zaczniesz używać Pushover, musisz <a href="%1$s" target="_blank"> zarejestrować aplikację</a> na ich stronie internetowej i wpisać tutaj App API Token.', 'pushover_api_token_description' => 'Zanim zaczniesz używać Pushover, musisz <a href="%1$s" target="_blank"> zarejestrować aplikację</a> na ich stronie internetowej i wpisać tutaj App API Token.',
'alert_type' => 'Wybierz kiedy chcesz być powiadomiony.', 'alert_type' => 'Wybierz kiedy chcesz być powiadomiony.',
'alert_type_description' => '<b>Zmiana statusu:</b> '. 'alert_type_description' => '<b>Zmiana statusu:</b> '.
'Otrzymasz powiadomienie gdy serwer zmieni status. Z online -> offline lub offline -> online.<br/>'. 'Otrzymasz powiadomienie gdy serwer zmieni status. Z online -> offline lub offline -> online.<br/>'.
'<br /><b>Offline:</b> '. '<br /><b>Offline:</b> '.
'Otrzymasz powiadomienie gdy serwer zmieni status na offline po raz pierwszy. Na przykład, '. 'Otrzymasz powiadomienie gdy serwer zmieni status na offline po raz pierwszy. Na przykład, '.
'Twój cronjob uruchamia się co 15 minut, a Twój serwer przestaje odpowiadać o 13 i nie działa do 18. '. 'Twój cronjob uruchamia się co 15 minut, a Twój serwer przestaje odpowiadać o 13 i nie działa do 18. '.
'Otrzymasz *TYLKO* jedno powiadomienie o 13.<br/>'. 'Otrzymasz *TYLKO* jedno powiadomienie o 13.<br/>'.
'<br><b>Zawsze:</b> '. '<br><b>Zawsze:</b> '.
'Otrzymasz powiadomienie za każdym razem gdy skrypt zostanie uruchomiony a strona będzie niedostępna.', 'Otrzymasz powiadomienie za każdym razem gdy skrypt zostanie uruchomiony a strona będzie niedostępna.',
'alert_type_status' => 'Zmiana statusu', 'alert_type_status' => 'Zmiana statusu',
'alert_type_offline' => 'Offline', 'alert_type_offline' => 'Offline',
'alert_type_always' => 'Zawsze', 'alert_type_always' => 'Zawsze',

View File

@ -30,21 +30,21 @@ $sm_lang = array(
'locale' => array('pt_BR.UTF-8', 'pt_BR', 'portuguese-brazilian'), 'locale' => array('pt_BR.UTF-8', 'pt_BR', 'portuguese-brazilian'),
'locale_tag' => 'BR', 'locale_tag' => 'BR',
'locale_dir' => 'ltr', 'locale_dir' => 'ltr',
'system' => array( 'system' => array(
'title' => 'Server Monitor', 'title' => 'Server Monitor',
'install' => 'Instalar', 'install' => 'Instalar',
'action' => 'Ação', 'action' => 'Ação',
'save' => 'Salvar', 'save' => 'Salvar',
'edit' => 'Editar', 'edit' => 'Editar',
'delete' => 'Excluir', 'delete' => 'Excluir',
'date' => 'Data', 'date' => 'Data',
'message' => 'Mensagem', 'message' => 'Mensagem',
'yes' => 'Sim', 'yes' => 'Sim',
'no' => 'Não', 'no' => 'Não',
'insert' => 'Inserir', 'insert' => 'Inserir',
'add_new' => 'Adicionar novo', 'add_new' => 'Adicionar novo',
'update_available' => 'Uma atualização ({version}) disponível em <a href="http://www.phpservermonitor.org" target="_blank">http://www.phpservermonitor.org</a>.', 'update_available' => 'Uma atualização ({version}) disponível em <a href="http://www.phpservermonitor.org" target="_blank">http://www.phpservermonitor.org</a>.',
'back_to_top' => 'Voltar ao topo', 'back_to_top' => 'Voltar ao topo',
'go_back' => 'Voltar', 'go_back' => 'Voltar',
'ok' => 'OK', 'ok' => 'OK',
'cancel' => 'Cancel', 'cancel' => 'Cancel',
@ -72,7 +72,7 @@ $sm_lang = array(
'minutes' => 'minutes', 'minutes' => 'minutes',
'second' => 'second', 'second' => 'second',
'seconds' => 'seconds', 'seconds' => 'seconds',
), ),
'menu' => array( 'menu' => array(
'config' => 'Configuração', 'config' => 'Configuração',
'server' => 'Servidores', 'server' => 'Servidores',
@ -82,9 +82,9 @@ $sm_lang = array(
'user' => 'Usuários', 'user' => 'Usuários',
'help' => 'Ajuda', 'help' => 'Ajuda',
), ),
'users' => array( 'users' => array(
'user' => 'Usuário', 'user' => 'Usuário',
'name' => 'Nome', 'name' => 'Nome',
'user_name' => 'Username', 'user_name' => 'Username',
'password' => 'Senha', 'password' => 'Senha',
'password_repeat' => 'Repetir senha', 'password_repeat' => 'Repetir senha',
@ -93,8 +93,8 @@ $sm_lang = array(
'level_10' => 'Administrador', 'level_10' => 'Administrador',
'level_20' => 'Usuário', 'level_20' => 'Usuário',
'level_description' => '<b>Administradores</b> Tem total acesso: podem gerenciar servidores, usuários e configurações globais.<br/><b>Usuários</b> só podem executar atualizações para servidores que lhe foram atribuídos.', 'level_description' => '<b>Administradores</b> Tem total acesso: podem gerenciar servidores, usuários e configurações globais.<br/><b>Usuários</b> só podem executar atualizações para servidores que lhe foram atribuídos.',
'mobile' => 'Celular', 'mobile' => 'Celular',
'email' => 'Email', 'email' => 'Email',
'pushover' => 'Pushover', 'pushover' => 'Pushover',
'pushover_description' => 'Pushover para enviar notificações em real-tome. Veja <a href="https://pushover.net/">o website</a> para mais informações.', 'pushover_description' => 'Pushover para enviar notificações em real-tome. Veja <a href="https://pushover.net/">o website</a> para mais informações.',
'pushover_key' => 'Pushover Key', 'pushover_key' => 'Pushover Key',
@ -103,8 +103,8 @@ $sm_lang = array(
'delete_title' => 'Excluir Usuário', 'delete_title' => 'Excluir Usuário',
'delete_message' => 'Tem certeza que deseja excluir o usuário \'%1\'?', 'delete_message' => 'Tem certeza que deseja excluir o usuário \'%1\'?',
'deleted' => 'Usuário excluído.', 'deleted' => 'Usuário excluído.',
'updated' => 'Usuário atualizado.', 'updated' => 'Usuário atualizado.',
'inserted' => 'Usuário adicionado.', 'inserted' => 'Usuário adicionado.',
'profile' => 'Perfil', 'profile' => 'Perfil',
'profile_updated' => 'Seu perfil foi atualizado.', 'profile_updated' => 'Seu perfil foi atualizado.',
'error_user_name_bad_length' => 'Usernames deve conter entre 2 e 64 caracteres.', 'error_user_name_bad_length' => 'Usernames deve conter entre 2 e 64 caracteres.',
@ -116,49 +116,49 @@ $sm_lang = array(
'error_user_no_match' => 'O usuário não pode ser encontrado no banco de dados.', 'error_user_no_match' => 'O usuário não pode ser encontrado no banco de dados.',
'error_user_password_invalid' => 'A senha informada é inválida.', 'error_user_password_invalid' => 'A senha informada é inválida.',
'error_user_password_no_match' => 'A senha informada não combina.', 'error_user_password_no_match' => 'A senha informada não combina.',
), ),
'log' => array( 'log' => array(
'title' => 'Entradas do Log', 'title' => 'Entradas do Log',
'type' => 'Tipo', 'type' => 'Tipo',
'status' => 'Status', 'status' => 'Status',
'email' => 'Email', 'email' => 'Email',
'sms' => 'SMS', 'sms' => 'SMS',
'pushover' => 'Pushover', 'pushover' => 'Pushover',
'no_logs' => 'Sem logs', 'no_logs' => 'Sem logs',
'clear' => 'Log clara', 'clear' => 'Log clara',
'delete_title' => 'Log clara', 'delete_title' => 'Log clara',
'delete_message' => 'Tem certeza de que deseja excluir <b>todos</b> os logs?', 'delete_message' => 'Tem certeza de que deseja excluir <b>todos</b> os logs?',
), ),
'servers' => array( 'servers' => array(
'server' => 'Servidor', 'server' => 'Servidor',
'status' => 'Status', 'status' => 'Status',
'label' => 'Etiqueta', 'label' => 'Etiqueta',
'domain' => 'Domínio/IP', 'domain' => 'Domínio/IP',
'timeout' => 'Timeout', 'timeout' => 'Timeout',
'timeout_description' => 'Segundos para aguardar a resposta do servidor.', 'timeout_description' => 'Segundos para aguardar a resposta do servidor.',
'port' => 'Porta', 'port' => 'Porta',
'type' => 'Tipo', 'type' => 'Tipo',
'type_website' => 'Website', 'type_website' => 'Website',
'type_service' => 'Service', 'type_service' => 'Service',
'pattern' => 'Pesquisa palavra/padrão', 'pattern' => 'Pesquisa palavra/padrão',
'pattern_description' => 'Se esse padrão não for encontrado no site, o servidor será marcado offline. As expressões regulares são permitidas.', 'pattern_description' => 'Se esse padrão não for encontrado no site, o servidor será marcado offline. As expressões regulares são permitidas.',
'last_check' => 'Última verificação', 'last_check' => 'Última verificação',
'last_online' => 'Última vez online', 'last_online' => 'Última vez online',
'last_offline' => 'Última vez offline', 'last_offline' => 'Última vez offline',
'monitoring' => 'Monitoramento', 'monitoring' => 'Monitoramento',
'no_monitoring' => 'Sem monitoring', 'no_monitoring' => 'Sem monitoring',
'email' => 'Email', 'email' => 'Email',
'send_email' => 'Enviar Email', 'send_email' => 'Enviar Email',
'sms' => 'SMS', 'sms' => 'SMS',
'send_sms' => 'Enviar SMS', 'send_sms' => 'Enviar SMS',
'pushover' => 'Pushover', 'pushover' => 'Pushover',
'users' => 'Usuários', 'users' => 'Usuários',
'delete_title' => 'Exluir Servidor', 'delete_title' => 'Exluir Servidor',
'delete_message' => 'Tem certeza que deseja excluir o servidor \'%1\'?', 'delete_message' => 'Tem certeza que deseja excluir o servidor \'%1\'?',
'deleted' => 'Servidor excluído.', 'deleted' => 'Servidor excluído.',
'updated' => 'Servidor atualizado.', 'updated' => 'Servidor atualizado.',
'inserted' => 'Servidor adicionar.', 'inserted' => 'Servidor adicionar.',
'latency' => 'Tempo de resposta', 'latency' => 'Tempo de resposta',
'latency_max' => 'Latência (máxima)', 'latency_max' => 'Latência (máxima)',
'latency_min' => 'Latência (minima)', 'latency_min' => 'Latência (minima)',
'latency_avg' => 'Latência (média)', 'latency_avg' => 'Latência (média)',
@ -187,14 +187,14 @@ $sm_lang = array(
'error_server_ip_bad_website' => 'A URL não é válida.', 'error_server_ip_bad_website' => 'A URL não é válida.',
'error_server_type_invalid' => 'O tipo de servidor selecionado não é valido.', 'error_server_type_invalid' => 'O tipo de servidor selecionado não é valido.',
'error_server_warning_threshold_invalid' => 'O limite de aviso deve ser um número inteiro maior que 0.', 'error_server_warning_threshold_invalid' => 'O limite de aviso deve ser um número inteiro maior que 0.',
), ),
'config' => array( 'config' => array(
'general' => 'Geral', 'general' => 'Geral',
'language' => 'Idioma', 'language' => 'Idioma',
'show_update' => 'verificar atualizações semanalmente?', 'show_update' => 'verificar atualizações semanalmente?',
'email_status' => 'Habilitar envio de email?', 'email_status' => 'Habilitar envio de email?',
'email_from_email' => 'Endereço do envio de email', 'email_from_email' => 'Endereço do envio de email',
'email_from_name' => 'Nome do envio de email', 'email_from_name' => 'Nome do envio de email',
'email_smtp' => 'Enable SMTP', 'email_smtp' => 'Enable SMTP',
'email_smtp_host' => 'SMTP host', 'email_smtp_host' => 'SMTP host',
'email_smtp_port' => 'SMTP port', 'email_smtp_port' => 'SMTP port',
@ -203,48 +203,48 @@ $sm_lang = array(
'email_smtp_username' => 'SMTP username', 'email_smtp_username' => 'SMTP username',
'email_smtp_password' => 'SMTP password', 'email_smtp_password' => 'SMTP password',
'email_smtp_noauth' => 'Deixe em branco para nenhuma autenticação', 'email_smtp_noauth' => 'Deixe em branco para nenhuma autenticação',
'sms_status' => 'Habilitar o envio de mensagem de texto?', 'sms_status' => 'Habilitar o envio de mensagem de texto?',
'sms_gateway' => 'Gateway para o uso de envio de mensagens', 'sms_gateway' => 'Gateway para o uso de envio de mensagens',
'sms_gateway_username' => 'Usuário do Gateway', 'sms_gateway_username' => 'Usuário do Gateway',
'sms_gateway_password' => 'Senha do Gateway', 'sms_gateway_password' => 'Senha do Gateway',
'sms_from' => 'Número de telefone de envio', 'sms_from' => 'Número de telefone de envio',
'pushover_status' => 'Habilitar envio de mensagens Pushover', 'pushover_status' => 'Habilitar envio de mensagens Pushover',
'pushover_description' => 'Pushover é um serviço de notificações em tempo real. Veja <a href="https://pushover.net/">o website</a> para mais informações.', 'pushover_description' => 'Pushover é um serviço de notificações em tempo real. Veja <a href="https://pushover.net/">o website</a> para mais informações.',
'pushover_clone_app' => 'Clique aqui para criar sua app Pushover', 'pushover_clone_app' => 'Clique aqui para criar sua app Pushover',
'pushover_api_token' => 'Pushover App API Token', 'pushover_api_token' => 'Pushover App API Token',
'pushover_api_token_description' => 'Before you can use Pushover, you need to <a href="%1$s" target="_blank">register an App</a> at their website and enter the App API Token here.', 'pushover_api_token_description' => 'Before you can use Pushover, you need to <a href="%1$s" target="_blank">register an App</a> at their website and enter the App API Token here.',
'alert_type' => 'Selecione como você gostaria de ser notificado.', 'alert_type' => 'Selecione como você gostaria de ser notificado.',
'alert_type_description' => '<b>Mudança de Status:</b> '. 'alert_type_description' => '<b>Mudança de Status:</b> '.
'Você receberá uma notificação quando o seridor tive uma mudança de status. De online -> offline ou offline -> online.<br/>'. 'Você receberá uma notificação quando o seridor tive uma mudança de status. De online -> offline ou offline -> online.<br/>'.
'<br /><b>Offline:</b> '. '<br /><b>Offline:</b> '.
'Você receberá uma notificação quando o servidor fica OFFLINE (Pela primeira vez). Por exemplo, '. 'Você receberá uma notificação quando o servidor fica OFFLINE (Pela primeira vez). Por exemplo, '.
'A cronjob é a cada 15 minutos e seu servidor caiu em 1:00 e permanece offline até 6 am. '. 'A cronjob é a cada 15 minutos e seu servidor caiu em 1:00 e permanece offline até 6 am. '.
'Você receberá uma notificação a 1:00 apenas<br/>'. 'Você receberá uma notificação a 1:00 apenas<br/>'.
'<br><b>Sempre:</b> '. '<br><b>Sempre:</b> '.
'Você receberá uma notificação toda vez que o script é executado e um site esta offline, mesmo se o site tenha ficado offline por horas.', 'Você receberá uma notificação toda vez que o script é executado e um site esta offline, mesmo se o site tenha ficado offline por horas.',
'alert_type_status' => 'Mudança de Status', 'alert_type_status' => 'Mudança de Status',
'alert_type_offline' => 'Offline', 'alert_type_offline' => 'Offline',
'alert_type_always' => 'Sempre', 'alert_type_always' => 'Sempre',
'log_status' => 'Log status', 'log_status' => 'Log status',
'log_status_description' => 'Se o status de registro é definido como TRUE, o monitor irá registrar o evento sempre que as configurações de notificação forem passadas.', 'log_status_description' => 'Se o status de registro é definido como TRUE, o monitor irá registrar o evento sempre que as configurações de notificação forem passadas.',
'log_email' => 'Registrar no Log os envios de email feitos pelo script?', 'log_email' => 'Registrar no Log os envios de email feitos pelo script?',
'log_sms' => 'Registrar no Log os envios de mensagens de texto feitos pelo script?', 'log_sms' => 'Registrar no Log os envios de mensagens de texto feitos pelo script?',
'log_pushover' => 'Log pushover messages sent by the script', 'log_pushover' => 'Log pushover messages sent by the script',
'updated' => 'A configuração foi atualizada.', 'updated' => 'A configuração foi atualizada.',
'tab_email' => 'Email', 'tab_email' => 'Email',
'tab_sms' => 'Texto', 'tab_sms' => 'Texto',
'tab_pushover' => 'Pushover', 'tab_pushover' => 'Pushover',
'settings_email' => 'Configuração de email', 'settings_email' => 'Configuração de email',
'settings_sms' => 'Configuração de mensagens de texto', 'settings_sms' => 'Configuração de mensagens de texto',
'settings_pushover' => 'Pushover settings', 'settings_pushover' => 'Pushover settings',
'settings_notification' => 'Configuração de notificações', 'settings_notification' => 'Configuração de notificações',
'settings_log' => 'Configuração de Logs', 'settings_log' => 'Configuração de Logs',
'auto_refresh' => 'Atualizar automaticamente', 'auto_refresh' => 'Atualizar automaticamente',
'auto_refresh_servers' => 'auto_refresh_servers' =>
'Atualizar automaticamente a página de servidores.<br/>'. 'Atualizar automaticamente a página de servidores.<br/>'.
'<span class="small">'. '<span class="small">'.
'Tempo em segundos, Se 0 a página não será atualizada.'. 'Tempo em segundos, Se 0 a página não será atualizada.'.
'</span>', '</span>',
'seconds' => 'segundos', 'seconds' => 'segundos',
'test' => 'Teste', 'test' => 'Teste',
'test_email' => 'Um e-mail será enviado para o endereço especificado em seu perfil de usuário.', 'test_email' => 'Um e-mail será enviado para o endereço especificado em seu perfil de usuário.',
@ -265,20 +265,20 @@ $sm_lang = array(
'log_retention_period' => 'Período de retenção do Log', 'log_retention_period' => 'Período de retenção do Log',
'log_retention_period_description' => 'Número de dias para manter os registros de notificações e arquivos de tempo de atividade do servidor. Digite 0 para desativar a limpeza de registro.', 'log_retention_period_description' => 'Número de dias para manter os registros de notificações e arquivos de tempo de atividade do servidor. Digite 0 para desativar a limpeza de registro.',
'log_retention_days' => 'dias', 'log_retention_days' => 'dias',
), ),
// for newlines in the email messages use <br/> // for newlines in the email messages use <br/>
'notifications' => array( 'notifications' => array(
'off_sms' => 'Servidor \'%LABEL%\' está OFFLINE: ip=%IP%, porta=%PORT%. Erro=%ERROR%', 'off_sms' => 'Servidor \'%LABEL%\' está OFFLINE: ip=%IP%, porta=%PORT%. Erro=%ERROR%',
'off_email_subject' => 'IMPORTANTE: Servidor \'%LABEL%\' está OFFLINE', 'off_email_subject' => 'IMPORTANTE: Servidor \'%LABEL%\' está OFFLINE',
'off_email_body' => "Falha ao conectar ao servidor:<br/><br/>Servidor: %LABEL%<br/>IP: %IP%<br/>Porta: %PORT%<br/>Erro: %ERROR%<br/>Data: %DATE%", 'off_email_body' => "Falha ao conectar ao servidor:<br/><br/>Servidor: %LABEL%<br/>IP: %IP%<br/>Porta: %PORT%<br/>Erro: %ERROR%<br/>Data: %DATE%",
'off_pushover_title' => 'Servidor \'%LABEL%\' está OFFLINE', 'off_pushover_title' => 'Servidor \'%LABEL%\' está OFFLINE',
'off_pushover_message' => "Falha ao conectar ao servidor:<br/><br/>Servidor: %LABEL%<br/>IP: %IP%<br/>Porta: %PORT%<br/>Erro: %ERROR%<br/>Data: %DATE%", 'off_pushover_message' => "Falha ao conectar ao servidor:<br/><br/>Servidor: %LABEL%<br/>IP: %IP%<br/>Porta: %PORT%<br/>Erro: %ERROR%<br/>Data: %DATE%",
'on_sms' => 'Servidor \'%LABEL%\' esta ONLINE: ip=%IP%, porta=%PORT%', 'on_sms' => 'Servidor \'%LABEL%\' esta ONLINE: ip=%IP%, porta=%PORT%',
'on_email_subject' => 'IMPORTANTE: Servidor \'%LABEL%\' esta ONLINE', 'on_email_subject' => 'IMPORTANTE: Servidor \'%LABEL%\' esta ONLINE',
'on_email_body' => "Servidor '%LABEL%' esta ONLINE novamente:<br/><br/>Servidor: %LABEL%<br/>IP: %IP%<br/>Porta: %PORT%<br/>Data: %DATE%", 'on_email_body' => "Servidor '%LABEL%' esta ONLINE novamente:<br/><br/>Servidor: %LABEL%<br/>IP: %IP%<br/>Porta: %PORT%<br/>Data: %DATE%",
'on_pushover_title' => 'Servidor \'%LABEL%\' esta ONLINE', 'on_pushover_title' => 'Servidor \'%LABEL%\' esta ONLINE',
'on_pushover_message' => "Servidor '%LABEL%' esta ONLINE novamente:<br/><br/>Servidor: %LABEL%<br/>IP: %IP%<br/>Porta: %PORT%<br/>Data: %DATE%", 'on_pushover_message' => "Servidor '%LABEL%' esta ONLINE novamente:<br/><br/>Servidor: %LABEL%<br/>IP: %IP%<br/>Porta: %PORT%<br/>Data: %DATE%",
), ),
'login' => array( 'login' => array(
'welcome_usermenu' => 'Bem vindo, %user_name%', 'welcome_usermenu' => 'Bem vindo, %user_name%',
'title_sign_in' => 'Por favor efetue login', 'title_sign_in' => 'Por favor efetue login',

View File

@ -214,14 +214,14 @@ $sm_lang = array(
'pushover_api_token' => 'Pushover App API Token', 'pushover_api_token' => 'Pushover App API Token',
'pushover_api_token_description' => 'Прежде чем вы сможете начать пользоваться Pushover, вам необходимо зарегестрировать <a href="%1$s" target="_blank">"App"</a> на их веб-сайте и ввести "App API Token" сюда.', 'pushover_api_token_description' => 'Прежде чем вы сможете начать пользоваться Pushover, вам необходимо зарегестрировать <a href="%1$s" target="_blank">"App"</a> на их веб-сайте и ввести "App API Token" сюда.',
'alert_type' => 'Выбeрите, какие вы хотите получать уведомления', 'alert_type' => 'Выбeрите, какие вы хотите получать уведомления',
'alert_type_description' => '<b>Изменение статуса :</b> '. 'alert_type_description' => '<b>Изменение статуса :</b> '.
'Вы получите уведомление об изменение статуса. Для онлайн -> оффлайн или офлайн -> онлайн.<br/>'. 'Вы получите уведомление об изменение статуса. Для онлайн -> оффлайн или офлайн -> онлайн.<br/>'.
'<br /><b>Оффлайн:</b> '. '<br /><b>Оффлайн:</b> '.
'Вы получите уведомление только когда сервер перейдет в статус оффлайн. Например, '. 'Вы получите уведомление только когда сервер перейдет в статус оффлайн. Например, '.
'Задание Cron выставлено на каждые 15 минут. Сервер перейдет в статус оффлайн в 1:00 и не измениться до 6:00. '. 'Задание Cron выставлено на каждые 15 минут. Сервер перейдет в статус оффлайн в 1:00 и не измениться до 6:00. '.
'Вы получите 1 уведомление только в 1:00<br/>'. 'Вы получите 1 уведомление только в 1:00<br/>'.
'<br><b>Всегда:</b> '. '<br><b>Всегда:</b> '.
'Вы будете получать уведомление при каждом запуске скрипта проверки, как только сервер перейдет в статус оффлайн, даже если сервер находится в этом статусе несколько часов', 'Вы будете получать уведомление при каждом запуске скрипта проверки, как только сервер перейдет в статус оффлайн, даже если сервер находится в этом статусе несколько часов',
'alert_type_status' => 'Изменение статуса', 'alert_type_status' => 'Изменение статуса',
'alert_type_offline' => 'Оффлайн', 'alert_type_offline' => 'Оффлайн',
'alert_type_always' => 'Всегда', 'alert_type_always' => 'Всегда',

View File

@ -213,14 +213,14 @@ $sm_lang = array(
'pushover_api_token' => 'Pushover App API Token', 'pushover_api_token' => 'Pushover App API Token',
'pushover_api_token_description' => 'Pred použitím Pushoveru sa musíte <a href="%1$s" target="_blank">registrovať</a> a získať API Token.', 'pushover_api_token_description' => 'Pred použitím Pushoveru sa musíte <a href="%1$s" target="_blank">registrovať</a> a získať API Token.',
'alert_type' => 'Zvoľte kedy si prajete byť upozornení.', 'alert_type' => 'Zvoľte kedy si prajete byť upozornení.',
'alert_type_description' => '<b>Zmena stavu:</b> '. 'alert_type_description' => '<b>Zmena stavu:</b> '.
'Obdržíte upozornenie pri zmene stavu, teda: online -> offline alebo offline -> online.<br/>'. 'Obdržíte upozornenie pri zmene stavu, teda: online -> offline alebo offline -> online.<br/>'.
'<br /><b>Offline:</b> '. '<br /><b>Offline:</b> '.
'Obdržíte upozornenie, keď server prejde *PO PRVÝ KRÁT* do offline stavu. Napríklad, '. 'Obdržíte upozornenie, keď server prejde *PO PRVÝ KRÁT* do offline stavu. Napríklad, '.
'pokiaľ je cron nastavený na 15 minút a sledovaný server bude offline mezi 01:00 a 06:00, '. 'pokiaľ je cron nastavený na 15 minút a sledovaný server bude offline mezi 01:00 a 06:00, '.
'tak obdržíte upozornenie iba o 01:00.<br/>'. 'tak obdržíte upozornenie iba o 01:00.<br/>'.
'<br><b>Vždy:</b> '. '<br><b>Vždy:</b> '.
'Obdržíte upozornenie pri každom spustení kontroly, teda aj pokiaľ bude server offline niekoľko hodín.', 'Obdržíte upozornenie pri každom spustení kontroly, teda aj pokiaľ bude server offline niekoľko hodín.',
'alert_type_status' => 'Zmena stavu', 'alert_type_status' => 'Zmena stavu',
'alert_type_offline' => 'Offline', 'alert_type_offline' => 'Offline',
'alert_type_always' => 'Vždy', 'alert_type_always' => 'Vždy',

View File

@ -26,269 +26,269 @@
**/ **/
$sm_lang = array( $sm_lang = array(
'name' => 'Slovenščina - Slovenian', 'name' => 'Slovenščina - Slovenian',
'locale' => array('sl_SI.UTF-8', 'sl_SI', 'slovenščina', 'slovenščina'), 'locale' => array('sl_SI.UTF-8', 'sl_SI', 'slovenščina', 'slovenščina'),
'system' => array( 'system' => array(
'title' => 'Server Monitor', 'title' => 'Server Monitor',
'install' => 'Install', 'install' => 'Install',
'action' => 'Action', 'action' => 'Action',
'save' => 'Shrani', 'save' => 'Shrani',
'edit' => 'Uredi', 'edit' => 'Uredi',
'delete' => 'Izbriši', 'delete' => 'Izbriši',
'date' => 'Datum', 'date' => 'Datum',
'message' => 'Sporočilo', 'message' => 'Sporočilo',
'yes' => 'da', 'yes' => 'da',
'no' => 'ne', 'no' => 'ne',
'insert' => 'Vstavi', 'insert' => 'Vstavi',
'add_new' => 'Dodaj novega', 'add_new' => 'Dodaj novega',
'update_available' => 'Na voljo je nova različica ({version}); prenesti jo je mogoče iz <a href="http://www.phpservermonitor.org" target="_blank">http://www.phpservermonitor.org</a>.', 'update_available' => 'Na voljo je nova različica ({version}); prenesti jo je mogoče iz <a href="http://www.phpservermonitor.org" target="_blank">http://www.phpservermonitor.org</a>.',
'back_to_top' => 'Nazaj na vrh', 'back_to_top' => 'Nazaj na vrh',
'go_back' => 'Nazaj', 'go_back' => 'Nazaj',
'ok' => 'OK', 'ok' => 'OK',
'cancel' => 'Prekini', 'cancel' => 'Prekini',
// date/time format according the strftime php function format parameter http://php.net/manual/function.strftime.php // date/time format according the strftime php function format parameter http://php.net/manual/function.strftime.php
'short_day_format' => '%B %e', 'short_day_format' => '%B %e',
'long_day_format' => '%B %e, %Y', 'long_day_format' => '%B %e, %Y',
'yesterday_format' => 'včeraj ob %k:%M', 'yesterday_format' => 'včeraj ob %k:%M',
'other_day_format' => '%A at %k:%M', 'other_day_format' => '%A at %k:%M',
'never' => 'nikoli', 'never' => 'nikoli',
'hours_ago' => 'pred %d urami', 'hours_ago' => 'pred %d urami',
'an_hour_ago' => 'pred približno uro', 'an_hour_ago' => 'pred približno uro',
'minutes_ago' => 'pred %d minutami', 'minutes_ago' => 'pred %d minutami',
'a_minute_ago' => 'pred približno minuto', 'a_minute_ago' => 'pred približno minuto',
'seconds_ago' => 'pred %d sekundami', 'seconds_ago' => 'pred %d sekundami',
'a_second_ago' => 'pred sekundo', 'a_second_ago' => 'pred sekundo',
), ),
'menu' => array( 'menu' => array(
'config' => 'Nastavitve', 'config' => 'Nastavitve',
'server' => 'Strežniki', 'server' => 'Strežniki',
'server_log' => 'Dnevnik', 'server_log' => 'Dnevnik',
'server_status' => 'Status', 'server_status' => 'Status',
'server_update' => 'Posodobitev statusa', 'server_update' => 'Posodobitev statusa',
'user' => 'Uporabniki', 'user' => 'Uporabniki',
'help' => 'Pomoč', 'help' => 'Pomoč',
), ),
'users' => array( 'users' => array(
'user' => 'Uporabnik', 'user' => 'Uporabnik',
'name' => 'Ime', 'name' => 'Ime',
'user_name' => 'Uporabniško ime', 'user_name' => 'Uporabniško ime',
'password' => 'Geslo', 'password' => 'Geslo',
'password_repeat' => 'Geslo (ponovno)', 'password_repeat' => 'Geslo (ponovno)',
'password_leave_blank' => 'Če ne želite spremeniti pustite prazno', 'password_leave_blank' => 'Če ne želite spremeniti pustite prazno',
'level' => 'Nivo dostopa', 'level' => 'Nivo dostopa',
'level_10' => 'Administrator', 'level_10' => 'Administrator',
'level_20' => 'Uporabnik', 'level_20' => 'Uporabnik',
'level_description' => '<b>Administratorji</b> imajo poln dostop: lahko upravljajo strežnike, uporabnike in urejajo globalne nastavitve.<br/><b>Uporabniki</b> lahko samo vidijo status in poganjajo posodobitev statusa za strežnike, ki so jim bili dodeljeni.', 'level_description' => '<b>Administratorji</b> imajo poln dostop: lahko upravljajo strežnike, uporabnike in urejajo globalne nastavitve.<br/><b>Uporabniki</b> lahko samo vidijo status in poganjajo posodobitev statusa za strežnike, ki so jim bili dodeljeni.',
'mobile' => 'Mobilni telefon', 'mobile' => 'Mobilni telefon',
'email' => 'E-pošta', 'email' => 'E-pošta',
'pushover' => 'Pushover', 'pushover' => 'Pushover',
'pushover_description' => 'Pushover je storitev, ki omogoča enostavno prejemanje obvestil v realnem času. Več informacij je na voljo <a href="https://pushover.net/">na njihovi spletni strani</a>.', 'pushover_description' => 'Pushover je storitev, ki omogoča enostavno prejemanje obvestil v realnem času. Več informacij je na voljo <a href="https://pushover.net/">na njihovi spletni strani</a>.',
'pushover_key' => 'Pushover ključ', 'pushover_key' => 'Pushover ključ',
'pushover_device' => 'Pushover naprava', 'pushover_device' => 'Pushover naprava',
'pushover_device_description' => 'Ime naprave na katero naj se pošlje obvestilo. Če želite obvestilo poslati na vse naprave, pustite prazno.', 'pushover_device_description' => 'Ime naprave na katero naj se pošlje obvestilo. Če želite obvestilo poslati na vse naprave, pustite prazno.',
'delete_title' => 'Izbriši uporabnika', 'delete_title' => 'Izbriši uporabnika',
'delete_message' => 'Ste prepričani, da želite izbrisati uporabnika \'%1\'?', 'delete_message' => 'Ste prepričani, da želite izbrisati uporabnika \'%1\'?',
'deleted' => 'Uporabnik izbrisan.', 'deleted' => 'Uporabnik izbrisan.',
'updated' => 'Podatki uporabnika posodobljeni.', 'updated' => 'Podatki uporabnika posodobljeni.',
'inserted' => 'Uporabnik dodan.', 'inserted' => 'Uporabnik dodan.',
'profile' => 'Profil', 'profile' => 'Profil',
'profile_updated' => 'Vaš profil je bil posodobljen.', 'profile_updated' => 'Vaš profil je bil posodobljen.',
'error_user_name_bad_length' => 'Uporabniško ime mora biti dolgo med 2 in 64 znakov.', 'error_user_name_bad_length' => 'Uporabniško ime mora biti dolgo med 2 in 64 znakov.',
'error_user_name_invalid' => 'Uporabniško ime lahko vsebuje samo črke (a-z, A-Z), številke (0-9), pike (.) in podčrtaje (_).', 'error_user_name_invalid' => 'Uporabniško ime lahko vsebuje samo črke (a-z, A-Z), številke (0-9), pike (.) in podčrtaje (_).',
'error_user_name_exists' => 'Uporabniško ime v bazi podatkov že obstaja.', 'error_user_name_exists' => 'Uporabniško ime v bazi podatkov že obstaja.',
'error_user_email_bad_length' => 'E-naslov mora biti med 5 in 255 znaki.', 'error_user_email_bad_length' => 'E-naslov mora biti med 5 in 255 znaki.',
'error_user_email_invalid' => 'E-naslov ni veljaven.', 'error_user_email_invalid' => 'E-naslov ni veljaven.',
'error_user_level_invalid' => 'Izbrani nivo dostopa za uporabnika ni veljaven.', 'error_user_level_invalid' => 'Izbrani nivo dostopa za uporabnika ni veljaven.',
'error_user_no_match' => 'Uporabnika ne najdem v bazi podatkov.', 'error_user_no_match' => 'Uporabnika ne najdem v bazi podatkov.',
'error_user_password_invalid' => 'Vneseno geslo ni veljavno.', 'error_user_password_invalid' => 'Vneseno geslo ni veljavno.',
'error_user_password_no_match' => 'Gesli se ne ujemata.', 'error_user_password_no_match' => 'Gesli se ne ujemata.',
), ),
'log' => array( 'log' => array(
'title' => 'Dnevniški zapisi', 'title' => 'Dnevniški zapisi',
'type' => 'Tip', 'type' => 'Tip',
'status' => 'Status', 'status' => 'Status',
'email' => 'E-pošta', 'email' => 'E-pošta',
'sms' => 'SMS', 'sms' => 'SMS',
'pushover' => 'Pushover', 'pushover' => 'Pushover',
'no_logs' => 'ni dnevniških zapisov', 'no_logs' => 'ni dnevniških zapisov',
'clear' => 'Počisti dnevnik', 'clear' => 'Počisti dnevnik',
'delete_title' => 'Brisanje dnevnika', 'delete_title' => 'Brisanje dnevnika',
'delete_message' => 'Ali ste prepričani, da želite izbrisati <b>vse</b> dnevnike?', 'delete_message' => 'Ali ste prepričani, da želite izbrisati <b>vse</b> dnevnike?',
), ),
'servers' => array( 'servers' => array(
'server' => 'Strežnik', 'server' => 'Strežnik',
'status' => 'Status', 'status' => 'Status',
'label' => 'Ime', 'label' => 'Ime',
'domain' => 'Domena / IP naslov', 'domain' => 'Domena / IP naslov',
'timeout' => 'Časovna omejitev', 'timeout' => 'Časovna omejitev',
'timeout_description' => 'Koliko sekund naj čakam na odgovor strežnika.', 'timeout_description' => 'Koliko sekund naj čakam na odgovor strežnika.',
'port' => 'Vrata', 'port' => 'Vrata',
'type' => 'Tip', 'type' => 'Tip',
'type_website' => 'Spletna stran (website)', 'type_website' => 'Spletna stran (website)',
'type_service' => 'Storitev (service)', 'type_service' => 'Storitev (service)',
'pattern' => 'Iskani niz oz. vzorec', 'pattern' => 'Iskani niz oz. vzorec',
'pattern_description' => 'Če ta vzorec ne bo najden na spletni strani, bo strežnik označen kot nedelujoč. Dovoljeni so regularni izrazi.', 'pattern_description' => 'Če ta vzorec ne bo najden na spletni strani, bo strežnik označen kot nedelujoč. Dovoljeni so regularni izrazi.',
'last_check' => 'Zadnje preverjanje', 'last_check' => 'Zadnje preverjanje',
'last_online' => 'Nazadnje dostopen', 'last_online' => 'Nazadnje dostopen',
'monitoring' => 'Spremljanje', 'monitoring' => 'Spremljanje',
'no_monitoring' => 'Se ne spremlja', 'no_monitoring' => 'Se ne spremlja',
'email' => 'E-pošta', 'email' => 'E-pošta',
'send_email' => 'Pošlji e-pošto', 'send_email' => 'Pošlji e-pošto',
'sms' => 'SMS', 'sms' => 'SMS',
'send_sms' => 'Pošlji SMS', 'send_sms' => 'Pošlji SMS',
'pushover' => 'Pushover', 'pushover' => 'Pushover',
'users' => 'Uporabniki', 'users' => 'Uporabniki',
'delete_title' => 'Izbriši strežnik', 'delete_title' => 'Izbriši strežnik',
'delete_message' => 'Ste prepričani, da želite izbrisati strežnik \'%1\'?', 'delete_message' => 'Ste prepričani, da želite izbrisati strežnik \'%1\'?',
'deleted' => 'Strežnik izbrisan.', 'deleted' => 'Strežnik izbrisan.',
'updated' => 'Podatki o strežniku posodobljeni.', 'updated' => 'Podatki o strežniku posodobljeni.',
'inserted' => 'Strežnik dodan.', 'inserted' => 'Strežnik dodan.',
'latency' => 'Zakasnitev', 'latency' => 'Zakasnitev',
'latency_max' => 'Zakasnitev (največja)', 'latency_max' => 'Zakasnitev (največja)',
'latency_min' => 'Zakasnitev (najmanjša)', 'latency_min' => 'Zakasnitev (najmanjša)',
'latency_avg' => 'Zakasnitev (povprečna)', 'latency_avg' => 'Zakasnitev (povprečna)',
'uptime' => 'Neprekinjeno delovanje', 'uptime' => 'Neprekinjeno delovanje',
'year' => 'leto', 'year' => 'leto',
'month' => 'mesec', 'month' => 'mesec',
'week' => 'teden', 'week' => 'teden',
'day' => 'dan', 'day' => 'dan',
'hour' => 'ura', 'hour' => 'ura',
'warning_threshold' => 'Prag za opozorilo', 'warning_threshold' => 'Prag za opozorilo',
'warning_threshold_description' => 'Število neuspešnih preverjanj preden je strežnik označen kot nedelujoč.', 'warning_threshold_description' => 'Število neuspešnih preverjanj preden je strežnik označen kot nedelujoč.',
'chart_last_week' => 'prejšnji teden', 'chart_last_week' => 'prejšnji teden',
'chart_history' => 'Zgodovina', 'chart_history' => 'Zgodovina',
// Charts date format according jqPlot date format http://www.jqplot.com/docs/files/plugins/jqplot-dateAxisRenderer-js.html // Charts date format according jqPlot date format http://www.jqplot.com/docs/files/plugins/jqplot-dateAxisRenderer-js.html
'chart_day_format' => '%m. %d. %Y', 'chart_day_format' => '%m. %d. %Y',
'chart_long_date_format' => '%m. %d. %Y %H:%M:%S', 'chart_long_date_format' => '%m. %d. %Y %H:%M:%S',
'chart_short_date_format' => '%m/%d %H:%M', 'chart_short_date_format' => '%m/%d %H:%M',
'chart_short_time_format' => '%H:%M', 'chart_short_time_format' => '%H:%M',
'warning_notifications_disabled_sms' => 'SMS obvestila so onemogočena.', 'warning_notifications_disabled_sms' => 'SMS obvestila so onemogočena.',
'warning_notifications_disabled_email' => 'Obvestila po e-pošti so onemogočena.', 'warning_notifications_disabled_email' => 'Obvestila po e-pošti so onemogočena.',
'warning_notifications_disabled_pushover' => 'Pushover obvestila so onemogočena.', 'warning_notifications_disabled_pushover' => 'Pushover obvestila so onemogočena.',
'error_server_no_match' => 'Strežnik ni najden.', 'error_server_no_match' => 'Strežnik ni najden.',
'error_server_label_bad_length' => 'Ime mora biti med 1 in 255 znaki.', 'error_server_label_bad_length' => 'Ime mora biti med 1 in 255 znaki.',
'error_server_ip_bad_length' => 'Domena / IP naslov mora biti med 1 in 255 znaki.', 'error_server_ip_bad_length' => 'Domena / IP naslov mora biti med 1 in 255 znaki.',
'error_server_ip_bad_service' => 'IP naslov ni veljaven.', 'error_server_ip_bad_service' => 'IP naslov ni veljaven.',
'error_server_ip_bad_website' => 'URL naslov spletne strani ni veljaven.', 'error_server_ip_bad_website' => 'URL naslov spletne strani ni veljaven.',
'error_server_type_invalid' => 'Izbrani tip strežnika ni veljaven.', 'error_server_type_invalid' => 'Izbrani tip strežnika ni veljaven.',
'error_server_warning_threshold_invalid' => 'Prag za opozorilo mora biti število večje od 0.', 'error_server_warning_threshold_invalid' => 'Prag za opozorilo mora biti število večje od 0.',
), ),
'config' => array( 'config' => array(
'general' => 'Splošno', 'general' => 'Splošno',
'language' => 'Jezik', 'language' => 'Jezik',
'show_update' => 'Preverim za posodobitve?', 'show_update' => 'Preverim za posodobitve?',
'email_status' => 'Dovolim pošiljanje e-pošte', 'email_status' => 'Dovolim pošiljanje e-pošte',
'email_from_email' => 'E-poštni naslov pošiljatelja', 'email_from_email' => 'E-poštni naslov pošiljatelja',
'email_from_name' => 'Ime pošiljatelja', 'email_from_name' => 'Ime pošiljatelja',
'email_smtp' => 'Enable SMTP', 'email_smtp' => 'Enable SMTP',
'email_smtp_host' => 'SMTP strežnik', 'email_smtp_host' => 'SMTP strežnik',
'email_smtp_port' => 'SMTP vrata', 'email_smtp_port' => 'SMTP vrata',
'email_smtp_security' => 'SMTP varnost', 'email_smtp_security' => 'SMTP varnost',
'email_smtp_security_none' => 'brez', 'email_smtp_security_none' => 'brez',
'email_smtp_username' => 'SMTP uporabniško ime', 'email_smtp_username' => 'SMTP uporabniško ime',
'email_smtp_password' => 'SMTP geslo', 'email_smtp_password' => 'SMTP geslo',
'email_smtp_noauth' => 'Če ni potrebna overovitev, pustite prazno', 'email_smtp_noauth' => 'Če ni potrebna overovitev, pustite prazno',
'sms_status' => 'Dovolim pošiljanje SMS sporočil?', 'sms_status' => 'Dovolim pošiljanje SMS sporočil?',
'sms_gateway' => 'Prehod za pošiljanje SMS sporočil', 'sms_gateway' => 'Prehod za pošiljanje SMS sporočil',
'sms_gateway_username' => 'Uporabniško ime SMS prehoda', 'sms_gateway_username' => 'Uporabniško ime SMS prehoda',
'sms_gateway_password' => 'Geslo SMS prehoda', 'sms_gateway_password' => 'Geslo SMS prehoda',
'sms_from' => 'Telefonska številka pošiljatelja', 'sms_from' => 'Telefonska številka pošiljatelja',
'pushover_status' => 'Dovolim pošiljanje Pushover sporočil', 'pushover_status' => 'Dovolim pošiljanje Pushover sporočil',
'pushover_description' => 'Pushover je storitev, ki omogoča enostavno prejemanje obvestil v realnem času. Več informacij je na voljo <a href="https://pushover.net/">na njihovi spletni strani</a>.', 'pushover_description' => 'Pushover je storitev, ki omogoča enostavno prejemanje obvestil v realnem času. Več informacij je na voljo <a href="https://pushover.net/">na njihovi spletni strani</a>.',
'pushover_clone_app' => 'Kliknite za ustvarjanje vaše Pushover aplikacije', 'pushover_clone_app' => 'Kliknite za ustvarjanje vaše Pushover aplikacije',
'pushover_api_token' => 'Pushover API žeton', 'pushover_api_token' => 'Pushover API žeton',
'pushover_api_token_description' => 'Pred uporabo storitve Pushover, morate na njihovi spletni strani <a href="%1$s" target="_blank">registrirati aplikacijo</a>, tukaj pa vnesti API žeton.', 'pushover_api_token_description' => 'Pred uporabo storitve Pushover, morate na njihovi spletni strani <a href="%1$s" target="_blank">registrirati aplikacijo</a>, tukaj pa vnesti API žeton.',
'alert_type' => 'Izberite kdaj naj se vam pošljejo obvestila.', 'alert_type' => 'Izberite kdaj naj se vam pošljejo obvestila.',
'alert_type_description' => '<b>Sprememba statusa:</b> ' . 'alert_type_description' => '<b>Sprememba statusa:</b> '.
'Obvestilo boste dobili ob vsaki spremembi statusa, torej iz delujoč -> nedelujoč ter nedelujoč -> delujoč.<br/>' . 'Obvestilo boste dobili ob vsaki spremembi statusa, torej iz delujoč -> nedelujoč ter nedelujoč -> delujoč.<br/>'.
'<br /><b>Nedelujoč:</b> ' . '<br /><b>Nedelujoč:</b> '.
'Obvestilo boste dobili samo, ko se bo strežnik PRVIKRAT prenehal odzivati. Na primer:' . 'Obvestilo boste dobili samo, ko se bo strežnik PRVIKRAT prenehal odzivati. Na primer:'.
'nastavljeno imate preverjanje strežnikov vsakih 15 minut. Strežnik preneha delovati ob 13h in ostane nedelujoč do 18h. ' . 'nastavljeno imate preverjanje strežnikov vsakih 15 minut. Strežnik preneha delovati ob 13h in ostane nedelujoč do 18h. '.
'Dobili boste obvestilo samo ob 13h.<br/>' . 'Dobili boste obvestilo samo ob 13h.<br/>'.
'<br><b>Vedno:</b> ' . '<br><b>Vedno:</b> '.
'Obvestilo boste dobili vedno, ko se izvede skripta za preverjanje in strežnik ne deluje, pa čeprav bo strežnik nedelujoč več ur.', 'Obvestilo boste dobili vedno, ko se izvede skripta za preverjanje in strežnik ne deluje, pa čeprav bo strežnik nedelujoč več ur.',
'alert_type_status' => 'Sprememba statusa', 'alert_type_status' => 'Sprememba statusa',
'alert_type_offline' => 'Nedelujoč', 'alert_type_offline' => 'Nedelujoč',
'alert_type_always' => 'Vedno', 'alert_type_always' => 'Vedno',
'log_status' => 'Beleženje statusa', 'log_status' => 'Beleženje statusa',
'log_status_description' => 'Če je beleženje statusa vključeno, se bodo beležili vsi dogodki povezani s pošiljanjem obvestil.', 'log_status_description' => 'Če je beleženje statusa vključeno, se bodo beležili vsi dogodki povezani s pošiljanjem obvestil.',
'log_email' => 'Beleži e-pošto, ki jo pošilja aplikacija', 'log_email' => 'Beleži e-pošto, ki jo pošilja aplikacija',
'log_sms' => 'Beleži SMS sporočila, ki jih pošilja aplikacija', 'log_sms' => 'Beleži SMS sporočila, ki jih pošilja aplikacija',
'log_pushover' => 'Beleži Pushover sporočila, ki jih pošilja aplikacija', 'log_pushover' => 'Beleži Pushover sporočila, ki jih pošilja aplikacija',
'updated' => 'Nastavitve so bile posodobljene.', 'updated' => 'Nastavitve so bile posodobljene.',
'tab_email' => 'E-pošta', 'tab_email' => 'E-pošta',
'tab_sms' => 'SMS', 'tab_sms' => 'SMS',
'tab_pushover' => 'Pushover', 'tab_pushover' => 'Pushover',
'settings_email' => 'Nastavitve e-pošte', 'settings_email' => 'Nastavitve e-pošte',
'settings_sms' => 'Nastavitve SMS sporočil', 'settings_sms' => 'Nastavitve SMS sporočil',
'settings_pushover' => 'Nastavitve Pushover sporočil', 'settings_pushover' => 'Nastavitve Pushover sporočil',
'settings_notification' => 'Nastavitve obvestil', 'settings_notification' => 'Nastavitve obvestil',
'settings_log' => 'Hramba dnevniških zapisov', 'settings_log' => 'Hramba dnevniških zapisov',
'auto_refresh' => 'Samodejno posodabljanje', 'auto_refresh' => 'Samodejno posodabljanje',
'auto_refresh_servers' => 'auto_refresh_servers' =>
'Samodejno posodabljanje pregleda statusa strežnikov.<br/>' . 'Samodejno posodabljanje pregleda statusa strežnikov.<br/>'.
'<span class="small">' . '<span class="small">'.
'Čas v sekundah. Če je vrednost 0 se stran ne bo samodejno posodabljala.' . 'Čas v sekundah. Če je vrednost 0 se stran ne bo samodejno posodabljala.'.
'</span>', '</span>',
'seconds' => 'sekund', 'seconds' => 'sekund',
'test' => 'Test', 'test' => 'Test',
'test_email' => 'Na naslov, ki ste ga določili v vašem profilu, bo poslano e-sporočilo.', 'test_email' => 'Na naslov, ki ste ga določili v vašem profilu, bo poslano e-sporočilo.',
'test_sms' => 'Na telefonsko številko, ki ste jo določili v vašem profilu, bo poslan SMS.', 'test_sms' => 'Na telefonsko številko, ki ste jo določili v vašem profilu, bo poslan SMS.',
'test_pushover' => 'Na uporabniški ključ/napravo, ki ste ju določili v vašem profilu, bo poslano Pushover sporočilo.', 'test_pushover' => 'Na uporabniški ključ/napravo, ki ste ju določili v vašem profilu, bo poslano Pushover sporočilo.',
'send' => 'Pošlji', 'send' => 'Pošlji',
'test_subject' => 'Test', 'test_subject' => 'Test',
'test_message' => 'Testno sporočilo', 'test_message' => 'Testno sporočilo',
'email_sent' => 'E-pošta poslana', 'email_sent' => 'E-pošta poslana',
'email_error' => 'Napaka pri pošiljanju e-pošte', 'email_error' => 'Napaka pri pošiljanju e-pošte',
'sms_sent' => 'SMS sporočilo poslano', 'sms_sent' => 'SMS sporočilo poslano',
'sms_error' => 'Napaka pri pošiljanju SMS sporočila. %s', 'sms_error' => 'Napaka pri pošiljanju SMS sporočila. %s',
'sms_error_nomobile' => 'Ni mogoče poslati testnega SMS sporočila: v vašem profilu ni vpisana veljavna telefonska številka.', 'sms_error_nomobile' => 'Ni mogoče poslati testnega SMS sporočila: v vašem profilu ni vpisana veljavna telefonska številka.',
'pushover_sent' => 'Pushover obvestilo poslano', 'pushover_sent' => 'Pushover obvestilo poslano',
'pushover_error' => 'Napaka pri pošiljanju Pushover sporočila: %s', 'pushover_error' => 'Napaka pri pošiljanju Pushover sporočila: %s',
'pushover_error_noapp' => 'Ni mogoče poslati testnega sporočila: med globalnimi nastavitvami ne najdem Pushover API žetona.', 'pushover_error_noapp' => 'Ni mogoče poslati testnega sporočila: med globalnimi nastavitvami ne najdem Pushover API žetona.',
'pushover_error_nokey' => 'Ni mogoče poslati testnega sporočila: med vašimi nastavitvami ne najdem Pushover ključa.', 'pushover_error_nokey' => 'Ni mogoče poslati testnega sporočila: med vašimi nastavitvami ne najdem Pushover ključa.',
'log_retention_period' => 'Čas hrambe podatov', 'log_retention_period' => 'Čas hrambe podatov',
'log_retention_period_description' => 'Število dni, ko naj se hranijo podatki o obvestilih in statusu strežnikov. Če želite podatke hraniti trajno, vnesite 0.', 'log_retention_period_description' => 'Število dni, ko naj se hranijo podatki o obvestilih in statusu strežnikov. Če želite podatke hraniti trajno, vnesite 0.',
'log_retention_days' => 'dni', 'log_retention_days' => 'dni',
), ),
// for newlines in the email messages use <br/> // for newlines in the email messages use <br/>
'notifications' => array( 'notifications' => array(
'off_sms' => 'Streznik \'%LABEL%\' NE deluje: IP=%IP%, vrata=%PORT%. Napaka=%ERROR%', 'off_sms' => 'Streznik \'%LABEL%\' NE deluje: IP=%IP%, vrata=%PORT%. Napaka=%ERROR%',
'off_email_subject' => 'POMEMBNO: Strežnik \'%LABEL%\' NE deluje', 'off_email_subject' => 'POMEMBNO: Strežnik \'%LABEL%\' NE deluje',
'off_email_body' => "Pri povezovanju na streznik je prislo do napake:<br/><br/>Streznik: %LABEL%<br/>IP: %IP%<br/>vrata: %PORT%<br/>Napaka: %ERROR%<br/>Datum: %DATE%", 'off_email_body' => "Pri povezovanju na streznik je prislo do napake:<br/><br/>Streznik: %LABEL%<br/>IP: %IP%<br/>vrata: %PORT%<br/>Napaka: %ERROR%<br/>Datum: %DATE%",
'off_pushover_title' => 'Streznik \'%LABEL%\' NE deluje', 'off_pushover_title' => 'Streznik \'%LABEL%\' NE deluje',
'off_pushover_message' => "Ni se mogoče povezati na naslednji streznik:<br/><br/>Streznik: %LABEL%<br/>IP: %IP%<br/>Vrata: %PORT%<br/>Error: %ERROR%<br/>Datum: %DATE%", 'off_pushover_message' => "Ni se mogoče povezati na naslednji streznik:<br/><br/>Streznik: %LABEL%<br/>IP: %IP%<br/>Vrata: %PORT%<br/>Error: %ERROR%<br/>Datum: %DATE%",
'on_sms' => 'Streznik \'%LABEL%\' deluje: IP=%IP%, vrata=%PORT%', 'on_sms' => 'Streznik \'%LABEL%\' deluje: IP=%IP%, vrata=%PORT%',
'on_email_subject' => 'OBVESTILO: Streznik \'%LABEL%\' ponovno deluje', 'on_email_subject' => 'OBVESTILO: Streznik \'%LABEL%\' ponovno deluje',
'on_email_body' => "Streznik '%LABEL%' ponovno deluje:<br/><br/>Strežnik: %LABEL%<br/>IP: %IP%<br/>Vrata: %PORT%<br/>Datum: %DATE%", 'on_email_body' => "Streznik '%LABEL%' ponovno deluje:<br/><br/>Strežnik: %LABEL%<br/>IP: %IP%<br/>Vrata: %PORT%<br/>Datum: %DATE%",
'on_pushover_title' => 'Streznik \'%LABEL%\' deluje', 'on_pushover_title' => 'Streznik \'%LABEL%\' deluje',
'on_pushover_message' => 'Streznik \'%LABEL%\' ponovno deluje:<br/><br/>Server: %LABEL%<br/>IP: %IP%<br/>Vrata: %PORT%<br/>Datum: %DATE%', 'on_pushover_message' => 'Streznik \'%LABEL%\' ponovno deluje:<br/><br/>Server: %LABEL%<br/>IP: %IP%<br/>Vrata: %PORT%<br/>Datum: %DATE%',
), ),
'login' => array( 'login' => array(
'welcome_usermenu' => 'Pozdravljeni, %user_name%', 'welcome_usermenu' => 'Pozdravljeni, %user_name%',
'title_sign_in' => 'Prosimo, prijavite se', 'title_sign_in' => 'Prosimo, prijavite se',
'title_forgot' => 'Ali ste pozabili geslo?', 'title_forgot' => 'Ali ste pozabili geslo?',
'title_reset' => 'Ponastavitev gesla', 'title_reset' => 'Ponastavitev gesla',
'submit' => 'Pošlji', 'submit' => 'Pošlji',
'remember_me' => 'Zapomni si me', 'remember_me' => 'Zapomni si me',
'login' => 'Prijava', 'login' => 'Prijava',
'logout' => 'Odjava', 'logout' => 'Odjava',
'username' => 'Uporabniško ime', 'username' => 'Uporabniško ime',
'password' => 'Geslo', 'password' => 'Geslo',
'password_repeat' => 'Geslo (ponovno)', 'password_repeat' => 'Geslo (ponovno)',
'password_forgot' => 'Pozabljeno geslo?', 'password_forgot' => 'Pozabljeno geslo?',
'password_reset' => 'Ponastavitev gesla', 'password_reset' => 'Ponastavitev gesla',
'password_reset_email_subject' => 'Ponastavite svoje geslo za PHP Server Monitor', 'password_reset_email_subject' => 'Ponastavite svoje geslo za PHP Server Monitor',
'password_reset_email_body' => 'Za ponastavitev gesla uporabite spodnjo povezavo. Pomembno: povezava poteče v 1 uri.<br/><br/>%link%', 'password_reset_email_body' => 'Za ponastavitev gesla uporabite spodnjo povezavo. Pomembno: povezava poteče v 1 uri.<br/><br/>%link%',
'error_user_incorrect' => 'Vpisanega uporabniškega imena ne najdem.', 'error_user_incorrect' => 'Vpisanega uporabniškega imena ne najdem.',
'error_login_incorrect' => 'Podatki so napačni.', 'error_login_incorrect' => 'Podatki so napačni.',
'error_login_passwords_nomatch' => 'Vneseno geslo ni pravilno.', 'error_login_passwords_nomatch' => 'Vneseno geslo ni pravilno.',
'error_reset_invalid_link' => 'Povezava za ponastavitev gesla, ki ste jo vnesli, ni pravilna.', 'error_reset_invalid_link' => 'Povezava za ponastavitev gesla, ki ste jo vnesli, ni pravilna.',
'success_password_forgot' => 'Poslano vam je bilo sporočilo z navodili za ponastavitev vašega gesla.', 'success_password_forgot' => 'Poslano vam je bilo sporočilo z navodili za ponastavitev vašega gesla.',
'success_password_reset' => 'Vaše geslo je bilo uspešno ponastavljeno. Prijavite se prosim.', 'success_password_reset' => 'Vaše geslo je bilo uspešno ponastavljeno. Prijavite se prosim.',
), ),
'error' => array( 'error' => array(
'401_unauthorized' => 'Nepooblaščen dostop', '401_unauthorized' => 'Nepooblaščen dostop',
'401_unauthorized_description' => 'Nimate dovoljenja za ogled te strani.', '401_unauthorized_description' => 'Nimate dovoljenja za ogled te strani.',
), ),
); );

View File

@ -214,14 +214,14 @@ $sm_lang = array(
'pushover_api_token' => 'Pushover App API Token', 'pushover_api_token' => 'Pushover App API Token',
'pushover_api_token_description' => 'Innan du kan använda Pushover behöver du <a href="%1$s" target="_blank">registrera en App</a> på deras webbsida och skriva in App API Token här.', 'pushover_api_token_description' => 'Innan du kan använda Pushover behöver du <a href="%1$s" target="_blank">registrera en App</a> på deras webbsida och skriva in App API Token här.',
'alert_type' => 'Välj när du vill bli meddelad.', 'alert_type' => 'Välj när du vill bli meddelad.',
'alert_type_description' => '<b>Statusförändring:</b> '. 'alert_type_description' => '<b>Statusförändring:</b> '.
'Du får ett meddelande när status ändras. Så från online -> offline eller offline -> online.<br/>'. 'Du får ett meddelande när status ändras. Så från online -> offline eller offline -> online.<br/>'.
'<br /><b>Offline:</b> '. '<br /><b>Offline:</b> '.
'Du får ett meddelande när en server går offline *FÖR FÖRSTA GÅNGEN* Exempelvis, '. 'Du får ett meddelande när en server går offline *FÖR FÖRSTA GÅNGEN* Exempelvis, '.
'ditt cronjob körs var 15 minut och din server går ned kl 1 och är nere till kl 6. '. 'ditt cronjob körs var 15 minut och din server går ned kl 1 och är nere till kl 6. '.
'Du kommer få 1 meddelande kl 1 och inga mer.<br/>'. 'Du kommer få 1 meddelande kl 1 och inga mer.<br/>'.
'<br><b>Alltid:</b> '. '<br><b>Alltid:</b> '.
'Du kommer få ett meddelande varje gång kontrollen görs, även om servern har varit offline under en längre tid.', 'Du kommer få ett meddelande varje gång kontrollen görs, även om servern har varit offline under en längre tid.',
'alert_type_status' => 'Statusförändring', 'alert_type_status' => 'Statusförändring',
'alert_type_offline' => 'Offline', 'alert_type_offline' => 'Offline',
'alert_type_always' => 'Alltid', 'alert_type_always' => 'Alltid',

View File

@ -26,40 +26,40 @@
**/ **/
$sm_lang = array( $sm_lang = array(
'name' => 'Türkçe - Turkish', 'name' => 'Türkçe - Turkish',
'locale' => array('tr_TR.UTF-8', 'tr_TR', 'turkish', 'turkish-tr'), 'locale' => array('tr_TR.UTF-8', 'tr_TR', 'turkish', 'turkish-tr'),
'locale_tag' => 'tr', 'locale_tag' => 'tr',
'locale_dir' => 'ltr', 'locale_dir' => 'ltr',
'system' => array( 'system' => array(
'title' => 'Server Monitor', 'title' => 'Server Monitor',
'install' => 'Yükle', 'install' => 'Yükle',
'action' => 'Aksiyon', 'action' => 'Aksiyon',
'save' => 'Kaydet', 'save' => 'Kaydet',
'edit' => 'Düzenle', 'edit' => 'Düzenle',
'delete' => 'Sil', 'delete' => 'Sil',
'date' => 'Tarih', 'date' => 'Tarih',
'message' => 'Mesaj', 'message' => 'Mesaj',
'yes' => 'Evet', 'yes' => 'Evet',
'no' => 'Hayır', 'no' => 'Hayır',
'insert' => 'Ekle', 'insert' => 'Ekle',
'add_new' => 'Yeni ekle', 'add_new' => 'Yeni ekle',
'update_available' => '({version}) sürümü şu anda <a href="http://www.phpservermonitor.org" target="_blank">http://www.phpservermonitor.org</a> adresindedir.', 'update_available' => '({version}) sürümü şu anda <a href="http://www.phpservermonitor.org" target="_blank">http://www.phpservermonitor.org</a> adresindedir.',
'back_to_top' => 'Başa Dön', 'back_to_top' => 'Başa Dön',
'go_back' => 'Geri Git', 'go_back' => 'Geri Git',
'ok' => 'Tamam', 'ok' => 'Tamam',
'cancel' => 'İptal', 'cancel' => 'İptal',
// date/time format according the strftime php function format parameter http://php.net/manual/function.strftime.php // date/time format according the strftime php function format parameter http://php.net/manual/function.strftime.php
'short_day_format' => '%B %e', 'short_day_format' => '%B %e',
'long_day_format' => '%B %e, %Y', 'long_day_format' => '%B %e, %Y',
'yesterday_format' => 'Yesterday at %k:%M', 'yesterday_format' => 'Yesterday at %k:%M',
'other_day_format' => '%A at %k:%M', 'other_day_format' => '%A at %k:%M',
'never' => 'Hiç', 'never' => 'Hiç',
'hours_ago' => '%d saat önce', 'hours_ago' => '%d saat önce',
'an_hour_ago' => 'yaklaşık bir saat önce', 'an_hour_ago' => 'yaklaşık bir saat önce',
'minutes_ago' => '%d dakika önce', 'minutes_ago' => '%d dakika önce',
'a_minute_ago' => 'yaklaşık bir dakika önce', 'a_minute_ago' => 'yaklaşık bir dakika önce',
'seconds_ago' => '%d saniye önce', 'seconds_ago' => '%d saniye önce',
'a_second_ago' => 'bir saniye önce', 'a_second_ago' => 'bir saniye önce',
'year' => 'year', 'year' => 'year',
'years' => 'years', 'years' => 'years',
'month' => 'month', 'month' => 'month',
@ -72,238 +72,238 @@ $sm_lang = array(
'minutes' => 'minutes', 'minutes' => 'minutes',
'second' => 'second', 'second' => 'second',
'seconds' => 'seconds', 'seconds' => 'seconds',
), ),
'menu' => array( 'menu' => array(
'config' => 'Ayarlar', 'config' => 'Ayarlar',
'server' => 'Sunucular', 'server' => 'Sunucular',
'server_log' => 'Log', 'server_log' => 'Log',
'server_status' => 'Durum', 'server_status' => 'Durum',
'server_update' => 'Güncelle', 'server_update' => 'Güncelle',
'user' => 'Kullanıcılar', 'user' => 'Kullanıcılar',
'help' => 'Yardım', 'help' => 'Yardım',
), ),
'users' => array( 'users' => array(
'user' => 'Kullanıcı', 'user' => 'Kullanıcı',
'name' => 'İsim', 'name' => 'İsim',
'user_name' => 'Kullanıcı adı', 'user_name' => 'Kullanıcı adı',
'password' => 'Şifre', 'password' => 'Şifre',
'password_repeat' => 'Şifre tekrarı', 'password_repeat' => 'Şifre tekrarı',
'password_leave_blank' => 'Değiştirmemek için boş bırakın', 'password_leave_blank' => 'Değiştirmemek için boş bırakın',
'level' => 'Seviye', 'level' => 'Seviye',
'level_10' => 'Yönetici', 'level_10' => 'Yönetici',
'level_20' => 'Kullanıcı', 'level_20' => 'Kullanıcı',
'level_description' => '<b>Yöneticiler</b> tüm yetkilere sahiptir: Onlar sunucuları, kullanıcıları yönetebilir genel ayarlamaları düzenleyebilirler.<br/> <b>Kullanıcılar</b> sadece görüntüleyebilir ve onlara atanmış sunucu güncelleyicileri çalıştırabilirler.', 'level_description' => '<b>Yöneticiler</b> tüm yetkilere sahiptir: Onlar sunucuları, kullanıcıları yönetebilir genel ayarlamaları düzenleyebilirler.<br/> <b>Kullanıcılar</b> sadece görüntüleyebilir ve onlara atanmış sunucu güncelleyicileri çalıştırabilirler.',
'mobile' => 'Mobil', 'mobile' => 'Mobil',
'email' => 'E-posta', 'email' => 'E-posta',
'pushover' => 'Pushover', 'pushover' => 'Pushover',
'pushover_description' => 'Pushover gerçek zamanlı bildirim alabilmek için bir servistir. Daha fazla bilgi için <a href="https://pushover.net/">sitesine</a> bakabilirsiniz.', 'pushover_description' => 'Pushover gerçek zamanlı bildirim alabilmek için bir servistir. Daha fazla bilgi için <a href="https://pushover.net/">sitesine</a> bakabilirsiniz.',
'pushover_key' => 'Pushover Anahtarı', 'pushover_key' => 'Pushover Anahtarı',
'pushover_device' => 'Pushover Aracı', 'pushover_device' => 'Pushover Aracı',
'pushover_device_description' => 'Mesajın gönderileceği cihazın adı. Tüm cihazlara göndermek için boş bırakın.', 'pushover_device_description' => 'Mesajın gönderileceği cihazın adı. Tüm cihazlara göndermek için boş bırakın.',
'delete_title' => 'Kullanıcıyı Sil', 'delete_title' => 'Kullanıcıyı Sil',
'delete_message' => '\'%1\' kullanıcısını silmek istediğinize emin misiniz?', 'delete_message' => '\'%1\' kullanıcısını silmek istediğinize emin misiniz?',
'deleted' => 'Kullanıcı silindi.', 'deleted' => 'Kullanıcı silindi.',
'updated' => 'Kullanıcı güncellendi.', 'updated' => 'Kullanıcı güncellendi.',
'inserted' => 'Kullanıcı eklendi.', 'inserted' => 'Kullanıcı eklendi.',
'profile' => 'Profil', 'profile' => 'Profil',
'profile_updated' => 'Profiliniz güncellendi.', 'profile_updated' => 'Profiliniz güncellendi.',
'error_user_name_bad_length' => 'Kullanıcı adları en az 2 ve en fazla 64 karakter uzunluğunda olmalıdır.', 'error_user_name_bad_length' => 'Kullanıcı adları en az 2 ve en fazla 64 karakter uzunluğunda olmalıdır.',
'error_user_name_invalid' => 'Kullanıcı adları sadece harf (a-z, A-Z), sayı (0-9), noktalar (.) and alttan çizgi (_) karakterlerini içerebilir.', 'error_user_name_invalid' => 'Kullanıcı adları sadece harf (a-z, A-Z), sayı (0-9), noktalar (.) and alttan çizgi (_) karakterlerini içerebilir.',
'error_user_name_exists' => 'Bu kullanıcı adı daha önce alınmış.', 'error_user_name_exists' => 'Bu kullanıcı adı daha önce alınmış.',
'error_user_email_bad_length' => 'E-posta adresi en az 5 ve en fazla 255 karakter uzunluğunda olmalıdır.', 'error_user_email_bad_length' => 'E-posta adresi en az 5 ve en fazla 255 karakter uzunluğunda olmalıdır.',
'error_user_email_invalid' => 'Geçersiz e-posta adresi.', 'error_user_email_invalid' => 'Geçersiz e-posta adresi.',
'error_user_level_invalid' => 'Verilen kullanıcı seviyesi geçersiz.', 'error_user_level_invalid' => 'Verilen kullanıcı seviyesi geçersiz.',
'error_user_no_match' => 'Kullanıcı veritabanında bulunamadı.', 'error_user_no_match' => 'Kullanıcı veritabanında bulunamadı.',
'error_user_password_invalid' => 'Geçersiz bir şifre girdiniz.', 'error_user_password_invalid' => 'Geçersiz bir şifre girdiniz.',
'error_user_password_no_match' => 'Şifreler birbiri ile eşleşmedi.', 'error_user_password_no_match' => 'Şifreler birbiri ile eşleşmedi.',
), ),
'log' => array( 'log' => array(
'title' => 'Log Girdileri', 'title' => 'Log Girdileri',
'type' => 'Tip', 'type' => 'Tip',
'status' => 'Durum', 'status' => 'Durum',
'email' => 'E-posta', 'email' => 'E-posta',
'sms' => 'SMS', 'sms' => 'SMS',
'pushover' => 'Pushover', 'pushover' => 'Pushover',
'no_logs' => 'Kayıt yok.', 'no_logs' => 'Kayıt yok.',
'clear' => 'Günlüğü temizle', 'clear' => 'Günlüğü temizle',
'delete_title' => 'Günlüğü temizle', 'delete_title' => 'Günlüğü temizle',
'delete_message' => 'Tüm günlükleri silmek istediğinizden emin misiniz?', 'delete_message' => 'Tüm günlükleri silmek istediğinizden emin misiniz?',
), ),
'servers' => array( 'servers' => array(
'server' => 'Sunucu', 'server' => 'Sunucu',
'status' => 'Durum', 'status' => 'Durum',
'label' => 'Etiket', 'label' => 'Etiket',
'domain' => 'Domain/IP', 'domain' => 'Domain/IP',
'timeout' => 'Zaman Aşımı', 'timeout' => 'Zaman Aşımı',
'timeout_description' => 'Sunucunun cevap vermesini beklenecek saniye.', 'timeout_description' => 'Sunucunun cevap vermesini beklenecek saniye.',
'port' => 'Port', 'port' => 'Port',
'type' => 'Tip', 'type' => 'Tip',
'type_website' => 'Website', 'type_website' => 'Website',
'type_service' => 'Servis', 'type_service' => 'Servis',
'pattern' => 'String/Pattern ara', 'pattern' => 'String/Pattern ara',
'pattern_description' => 'Bu pattern web sitenizde bulunamaz ise, sunucu offline olarak işaretlenecek. Regular expression\'a izin verilmiştir.', 'pattern_description' => 'Bu pattern web sitenizde bulunamaz ise, sunucu offline olarak işaretlenecek. Regular expression\'a izin verilmiştir.',
'last_check' => 'Son kontrol', 'last_check' => 'Son kontrol',
'last_online' => 'Son çevrimiçi zamanı', 'last_online' => 'Son çevrimiçi zamanı',
'last_offline' => 'Last offline', 'last_offline' => 'Last offline',
'monitoring' => 'Monitoring', 'monitoring' => 'Monitoring',
'no_monitoring' => 'No monitoring', 'no_monitoring' => 'No monitoring',
'email' => 'E-posta', 'email' => 'E-posta',
'send_email' => 'E-posta Gönder', 'send_email' => 'E-posta Gönder',
'sms' => 'SMS', 'sms' => 'SMS',
'send_sms' => 'SMS Gönder', 'send_sms' => 'SMS Gönder',
'pushover' => 'Pushover', 'pushover' => 'Pushover',
'users' => 'Kullanıcılar', 'users' => 'Kullanıcılar',
'delete_title' => 'Sunucu Sil', 'delete_title' => 'Sunucu Sil',
'delete_message' => '\'%1\' sunucusunu silmek istediğinize emin misiniz?', 'delete_message' => '\'%1\' sunucusunu silmek istediğinize emin misiniz?',
'deleted' => 'Sunucu silindi.', 'deleted' => 'Sunucu silindi.',
'updated' => 'Sunucu güncellendi.', 'updated' => 'Sunucu güncellendi.',
'inserted' => 'Sunucu eklendi.', 'inserted' => 'Sunucu eklendi.',
'latency' => 'Gecikme', 'latency' => 'Gecikme',
'latency_max' => 'Gecikme (Azami)', 'latency_max' => 'Gecikme (Azami)',
'latency_min' => 'Gecikme (Asgari)', 'latency_min' => 'Gecikme (Asgari)',
'latency_avg' => 'Gecikme (Ortalama)', 'latency_avg' => 'Gecikme (Ortalama)',
'uptime' => 'Uptime', 'uptime' => 'Uptime',
'year' => 'Yıl', 'year' => 'Yıl',
'month' => 'Ay', 'month' => 'Ay',
'week' => 'Hafta', 'week' => 'Hafta',
'day' => 'Gün', 'day' => 'Gün',
'hour' => 'Saat', 'hour' => 'Saat',
'warning_threshold' => 'Uyarı Eşiği', 'warning_threshold' => 'Uyarı Eşiği',
'warning_threshold_description' => 'Number of failed checks required before it is marked offline.', 'warning_threshold_description' => 'Number of failed checks required before it is marked offline.',
'chart_last_week' => 'Geçen Hafta', 'chart_last_week' => 'Geçen Hafta',
'chart_history' => 'Geçmiş', 'chart_history' => 'Geçmiş',
// Charts date format according jqPlot date format http://www.jqplot.com/docs/files/plugins/jqplot-dateAxisRenderer-js.html // Charts date format according jqPlot date format http://www.jqplot.com/docs/files/plugins/jqplot-dateAxisRenderer-js.html
'chart_day_format' => '%Y-%m-%d', 'chart_day_format' => '%Y-%m-%d',
'chart_long_date_format' => '%Y-%m-%d %H:%M:%S', 'chart_long_date_format' => '%Y-%m-%d %H:%M:%S',
'chart_short_date_format' => '%m/%d %H:%M', 'chart_short_date_format' => '%m/%d %H:%M',
'chart_short_time_format' => '%H:%M', 'chart_short_time_format' => '%H:%M',
'warning_notifications_disabled_sms' => 'SMS bildirimi devre dışı.', 'warning_notifications_disabled_sms' => 'SMS bildirimi devre dışı.',
'warning_notifications_disabled_email' => 'E-posta bildirimi devre dışı.', 'warning_notifications_disabled_email' => 'E-posta bildirimi devre dışı.',
'warning_notifications_disabled_pushover' => 'Pushover bildirimi devre dışı.', 'warning_notifications_disabled_pushover' => 'Pushover bildirimi devre dışı.',
'error_server_no_match' => 'Sunucu bulunamadı.', 'error_server_no_match' => 'Sunucu bulunamadı.',
'error_server_label_bad_length' => 'Etiken en az 1 ve en çok 255 karakter olmalıdır.', 'error_server_label_bad_length' => 'Etiken en az 1 ve en çok 255 karakter olmalıdır.',
'error_server_ip_bad_length' => 'Alan adı / IP en az 1 ve en fazla 255 karakter olmalıdır.', 'error_server_ip_bad_length' => 'Alan adı / IP en az 1 ve en fazla 255 karakter olmalıdır.',
'error_server_ip_bad_service' => 'IP adresi geçerli değil.', 'error_server_ip_bad_service' => 'IP adresi geçerli değil.',
'error_server_ip_bad_website' => 'Site adresi geçerli değil.', 'error_server_ip_bad_website' => 'Site adresi geçerli değil.',
'error_server_type_invalid' => 'Seçilen sunucu tipi geçerli değil.', 'error_server_type_invalid' => 'Seçilen sunucu tipi geçerli değil.',
'error_server_warning_threshold_invalid' => 'Hata eşiği 0\'dan büyük bir tam sayı olmalıdır.', 'error_server_warning_threshold_invalid' => 'Hata eşiği 0\'dan büyük bir tam sayı olmalıdır.',
), ),
'config' => array( 'config' => array(
'general' => 'Genel', 'general' => 'Genel',
'language' => 'Dil', 'language' => 'Dil',
'show_update' => 'Güncellemeleri kontrol et?', 'show_update' => 'Güncellemeleri kontrol et?',
'email_status' => 'E-posta gönderimine izin ver', 'email_status' => 'E-posta gönderimine izin ver',
'email_from_email' => 'Gönderilen e-posta adresi', 'email_from_email' => 'Gönderilen e-posta adresi',
'email_from_name' => 'E-posta adresinde görünecek isim', 'email_from_name' => 'E-posta adresinde görünecek isim',
'email_smtp' => 'SMTP\'yi aktif et', 'email_smtp' => 'SMTP\'yi aktif et',
'email_smtp_host' => 'SMTP sunucusu', 'email_smtp_host' => 'SMTP sunucusu',
'email_smtp_port' => 'SMTP port', 'email_smtp_port' => 'SMTP port',
'email_smtp_security' => 'SMTP security', 'email_smtp_security' => 'SMTP security',
'email_smtp_security_none' => 'None', 'email_smtp_security_none' => 'None',
'email_smtp_username' => 'SMTP kullanıcı adı', 'email_smtp_username' => 'SMTP kullanıcı adı',
'email_smtp_password' => 'SMTP şifre', 'email_smtp_password' => 'SMTP şifre',
'email_smtp_noauth' => 'Doğrulama yapmamak için boş bırakın', 'email_smtp_noauth' => 'Doğrulama yapmamak için boş bırakın',
'sms_status' => 'SMS mesaj göndermeye izin ver', 'sms_status' => 'SMS mesaj göndermeye izin ver',
'sms_gateway' => 'Mesaj göndermek için servisi seçin', 'sms_gateway' => 'Mesaj göndermek için servisi seçin',
'sms_gateway_username' => 'Servis kullanıcı adı', 'sms_gateway_username' => 'Servis kullanıcı adı',
'sms_gateway_password' => 'Servis şifresi', 'sms_gateway_password' => 'Servis şifresi',
'sms_from' => 'Gönderen numarası', 'sms_from' => 'Gönderen numarası',
'pushover_status' => 'Pushover mesaj gönderimine izin ver', 'pushover_status' => 'Pushover mesaj gönderimine izin ver',
'pushover_description' => 'Pushover gerçek zamanlı bildirim alabilmek için bir servistir. Daha fazla bilgi için <a href="https://pushover.net/">sitesine</a> bakabilirsiniz.', 'pushover_description' => 'Pushover gerçek zamanlı bildirim alabilmek için bir servistir. Daha fazla bilgi için <a href="https://pushover.net/">sitesine</a> bakabilirsiniz.',
'pushover_clone_app' => 'Pushover uygulaması oluşturmak için buraya tıklayınız.', 'pushover_clone_app' => 'Pushover uygulaması oluşturmak için buraya tıklayınız.',
'pushover_api_token' => 'Pushover Uygulaması API Token Bilgisi', 'pushover_api_token' => 'Pushover Uygulaması API Token Bilgisi',
'pushover_api_token_description' => 'Pushover kullanmadan önce, <a href="%1$s" target="_blank">Pushover sitesi üzerinden</a> bir uygulama oluşturmalısınız ve API Token bilgilerini buraya yazmalısınız.', 'pushover_api_token_description' => 'Pushover kullanmadan önce, <a href="%1$s" target="_blank">Pushover sitesi üzerinden</a> bir uygulama oluşturmalısınız ve API Token bilgilerini buraya yazmalısınız.',
'alert_type' => 'Ne zaman uyarılmak istediğinizi seçin.', 'alert_type' => 'Ne zaman uyarılmak istediğinizi seçin.',
'alert_type_description' => '<b>Durum değişikliği:</b> '. 'alert_type_description' => '<b>Durum değişikliği:</b> '.
'Sunucu durumu değişiklik durumunda bildirim alacaksınız. Sunucu çevrimiçi durumundan çevrimdışı durumuna veya çevrimdışı durumundan çevrim için durumuna geçtiğinde.<br/>'. 'Sunucu durumu değişiklik durumunda bildirim alacaksınız. Sunucu çevrimiçi durumundan çevrimdışı durumuna veya çevrimdışı durumundan çevrim için durumuna geçtiğinde.<br/>'.
'<br /><b>Çevrimdışı:</b> '. '<br /><b>Çevrimdışı:</b> '.
'Sunucu çevrim dışı duruma geçtiğinde bildirim alırsınız. *SADECE İLK GEÇTİĞİNDE*. Örneğin, '. 'Sunucu çevrim dışı duruma geçtiğinde bildirim alırsınız. *SADECE İLK GEÇTİĞİNDE*. Örneğin, '.
'Cronjob her 15 dakikada bir çalışıyorsa ve sunucu 1\'de gidip 6\'ya kadar kapalı kalırsa. '. 'Cronjob her 15 dakikada bir çalışıyorsa ve sunucu 1\'de gidip 6\'ya kadar kapalı kalırsa. '.
'Sadece size saat 1\'de bildirim gönderilecektir.<br/>'. 'Sadece size saat 1\'de bildirim gönderilecektir.<br/>'.
'<br><b>Daima:</b> '. '<br><b>Daima:</b> '.
'Site çevrimdışı olduğu her zaman size bildirim gönderilecektir, site saatler boyunca kapalı kalse bile.', 'Site çevrimdışı olduğu her zaman size bildirim gönderilecektir, site saatler boyunca kapalı kalse bile.',
'alert_type_status' => 'Durum değişikliği', 'alert_type_status' => 'Durum değişikliği',
'alert_type_offline' => 'Çevrimdışı', 'alert_type_offline' => 'Çevrimdışı',
'alert_type_always' => 'Daima', 'alert_type_always' => 'Daima',
'log_status' => 'Log durumu', 'log_status' => 'Log durumu',
'log_status_description' => 'Eğer log durumu TRUE olarak işaretlenirse, bildirim ayarlarından geçen her olay log olarak tutulacaktır.', 'log_status_description' => 'Eğer log durumu TRUE olarak işaretlenirse, bildirim ayarlarından geçen her olay log olarak tutulacaktır.',
'log_email' => 'Log e-posta mesajı otomatik gönderilmiştir.', 'log_email' => 'Log e-posta mesajı otomatik gönderilmiştir.',
'log_sms' => 'Log sms mesajı otomatik gönderilmiştir.', 'log_sms' => 'Log sms mesajı otomatik gönderilmiştir.',
'log_pushover' => 'Log pushover mesajı otomatik gönderilmiştir.', 'log_pushover' => 'Log pushover mesajı otomatik gönderilmiştir.',
'updated' => 'Ayarlar güncellendi.', 'updated' => 'Ayarlar güncellendi.',
'tab_email' => 'E-posta', 'tab_email' => 'E-posta',
'tab_sms' => 'SMS', 'tab_sms' => 'SMS',
'tab_pushover' => 'Pushover', 'tab_pushover' => 'Pushover',
'settings_email' => 'E-posta ayarları', 'settings_email' => 'E-posta ayarları',
'settings_sms' => 'Sms mesaj ayarları', 'settings_sms' => 'Sms mesaj ayarları',
'settings_pushover' => 'Pushover ayarları', 'settings_pushover' => 'Pushover ayarları',
'settings_notification' => 'Bildirim ayarları', 'settings_notification' => 'Bildirim ayarları',
'settings_log' => 'Log ayarları', 'settings_log' => 'Log ayarları',
'auto_refresh' => 'Otomatik Yenileme', 'auto_refresh' => 'Otomatik Yenileme',
'auto_refresh_servers' => 'auto_refresh_servers' =>
'Otomatik yenileme sunucu sayfası<br/>'. 'Otomatik yenileme sunucu sayfası<br/>'.
'<span class="small">'. '<span class="small">'.
'Eğer sayfa yenilenmez ise.'. 'Eğer sayfa yenilenmez ise.'.
'</span>', '</span>',
'seconds' => 'saniye', 'seconds' => 'saniye',
'test' => 'Test', 'test' => 'Test',
'test_email' => 'Profilinizde tanımladığınız e-posta adresinize bir e-posta gönderilecek.', 'test_email' => 'Profilinizde tanımladığınız e-posta adresinize bir e-posta gönderilecek.',
'test_sms' => 'Profilinizde tanımladığınız numaranıza bir SMS mesajı gönderilecek.', 'test_sms' => 'Profilinizde tanımladığınız numaranıza bir SMS mesajı gönderilecek.',
'test_pushover' => 'Profilinizde tanımladığını bilgiler üzerinden bir pushover bildirimi gönderilecek.', 'test_pushover' => 'Profilinizde tanımladığını bilgiler üzerinden bir pushover bildirimi gönderilecek.',
'send' => 'Gönder', 'send' => 'Gönder',
'test_subject' => 'Test', 'test_subject' => 'Test',
'test_message' => 'Test mesaj', 'test_message' => 'Test mesaj',
'email_sent' => 'E-posta gönderildi', 'email_sent' => 'E-posta gönderildi',
'email_error' => 'E-posta gönderiminde hata.', 'email_error' => 'E-posta gönderiminde hata.',
'sms_sent' => 'Sms gönderildi', 'sms_sent' => 'Sms gönderildi',
'sms_error' => 'SMS gönderiminde hata. %s', 'sms_error' => 'SMS gönderiminde hata. %s',
'sms_error_nomobile' => 'SMS gönderilemiyor: profilinizde geçerli bir telefon numarası yok.', 'sms_error_nomobile' => 'SMS gönderilemiyor: profilinizde geçerli bir telefon numarası yok.',
'pushover_sent' => 'Pushover bildirimi gönderildi', 'pushover_sent' => 'Pushover bildirimi gönderildi',
'pushover_error' => 'Pushover bildirimi gönderilirken bir hata meydana geldi: %s', 'pushover_error' => 'Pushover bildirimi gönderilirken bir hata meydana geldi: %s',
'pushover_error_noapp' => 'Test için bildirim gönderilemiyor: Pushover Uygulaması API token bilgisi bulunamadı.', 'pushover_error_noapp' => 'Test için bildirim gönderilemiyor: Pushover Uygulaması API token bilgisi bulunamadı.',
'pushover_error_nokey' => 'Test için bildirim gönderilemiyor: Pushover key bilgisi profilinizde bulunamadı.', 'pushover_error_nokey' => 'Test için bildirim gönderilemiyor: Pushover key bilgisi profilinizde bulunamadı.',
'log_retention_period' => 'Log tutma süresi', 'log_retention_period' => 'Log tutma süresi',
'log_retention_period_description' => 'Bildirim loglarının ve sunucunun çalışma zamanlarının arşivinin saklanması için gün sayısı. Logların temizlenmesini kapatmak için 0 giriniz.', 'log_retention_period_description' => 'Bildirim loglarının ve sunucunun çalışma zamanlarının arşivinin saklanması için gün sayısı. Logların temizlenmesini kapatmak için 0 giriniz.',
'log_retention_days' => 'gün', 'log_retention_days' => 'gün',
), ),
// for newlines in the email messages use <br/> // for newlines in the email messages use <br/>
'notifications' => array( 'notifications' => array(
'off_sms' => '\'%LABEL%\' isimli sunucu KAPANDI: ip=%IP%, port=%PORT%. Error=%ERROR%', 'off_sms' => '\'%LABEL%\' isimli sunucu KAPANDI: ip=%IP%, port=%PORT%. Error=%ERROR%',
'off_email_subject' => 'ÖNEMLİ: \'%LABEL%\' isimli sunucu KAPANDI.', 'off_email_subject' => 'ÖNEMLİ: \'%LABEL%\' isimli sunucu KAPANDI.',
'off_email_body' => "Aşağıdaki sunuculara erişim sağlanamıyor:<br/><br/>Sunucu: %LABEL%<br/>IP: %IP%<br/>Port: %PORT%<br/>Hata: %ERROR%<br/>Tarih: %DATE%", 'off_email_body' => "Aşağıdaki sunuculara erişim sağlanamıyor:<br/><br/>Sunucu: %LABEL%<br/>IP: %IP%<br/>Port: %PORT%<br/>Hata: %ERROR%<br/>Tarih: %DATE%",
'off_pushover_title' => '\'%LABEL%\' isimli sunucu KAPANDI.', 'off_pushover_title' => '\'%LABEL%\' isimli sunucu KAPANDI.',
'off_pushover_message' => "Aşağıdaki nuculara erişim sağlanamıyor:<br/><br/>Sunucu: %LABEL%<br/>IP: %IP%<br/>Port: %PORT%<br/>Hata: %ERROR%<br/>Tarih: %DATE%", 'off_pushover_message' => "Aşağıdaki nuculara erişim sağlanamıyor:<br/><br/>Sunucu: %LABEL%<br/>IP: %IP%<br/>Port: %PORT%<br/>Hata: %ERROR%<br/>Tarih: %DATE%",
'on_sms' => '\'%LABEL%\' isimli sunucu YAYINDA: ip=%IP%, port=%PORT%', 'on_sms' => '\'%LABEL%\' isimli sunucu YAYINDA: ip=%IP%, port=%PORT%',
'on_email_subject' => 'ÖNEMLİ:\'%LABEL%\' isimli sunucu YAYINDA.', 'on_email_subject' => 'ÖNEMLİ:\'%LABEL%\' isimli sunucu YAYINDA.',
'on_email_body' => "'%LABEL%' isimli sunucu tekrar yayında:<br/><br/>Sunucu: %LABEL%<br/>IP: %IP%<br/>Port: %PORT%<br/>Tarih: %DATE%", 'on_email_body' => "'%LABEL%' isimli sunucu tekrar yayında:<br/><br/>Sunucu: %LABEL%<br/>IP: %IP%<br/>Port: %PORT%<br/>Tarih: %DATE%",
'on_pushover_title' => '\'%LABEL%\' isimli sunucu YAYINDA', 'on_pushover_title' => '\'%LABEL%\' isimli sunucu YAYINDA',
'on_pushover_message' => '\'%LABEL%\' isimli sunucu tekrar yayında:<br/><br/>Sunucu: %LABEL%<br/>IP: %IP%<br/>Port: %PORT%<br/>Tarih: %DATE%', 'on_pushover_message' => '\'%LABEL%\' isimli sunucu tekrar yayında:<br/><br/>Sunucu: %LABEL%<br/>IP: %IP%<br/>Port: %PORT%<br/>Tarih: %DATE%',
), ),
'login' => array( 'login' => array(
'welcome_usermenu' => 'Hoşgeldin, %user_name%', 'welcome_usermenu' => 'Hoşgeldin, %user_name%',
'title_sign_in' => 'Lütfen giriş yapın', 'title_sign_in' => 'Lütfen giriş yapın',
'title_forgot' => 'Şifreni mi unuttun?', 'title_forgot' => 'Şifreni mi unuttun?',
'title_reset' => 'Şifreni yenile', 'title_reset' => 'Şifreni yenile',
'submit' => 'Gönder', 'submit' => 'Gönder',
'remember_me' => 'Beni hatırla', 'remember_me' => 'Beni hatırla',
'login' => 'Giriş yap', 'login' => 'Giriş yap',
'logout' => ıkış yap', 'logout' => ıkış yap',
'username' => 'Kullanıcı adı', 'username' => 'Kullanıcı adı',
'password' => 'Şifre', 'password' => 'Şifre',
'password_repeat' => 'Şifre tekrarı', 'password_repeat' => 'Şifre tekrarı',
'password_forgot' => 'Şifreni mi unuttun?', 'password_forgot' => 'Şifreni mi unuttun?',
'password_reset' => 'Şifreni yenile', 'password_reset' => 'Şifreni yenile',
'password_reset_email_subject' => 'PHP Server Monitor için şifreni yenile', 'password_reset_email_subject' => 'PHP Server Monitor için şifreni yenile',
'password_reset_email_body' => 'Aşağıdaki bağlantıyı kullanarak şifrenizi güncelleyiniz. Bağlantı 1 saat sonra geçerliliğini kaybedecektir.<br/><br/>%link%', 'password_reset_email_body' => 'Aşağıdaki bağlantıyı kullanarak şifrenizi güncelleyiniz. Bağlantı 1 saat sonra geçerliliğini kaybedecektir.<br/><br/>%link%',
'error_user_incorrect' => 'Kullanıcı adı bulunamadı.', 'error_user_incorrect' => 'Kullanıcı adı bulunamadı.',
'error_login_incorrect' => 'Bilgi yanlış.', 'error_login_incorrect' => 'Bilgi yanlış.',
'error_login_passwords_nomatch' => 'Şifreleriniz uyuşmuyor.', 'error_login_passwords_nomatch' => 'Şifreleriniz uyuşmuyor.',
'error_reset_invalid_link' => 'Sağladığını sıfırlama bağlantısı geçersiz.', 'error_reset_invalid_link' => 'Sağladığını sıfırlama bağlantısı geçersiz.',
'success_password_forgot' => 'Şifrenizi yenilemeniz için gerekli bilgileri içeren bir e-posta gönderildi.', 'success_password_forgot' => 'Şifrenizi yenilemeniz için gerekli bilgileri içeren bir e-posta gönderildi.',
'success_password_reset' => 'Şifreniz başarıyla yenilendi. Şimdi giriş yapın.', 'success_password_reset' => 'Şifreniz başarıyla yenilendi. Şimdi giriş yapın.',
), ),
'error' => array( 'error' => array(
'401_unauthorized' => 'Yetkisiz', '401_unauthorized' => 'Yetkisiz',
'401_unauthorized_description' => 'Bu sayfayı görüntülemek için yetkin yok.', '401_unauthorized_description' => 'Bu sayfayı görüntülemek için yetkin yok.',
), ),
); );

View File

@ -199,14 +199,14 @@ $sm_lang = array(
'pushover_api_token' => 'Pushover App API Token', 'pushover_api_token' => 'Pushover App API Token',
'pushover_api_token_description' => 'Trước khi bạn có thể sử dụng Pushover, bạn cần phải <a href="%1$s" target="_blank">đăng ký một ứng dụng</a> tại trang web của họ và nhập Token App API ở đây.', 'pushover_api_token_description' => 'Trước khi bạn có thể sử dụng Pushover, bạn cần phải <a href="%1$s" target="_blank">đăng ký một ứng dụng</a> tại trang web của họ và nhập Token App API ở đây.',
'alert_type' => 'Chọn khi bạn muốn được thông báo.', 'alert_type' => 'Chọn khi bạn muốn được thông báo.',
'alert_type_description' => '<b>Thay đổi trạng thái:</b> '. 'alert_type_description' => '<b>Thay đổi trạng thái:</b> '.
'Bạn sẽ nhận được thông báo khi một máy chủ có một sự thay đổi trạng thái. Từ online -> offline hoặc offline -> online.<br/>'. 'Bạn sẽ nhận được thông báo khi một máy chủ có một sự thay đổi trạng thái. Từ online -> offline hoặc offline -> online.<br/>'.
'<br /><b>Offline:</b> '. '<br /><b>Offline:</b> '.
'Bạn sẽ nhận được thông báo khi một máy chủ offline *MỘT LẦN DUY NHẤT*. Ví dụ, '. 'Bạn sẽ nhận được thông báo khi một máy chủ offline *MỘT LẦN DUY NHẤT*. Ví dụ, '.
'cronjob của bạn hoạt động mỗi 15 phút và server của bạn down tại 01h00 cho đến 6h00. '. 'cronjob của bạn hoạt động mỗi 15 phút và server của bạn down tại 01h00 cho đến 6h00. '.
'Bạn sẽ nhận được 1 thông báo lúc 01h00 và đó là nó.<br/>'. 'Bạn sẽ nhận được 1 thông báo lúc 01h00 và đó là nó.<br/>'.
'<br><b>Always:</b> '. '<br><b>Always:</b> '.
'Bạn sẽ nhận được thông báo mỗi khi chạy đoạn script và một trang web tắt, ngay cả khi trang web đã được offline trong nhiều giờ.', 'Bạn sẽ nhận được thông báo mỗi khi chạy đoạn script và một trang web tắt, ngay cả khi trang web đã được offline trong nhiều giờ.',
'alert_type_status' => 'Thay đổi trạng thái', 'alert_type_status' => 'Thay đổi trạng thái',
'alert_type_offline' => 'Offline', 'alert_type_offline' => 'Offline',
'alert_type_always' => 'Always', 'alert_type_always' => 'Always',

View File

@ -230,14 +230,14 @@ $sm_lang = array(
'pushover_api_token' => 'Pushover API Token', 'pushover_api_token' => 'Pushover API Token',
'pushover_api_token_description' => '请先 <a href="%1$s" target="_blank">注册Pushover</a> 并获取 Api Token.', 'pushover_api_token_description' => '请先 <a href="%1$s" target="_blank">注册Pushover</a> 并获取 Api Token.',
'alert_type' => '如果想要收到提醒请选中此项.', 'alert_type' => '如果想要收到提醒请选中此项.',
'alert_type_description' => '<b>状态变化:</b> '. 'alert_type_description' => '<b>状态变化:</b> '.
'业务 online -> offline 或 offline -> online 的状态变化将会收到提醒.<br/>'. '业务 online -> offline 或 offline -> online 的状态变化将会收到提醒.<br/>'.
'<br /><b>离线状态:</b> '. '<br /><b>离线状态:</b> '.
'服务器首次发生离线状态将会收到提醒 ,如:'. '服务器首次发生离线状态将会收到提醒 ,如:'.
'cronjob 设定为15分钟执行一次 服务器从1:00-6:00一直处于当状态'. 'cronjob 设定为15分钟执行一次 服务器从1:00-6:00一直处于当状态'.
'那么你将于1:00首次发现脱机时收到一条提醒之后不会重复提醒.<br/>'. '那么你将于1:00首次发现脱机时收到一条提醒之后不会重复提醒.<br/>'.
'<br><b>总是提醒:</b> '. '<br><b>总是提醒:</b> '.
'每次脚本执行或站点离线(即使站点离线很久已提醒过)均发送提醒.', '每次脚本执行或站点离线(即使站点离线很久已提醒过)均发送提醒.',
'alert_type_status' => '状态变化', 'alert_type_status' => '状态变化',
'alert_type_offline' => '离线状态', 'alert_type_offline' => '离线状态',
'alert_type_always' => '总是提醒', 'alert_type_always' => '总是提醒',

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -45,7 +45,7 @@ class LoginController extends AbstractController {
} }
protected function executeLogin() { protected function executeLogin() {
if(isset($_POST['user_name']) && isset($_POST['user_password'])) { if (isset($_POST['user_name']) && isset($_POST['user_password'])) {
$rememberme = (isset($_POST['user_rememberme'])) ? true : false; $rememberme = (isset($_POST['user_rememberme'])) ? true : false;
$result = $this->getUser()->loginWithPostData( $result = $this->getUser()->loginWithPostData(
$_POST['user_name'], $_POST['user_name'],
@ -53,9 +53,9 @@ class LoginController extends AbstractController {
$rememberme $rememberme
); );
if($result) { if ($result) {
// success login, redirect // success login, redirect
header('Location: ' . psm_build_url($_SERVER['QUERY_STRING'])); header('Location: '.psm_build_url($_SERVER['QUERY_STRING']));
trigger_error("Redirect failed.", E_USER_ERROR); trigger_error("Redirect failed.", E_USER_ERROR);
} else { } else {
$this->addMessage(psm_get_lang('login', 'error_login_incorrect'), 'error'); $this->addMessage(psm_get_lang('login', 'error_login_incorrect'), 'error');
@ -82,10 +82,10 @@ class LoginController extends AbstractController {
* @return string * @return string
*/ */
protected function executeForgot() { protected function executeForgot() {
if(isset($_POST['user_name'])) { if (isset($_POST['user_name'])) {
$user = $this->getUser()->getUserByUsername($_POST['user_name']); $user = $this->getUser()->getUserByUsername($_POST['user_name']);
if(!empty($user)) { if (!empty($user)) {
$token = $this->getUser()->generatePasswordResetToken($user->user_id); $token = $this->getUser()->generatePasswordResetToken($user->user_id);
// we have a token, send it along // we have a token, send it along
$this->sendPasswordForgotMail( $this->sendPasswordForgotMail(
@ -118,18 +118,18 @@ class LoginController extends AbstractController {
$user_id = (isset($_GET['user_id'])) ? intval($_GET['user_id']) : 0; $user_id = (isset($_GET['user_id'])) ? intval($_GET['user_id']) : 0;
$token = (isset($_GET['token'])) ? $_GET['token'] : ''; $token = (isset($_GET['token'])) ? $_GET['token'] : '';
if(!$service_user->verifyPasswordResetToken($user_id, $token)) { if (!$service_user->verifyPasswordResetToken($user_id, $token)) {
$this->addMessage(psm_get_lang('login', 'error_reset_invalid_link'), 'error'); $this->addMessage(psm_get_lang('login', 'error_reset_invalid_link'), 'error');
return $this->executeLogin(); return $this->executeLogin();
} }
if(!empty($_POST['user_password_new']) && !empty($_POST['user_password_repeat'])) { if (!empty($_POST['user_password_new']) && !empty($_POST['user_password_repeat'])) {
if($_POST['user_password_new'] !== $_POST['user_password_repeat']) { if ($_POST['user_password_new'] !== $_POST['user_password_repeat']) {
$this->addMessage(psm_get_lang('login', 'error_login_passwords_nomatch'), 'error'); $this->addMessage(psm_get_lang('login', 'error_login_passwords_nomatch'), 'error');
} else { } else {
$result = $service_user->changePassword($user_id, $_POST['user_password_new']); $result = $service_user->changePassword($user_id, $_POST['user_password_new']);
if($result) { if ($result) {
$this->addMessage(psm_get_lang('login', 'success_password_reset'), 'success'); $this->addMessage(psm_get_lang('login', 'success_password_reset'), 'success');
return $this->executeLogin(); return $this->executeLogin();
} else { } else {
@ -151,15 +151,15 @@ class LoginController extends AbstractController {
return $this->twig->render('module/user/login/reset.tpl.html', $tpl_data); return $this->twig->render('module/user/login/reset.tpl.html', $tpl_data);
} }
/** /**
* Sends the password-reset-email. * Sends the password-reset-email.
* @param int $user_id * @param int $user_id
* @param string $user_email * @param string $user_email
* @param string $user_password_reset_hash * @param string $user_password_reset_hash
*/ */
protected function sendPasswordForgotMail($user_id, $user_email, $user_password_reset_hash) { protected function sendPasswordForgotMail($user_id, $user_email, $user_password_reset_hash) {
$mail = psm_build_mail(); $mail = psm_build_mail();
$mail->Subject = psm_get_lang('login' ,'password_reset_email_subject'); $mail->Subject = psm_get_lang('login', 'password_reset_email_subject');
$url = psm_build_url(array( $url = psm_build_url(array(
'action' => 'reset', 'action' => 'reset',
@ -171,7 +171,7 @@ class LoginController extends AbstractController {
$mail->Body = $body; $mail->Body = $body;
$mail->AltBody = str_replace('<br/>', "\n", $body); $mail->AltBody = str_replace('<br/>', "\n", $body);
$mail->AddAddress($user_email); $mail->AddAddress($user_email);
$mail->Send(); $mail->Send();
} }
} }

View File

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

View File

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

View File

@ -36,16 +36,16 @@ class UserEvent extends Event {
protected $user_id_by; protected $user_id_by;
public function __construct($user_id, $user_id_by = null) { public function __construct($user_id, $user_id_by = null) {
$this->user_id = $user_id; $this->user_id = $user_id;
$this->user_id_by = $user_id_by; $this->user_id_by = $user_id_by;
} }
public function getUserId() { public function getUserId() {
return $this->user_id; return $this->user_id;
} }
public function getUserIdBy() { public function getUserIdBy() {
return $this->user_id_by; return $this->user_id_by;
} }
} }

View File

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

View File

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

View File

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

View File

@ -44,11 +44,11 @@ use Symfony\Component\HttpFoundation\Session\SessionInterface;
*/ */
class User { class User {
/** /**
* The database connection * The database connection
* @var \PDO $db_connection * @var \PDO $db_connection
*/ */
protected $db_connection = null; protected $db_connection = null;
/** /**
* Local cache of user data * Local cache of user data
@ -62,11 +62,11 @@ class User {
*/ */
protected $session; protected $session;
/** /**
* Current user id * Current user id
* @var int $user_id * @var int $user_id
*/ */
protected $user_id; protected $user_id;
/** /**
*Current user preferences *Current user preferences
@ -76,55 +76,55 @@ class User {
/** /**
* The user's login status * The user's login status
* @var boolean $user_is_logged_in * @var boolean $user_is_logged_in
*/ */
protected $user_is_logged_in = false; protected $user_is_logged_in = false;
/** /**
* Open a new user service * Open a new user service
* *
* @param \psm\Service\Database $db * @param \psm\Service\Database $db
* @param \Symfony\Component\HttpFoundation\Session\SessionInterface $session if NULL, one will be created * @param \Symfony\Component\HttpFoundation\Session\SessionInterface $session if NULL, one will be created
*/ */
public function __construct(Database $db, SessionInterface $session = null) { public function __construct(Database $db, SessionInterface $session = null) {
$this->db_connection = $db->pdo(); $this->db_connection = $db->pdo();
if(!psm_is_cli()) { if (!psm_is_cli()) {
if($session == null) { if ($session == null) {
$session = new Session(); $session = new Session();
$session->start(); $session->start();
} }
$this->session = $session; $this->session = $session;
if((!defined('PSM_INSTALL') || !PSM_INSTALL)) { if ((!defined('PSM_INSTALL') || !PSM_INSTALL)) {
// check the possible login actions: // check the possible login actions:
// 1. login via session data (happens each time user opens a page on your php project AFTER he has successfully logged in via the login form) // 1. login via session data (happens each time user opens a page on your php project AFTER he has successfully logged in via the login form)
// 2. login via cookie // 2. login via cookie
// if user has an active session on the server // if user has an active session on the server
if(!$this->loginWithSessionData()) { if (!$this->loginWithSessionData()) {
$this->loginWithCookieData(); $this->loginWithCookieData();
} }
} }
} }
} }
/** /**
* Get user by id, or get current user. * Get user by id, or get current user.
* @param int $user_id if null it will attempt current user id * @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 * @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 * @return object|boolean FALSE if user not found, object otherwise
*/ */
public function getUser($user_id = null, $flush = false) { public function getUser($user_id = null, $flush = false) {
if($user_id == null) { if ($user_id == null) {
if(!$this->isUserLoggedIn()) { if (!$this->isUserLoggedIn()) {
return false; return false;
} else { } else {
$user_id = $this->getUserId(); $user_id = $this->getUserId();
} }
} }
if(!isset($this->user_data[$user_id]) || $flush) { if (!isset($this->user_data[$user_id]) || $flush) {
$query_user = $this->db_connection->prepare('SELECT * FROM '.PSM_DB_PREFIX.'users WHERE user_id = :user_id'); $query_user = $this->db_connection->prepare('SELECT * FROM '.PSM_DB_PREFIX.'users WHERE user_id = :user_id');
$query_user->bindValue(':user_id', $user_id, \PDO::PARAM_INT); $query_user->bindValue(':user_id', $user_id, \PDO::PARAM_INT);
$query_user->execute(); $query_user->execute();
@ -134,31 +134,31 @@ class User {
return $this->user_data[$user_id]; return $this->user_data[$user_id];
} }
/** /**
* Search into database for the user data of user_name specified as parameter * Search into database for the user data of user_name specified as parameter
* @return object|boolean user data as an object if existing user * @return object|boolean user data as an object if existing user
*/ */
public function getUserByUsername($user_name) { public function getUserByUsername($user_name) {
// database query, getting all the info of the selected user // database query, getting all the info of the selected user
$query_user = $this->db_connection->prepare('SELECT * FROM '.PSM_DB_PREFIX.'users WHERE user_name = :user_name'); $query_user = $this->db_connection->prepare('SELECT * FROM '.PSM_DB_PREFIX.'users WHERE user_name = :user_name');
$query_user->bindValue(':user_name', $user_name, \PDO::PARAM_STR); $query_user->bindValue(':user_name', $user_name, \PDO::PARAM_STR);
$query_user->execute(); $query_user->execute();
// get result row (as an object) // get result row (as an object)
return $query_user->fetchObject(); return $query_user->fetchObject();
} }
/** /**
* Logs in with SESSION data. * Logs in with SESSION data.
* *
* @return boolean * @return boolean
*/ */
protected function loginWithSessionData() { protected function loginWithSessionData() {
if(!$this->session->has('user_id')) { if (!$this->session->has('user_id')) {
return false; return false;
} }
$user = $this->getUser($this->session->get('user_id')); $user = $this->getUser($this->session->get('user_id'));
if(!empty($user)) { if (!empty($user)) {
$this->setUserLoggedIn($user->user_id); $this->setUserLoggedIn($user->user_id);
return true; return true;
} else { } else {
@ -167,64 +167,64 @@ class User {
$this->doLogout(); $this->doLogout();
return false; return false;
} }
} }
/** /**
* Logs in via the Cookie * Logs in via the Cookie
* @return bool success state of cookie login * @return bool success state of cookie login
*/ */
private function loginWithCookieData() { private function loginWithCookieData() {
if (isset($_COOKIE['rememberme'])) { if (isset($_COOKIE['rememberme'])) {
// extract data from the cookie // extract data from the cookie
list ($user_id, $token, $hash) = explode(':', $_COOKIE['rememberme']); list ($user_id, $token, $hash) = explode(':', $_COOKIE['rememberme']);
// check cookie hash validity // check cookie hash validity
if($hash == hash('sha256', $user_id . ':' . $token . PSM_LOGIN_COOKIE_SECRET_KEY) && !empty($token)) { if ($hash == hash('sha256', $user_id.':'.$token.PSM_LOGIN_COOKIE_SECRET_KEY) && !empty($token)) {
// cookie looks good, try to select corresponding user // cookie looks good, try to select corresponding user
// get real token from database (and all other data) // get real token from database (and all other data)
$user = $this->getUser($user_id); $user = $this->getUser($user_id);
if(!empty($user) && $token === $user->rememberme_token) { if (!empty($user) && $token === $user->rememberme_token) {
$this->setUserLoggedIn($user->user_id, true); $this->setUserLoggedIn($user->user_id, true);
// Cookie token usable only once // Cookie token usable only once
$this->newRememberMeCookie(); $this->newRememberMeCookie();
return true; return true;
} }
} }
// call logout to remove invalid cookie // call logout to remove invalid cookie
$this->doLogout(); $this->doLogout();
} }
return false; return false;
} }
/** /**
* Logs in with the data provided in $_POST, coming from the login form * Logs in with the data provided in $_POST, coming from the login form
* @param string $user_name * @param string $user_name
* @param string $user_password * @param string $user_password
* @param boolean $user_rememberme * @param boolean $user_rememberme
* @return boolean * @return boolean
*/ */
public function loginWithPostData($user_name, $user_password, $user_rememberme = false) { public function loginWithPostData($user_name, $user_password, $user_rememberme = false) {
$user_name = trim($user_name); $user_name = trim($user_name);
$user_password = trim($user_password); $user_password = trim($user_password);
if(empty($user_name) && empty($user_password)) { if (empty($user_name) && empty($user_password)) {
return false; return false;
} }
$user = $this->getUserByUsername($user_name); $user = $this->getUserByUsername($user_name);
// using PHP 5.5's password_verify() function to check if the provided passwords fits to the hash of that user's password // using PHP 5.5's password_verify() function to check if the provided passwords fits to the hash of that user's password
if(!isset($user->user_id)) { if (!isset($user->user_id)) {
password_verify($user_password, 'dummy_call_against_timing'); password_verify($user_password, 'dummy_call_against_timing');
return false; return false;
} else if(!password_verify($user_password, $user->password)) { } else if (!password_verify($user_password, $user->password)) {
return false; return false;
} }
$this->setUserLoggedIn($user->user_id, true); $this->setUserLoggedIn($user->user_id, true);
// if user has check the "remember me" checkbox, then generate token and write cookie // if user has check the "remember me" checkbox, then generate token and write cookie
if($user_rememberme) { if ($user_rememberme) {
$this->newRememberMeCookie(); $this->newRememberMeCookie();
} }
@ -232,14 +232,14 @@ class User {
// DELETE this if-block if you like, it only exists to recalculate users's hashes when you provide a cost factor, // DELETE this if-block if you like, it only exists to recalculate users's hashes when you provide a cost factor,
// by default the script will use a cost factor of 10 and never change it. // by default the script will use a cost factor of 10 and never change it.
// check if the have defined a cost factor in config/hashing.php // check if the have defined a cost factor in config/hashing.php
if(defined('PSM_LOGIN_HASH_COST_FACTOR')) { if (defined('PSM_LOGIN_HASH_COST_FACTOR')) {
// check if the hash needs to be rehashed // check if the hash needs to be rehashed
if(password_needs_rehash($user->password, PASSWORD_DEFAULT, array('cost' => PSM_LOGIN_HASH_COST_FACTOR))) { if (password_needs_rehash($user->password, PASSWORD_DEFAULT, array('cost' => PSM_LOGIN_HASH_COST_FACTOR))) {
$this->changePassword($user->user_id, $user_password); $this->changePassword($user->user_id, $user_password);
} }
} }
return true; return true;
} }
/** /**
* Set the user logged in * Set the user logged in
@ -247,7 +247,7 @@ class User {
* @param boolean $regenerate regenerate session id against session fixation? * @param boolean $regenerate regenerate session id against session fixation?
*/ */
protected function setUserLoggedIn($user_id, $regenerate = false) { protected function setUserLoggedIn($user_id, $regenerate = false) {
if($regenerate) { if ($regenerate) {
$this->session->invalidate(); $this->session->invalidate();
} }
$this->session->set('user_id', $user_id); $this->session->set('user_id', $user_id);
@ -258,72 +258,72 @@ class User {
$this->user_is_logged_in = true; $this->user_is_logged_in = true;
} }
/** /**
* Create all data needed for remember me cookie connection on client and server side * Create all data needed for remember me cookie connection on client and server side
*/ */
protected function newRememberMeCookie() { protected function newRememberMeCookie() {
// generate 64 char random string and store it in current user data // generate 64 char random string and store it in current user data
$random_token_string = hash('sha256', mt_rand()); $random_token_string = hash('sha256', mt_rand());
$sth = $this->db_connection->prepare('UPDATE '.PSM_DB_PREFIX.'users SET rememberme_token = :user_rememberme_token WHERE user_id = :user_id'); $sth = $this->db_connection->prepare('UPDATE '.PSM_DB_PREFIX.'users SET rememberme_token = :user_rememberme_token WHERE user_id = :user_id');
$sth->execute(array(':user_rememberme_token' => $random_token_string, ':user_id' => $this->getUserId())); $sth->execute(array(':user_rememberme_token' => $random_token_string, ':user_id' => $this->getUserId()));
// generate cookie string that consists of userid, randomstring and combined hash of both // generate cookie string that consists of userid, randomstring and combined hash of both
$cookie_string_first_part = $this->getUserId() . ':' . $random_token_string; $cookie_string_first_part = $this->getUserId().':'.$random_token_string;
$cookie_string_hash = hash('sha256', $cookie_string_first_part . PSM_LOGIN_COOKIE_SECRET_KEY); $cookie_string_hash = hash('sha256', $cookie_string_first_part.PSM_LOGIN_COOKIE_SECRET_KEY);
$cookie_string = $cookie_string_first_part . ':' . $cookie_string_hash; $cookie_string = $cookie_string_first_part.':'.$cookie_string_hash;
// set cookie // set cookie
setcookie('rememberme', $cookie_string, time() + PSM_LOGIN_COOKIE_RUNTIME, "/", PSM_LOGIN_COOKIE_DOMAIN); setcookie('rememberme', $cookie_string, time() + PSM_LOGIN_COOKIE_RUNTIME, "/", PSM_LOGIN_COOKIE_DOMAIN);
} }
/** /**
* Delete all data needed for remember me cookie connection on client and server side * Delete all data needed for remember me cookie connection on client and server side
*/ */
protected function deleteRememberMeCookie() { protected function deleteRememberMeCookie() {
// Reset rememberme token // Reset rememberme token
if($this->session->has('user_id')) { if ($this->session->has('user_id')) {
$sth = $this->db_connection->prepare('UPDATE '.PSM_DB_PREFIX.'users SET rememberme_token = NULL WHERE user_id = :user_id'); $sth = $this->db_connection->prepare('UPDATE '.PSM_DB_PREFIX.'users SET rememberme_token = NULL WHERE user_id = :user_id');
$sth->execute(array(':user_id' => $this->session->get('user_id'))); $sth->execute(array(':user_id' => $this->session->get('user_id')));
} }
// set the rememberme-cookie to ten years ago (3600sec * 365 days * 10). // set the rememberme-cookie to ten years ago (3600sec * 365 days * 10).
// that's obivously the best practice to kill a cookie via php // that's obivously the best practice to kill a cookie via php
// @see http://stackoverflow.com/a/686166/1114320 // @see http://stackoverflow.com/a/686166/1114320
setcookie('rememberme', false, time() - (3600 * 3650), '/', PSM_LOGIN_COOKIE_DOMAIN); setcookie('rememberme', false, time() - (3600 * 3650), '/', PSM_LOGIN_COOKIE_DOMAIN);
} }
/** /**
* Perform the logout, resetting the session * Perform the logout, resetting the session
*/ */
public function doLogout() { public function doLogout() {
$this->deleteRememberMeCookie(); $this->deleteRememberMeCookie();
$this->session->clear(); $this->session->clear();
$this->session->invalidate(); $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 * Simply return the current state of the user's login
* @return bool user's login status * @return bool user's login status
*/ */
public function isUserLoggedIn() { public function isUserLoggedIn() {
return $this->user_is_logged_in; 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 * 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 * in the email) and returns it
* @param int $user_id * @param int $user_id
* @return string|boolean FALSE on error, string otherwise * @return string|boolean FALSE on error, string otherwise
*/ */
public function generatePasswordResetToken($user_id) { public function generatePasswordResetToken($user_id) {
$user_id = intval($user_id); $user_id = intval($user_id);
if($user_id == 0) { if ($user_id == 0) {
return false; return false;
} }
// generate timestamp (to see when exactly the user (or an attacker) requested the password reset mail) // generate timestamp (to see when exactly the user (or an attacker) requested the password reset mail)
$temporary_timestamp = time(); $temporary_timestamp = time();
// generate random hash for email password reset verification (40 char string) // generate random hash for email password reset verification (40 char string)
@ -343,47 +343,47 @@ class User {
} else { } else {
return false; return false;
} }
} }
/** /**
* Checks if the verification string in the account verification mail is valid and matches to the user. * 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. * Please note it is valid for 1 hour.
* @param int $user_id * @param int $user_id
* @param string $token * @param string $token
* @return boolean * @return boolean
*/ */
public function verifyPasswordResetToken($user_id, $token) { public function verifyPasswordResetToken($user_id, $token) {
$user_id = intval($user_id); $user_id = intval($user_id);
if(empty($user_id) || empty($token)) { if (empty($user_id) || empty($token)) {
return false; return false;
} }
$user = $this->getUser($user_id); $user = $this->getUser($user_id);
if(isset($user->user_id) && $user->password_reset_hash == $token) { if (isset($user->user_id) && $user->password_reset_hash == $token) {
$runtime = (defined('PSM_LOGIN_RESET_RUNTIME')) ? PSM_LOGIN_RESET_RUNTIME : 3600; $runtime = (defined('PSM_LOGIN_RESET_RUNTIME')) ? PSM_LOGIN_RESET_RUNTIME : 3600;
$timestamp_max_interval = time() - $runtime; $timestamp_max_interval = time() - $runtime;
if($user->password_reset_timestamp > $timestamp_max_interval) { if ($user->password_reset_timestamp > $timestamp_max_interval) {
return true; return true;
} }
} }
return false; return false;
} }
/** /**
* Change the password of a user * Change the password of a user
* @param int $user_id * @param int $user_id
* @param string $password * @param string $password
* @return boolean TRUE on success, FALSE on failure * @return boolean TRUE on success, FALSE on failure
*/ */
public function changePassword($user_id, $password) { public function changePassword($user_id, $password) {
$user_id = intval($user_id); $user_id = intval($user_id);
if(empty($user_id) || empty($password)) { if (empty($user_id) || empty($password)) {
return false; return false;
} }
// now it gets a little bit crazy: check if we have a constant PSM_LOGIN_HASH_COST_FACTOR defined (in src/includes/psmconfig.inc.php), // now it gets a little bit crazy: check if we have a constant PSM_LOGIN_HASH_COST_FACTOR defined (in src/includes/psmconfig.inc.php),
// if so: put the value into $hash_cost_factor, if not, make $hash_cost_factor = null // 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); $hash_cost_factor = (defined('PSM_LOGIN_HASH_COST_FACTOR') ? PSM_LOGIN_HASH_COST_FACTOR : null);
@ -408,7 +408,7 @@ class User {
} else { } else {
return false; return false;
} }
} }
/** /**
* Gets the user id * Gets the user id
@ -418,14 +418,14 @@ class User {
return $this->user_id; return $this->user_id;
} }
/** /**
* Gets the username * Gets the username
* @return string * @return string
*/ */
public function getUsername() { public function getUsername() {
$user = $this->getUser(); $user = $this->getUser();
return (isset($user->user_name) ? $user->user_name : null); return (isset($user->user_name) ? $user->user_name : null);
} }
/** /**
* Gets the user level * Gets the user level
@ -434,7 +434,7 @@ class User {
public function getUserLevel() { public function getUserLevel() {
$user = $this->getUser(); $user = $this->getUser();
if(isset($user->level)) { if (isset($user->level)) {
return $user->level; return $user->level;
} else { } else {
return PSM_USER_ANONYMOUS; return PSM_USER_ANONYMOUS;
@ -446,13 +446,13 @@ class User {
* @return boolean return false is user not connected * @return boolean return false is user not connected
*/ */
protected function loadPreferences() { protected function loadPreferences() {
if($this->user_preferences === null) { if ($this->user_preferences === null) {
if(!$this->getUser()) { if (!$this->getUser()) {
return false; return false;
} }
$this->user_preferences = array(); $this->user_preferences = array();
foreach($this->db_connection->query('SELECT `key`,`value` FROM `' . PSM_DB_PREFIX . 'users_preferences` WHERE `user_id` = ' . $this->user_id) as $row) { foreach ($this->db_connection->query('SELECT `key`,`value` FROM `'.PSM_DB_PREFIX.'users_preferences` WHERE `user_id` = '.$this->user_id) as $row) {
$this->user_preferences[$row['key']] = $row['value']; $this->user_preferences[$row['key']] = $row['value'];
} }
} }
@ -466,7 +466,7 @@ class User {
* @return mixed * @return mixed
*/ */
public function getUserPref($key, $default = '') { public function getUserPref($key, $default = '') {
if(!$this->loadPreferences() || !isset($this->user_preferences[$key])) { if (!$this->loadPreferences() || !isset($this->user_preferences[$key])) {
return $default; return $default;
} }
@ -481,14 +481,14 @@ class User {
* @param mixed $value * @param mixed $value
*/ */
public function setUserPref($key, $value) { public function setUserPref($key, $value) {
if($this->loadPreferences()) { if ($this->loadPreferences()) {
if(isset($this->user_preferences[$key])) { if (isset($this->user_preferences[$key])) {
if($this->user_preferences[$key] == $value) { if ($this->user_preferences[$key] == $value) {
return; // no change return; // no change
} }
$sql = 'UPDATE `' . PSM_DB_PREFIX . 'users_preferences` SET `key` = ?, `value` = ? WHERE `user_id` = ?'; $sql = 'UPDATE `'.PSM_DB_PREFIX.'users_preferences` SET `key` = ?, `value` = ? WHERE `user_id` = ?';
} else{ } else {
$sql = 'INSERT INTO `' . PSM_DB_PREFIX . 'users_preferences` SET `key` = ?, `value` = ?, `user_id` = ?'; $sql = 'INSERT INTO `'.PSM_DB_PREFIX.'users_preferences` SET `key` = ?, `value` = ?, `user_id` = ?';
} }
$sth = $this->db_connection->prepare($sql); $sth = $this->db_connection->prepare($sql);
$sth->execute(array($key, $value, $this->user_id)); $sth->execute(array($key, $value, $this->user_id));

View File

@ -37,194 +37,194 @@ namespace psm\Txtmsg;
* Requirements: cURL v7.18.1+ and OpenSSL 0.9.8j+ * Requirements: cURL v7.18.1+ and OpenSSL 0.9.8j+
*/ */
class CMBulkSMS extends Core { class CMBulkSMS extends Core {
/** @var bool|null True when cURL request succeeded */ /** @var bool|null True when cURL request succeeded */
public $result; public $result;
/** @var string|null Contains error message if cURL request failed */ /** @var string|null Contains error message if cURL request failed */
public $error; public $error;
/** @var bool Set to true for debug output/logging */ /** @var bool Set to true for debug output/logging */
protected $debug = false; protected $debug = false;
/** @var bool Set to false if your operator isn't able to handle multipart messages */ /** @var bool Set to false if your operator isn't able to handle multipart messages */
protected $multipartMessage = true; protected $multipartMessage = true;
/** @var string|null Gateway API URL uses const GATEWAY_URL_XML or GATEWAY_URL_JSON */ /** @var string|null Gateway API URL uses const GATEWAY_URL_XML or GATEWAY_URL_JSON */
protected $apiUrl; protected $apiUrl;
/** @var string Gateway API Type: Use 'json' (default) or 'xml' */ /** @var string Gateway API Type: Use 'json' (default) or 'xml' */
protected $apiType = 'json'; protected $apiType = 'json';
/** @var string|null JSON or XML message for cURL request */ /** @var string|null JSON or XML message for cURL request */
protected $request; protected $request;
/** @var string|null HTTP Content-Type for cURL request */ /** @var string|null HTTP Content-Type for cURL request */
protected $contentType; protected $contentType;
/** @var string|null Raw sms text message */ /** @var string|null Raw sms text message */
protected $messageBody; protected $messageBody;
/** @var string JSON Gateway API URL */ /** @var string JSON Gateway API URL */
const GATEWAY_URL_JSON = "https://gw.cmtelecom.com/v1.0/message"; const GATEWAY_URL_JSON = "https://gw.cmtelecom.com/v1.0/message";
/** @var string XML Gateway API URL */ /** @var string XML Gateway API URL */
const GATEWAY_URL_XML = "https://sgw01.cm.nl/gateway.ashx"; const GATEWAY_URL_XML = "https://sgw01.cm.nl/gateway.ashx";
/** /**
* Build the message and send cURL request to the sms gateway * 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 * @see https://docs.cmtelecom.com/bulk-sms/v1.0#/send_a_message%7Csample_requests
* @param string $message Your text message * @param string $message Your text message
* @return boolean True when cURL request was successful * @return boolean True when cURL request was successful
*/ */
public function sendSMS($message) { public function sendSMS($message) {
// Check if recipient and text message are available // Check if recipient and text message are available
if(count($this->recipients) < 1 || empty($message)) { if (count($this->recipients) < 1 || empty($message)) {
return false; return false;
} }
// Prepare the message in CM's XML or JSON format // Prepare the message in CM's XML or JSON format
switch($this->apiType) { switch ($this->apiType) {
case 'xml': case 'xml':
$this->request = $this->buildMessageXml(); $this->request = $this->buildMessageXml();
$this->contentType = 'Content-Type: application/xml'; $this->contentType = 'Content-Type: application/xml';
$this->apiUrl = self::GATEWAY_URL_XML; $this->apiUrl = self::GATEWAY_URL_XML;
break; break;
case 'json': case 'json':
default: default:
$this->request = $this->buildMessageJson(); $this->request = $this->buildMessageJson();
$this->contentType = 'Content-Type: application/json'; $this->contentType = 'Content-Type: application/json';
$this->apiUrl = self::GATEWAY_URL_JSON; $this->apiUrl = self::GATEWAY_URL_JSON;
break; break;
} }
$request = $this->executeCurlRequest(); $request = $this->executeCurlRequest();
return $request; return $request;
} }
/** /**
* Create a JSON batch sms message using CM's format * 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%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%7Csample_requests
* @see https://docs.cmtelecom.com/bulk-sms/v1.0#/send_a_message%7Cmultipart * @see https://docs.cmtelecom.com/bulk-sms/v1.0#/send_a_message%7Cmultipart
* @return string JSON message object * @return string JSON message object
*/ */
protected function buildMessageJson() { protected function buildMessageJson() {
// Prepare recipient array for batch message // Prepare recipient array for batch message
$recipients = array(); $recipients = array();
foreach($this->recipients as $recipient) { foreach ($this->recipients as $recipient) {
$recipients[] = array('number' => $recipient); $recipients[] = array('number' => $recipient);
} }
// Build message array in CM's Bulk SMS format // Build message array in CM's Bulk SMS format
$msgArray = array( $msgArray = array(
'messages' => array( 'messages' => array(
'authentication' => array( 'authentication' => array(
'producttoken' => $this->password 'producttoken' => $this->password
), ),
'msg' => array( 'msg' => array(
array( array(
'from' => substr($this->originator, 0, 11), 'from' => substr($this->originator, 0, 11),
'to' => $recipients, 'to' => $recipients,
'body' => array( 'body' => array(
'content' => $message 'content' => $message
) )
) )
) )
) )
); );
// Multipart message // Multipart message
if($this->multipartMessage) { if ($this->multipartMessage) {
$msgArray['messages']['msg'][0]['minimumNumberOfMessageParts'] = 1; $msgArray['messages']['msg'][0]['minimumNumberOfMessageParts'] = 1;
$msgArray['messages']['msg'][0]['maximumNumberOfMessageParts'] = 8; $msgArray['messages']['msg'][0]['maximumNumberOfMessageParts'] = 8;
} }
// Convert array in JSON object // Convert array in JSON object
return json_encode($msgArray); return json_encode($msgArray);
} }
/** /**
* Create a XML batch sms message in CM's format * 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%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%7Csample_requests
* @see https://docs.cmtelecom.com/bulk-sms/v1.0#/send_a_message%7Cmultipart * @see https://docs.cmtelecom.com/bulk-sms/v1.0#/send_a_message%7Cmultipart
* @return string XML message * @return string XML message
*/ */
protected function buildMessageXml() { protected function buildMessageXml() {
// Create XML string // Create XML string
$xml = new \SimpleXMLElement('<MESSAGES/>'); $xml = new \SimpleXMLElement('<MESSAGES/>');
// API-Token // API-Token
$auth = $xml->addChild('AUTHENTICATION'); $auth = $xml->addChild('AUTHENTICATION');
$auth->addChild('PRODUCTTOKEN', $this->password); $auth->addChild('PRODUCTTOKEN', $this->password);
// Message // Message
$msg = $xml->addChild('MSG'); $msg = $xml->addChild('MSG');
// From // From
$msg->addChild('FROM', substr($this->originator, 0, 11)); $msg->addChild('FROM', substr($this->originator, 0, 11));
// Recipients // Recipients
foreach($this->recipients as $recipient) { foreach ($this->recipients as $recipient) {
$msg->addChild('TO', $recipient); $msg->addChild('TO', $recipient);
} }
// Multipart message // Multipart message
if($this->multipartMessage) { if ($this->multipartMessage) {
$msg->addChild('MINIMUMNUMBEROFMESSAGEPARTS', 1); $msg->addChild('MINIMUMNUMBEROFMESSAGEPARTS', 1);
$msg->addChild('MAXIMUMNUMBEROFMESSAGEPARTS', 8); $msg->addChild('MAXIMUMNUMBEROFMESSAGEPARTS', 8);
} }
// Add body text // Add body text
$msg->addChild('BODY', $message); $msg->addChild('BODY', $message);
return $xml->asXML(); return $xml->asXML();
} }
/** /**
* Create and execute the curl request * Create and execute the curl request
* *
* @return boolean True if message is sent * @return boolean True if message is sent
*/ */
protected function executeCurlRequest() { protected function executeCurlRequest() {
$cr = curl_init(); $cr = curl_init();
curl_setopt_array($cr, array( curl_setopt_array($cr, array(
CURLOPT_URL => $this->apiUrl, CURLOPT_URL => $this->apiUrl,
CURLOPT_HTTPHEADER => array($this->contentType), CURLOPT_HTTPHEADER => array($this->contentType),
CURLOPT_POST => true, CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $this->request, CURLOPT_POSTFIELDS => $this->request,
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_FAILONERROR => true CURLOPT_FAILONERROR => true
) )
); );
// execute curl request and fetch the response/error // execute curl request and fetch the response/error
$cResponse = curl_exec($cr); $cResponse = curl_exec($cr);
$cError = curl_error($cr); $cError = curl_error($cr);
$cErrorCode = curl_errno($cr); $cErrorCode = curl_errno($cr);
curl_close($cr); curl_close($cr);
$this->result = 1; $this->result = 1;
// set result and log error if needed // set result and log error if needed
if($cError) { if ($cError) {
$this->error = 'Response: CM SMS API:' . $cResponse . ' cURL Error Code: ' . $cErrorCode . '"' . $cError . '"'; $this->error = 'Response: CM SMS API:'.$cResponse.' cURL Error Code: '.$cErrorCode.'"'.$cError.'"';
error_log($this->error, E_USER_ERROR); error_log($this->error, E_USER_ERROR);
$this->result = $this->error; $this->result = $this->error;
} }
// Debug output // Debug output
// Note: CM's XML gateway gives no response when message is sent successfully :/ // Note: CM's XML gateway gives no response when message is sent successfully :/
if($this->debug || PSM_DEBUG) { if ($this->debug || PSM_DEBUG) {
$debug = '<pre>Request: '. $this->request . '<br>Response: ' . $cResponse.'</pre>'; $debug = '<pre>Request: '.$this->request.'<br>Response: '.$cResponse.'</pre>';
error_log("Request: $this->request\r\nResponse: $cResponse", E_USER_NOTICE); error_log("Request: $this->request\r\nResponse: $cResponse", E_USER_NOTICE);
echo $debug; echo $debug;
} }
return $this->result; return $this->result;
} }
} }

View File

@ -32,31 +32,31 @@ namespace psm\Txtmsg;
class Callr extends Core { class Callr extends Core {
/** /**
* Send sms using the Callr API * Send sms using the Callr API
* *
* @var string $message * @var string $message
* @var string $this->password * @var string $this->password
* @var array $this->recipients * @var array $this->recipients
* @var array $this->originator * @var array $this->originator
* @var string $recipient * @var string $recipient
* *
* @var mixed $result * @var mixed $result
* @var array $headers * @var array $headers
* *
* @var resource $curl * @var resource $curl
* @var string $err * @var string $err
* *
* @var int $success * @var int $success
* @var string $error * @var string $error
* *
* @return int or string * @return int or string
*/ */
public function sendSMS($message) { public function sendSMS($message) {
$error = ""; $error = "";
$success = 1; $success = 1;
foreach($this->recipients as $recipient) { foreach ($this->recipients as $recipient) {
$curl = curl_init(); $curl = curl_init();
curl_setopt_array($curl, array( curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.callr.com/rest/v1.1/sms", CURLOPT_URL => "https://api.callr.com/rest/v1.1/sms",
@ -74,7 +74,7 @@ class Callr extends Core {
) )
), ),
CURLOPT_HTTPHEADER => array( CURLOPT_HTTPHEADER => array(
"authorization: Basic " . base64_encode($this->username . ":" . $this->password), "authorization: Basic ".base64_encode($this->username.":".$this->password),
"content-type: application/json" "content-type: application/json"
), ),
)); ));
@ -82,13 +82,15 @@ class Callr extends Core {
$result = json_decode(curl_exec($curl), true); $result = json_decode(curl_exec($curl), true);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if($err = curl_errno($curl) || $httpcode != 200 || $result['status'] == "error") { if ($err = curl_errno($curl) || $httpcode != 200 || $result['status'] == "error") {
$success = 0; $success = 0;
$error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". Result: ".$result['data']['code']." - ".$result['data']['message']; $error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". Result: ".$result['data']['code']." - ".$result['data']['message'];
} }
curl_close($curl); curl_close($curl);
} }
if($success) return 1; if ($success) {
return 1;
}
return $error; return $error;
} }
} }

View File

@ -31,35 +31,37 @@ namespace psm\Txtmsg;
class ClickSend extends Core { class ClickSend extends Core {
/** /**
* Send sms using the SMSgw.NET API * Send sms using the SMSgw.NET API
* *
* @var string $message * @var string $message
* @var string $this->password * @var string $this->password
* @var array $this->recipients * @var array $this->recipients
* @var array $this->originator * @var array $this->originator
* @var string $recipients * @var string $recipients
* *
* @var resource $curl * @var resource $curl
* @var string $err * @var string $err
* @var mixed $result * @var mixed $result
* *
* @var int $success * @var int $success
* @var string $error * @var string $error
* *
* @return int or string * @return int or string
*/ */
public function sendSMS($message) { public function sendSMS($message) {
$error = ""; $error = "";
$success = 1; $success = 1;
if(empty($this->recipients)) return false; if (empty($this->recipients)) {
return false;
}
$data = array('messages' => array()); $data = array('messages' => array());
foreach($this->recipients as $recipient) { foreach ($this->recipients as $recipient) {
$data['messages'][] = array( $data['messages'][] = array(
'source' => 'phpservermon', 'source' => 'phpservermon',
'from' => substr($this->originator,0,11), 'from' => substr($this->originator, 0, 11),
'to' => $recipient, 'to' => $recipient,
'body' => $message, 'body' => $message,
); );
@ -76,21 +78,23 @@ class ClickSend extends Core {
CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode($data), CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => array( CURLOPT_HTTPHEADER => array(
"authorization: Basic " . base64_encode($this->username . ":" . $this->password), "authorization: Basic ".base64_encode($this->username.":".$this->password),
"content-type: application/json" "content-type: application/json"
), ),
)); ));
$result = json_decode(curl_exec($curl),true); $result = json_decode(curl_exec($curl), true);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if($err = curl_errno($curl) || ($httpcode != '200' && $httpcode != '201' && $httpcode != '202' && $result['response_code'] != "SUCCESS")) { if ($err = curl_errno($curl) || ($httpcode != '200' && $httpcode != '201' && $httpcode != '202' && $result['response_code'] != "SUCCESS")) {
$success = 0; $success = 0;
$error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". Result: ".$result.""; $error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". Result: ".$result."";
} }
curl_close($curl); curl_close($curl);
if($success) return 1; if ($success) {
return 1;
}
return $error; return $error;
} }
} }

View File

@ -31,23 +31,23 @@ namespace psm\Txtmsg;
class Clickatell extends Core { class Clickatell extends Core {
/** /**
* Send sms using the Clickatell API * Send sms using the Clickatell API
* @var string $message * @var string $message
* @var array $this->recipients * @var array $this->recipients
* @var string $recipient * @var string $recipient
* @var string $this->password * @var string $this->password
* @var string $this->originator * @var string $this->originator
* *
* @var int $success * @var int $success
* @var string $error * @var string $error
* *
* @return int or string * @return int or string
*/ */
public function sendSMS($message) { public function sendSMS($message) {
$success = 1; $success = 1;
$error = ''; $error = '';
foreach($this->recipients as $recipient) { foreach ($this->recipients as $recipient) {
$ch = curl_init(); $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://platform.clickatell.com/messages/http/send?apiKey=".urlencode($this->password)."&to=".urlencode($recipient)."&content=".urlencode($message)); curl_setopt($ch, CURLOPT_URL, "https://platform.clickatell.com/messages/http/send?apiKey=".urlencode($this->password)."&to=".urlencode($recipient)."&content=".urlencode($message));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
@ -63,7 +63,7 @@ class Clickatell extends Core {
$success = 0; $success = 0;
} }
} }
if($success == 1){ if ($success) {
return 1; return 1;
} }
return $error; return $error;

View File

@ -30,28 +30,28 @@ namespace psm\Txtmsg;
class FreeMobileSMS extends Core { class FreeMobileSMS extends Core {
/** /**
* Send sms using the FreeMobileSMS API * Send sms using the FreeMobileSMS API
* *
* @var string $message * @var string $message
* @var string $this->password * @var string $this->password
* @var string $this->username * @var string $this->username
* *
* @var resource $curl * @var resource $curl
* @var string $err * @var string $err
* @var int $success * @var int $success
* @var string $error * @var string $error
* @var string $http_code * @var string $http_code
* *
* @return int or string * @return int or string
*/ */
public function sendSMS($message) { public function sendSMS($message) {
$success = 1; $success = 1;
$error = ""; $error = "";
$curl = curl_init(); $curl = curl_init();
curl_setopt($curl,CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl,CURLOPT_URL, "https://smsapi.free-mobile.fr/sendmsg?" . http_build_query( curl_setopt($curl, CURLOPT_URL, "https://smsapi.free-mobile.fr/sendmsg?".http_build_query(
array( array(
"user" => $this->username, "user" => $this->username,
"pass" => $this->password, "pass" => $this->password,
@ -63,13 +63,15 @@ class FreeMobileSMS extends Core {
$result = curl_exec($curl); $result = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if($err = curl_errno($curl) || $httpcode != 200) { if ($err = curl_errno($curl) || $httpcode != 200) {
$success = 0; $success = 0;
$error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err); $error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err);
} }
curl_close($curl); curl_close($curl);
if($success) return 1; if ($success) {
return 1;
}
return $error; return $error;
} }
} }

View File

@ -31,22 +31,22 @@ namespace psm\Txtmsg;
class FreeVoipDeal extends Core { class FreeVoipDeal extends Core {
/** /**
* Send sms using the FreeVoipDeal API * Send sms using the FreeVoipDeal API
* @var string $message * @var string $message
* @var string $this->password * @var string $this->password
* @var array $this->recipients * @var array $this->recipients
* @var array $this->originator * @var array $this->originator
* *
* @var resource $curl * @var resource $curl
* @var string $err * @var string $err
* @var string $recipient * @var string $recipient
* @var string $from * @var string $from
* @var mixed $result * @var mixed $result
* @var int $success * @var int $success
* @var string $error * @var string $error
* *
* @return int or string * @return int or string
*/ */
public function sendSMS($message) { public function sendSMS($message) {
$error = ""; $error = "";
@ -54,10 +54,10 @@ class FreeVoipDeal extends Core {
$message = rawurlencode($message); $message = rawurlencode($message);
foreach($this->recipients as $recipient) { foreach ($this->recipients as $recipient) {
$curl = curl_init(); $curl = curl_init();
curl_setopt($curl,CURLOPT_URL, "https://www.freevoipdeal.com/myaccount/sendsms.php?" . http_build_query( curl_setopt($curl, CURLOPT_URL, "https://www.freevoipdeal.com/myaccount/sendsms.php?".http_build_query(
array( array(
"username" => $this->username, "username" => $this->username,
"password" => $this->password, "password" => $this->password,
@ -67,19 +67,21 @@ class FreeVoipDeal extends Core {
) )
) )
); );
curl_setopt($curl,CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl); $result = curl_exec($curl);
$err = curl_error($curl); $err = curl_error($curl);
curl_close($curl); curl_close($curl);
if($err || is_numeric(strpos($result, "failure"))) { if ($err || is_numeric(strpos($result, "failure"))) {
$success = 0; $success = 0;
$error = $result; $error = $result;
} }
} }
if($success) return 1; if ($success) {
return 1;
}
return $error; return $error;
} }
} }

View File

@ -32,28 +32,30 @@ namespace psm\Txtmsg;
class GatewayAPI extends Core { class GatewayAPI extends Core {
/** /**
* Send sms using the GatewayAPI API * Send sms using the GatewayAPI API
* *
* @var string $message * @var string $message
* @var string $this->password * @var string $this->password
* @var array $this->recipients * @var array $this->recipients
* @var array $this->originator * @var array $this->originator
* @var string $recipient * @var string $recipient
* @var mixed $result * @var mixed $result
* *
* @var resource $curl * @var resource $curl
* @var string $err * @var string $err
* @var int $success * @var int $success
* @var string $error * @var string $error
* *
* @return int or string * @return int or string
*/ */
public function sendSMS($message) { public function sendSMS($message) {
$error = ""; $error = "";
$success = 1; $success = 1;
if(empty($this->recipients)) return false; if (empty($this->recipients)) {
return false;
}
$json = [ $json = [
'sender' => isset($this->originator) ? $this->originator : "PHPServerMon", 'sender' => isset($this->originator) ? $this->originator : "PHPServerMon",
@ -61,28 +63,30 @@ class GatewayAPI extends Core {
'recipients' => [], 'recipients' => [],
]; ];
foreach($this->recipients as $recipient) { foreach ($this->recipients as $recipient) {
$json['recipients'][] = ['msisdn' => $recipient]; $json['recipients'][] = ['msisdn' => $recipient];
} }
$curl = curl_init(); $curl = curl_init();
curl_setopt($curl,CURLOPT_URL, "https://gatewayapi.com/rest/mtsms"); curl_setopt($curl, CURLOPT_URL, "https://gatewayapi.com/rest/mtsms");
curl_setopt($curl,CURLOPT_HTTPHEADER, array("Content-Type: application/json")); curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
curl_setopt($curl,CURLOPT_USERPWD, $this->password . ":"); curl_setopt($curl, CURLOPT_USERPWD, $this->password.":");
curl_setopt($curl,CURLOPT_POSTFIELDS, json_encode($json)); curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($json));
curl_setopt($curl,CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = json_decode(curl_exec($curl),true); $result = json_decode(curl_exec($curl), true);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$err = curl_error($curl); $err = curl_error($curl);
curl_close($curl); curl_close($curl);
if($err || $httpcode != 200) { if ($err || $httpcode != 200) {
$success = 0; $success = 0;
$error = $result['code']." - ".$result['message']; $error = $result['code']." - ".$result['message'];
} }
if($success) return 1; if ($success) {
return 1;
}
return $error; return $error;
} }
} }

View File

@ -31,29 +31,29 @@ namespace psm\Txtmsg;
class Inetworx extends Core { class Inetworx extends Core {
/** /**
* Send sms using the Inetworx API * Send sms using the Inetworx API
* *
* @var string $message * @var string $message
* @var string $this->password * @var string $this->password
* @var array $this->recipients * @var array $this->recipients
* @var array $this->originator * @var array $this->originator
* *
* @var resource $curl * @var resource $curl
* @var string $err * @var string $err
* @var string $recipient * @var string $recipient
* @var mixed $result * @var mixed $result
* *
* @var int $success * @var int $success
* @var string $error * @var string $error
* *
* @return int or string * @return int or string
*/ */
public function sendSMS($message) { public function sendSMS($message) {
$error = ""; $error = "";
$success = 1; $success = 1;
foreach($this->recipients as $recipient) { foreach ($this->recipients as $recipient) {
$curl = curl_init(); $curl = curl_init();
curl_setopt_array($curl, array( curl_setopt_array($curl, array(
@ -74,7 +74,7 @@ class Inetworx extends Core {
) )
), ),
CURLOPT_HTTPHEADER => array( CURLOPT_HTTPHEADER => array(
"authorization: Basic " . base64_encode("inetworxag:conn2smsapp"), "authorization: Basic ".base64_encode("inetworxag:conn2smsapp"),
"content-type: application/x-www-form-urlencoded" "content-type: application/x-www-form-urlencoded"
), ),
)); ));
@ -82,14 +82,16 @@ class Inetworx extends Core {
$result = curl_exec($curl); $result = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if($err = curl_errno($curl) || $httpcode != 200 || strpos($result, "200") === false) { if ($err = curl_errno($curl) || $httpcode != 200 || strpos($result, "200") === false) {
$success = 0; $success = 0;
$error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". \nResult: ".$result; $error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". \nResult: ".$result;
} }
curl_close($curl); curl_close($curl);
} }
if($success) return 1; if ($success) {
return 1;
}
return $error; return $error;
} }
} }

View File

@ -32,23 +32,23 @@ namespace psm\Txtmsg;
class Messagebird extends Core { class Messagebird extends Core {
/** /**
* Send sms using the Messagebird API * Send sms using the Messagebird API
* @var string $message * @var string $message
* @var array $this->recipients * @var array $this->recipients
* @var array $this->originator (Max 11 characters) * @var array $this->originator (Max 11 characters)
* @var array $recipients_chunk * @var array $recipients_chunk
* @var string $this->password * @var string $this->password
* *
* @var mixed $result * @var mixed $result
* @var array $headers * @var array $headers
* *
* @var int $success * @var int $success
* @var string $error * @var string $error
* *
* @return int or string * @return int or string
*/ */
public function sendSMS($message) { public function sendSMS($message) {
$success = 1; $success = 1;
$error = ''; $error = '';
// Maximum of 50 users a time. // Maximum of 50 users a time.
@ -76,9 +76,9 @@ class Messagebird extends Core {
$success = 0; $success = 0;
} }
} }
if($success == 1){ if ($success) {
return 1; return 1;
} }
return $error; return $error;
} }
} }

View File

@ -31,32 +31,32 @@ namespace psm\Txtmsg;
class Mosms extends Core { class Mosms extends Core {
/** /**
* Send sms using the Mosms API * Send sms using the Mosms API
* *
* @var string $message * @var string $message
* @var array $this->username * @var array $this->username
* @var string $this->password * @var string $this->password
* @var array $this->recipients * @var array $this->recipients
* @var string $recipient * @var string $recipient
* @var array $this->originator (Max 11 characters) * @var array $this->originator (Max 11 characters)
* *
* @var resource $curl * @var resource $curl
* @var string $err * @var string $err
* @var int $success * @var int $success
* @var string $error * @var string $error
* *
* @return int or string * @return int or string
*/ */
public function sendSMS($message) { public function sendSMS($message) {
$error = ""; $error = "";
$success = 1; $success = 1;
$message = rawurlencode($message); $message = rawurlencode($message);
foreach($this->recipients as $recipient) { foreach ($this->recipients as $recipient) {
$curl = curl_init(); $curl = curl_init();
curl_setopt($curl,CURLOPT_URL, "https://www.mosms.com/se/sms-send.php?" . http_build_query( curl_setopt($curl, CURLOPT_URL, "https://www.mosms.com/se/sms-send.php?".http_build_query(
array( array(
"username" => $this->username, "username" => $this->username,
"password" => $this->password, "password" => $this->password,
@ -67,13 +67,13 @@ class Mosms extends Core {
) )
) )
); );
curl_setopt($curl,CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$result = curl_exec($curl); $result = curl_exec($curl);
$err = curl_error($curl); $err = curl_error($curl);
if($err = curl_errno($curl) || $httpcode != 200 || $result == 2 || $result == 5) { if ($err = curl_errno($curl) || $httpcode != 200 || $result == 2 || $result == 5) {
$success = 0; $success = 0;
$error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". \nResult: ".$result; $error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". \nResult: ".$result;
} }
@ -81,7 +81,9 @@ class Mosms extends Core {
} }
if($success) return 1; if ($success) {
return 1;
}
return $error; return $error;
} }
} }

View File

@ -32,23 +32,23 @@ class Nexmo extends Core {
/** /**
* Send sms using the GatewayAPI API * Send sms using the GatewayAPI API
* *
* @var string $message * @var string $message
* @var string $this->password * @var string $this->password
* @var array $this->recipients * @var array $this->recipients
* @var array $this->originator * @var array $this->originator
* @var string $recipient * @var string $recipient
* *
* @var resource $curl * @var resource $curl
* @var string $err * @var string $err
* @var mixed $result * @var mixed $result
* *
* @var int $success * @var int $success
* @var string $error * @var string $error
* *
* @return int or string * @return int or string
*/ */
public function sendSMS($message) { public function sendSMS($message) {
$success = 1; $success = 1;
@ -56,11 +56,11 @@ class Nexmo extends Core {
$message = rawurlencode($message); $message = rawurlencode($message);
foreach($this->recipients as $recipient) { foreach ($this->recipients as $recipient) {
$curl = curl_init(); $curl = curl_init();
curl_setopt($curl,CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl,CURLOPT_URL, "https://rest.nexmo.com/sms/json?" . http_build_query( curl_setopt($curl, CURLOPT_URL, "https://rest.nexmo.com/sms/json?".http_build_query(
array( array(
"api_key" => $this->username, "api_key" => $this->username,
"api_secret" => $this->password, "api_secret" => $this->password,
@ -71,12 +71,12 @@ class Nexmo extends Core {
) )
); );
$result = json_decode(curl_exec($curl),true); $result = json_decode(curl_exec($curl), true);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$err = curl_error($curl); $err = curl_error($curl);
if($err = curl_errno($curl) || $httpcode != 200 || $result['messages'][0]['status'] != "0") { if ($err = curl_errno($curl) || $httpcode != 200 || $result['messages'][0]['status'] != "0") {
$success = 0; $success = 0;
$error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". \nResult: ".$result['messages'][0]['error-text']; $error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". \nResult: ".$result['messages'][0]['error-text'];
} }
@ -84,7 +84,9 @@ class Nexmo extends Core {
} }
if($success) return 1; if ($success) {
return 1;
}
return $error; return $error;
} }
} }

View File

@ -33,25 +33,25 @@ namespace psm\Txtmsg;
class Octopush extends Core { class Octopush extends Core {
/** /**
* Send sms using the Octopush API * Send sms using the Octopush API
* @var string $message * @var string $message
* @var string $this->username * @var string $this->username
* @var string $this->password * @var string $this->password
* @var array $this->recipients * @var array $this->recipients
* @var array $this->originator * @var array $this->originator
* *
* @var resource $curl * @var resource $curl
* @var SimpleXMLElement $xmlResults * @var SimpleXMLElement $xmlResults
* @var string $err * @var string $err
* @var string $recipient * @var string $recipient
* @var string $smsType * @var string $smsType
* @var mixed $result * @var mixed $result
* *
* @var int $success * @var int $success
* @var string $error * @var string $error
* *
* @return int or string * @return int or string
*/ */
public function sendSMS($message) { public function sendSMS($message) {
$error = ""; $error = "";
@ -60,10 +60,10 @@ class Octopush extends Core {
$recipients = join(',', $this->recipients); $recipients = join(',', $this->recipients);
$message = ($smsType == "FR") ? urlencode($message . " STOP au XXXX") : urlencode($message); $message = ($smsType == "FR") ? urlencode($message." STOP au XXXX") : urlencode($message);
$curl = curl_init(); $curl = curl_init();
curl_setopt($curl,CURLOPT_URL, "http://www.octopush-dm.com/api/sms/?" . http_build_query( curl_setopt($curl, CURLOPT_URL, "http://www.octopush-dm.com/api/sms/?".http_build_query(
array( array(
"user_login" => $this->username, "user_login" => $this->username,
"api_key" => $this->password, "api_key" => $this->password,
@ -74,19 +74,21 @@ class Octopush extends Core {
) )
) )
); );
curl_setopt($curl,CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl); $result = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$xmlResults = simplexml_load_string($result); $xmlResults = simplexml_load_string($result);
if($err = curl_errno($curl) || $httpcode != 200 || $xmlResults === false || $xmlResults->error_code != '000') { if ($err = curl_errno($curl) || $httpcode != 200 || $xmlResults === false || $xmlResults->error_code != '000') {
$success = 0; $success = 0;
$error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". \nResult: ".$xmlResults->error_code.". Look at http://www.octopush-dm.com/en/errors for the error description."; $error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". \nResult: ".$xmlResults->error_code.". Look at http://www.octopush-dm.com/en/errors for the error description.";
} }
curl_close($curl); curl_close($curl);
if($success) return 1; if ($success) {
return 1;
}
return $error; return $error;
} }
} }

View File

@ -32,33 +32,35 @@ namespace psm\Txtmsg;
class Plivo extends Core { class Plivo extends Core {
/** /**
* Send sms using the Plivo API * Send sms using the Plivo API
* *
* @var string $message * @var string $message
* @var string $this->password * @var string $this->password
* @var array $this->recipients * @var array $this->recipients
* @var array $this->originator * @var array $this->originator
* @var string $recipients * @var string $recipients
* *
* @var resource $curl * @var resource $curl
* @var string $err * @var string $err
* @var int $success * @var int $success
* @var string $error * @var string $error
* *
* @return int or string * @return int or string
*/ */
public function sendSMS($message) { public function sendSMS($message) {
$error = ""; $error = "";
$success = 1; $success = 1;
if(empty($this->recipients)) return false; if (empty($this->recipients)) {
return false;
}
$recipients = join('<', $this->recipients); $recipients = join('<', $this->recipients);
$curl = curl_init(); $curl = curl_init();
curl_setopt_array($curl, array( curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.plivo.com/v1/Account/" . $this->username . "/Message/", CURLOPT_URL => "https://api.plivo.com/v1/Account/".$this->username."/Message/",
CURLOPT_RETURNTRANSFER => true, CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "", CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10, CURLOPT_MAXREDIRS => 10,
@ -73,20 +75,22 @@ class Plivo extends Core {
) )
), ),
CURLOPT_HTTPHEADER => array( CURLOPT_HTTPHEADER => array(
"authorization: Basic " . base64_encode($this->username . ":" . $this->password), "authorization: Basic ".base64_encode($this->username.":".$this->password),
"content-type: application/json" "content-type: application/json"
), ),
)); ));
$result = curl_exec($curl); $result = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if($err = curl_errno($curl) || ($httpcode != '200' && $httpcode != '201' && $httpcode != '202')) { if ($err = curl_errno($curl) || ($httpcode != '200' && $httpcode != '201' && $httpcode != '202')) {
$success = 0; $success = 0;
$error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". Result: ".$result.""; $error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". Result: ".$result."";
} }
curl_close($curl); curl_close($curl);
if($success) return 1; if ($success) {
return 1;
}
return $error; return $error;
} }
} }

View File

@ -31,23 +31,23 @@ namespace psm\Txtmsg;
class Smsglobal extends Core { class Smsglobal extends Core {
/** /**
* Send sms using the Smsglobal API * Send sms using the Smsglobal API
* @var string $message * @var string $message
* @var string $this->password * @var string $this->password
* @var array $this->recipients * @var array $this->recipients
* @var array $this->originator * @var array $this->originator
* *
* @var resource $curl * @var resource $curl
* @var string $err * @var string $err
* @var string $recipient * @var string $recipient
* @var string $from * @var string $from
* @var mixed $result * @var mixed $result
* *
* @var int $success * @var int $success
* @var string $error * @var string $error
* *
* @return int or string * @return int or string
*/ */
public function sendSMS($message) { public function sendSMS($message) {
$error = ""; $error = "";
@ -55,13 +55,13 @@ class Smsglobal extends Core {
$recipients = join(',', $this->recipients); $recipients = join(',', $this->recipients);
$from = substr($this->originator,0 , 11); // Max 11 Characters $from = substr($this->originator, 0, 11); // Max 11 Characters
$message = substr(rawurlencode($message), 0, 153); $message = substr(rawurlencode($message), 0, 153);
$curl = curl_init(); $curl = curl_init();
curl_setopt($curl,CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl,CURLOPT_TIMEOUT, 30); curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl,CURLOPT_URL, "https://www.smsglobal.com/http-api.php?" . http_build_query( curl_setopt($curl, CURLOPT_URL, "https://www.smsglobal.com/http-api.php?".http_build_query(
array( array(
"action" => "sendsms", "action" => "sendsms",
"user" => $this->username, "user" => $this->username,
@ -79,14 +79,16 @@ class Smsglobal extends Core {
$result = curl_exec($curl); $result = curl_exec($curl);
$err = curl_error($curl); $err = curl_error($curl);
if($err = curl_errno($curl) || substr($result, 0, 5) != "OK: 0") { if ($err = curl_errno($curl) || substr($result, 0, 5) != "OK: 0") {
$success = 0; $success = 0;
$result = ($result == '') ? 'Wrong input, please check if all values are correct!' : $result; $result = ($result == '') ? 'Wrong input, please check if all values are correct!' : $result;
$error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". \nResult: ".$result; $error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". \nResult: ".$result;
} }
curl_close($curl); curl_close($curl);
if($success) return 1; if ($success) {
return 1;
}
return $error; return $error;
} }
} }

View File

@ -32,21 +32,21 @@ namespace psm\Txtmsg;
class Smsgw extends Core { class Smsgw extends Core {
/** /**
* Send sms using the SMSgw.NET API * Send sms using the SMSgw.NET API
* *
* @var string $message * @var string $message
* @var string $this->password * @var string $this->password
* @var array $this->recipients * @var array $this->recipients
* @var array $this->originator * @var array $this->originator
* @var string $recipients * @var string $recipients
* *
* @var resource $curl * @var resource $curl
* @var string $err * @var string $err
* @var int $success * @var int $success
* @var string $error * @var string $error
* *
* @return int or string * @return int or string
*/ */
public function sendSMS($message) { public function sendSMS($message) {
$error = ""; $error = "";
@ -74,13 +74,15 @@ class Smsgw extends Core {
$result = curl_exec($curl); $result = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if($err = curl_errno($curl) || ($httpcode != '200' && $httpcode != '201' && $httpcode != '202' && $result != "1")) { if ($err = curl_errno($curl) || ($httpcode != '200' && $httpcode != '201' && $httpcode != '202' && $result != "1")) {
$success = 0; $success = 0;
$error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". Result: ".$result.""; $error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". Result: ".$result."";
} }
curl_close($curl); curl_close($curl);
if($success) return 1; if ($success) {
return 1;
}
return $error; return $error;
} }
} }

View File

@ -31,53 +31,55 @@ namespace psm\Txtmsg;
class Smsit extends Core { class Smsit extends Core {
/** /**
* Send sms using the Smsit API * Send sms using the Smsit API
* *
* @var string $message * @var string $message
* @var string $this->password * @var string $this->password
* @var array $this->recipients * @var array $this->recipients
* @var array $this->originator * @var array $this->originator
* *
* @var resource $curl * @var resource $curl
* @var string $err * @var string $err
* @var String $recipient * @var String $recipient
* @var mixed $result * @var mixed $result
* *
* @var int $success * @var int $success
* @var string $error * @var string $error
* *
* @return int or string * @return int or string
*/ */
public function sendSMS($message) { public function sendSMS($message) {
$success = 1; $success = 1;
$error = ""; $error = "";
foreach( $this->recipients as $recipient ){ foreach ($this->recipients as $recipient) {
$curl = curl_init(); $curl = curl_init();
curl_setopt($curl,CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl,CURLOPT_URL, "https://www.smsit.dk/api/v2?" . http_build_query( curl_setopt($curl, CURLOPT_URL, "https://www.smsit.dk/api/v2?".http_build_query(
array( array(
"apiKey" => $this->password, "apiKey" => $this->password,
"mobile" => $recipient, "mobile" => $recipient,
"message" => urlencode($message), "message" => urlencode($message),
"senderId" => substr($this->originator,0,11), "senderId" => substr($this->originator, 0, 11),
) )
) )
); );
$result = curl_exec($curl); $result = curl_exec($curl);
$err =curl_error($curl); $err = curl_error($curl);
curl_close($curl); curl_close($curl);
if($err || is_numeric(strpos($result, "{\"errors\":[{\"code\":"))) { if ($err || is_numeric(strpos($result, "{\"errors\":[{\"code\":"))) {
$success = 0; $success = 0;
$error = $result; $error = $result;
} }
} }
if($success) return 1; if ($success) {
return 1;
}
return $error; return $error;
} }
} }

View File

@ -32,22 +32,22 @@ namespace psm\Txtmsg;
class SolutionsInfini extends Core { class SolutionsInfini extends Core {
/** /**
* Send sms using the SolutionsInfini API * Send sms using the SolutionsInfini API
* *
* @var string $message * @var string $message
* @var string $this->password * @var string $this->password
* @var array $this->recipients * @var array $this->recipients
* @var string $recipients * @var string $recipients
* @var array $this->originator (Max 11 characters) * @var array $this->originator (Max 11 characters)
* *
* @var resource $curl * @var resource $curl
* @var string $err * @var string $err
* *
* @var int $success * @var int $success
* @var string $error * @var string $error
* *
* @return int or string * @return int or string
*/ */
public function sendSMS($message) { public function sendSMS($message) {
$error = ""; $error = "";
@ -58,7 +58,7 @@ class SolutionsInfini extends Core {
$recipients = join(',', $this->recipients); $recipients = join(',', $this->recipients);
$curl = curl_init(); $curl = curl_init();
curl_setopt($curl,CURLOPT_URL, "https://api-alerts.solutionsinfini.com/v4/?" . http_build_query( curl_setopt($curl, CURLOPT_URL, "https://api-alerts.solutionsinfini.com/v4/?".http_build_query(
array( array(
"api_key" => $this->password, "api_key" => $this->password,
"method" => "sms", "method" => "sms",
@ -68,18 +68,20 @@ class SolutionsInfini extends Core {
) )
) )
); );
curl_setopt($curl,CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$result = json_decode(curl_exec($curl), true); $result = json_decode(curl_exec($curl), true);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if($err = curl_errno($curl) || $httpcode != 200 || $result['status'] != "OK") { if ($err = curl_errno($curl) || $httpcode != 200 || $result['status'] != "OK") {
$success = 0; $success = 0;
$error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". Result: ".$result['status']." - ".$result['message']."."; $error = "HTTP_code: ".$httpcode.".\ncURL error (".$err."): ".curl_strerror($err).". Result: ".$result['status']." - ".$result['message'].".";
} }
curl_close($curl); curl_close($curl);
if($success) return 1; if ($success) {
return 1;
}
return $error; return $error;
} }
} }

View File

@ -30,23 +30,22 @@ namespace psm\Txtmsg;
class Spryng extends Core { class Spryng extends Core {
/** /**
* Send sms using the Spryngsms API * Send sms using the Spryngsms API
* @var string $message * @var string $message
* @var array $this->recipients * @var array $this->recipients
* @var string $this->username * @var string $this->username
* @var string $this->password * @var string $this->password
* @var string $this->originator * @var string $this->originator
* @var mixed $result
* @var mixed $result * @var array $headers
* @var array $headers *
* * @var int $success
* @var int $success * @var string $error
* @var string $error *
* * @return int or string
* @return int or string */
*/
public function sendSMS($message) { public function sendSMS($message) {
$recipients = implode(",", $this->recipients); $recipients = implode(",", $this->recipients);
$ch = curl_init(); $ch = curl_init();

View File

@ -32,27 +32,27 @@ namespace psm\Txtmsg;
class Textmarketer extends Core { class Textmarketer extends Core {
/** /**
* Send sms using the Textmarketer API * Send sms using the Textmarketer API
* @var string $message * @var string $message
* @var array $this->recipients * @var array $this->recipients
* @var string $recipient * @var string $recipient
* @var string $this->username * @var string $this->username
* @var string $this->password * @var string $this->password
* @var mixed $result * @var mixed $result
* @var array $headers * @var array $headers
* *
* @var int $success * @var int $success
* @var string $error * @var string $error
* *
* @return int or string * @return int or string
*/ */
public function sendSMS($message) { public function sendSMS($message) {
$success = 1; $success = 1;
$error = ''; $error = '';
foreach( $this->recipients as $recipient ){ foreach ($this->recipients as $recipient) {
$ch = curl_init(); $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.textmarketer.co.uk/gateway/?username=".$this->username."&password=".$this->password."&to=".$recipient."&message=".urlencode($message)."&orig=SERVERALERT"); curl_setopt($ch, CURLOPT_URL, "https://api.textmarketer.co.uk/gateway/?username=".$this->username."&password=".$this->password."&to=".$recipient."&message=".urlencode($message)."&orig=SERVERALERT");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$headers = array(); $headers = array();
@ -61,15 +61,15 @@ class Textmarketer extends Core {
$result = curl_exec($ch); $result = curl_exec($ch);
curl_close($ch); curl_close($ch);
// Check on error // Check on error
if (is_numeric(strpos($result, "FAILED"))) { if (is_numeric(strpos($result, "FAILED"))) {
$error = $result; $error = $result;
$success = 0; $success = 0;
} }
} }
if($success == 1){ if ($success == 1) {
return 1; return 1;
} }
return $error; return $error;
} }
} }

View File

@ -30,34 +30,34 @@ namespace psm\Txtmsg;
class Twilio extends Core { class Twilio extends Core {
/** /**
* Send sms using the Twilio API * Send sms using the Twilio API
* https://www.twilio.com/docs/sms/api#send-an-sms-with-the-sms-api * https://www.twilio.com/docs/sms/api#send-an-sms-with-the-sms-api
* @var string $message * @var string $message
* @var array $this->recipients * @var array $this->recipients
* @var string $recipient * @var string $recipient
* @var string $this->username * @var string $this->username
* @var string $this->password * @var string $this->password
* @var string $this->originator * @var string $this->originator
* @var mixed $result * @var mixed $result
* @var array $headers * @var array $headers
* *
* @var int $success * @var int $success
* @var string $error * @var string $error
* *
* @return int or string * @return int or string
*/ */
public function sendSMS($message) { public function sendSMS($message) {
$success = 1; $success = 1;
$error = ''; $error = '';
foreach($this->recipients as $recipient) { foreach ($this->recipients as $recipient) {
$ch = curl_init(); $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.twilio.com/2010-04-01/Accounts/".$this->username."/Messages.json"); curl_setopt($ch, CURLOPT_URL, "https://api.twilio.com/2010-04-01/Accounts/".$this->username."/Messages.json");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "From=".urlencode($this->originator)."&Body=".urlencode($message)."&To=".urlencode($recipient)); curl_setopt($ch, CURLOPT_POSTFIELDS, "From=".urlencode($this->originator)."&Body=".urlencode($message)."&To=".urlencode($recipient));
curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, $this->username . ":" . $this->password); curl_setopt($ch, CURLOPT_USERPWD, $this->username.":".$this->password);
$headers = array(); $headers = array();
$headers[] = "Content-Type: application/x-www-form-urlencoded"; $headers[] = "Content-Type: application/x-www-form-urlencoded";
@ -72,9 +72,9 @@ class Twilio extends Core {
$success = 0; $success = 0;
} }
} }
if($success == 1){ if ($success) {
return 1; return 1;
} }
return $error; return $error;
} }
} }

View File

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

View File

@ -69,7 +69,7 @@ class Modal implements ModalInterface {
*/ */
protected $twig; protected $twig;
public function __construct(\Twig_Environment $twig, $modal_id = 'main', $type = self::MODAL_TYPE_OK ) { public function __construct(\Twig_Environment $twig, $modal_id = 'main', $type = self::MODAL_TYPE_OK) {
$this->modal_id = $modal_id; $this->modal_id = $modal_id;
$this->twig = $twig; $this->twig = $twig;
$this->type = $type; $this->type = $type;
@ -89,7 +89,7 @@ class Modal implements ModalInterface {
* @return \psm\Util\Module\Modal * @return \psm\Util\Module\Modal
*/ */
public function setType($type) { public function setType($type) {
if(in_array($type, array(self::MODAL_TYPE_OK, self::MODAL_TYPE_OKCANCEL, self::MODAL_TYPE_DANGER))) { if (in_array($type, array(self::MODAL_TYPE_OK, self::MODAL_TYPE_OKCANCEL, self::MODAL_TYPE_DANGER))) {
$this->type = $type; $this->type = $type;
} }
return $this; return $this;
@ -127,19 +127,19 @@ class Modal implements ModalInterface {
$message = !empty($this->message) ? $this->message : ''; $message = !empty($this->message) ? $this->message : '';
$matches = array(); $matches = array();
if(preg_match_all('/%(\d)/', $message, $matches, PREG_SET_ORDER)) { if (preg_match_all('/%(\d)/', $message, $matches, PREG_SET_ORDER)) {
foreach($matches as $match) { foreach ($matches as $match) {
$message = str_replace($match[0], '<span class="modalP' . $match[1] . '"></span>', $message); $message = str_replace($match[0], '<span class="modalP'.$match[1].'"></span>', $message);
} }
} }
$tpl = $this->twig->loadTemplate('util/module/modal.tpl.html'); $tpl = $this->twig->loadTemplate('util/module/modal.tpl.html');
$html = $tpl->render(array( $html = $tpl->render(array(
'modal_id' => $this->modal_id, 'modal_id' => $this->modal_id,
'modal_title' => !empty($this->title) ? $this->title : psm_get_lang('system', 'title'), 'modal_title' => !empty($this->title) ? $this->title : psm_get_lang('system', 'title'),
'modal_body' => $message, 'modal_body' => $message,
'has_cancel' => $has_cancel, 'has_cancel' => $has_cancel,
'label_cancel' => psm_get_lang('system', 'cancel'), 'label_cancel' => psm_get_lang('system', 'cancel'),
'modal_button_type' => $button_type, 'modal_button_type' => $button_type,
'modal_button_label'=> $button_label, 'modal_button_label'=> $button_label,
)); ));

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -57,7 +57,7 @@ class UserValidator {
*/ */
public function userId($user_id) { public function userId($user_id) {
$user = $this->user->getUser($user_id); $user = $this->user->getUser($user_id);
if(empty($user)) { if (empty($user)) {
throw new \InvalidArgumentException('user_no_match'); throw new \InvalidArgumentException('user_no_match');
} }
return true; return true;
@ -75,15 +75,15 @@ class UserValidator {
* @throws \InvalidArgumentException * @throws \InvalidArgumentException
*/ */
public function username($username, $user_id = 0) { public function username($username, $user_id = 0) {
if(strlen($username) > 64 || strlen($username) < 2) { if (strlen($username) > 64 || strlen($username) < 2) {
throw new \InvalidArgumentException('user_name_bad_length'); throw new \InvalidArgumentException('user_name_bad_length');
} }
if (!preg_match('/^[a-zA-Z\d_\.]{2,64}$/i', $username)) { if (!preg_match('/^[a-zA-Z\d_\.]{2,64}$/i', $username)) {
throw new \InvalidArgumentException('user_name_invalid'); throw new \InvalidArgumentException('user_name_invalid');
} }
$user_exists = $this->user->getUserByUsername($username); $user_exists = $this->user->getUserByUsername($username);
if(!empty($user_exists) && ($user_id == 0 || $user_id != $user_exists->user_id)) { if (!empty($user_exists) && ($user_id == 0 || $user_id != $user_exists->user_id)) {
throw new \InvalidArgumentException('user_name_exists'); throw new \InvalidArgumentException('user_name_exists');
} }
return true; return true;
@ -97,26 +97,26 @@ class UserValidator {
* @throws \InvalidArgumentException * @throws \InvalidArgumentException
*/ */
public function password($password, $password_repeat) { public function password($password, $password_repeat) {
if(empty($password) || empty($password_repeat)) { if (empty($password) || empty($password_repeat)) {
throw new \InvalidArgumentException('user_password_invalid'); throw new \InvalidArgumentException('user_password_invalid');
} }
if($password !== $password_repeat) { if ($password !== $password_repeat) {
throw new \InvalidArgumentException('user_password_no_match'); throw new \InvalidArgumentException('user_password_no_match');
} }
return true; return true;
} }
/** /**
* Install only; Check username on: * Install only; Check username on:
* *
* - Length (2-64 chars) * - Length (2-64 chars)
* - Contents (alphabetic chars and digits only) * - Contents (alphabetic chars and digits only)
* @param string $username * @param string $username
* @return boolean * @return boolean
* @throws \InvalidArgumentException * @throws \InvalidArgumentException
*/ */
public function username_new($username) { public function username_new($username) {
if(strlen($username) > 64 || strlen($username) < 2) { if (strlen($username) > 64 || strlen($username) < 2) {
throw new \InvalidArgumentException('user_name_bad_length'); throw new \InvalidArgumentException('user_name_bad_length');
} }
if (!preg_match('/^[a-zA-Z\d_\.]{2,64}$/i', $username)) { if (!preg_match('/^[a-zA-Z\d_\.]{2,64}$/i', $username)) {
@ -126,16 +126,16 @@ class UserValidator {
} }
/** /**
* Check email * Check email
* @param string $email * @param string $email
* @return boolean * @return boolean
* @throws \InvalidArgumentException * @throws \InvalidArgumentException
*/ */
public function email($email) { public function email($email) {
if(strlen($email) > 255 || strlen($email) < 5) { if (strlen($email) > 255 || strlen($email) < 5) {
throw new \InvalidArgumentException('user_email_bad_length'); throw new \InvalidArgumentException('user_email_bad_length');
} }
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) { if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new \InvalidArgumentException('user_email_invalid'); throw new \InvalidArgumentException('user_email_invalid');
} }
return true; return true;
@ -148,7 +148,7 @@ class UserValidator {
* @throws \InvalidArgumentException * @throws \InvalidArgumentException
*/ */
public function level($level) { public function level($level) {
if(!in_array($level, $this->user_levels)) { if (!in_array($level, $this->user_levels)) {
throw new \InvalidArgumentException('user_level_invalid'); throw new \InvalidArgumentException('user_level_invalid');
} }
return true; return true;

View File

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