Umbau der Statistik Ausgabe (each enfernt)

Optimierungen
This commit is contained in:
Gregor Schulte
2021-11-29 15:23:19 +01:00
parent b303dd00d6
commit c464f9e3a3
18 changed files with 580 additions and 545 deletions

124
.gitignore vendored
View File

@@ -1,50 +1,100 @@
# These are some examples of commonly ignored file patterns. ### JetBrains template
# You should customize this list as applicable to your project. # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Learn more about .gitignore: # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# https://www.atlassian.com/git/tutorials/saving-changes/gitignore
# Node artifact files # User-specific stuff
node_modules/ .idea/**/workspace.xml
dist/ .idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
.idea
# Compiled Java class files # Generated files
*.class .idea/**/contentModel.xml
# Compiled Python bytecode # Sensitive or high-churn files
*.py[cod] .idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Log files # Gradle
*.log .idea/**/gradle.xml
.idea/**/libraries
Pi Control.iml
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# Package files # CMake
*.jar cmake-build-*/
# Maven # Mongo Explorer plugin
target/ .idea/**/mongoSettings.xml
dist/
# JetBrains IDE # File-based project format
.idea/ *.iws
# Unit test reports # IntelliJ
TEST*.xml out/
# Generated by MacOS # mpeltonen/sbt-idea plugin
.DS_Store .idea_modules/
# Generated by Windows # JIRA plugin
Thumbs.db atlassian-ide-plugin.xml
# Applications # Cursive Clojure plugin
*.app .idea/replstate.xml
*.exe
*.war
# Large media files # Crashlytics plugin (for Android Studio and IntelliJ)
*.mp4 com_crashlytics_export_strings.xml
*.tiff crashlytics.properties
*.avi crashlytics-build.properties
*.flv fabric.properties
*.mov
*.wmv # Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### ZendFramework template
# Composer files
composer.phar
vendor/
# Local configs
config/autoload/*.local.php
# Binary gettext files
*.mo
# Data
data/logs/
data/cache/
data/sessions/
data/tmp/
temp/
#Doctrine 2
data/DoctrineORMModule/Proxy/
data/DoctrineORMModule/cache/
# Legacy ZF1
demos/
extras/documentation

View File

@@ -1,5 +1,5 @@
<?php <?php
define('PICONTROL', true); const PICONTROL = true;
(include_once realpath(dirname(__FILE__)).'/../../resources/init.php') or die('Error: 0x0000'); (include_once realpath(dirname(__FILE__)).'/../../resources/init.php') or die('Error: 0x0000');
(include_once LIBRARY_PATH.'main/main.function.php') or die('Error: 0x0001'); (include_once LIBRARY_PATH.'main/main.function.php') or die('Error: 0x0001');
@@ -14,34 +14,34 @@ if (isset($_POST['id']))
{ {
$controller = new StatisticController(); $controller = new StatisticController();
$controller->loadStatistics(); $controller->loadStatistics();
if (($name = $controller->getStatisticName($_POST['id'])) !== false) if (($name = $controller->getStatisticName($_POST['id'])) !== false)
{ {
if (isset($_POST['plugin']) && trim($_POST['plugin']) != '') if (isset($_POST['plugin']) && trim($_POST['plugin']) != '')
pluginLanguage(trim($_POST['plugin'])); pluginLanguage(trim($_POST['plugin']));
$builder = new StatisticBuilder(); $builder = new StatisticBuilder();
$builder->loadFromFile($name, (isset($_POST['plugin']) && trim($_POST['plugin']) != '') ? $_POST['plugin'] : NULL); $builder->loadFromFile($name, (isset($_POST['plugin']) && trim($_POST['plugin']) != '') ? $_POST['plugin'] : NULL);
$statistic = $builder->getArray(); $statistic = $builder->getArray();
$log = new LogStatistic(); $log = new LogStatistic();
$log->setFile(LOG_PATH.$statistic['raw'].'.csv'); $log->setFile(LOG_PATH.$statistic['raw'].'.csv');
$arr = $info = array(); $arr = $info = array();
foreach ($statistic['columns'] as $column) foreach ($statistic['columns'] as $column)
$arr['cols'][] = array('id' => '', 'label' => _t($column['label']), 'type' => $column['type']); $arr['cols'][] = array('id' => '', 'label' => _t($column['label']), 'type' => $column['type']);
getRowsFromLog($arr, $info, $log->getAll(), $statistic['columns'], $statistic['cycle']); getRowsFromLog($arr, $info, $log->getAll(), $statistic['columns'], $statistic['cycle']);
if (isset($arr['rows'])) if (isset($arr['rows']))
{ {
if (isset($_POST['type']) && $_POST['type'] == 'googleChart') if (isset($_POST['type']) && $_POST['type'] == 'googleChart')
$arr['rows'] = convertForGoogleChart($arr['rows']); $arr['rows'] = convertForGoogleChart($arr['rows']);
$arr['rows'] = array_slice($arr['rows'], -2016); $arr['rows'] = array_slice($arr['rows'], -2016);
$arr['periods'] = $info['periods']; $arr['periods'] = $info['periods'];
foreach (array('min', 'max') as $type) foreach (array('min', 'max') as $type)
{ {
if ($statistic['limits'][$type]['use'] == 'multiply') if ($statistic['limits'][$type]['use'] == 'multiply')
@@ -54,7 +54,7 @@ if (isset($_POST['id']))
$arr[$type] = round($info[$type]); $arr[$type] = round($info[$type]);
} }
} }
$api->addData('statistic', $arr); $api->addData('statistic', $arr);
} }
else else
@@ -67,23 +67,22 @@ else
{ {
$statistics = array(); $statistics = array();
$hiddenStatistics = unserialize(htmlspecialchars_decode(getConfig('main:statistic.hidden', 'a:0:{}'))); $hiddenStatistics = unserialize(htmlspecialchars_decode(getConfig('main:statistic.hidden', 'a:0:{}')));
$controller = new StatisticController(); $controller = new StatisticController();
$controller->loadStatistics(); $controller->loadStatistics();
foreach ($controller->getStatistics() as $statistic) foreach ($controller->getStatistics() as $statistic)
{ {
$builder = new StatisticBuilder(); $builder = new StatisticBuilder();
$builder->loadFromFile($statistic); $builder->loadFromFile($statistic);
$array = $builder->getArray(); $array = $builder->getArray();
if (!in_array($builder->getId(), $hiddenStatistics)) if (!in_array($builder->getId(), $hiddenStatistics))
$statistics[] = array('array' => $array); $statistics[] = array('array' => $array);
} }
$api->addData('statistics', $statistics); $api->addData('statistics', $statistics);
$api->addData('hidden', $hiddenStatistics); $api->addData('hidden', $hiddenStatistics);
} }
$api->display(); $api->display();
?>

View File

@@ -1,5 +1,5 @@
<?php <?php
define('PICONTROL', true); const PICONTROL = true;
$doNotCheckForAuthentification = true; $doNotCheckForAuthentification = true;
(include_once realpath(dirname(__FILE__)).'/resources/init.php') or die('Error: 0x0000'); (include_once realpath(dirname(__FILE__)).'/resources/init.php') or die('Error: 0x0000');
@@ -65,14 +65,14 @@ try
else else
include_once CONTENT_PATH.'overview.php'; include_once CONTENT_PATH.'overview.php';
} }
if ($tpl->tplDraw === false) if ($tpl->tplDraw === false)
$tpl->draw(); $tpl->draw();
} }
catch(Exception $e) catch(Exception $e)
{ {
$errorHandler[] = 'Fehler [TPL]: '.$e->getFile().':'.$e->getLine().' => '.$e->getMessage(); $errorHandler[] = 'Fehler [TPL]: '.$e->getFile().':'.$e->getLine().' => '.$e->getMessage();
echo '<!DOCTYPE HTML> echo '<!DOCTYPE HTML>
<html> <html>
<head> <head>
@@ -91,4 +91,4 @@ catch(Exception $e)
</body> </body>
</html>'; </html>';
} }
?> ?>

View File

@@ -41,12 +41,12 @@
<div class="inner-table"> <div class="inner-table">
<table class="table table-borderless table-form"> <table class="table table-borderless table-form">
<tr> <tr>
<td style="width: 50%;"><?php _e('Version %s', '>= 5.5'); ?></td> <td style="width: 50%;"><?php _e('Version %s', '>= 7.0'); ?></td>
<td class="<?php echo ($data['phpVersion']['status'] == true) ? 'green' : 'red'; ?>"><?php echo ($data['phpVersion']['status'] == true) ? '&#10004;' : '&#10006;'; echo ' '.$data['phpVersion']['version']; ?></td> <td class="<?php echo ($data['phpVersion']['status'] == true) ? 'green' : 'red'; ?>"><?php echo ($data['phpVersion']['status'] == true) ? '&#10004;' : '&#10006;'; echo ' '.$data['phpVersion']['version']; ?></td>
</tr> </tr>
<tr> <tr>
<td><?php _e('SSH2-Erweiterung installiert'); ?></td> <td><?php _e('SSH2-Erweiterung installiert'); ?></td>
<td class="<?php echo ($data['phpSSH']['status'] == true) ? 'green' : 'red'; ?>"><?php echo ($data['phpSSH']['status'] == true) ? '&#10004;' : '&#10006; <a style="color: inherit; text-decoration: underline" href="'.$data['configHelp'].'?s=view&amp;i=11'.getURLLangParam().'" target="_blank">'._t('Anleitung zur Installation').'</a>'; ?></td> <td class="<?php echo ($data['phpSSH']['status'] == true) ? 'green' : 'red'; ?>"><?php echo ($data['phpSSH']['status'] == true) ? '&#10004;' : '&#10006; <a style="color: inherit; text-decoration: underline" href="'.$data['configHelp'].'#phpssh'.getURLLangParam().'" target="_blank">'._t('Anleitung zur Installation').'</a>'; ?></td>
</tr> </tr>
<tr> <tr>
<td><?php _e('Mcrypt-Erweiterung installiert'); ?></td> <td><?php _e('Mcrypt-Erweiterung installiert'); ?></td>
@@ -58,7 +58,7 @@
</tr> </tr>
<tr> <tr>
<td><?php _e('cURL-Erweiterung installiert'); ?></td> <td><?php _e('cURL-Erweiterung installiert'); ?></td>
<td class="<?php echo ($data['phpCURL']['status'] == true) ? 'green' : 'red'; ?>"><?php echo ($data['phpCURL']['status'] == true) ? '&#10004;' : '&#10006; <a style="color: inherit; text-decoration: underline" href="'.$data['configHelp'].'?s=view&amp;i=14'.getURLLangParam().'" target="_blank">'._t('Anleitung zur Installation').'</a>'; ?></td> <td class="<?php echo ($data['phpCURL']['status'] == true) ? 'green' : 'red'; ?>"><?php echo ($data['phpCURL']['status'] == true) ? '&#10004;' : '&#10006; <a style="color: inherit; text-decoration: underline" href="'.$data['configHelp'].'#phpcurl'.getURLLangParam().'" target="_blank">'._t('Anleitung zur Installation').'</a>'; ?></td>
</tr> </tr>
<tr> <tr>
<td><?php _e('ZipArchive-Erweiterung installiert'); ?></td> <td><?php _e('ZipArchive-Erweiterung installiert'); ?></td>

View File

@@ -19,7 +19,7 @@ $otherDistribution = array('version' => rpi_getDistribution(), 'status' => false
$otherCookie = array('status' => false); $otherCookie = array('status' => false);
$error = false; $error = false;
if (version_compare(PHP_VERSION, '5.5.0') >= 0) if (version_compare(PHP_VERSION, '7.0.0') >= 0)
$phpVersion['status'] = true; $phpVersion['status'] = true;
if (extension_loaded('ssh2')) if (extension_loaded('ssh2'))
@@ -28,7 +28,7 @@ if (extension_loaded('ssh2'))
//if (function_exists('mcrypt_encrypt') !== false) //if (function_exists('mcrypt_encrypt') !== false)
$phpMcrypt['status'] = true; $phpMcrypt['status'] = true;
if (trim(exec('dpkg -s php5-cli | grep Status: ')) != '' || trim(exec('dpkg -s php7.0-cli | grep Status: ')) || trim(exec('dpkg -s php7.3-cli | grep Status: ')) != '') if (trim(exec('dpkg -s php7.3-cli | grep Status: ')) != '' || trim(exec('dpkg -s php7.4-cli | grep Status: ')) != '')
$phpCLI['status'] = true; $phpCLI['status'] = true;
if (function_exists('curl_init') !== false) if (function_exists('curl_init') !== false)
@@ -52,7 +52,7 @@ foreach ($filesFolders as $file => $info)
$filesFoldersExist['count'] += 1; $filesFoldersExist['count'] += 1;
$filesFoldersExist['status'] = false; $filesFoldersExist['status'] = false;
} }
if ($info['permissionBool'] === false || $info['userGroupBool'] === false) if ($info['permissionBool'] === false || $info['userGroupBool'] === false)
{ {
$filesFoldersPermission['count'] += 1; $filesFoldersPermission['count'] += 1;
@@ -62,7 +62,7 @@ foreach ($filesFolders as $file => $info)
} }
// Sonstiges // Sonstiges
if ($otherDistribution['version'] == 'Raspbian GNU/Linux 7' || $otherDistribution['version'] == 'Raspbian GNU/Linux 8' || $otherDistribution['version'] == 'Raspbian GNU/Linux 9' || $otherDistribution['version'] == 'Raspbian GNU/Linux 10') if ($otherDistribution['version'] == 'Raspbian GNU/Linux 10' || $otherDistribution['version'] == 'Raspbian GNU/Linux 11')
$otherDistribution['status'] = true; $otherDistribution['status'] = true;
if (isset($_COOKIE['_pi-control_install_language']) && $_COOKIE['_pi-control_install_language'] != '') if (isset($_COOKIE['_pi-control_install_language']) && $_COOKIE['_pi-control_install_language'] != '')
@@ -90,4 +90,4 @@ $tpl->assign('langUrl', (isset($_GET['lang']) && $_GET['lang'] != '') ? '&amp;la
$tpl->assign('configHelp', $config['url']['help']); $tpl->assign('configHelp', $config['url']['help']);
$tpl->draw('install_requirement'); $tpl->draw('install_requirement');
?> ?>

View File

@@ -16,7 +16,7 @@ if (!isset($config))
'update' => 'https://pi-control.de/service/v1/update/', 'update' => 'https://pi-control.de/service/v1/update/',
'updateDownload' => 'https://pi-control.de/?service=update', 'updateDownload' => 'https://pi-control.de/?service=update',
'updateNotification' => 'https://pi-control.de/?service=update_notification', 'updateNotification' => 'https://pi-control.de/?service=update_notification',
'help' => 'https://pi-control.de/help/' 'help' => 'https://www.die-schultes.eu/pi-control-hilfe/'
) )
); );
} }

View File

@@ -14,19 +14,17 @@
<a href="https://willy-tech.de/kontakt/" target="_blank" data-lang="<?php echo $data['language']; ?>"><?php _e('Feedback'); ?></a><br /> <a href="https://willy-tech.de/kontakt/" target="_blank" data-lang="<?php echo $data['language']; ?>"><?php _e('Feedback'); ?></a><br />
<a href="<?php echo $data['helpLink']; ?>" target="_blank"><?php _e('Hilfe'); ?></a><br /> <a href="<?php echo $data['helpLink']; ?>" target="_blank"><?php _e('Hilfe'); ?></a><br />
<a href="https://play.google.com/store/apps/details?id=de.willytech.picontrol" target="_blank" title="<?php _e('&Ouml;ffne im Play Store'); ?>"><?php _e('App im Play Store'); ?></a><br /> <a href="https://play.google.com/store/apps/details?id=de.willytech.picontrol" target="_blank" title="<?php _e('&Ouml;ffne im Play Store'); ?>"><?php _e('App im Play Store'); ?></a><br />
<a href="https://gitlab.com/pi-control" target="_blank"><?php _e('GitLab'); ?></a></td> <a href="https://bitbucket.org/GSchulte/pi-control/" target="_blank"><?php _e('Git Repo'); ?></a></td>
<td rowspan="2"><a href="https://willy-tech.de/" target="_blank"><?php _e('Mein Blog'); ?></a><br /> <td rowspan="2"><a href="https://www.die-schultes.eu/" target="_blank"><?php _e('Mein Blog'); ?></a><br />
<a href="https://twitter.com/Willys_TechBlog" target="_blank"><?php _e('Twitter'); ?></a><br />
<a href="https://www.paypal.me/fritzsche" target="_blank"><?php _e('Spenden'); ?></a></td>
<td><?php echo $data['version']; ?></td> <td><?php echo $data['version']; ?></td>
</tr> </tr>
<tr> <tr>
<td><strong><?php _e('LIZENZ'); ?></strong><span><?php _e('Raspberry Pi ist ein Markenzeichen<br />der %s.', '<a href="https://www.raspberrypi.org/" target="_blank">Raspberry Pi Foundation</a>'); ?></span></td> <td><strong><?php _e('LIZENZ'); ?></strong><span><?php _e('Raspberry Pi ist ein Markenzeichen<br />der %s.', '<a href="https://www.raspberrypi.org/" target="_blank">Raspberry Pi Foundation</a>'); ?></span></td>
</tr> </tr>
</table> </table>
<div id="footer-copyright"><?php _e('Mit %s entwickelt von %s.', '<span style="color: #F44336;">&#10084;</span>', '<a href="https://willy-tech.de/" target="_blank">Willy Fritzsche</a>'); ?> 2013-2017</div> <div id="footer-copyright"><?php _e('Mit %s entwickelt von %s.', '<span style="color: #F44336;">&#10084;</span>', '<a href="https://willy-tech.de/" target="_blank">Willy Fritzsche</a>'); ?> 2013-2017 <br>Weiterentwickelt von <a href="https://www.die-schultes.eu">Gregor Schulte</a> 2021</div>
</div> </div>
</div> </div>
<script type="text/javascript">var errorHandler = '<?php echo $data['errorHandler']; ?>';</script> <script type="text/javascript">var errorHandler = '<?php echo $data['errorHandler']; ?>';</script>
</body> </body>
</html> </html>

View File

@@ -74,4 +74,4 @@
statisticBuilder(<?php echo $statistic['json']; ?>, null); statisticBuilder(<?php echo $statistic['json']; ?>, null);
<?php } ?> <?php } ?>
} }
</script> </script>

View File

@@ -38,7 +38,7 @@ $tpl->assign('configHelpFilesFolders', $config['url']['help'].'?s=view&amp;i=1'.
$tpl->assign('configHelpCron', $config['url']['help'].'?s=view&amp;i=10'.getURLLangParam()); $tpl->assign('configHelpCron', $config['url']['help'].'?s=view&amp;i=10'.getURLLangParam());
$tpl->assign('cronEntry', $cronEntry); $tpl->assign('cronEntry', $cronEntry);
$tpl->assign('cronMatch', $cronMatch); $tpl->assign('cronMatch', $cronMatch);
$tpl->assign('cronPHPCLI', ($cronPHPCLI = (trim(exec('dpkg -s php5-cli | grep Status: ')) != '' || trim(exec('dpkg -s php7.0-cli | grep Status: ')) != '') ? true : false)); $tpl->assign('cronPHPCLI', ($cronPHPCLI = (trim(exec('dpkg -s php7.0-cli | grep Status: ')) != '' || trim(exec('dpkg -s php7.3-cli | grep Status: ')) != '') ? true : false));
$tpl->assign('cronLastExecution', formatTime(getConfig('cron:execution.cron', 0))); $tpl->assign('cronLastExecution', formatTime(getConfig('cron:execution.cron', 0)));
$tpl->assign('cronLastExecutionBool', ($cronLastExecutionBool = (getConfig('cron:execution.cron', 0) > time()-150) ? true : false)); $tpl->assign('cronLastExecutionBool', ($cronLastExecutionBool = (getConfig('cron:execution.cron', 0) > time()-150) ? true : false));
$tpl->assign('cronLastExecutionLog', formatTime($lastExecutionLog[0])); $tpl->assign('cronLastExecutionLog', formatTime($lastExecutionLog[0]));
@@ -52,4 +52,4 @@ $tpl->assign('cronCharacterEncodingBool', ($cronCharacterEncodingBool = trim(exe
$tpl->assign('cronError', ($cronMatch !== 1) ? 1 : (($cronPHPCLI !== true || $cronLastExecutionBool !== true || $cronLastExecutionLogBool !== true || $cronPermissionBool !== true || $cronUserGroupBool !== true || $cronCharacterEncodingBool !== true ) ? 2 : 0)); $tpl->assign('cronError', ($cronMatch !== 1) ? 1 : (($cronPHPCLI !== true || $cronLastExecutionBool !== true || $cronLastExecutionLogBool !== true || $cronPermissionBool !== true || $cronUserGroupBool !== true || $cronCharacterEncodingBool !== true ) ? 2 : 0));
$tpl->draw('settings/troubleshooting'); $tpl->draw('settings/troubleshooting');
?> ?>

View File

@@ -1,6 +1,6 @@
<?php <?php
if (PHP_SAPI != 'cli') exit(); if (PHP_SAPI != 'cli') exit();
define('PICONTROL', true); const PICONTROL = true;
$doNotCheckForAuthentification = true; $doNotCheckForAuthentification = true;
(include_once realpath(dirname(__FILE__)).'/../init.php') or die('Error: 0x0000'); (include_once realpath(dirname(__FILE__)).'/../init.php') or die('Error: 0x0000');
@@ -13,4 +13,3 @@ $log->setFile(LOG_PATH.'statistic/coretemp.csv');
$log->setLimit(2016); $log->setLimit(2016);
$log->add(array(time(), rpi_getCoreTemprature())); $log->add(array(time(), rpi_getCoreTemprature()));
$log->close(); $log->close();
?>

View File

@@ -1,6 +1,6 @@
<?php <?php
if (PHP_SAPI != 'cli') exit(); if (PHP_SAPI != 'cli') exit();
define('PICONTROL', true); const PICONTROL = true;
$doNotCheckForAuthentification = true; $doNotCheckForAuthentification = true;
(include_once realpath(dirname(__FILE__)).'/../init.php') or die('Error: 0x0000'); (include_once realpath(dirname(__FILE__)).'/../init.php') or die('Error: 0x0000');
@@ -22,7 +22,7 @@ foreach ($fileArray as $file)
{ {
$timeOfFile = str_replace('-', '', substr($file, 0, 2)); $timeOfFile = str_replace('-', '', substr($file, 0, 2));
$rest = date('i', time()) % $timeOfFile; $rest = date('i', time()) % $timeOfFile;
if (is_numeric($rest) && $rest == 0) if (is_numeric($rest) && $rest == 0)
{ {
exec('/usr/bin/php -f "'.CRON_PATH.$file.'"'); exec('/usr/bin/php -f "'.CRON_PATH.$file.'"');
@@ -31,6 +31,5 @@ foreach ($fileArray as $file)
} }
} }
if (trim(exec('dpkg -s php5-cli | grep Status: ')) != '' || trim(exec('dpkg -s php7.0-cli | grep Status: ')) || trim(exec('dpkg -s php7.3-cli | grep Status: ')) != '') if (trim(exec('dpkg -s php7.0-cli | grep Status: ')) != '' || trim(exec('dpkg -s php7.3-cli | grep Status: ')) != '')
setConfig('cron:execution.cron', time()); setConfig('cron:execution.cron', time());
?>

View File

@@ -10,7 +10,7 @@ if (!isset($config))
'ssh_ip' => '127.0.0.1' 'ssh_ip' => '127.0.0.1'
), ),
'version' => array( 'version' => array(
'version' => '2.1.2', 'version' => '2.2.0beta',
'versioncode' => 29, 'versioncode' => 29,
'android_comp_level' => 25 'android_comp_level' => 25
), ),
@@ -63,7 +63,7 @@ function myErrorHandler($code, $msg, $file, $line)
{ {
global $errorHandler; global $errorHandler;
$errorHandler[] = 'Fehler ['.$code.']: '.$msg.' in der Datei '.$file.', Zeile '.$line; $errorHandler[] = 'Fehler ['.$code.']: '.$msg.' in der Datei '.$file.', Zeile '.$line;
if (isset($_COOKIE['debug']) && $_COOKIE['debug'] == 'debug_mode') if (isset($_COOKIE['debug']) && $_COOKIE['debug'] == 'debug_mode')
return false; return false;
else else
@@ -81,4 +81,4 @@ if (isset($_COOKIE['debug'], $_GET['s']) && $_COOKIE['debug'] == 'debug_mode')
if (!isset($doNotCheckForAuthentification)) if (!isset($doNotCheckForAuthentification))
(include LIBRARY_PATH.'main/authentification.php') or die('Nicht gefunden!'); (include LIBRARY_PATH.'main/authentification.php') or die('Nicht gefunden!');
?> ?>

View File

@@ -5,27 +5,27 @@ class API
{ {
// Startzeit // Startzeit
private $startTime = 0; private $startTime = 0;
// Statuscode // Statuscode
private $status = 200; private $status = 200;
// Daten // Daten
private $dataArray = array(); private $dataArray = array();
// Fehler // Fehler
private $error = array(); private $error = array();
/** /**
* Konstrukter, welcher die Startzeit für die Lauftzeit festlegt. * Konstrukter, welcher die Startzeit für die Lauftzeit festlegt.
* *
* <code>$api = new API;</code> * <code>$api = new API;</code>
*/ */
function __construct() function __construct()
{ {
$this->startTime = microtime(true); $this->startTime = microtime(true);
} }
/** /**
* Fügt ein Element hinzu. * Fügt ein Element hinzu.
* *
@@ -35,20 +35,20 @@ class API
* @param string|array|bool $value Wert * @param string|array|bool $value Wert
* @return bool * @return bool
*/ */
public function addData($key, $value) public function addData($key, $value)
{ {
if (!empty($this->error)) if (!empty($this->error))
return false; return false;
$dummyStatus = $this->status; $dummyStatus = $this->status;
$this->status = 500; $this->status = 500;
if (($key = trim($key)) == '') if (($key = trim($key)) == '')
return false; return false;
$splits = explode('.', $key); $splits = explode('.', $key);
switch (count($splits)) switch (count($splits))
{ {
case 1: case 1:
@@ -69,12 +69,12 @@ class API
default: default:
return false; return false;
} }
$this->status = $dummyStatus; $this->status = $dummyStatus;
return true; return true;
} }
/** /**
* Setzt den Statuscode. * Setzt den Statuscode.
* *
@@ -83,17 +83,17 @@ class API
* @param int $status Statuscode * @param int $status Statuscode
* @return bool * @return bool
*/ */
public function setStatus($status) public function setStatus($status)
{ {
if (!is_int($status)) if (!is_int($status))
return false; return false;
$this->status = $status; $this->status = $status;
return true; return true;
} }
/** /**
* Setzt eine Fehlermeldung. * Setzt eine Fehlermeldung.
* *
@@ -104,26 +104,26 @@ class API
* @param int $status Statuscode * @param int $status Statuscode
* @return bool * @return bool
*/ */
public function setError($type, $message, $status = 500) public function setError($type, $message, $status = 500)
{ {
if (($type = trim($type)) == '') if (($type = trim($type)) == '')
return false; return false;
if (($message = trim($message)) == '') if (($message = trim($message)) == '')
return false; return false;
if (!is_int($status)) if (!is_int($status))
return false; return false;
header('HTTP/1.0 '.$status); header('HTTP/1.0 '.$status);
$this->error = array('type' => $type, 'message' => $message); $this->error = array('type' => $type, 'message' => $message);
$this->status = $status; $this->status = $status;
return true; return true;
} }
/** /**
* Erzeugt das fertige JSON und gibt dieses anschließend aus. * Erzeugt das fertige JSON und gibt dieses anschließend aus.
* *
@@ -132,19 +132,18 @@ class API
* @param bool $prettyPrint Eingerückte Ausgabe des JSON * @param bool $prettyPrint Eingerückte Ausgabe des JSON
* @return bool Ausgabe erfolgt mit "echo". * @return bool Ausgabe erfolgt mit "echo".
*/ */
public function display($prettyPrint = false) public function display($prettyPrint = false)
{ {
header('Content-Type: application/json'); header('Content-Type: application/json');
$executionTime = microtime(true) - $this->startTime; $executionTime = microtime(true) - $this->startTime;
if (empty($this->error)) if (empty($this->error))
echo json_encode(array('data' => $this->dataArray, 'executionTime' => $executionTime, 'status' => $this->status), ($prettyPrint != false) ? JSON_PRETTY_PRINT : 0); echo json_encode(array('data' => $this->dataArray, 'executionTime' => $executionTime, 'status' => $this->status), ($prettyPrint != false) ? JSON_PRETTY_PRINT : 0);
else else
echo json_encode(array('error' => $this->error, 'executionTime' => $executionTime, 'status' => $this->status), ($prettyPrint != false) ? JSON_PRETTY_PRINT : 0); echo json_encode(array('error' => $this->error, 'executionTime' => $executionTime, 'status' => $this->status), ($prettyPrint != false) ? JSON_PRETTY_PRINT : 0);
return true; return true;
} }
} }
?>

View File

@@ -5,19 +5,19 @@ function getCacheList()
{ {
$fileSuffix = '.cache.php'; $fileSuffix = '.cache.php';
$cacheArray = array('usb_devices' => array(), 'users' => array(), 'weather' => array()); $cacheArray = array('usb_devices' => array(), 'users' => array(), 'weather' => array());
foreach ($cacheArray as $name => $info) foreach ($cacheArray as $name => $info)
{ {
$cacheArray[$name]['active'] = (getConfig('cache:activation.'.$name, 'false') == 'true') ? true : false; $cacheArray[$name]['active'] = (getConfig('cache:activation.'.$name, 'false') == 'true') ? true : false;
$cacheArray[$name]['lifetime'] = getConfig('cache:lifetime.'.$name, 0); $cacheArray[$name]['lifetime'] = getConfig('cache:lifetime.'.$name, 0);
if (file_exists(CACHE_PATH.$name.$fileSuffix) && is_file(CACHE_PATH.$name.$fileSuffix)) if (file_exists(CACHE_PATH.$name.$fileSuffix) && is_file(CACHE_PATH.$name.$fileSuffix))
{ {
$cacheArray[$name]['filesize'] = filesize(CACHE_PATH.$name.$fileSuffix); $cacheArray[$name]['filesize'] = filesize(CACHE_PATH.$name.$fileSuffix);
$cacheArray[$name]['modification'] = filemtime(CACHE_PATH.$name.$fileSuffix); $cacheArray[$name]['modification'] = filemtime(CACHE_PATH.$name.$fileSuffix);
} }
} }
return $cacheArray; return $cacheArray;
} }
@@ -35,4 +35,3 @@ function getCacheName($file)
return $file; return $file;
} }
} }
?>

View File

@@ -17,53 +17,53 @@ function rpi_getHostAddr()
{ {
if (!isset($_SERVER['SERVER_ADDR'])) if (!isset($_SERVER['SERVER_ADDR']))
return 'unknown'; return 'unknown';
if (!$ip = $_SERVER['SERVER_ADDR']) if (!$ip = $_SERVER['SERVER_ADDR'])
return gethostbyname($this->getHostname()); return gethostbyname($this->getHostname());
return $ip; return $ip;
} }
function rpi_getCoreTemprature() function rpi_getCoreTemprature()
{ {
$file = 85000; $file = 85000;
while ($file == 85000) while ($file == 85000)
$file = @shell_exec('cat /sys/class/thermal/thermal_zone0/temp'); $file = @shell_exec('cat /sys/class/thermal/thermal_zone0/temp');
if ($file != false) if ($file != false)
return round((trim($file)/1000), 2); return round((trim($file)/1000), 2);
return 0; return 0;
} }
function rpi_getCpuClock() function rpi_getCpuClock()
{ {
$file = shell_exec('cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq'); $file = shell_exec('cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq');
if ($file !== false) if ($file !== false)
return (int) round(trim($file)/1000); return (int) round(trim($file)/1000);
return 0; return 0;
} }
function rpi_getCpuMinClock() function rpi_getCpuMinClock()
{ {
$file = shell_exec('cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq'); $file = shell_exec('cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq');
if ($file !== false) if ($file !== false)
return (int) round(trim($file)/1000); return (int) round(trim($file)/1000);
return 0; return 0;
} }
function rpi_getCpuMaxClock() function rpi_getCpuMaxClock()
{ {
$file = shell_exec('cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq'); $file = shell_exec('cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq');
if ($file !== false) if ($file !== false)
return (int) round(trim($file)/1000); return (int) round(trim($file)/1000);
return 0; return 0;
} }
@@ -71,10 +71,10 @@ function rpi_getCPUType()
{ {
$file = shell_exec('cat /proc/cpuinfo'); $file = shell_exec('cat /proc/cpuinfo');
preg_match('#Hardware\s*:\s*([^\s]+)#i', $file, $match); preg_match('#Hardware\s*:\s*([^\s]+)#i', $file, $match);
if (isset($match[1])) if (isset($match[1]))
return $match[1]; return $match[1];
return NULL; return NULL;
} }
@@ -87,69 +87,69 @@ function rpi_getCpuModel()
function rpi_getCPULoad($accurate = false, $mulitcore = false) function rpi_getCPULoad($accurate = false, $mulitcore = false)
{ {
$return = NULL; $return = NULL;
if ($accurate === true) if ($accurate === true)
$file = shell_exec('cat /proc/stat; sleep 2; echo "##--##"; cat /proc/stat'); $file = shell_exec('cat /proc/stat; sleep 2; echo "##--##"; cat /proc/stat');
else else
$file = shell_exec('cat /proc/stat; sleep 0.5; echo "##--##"; cat /proc/stat'); $file = shell_exec('cat /proc/stat; sleep 0.5; echo "##--##"; cat /proc/stat');
$file = explode('##--##', $file); $file = explode('##--##', $file);
if (!isset($file[0], $file[1])) if (!isset($file[0], $file[1]))
return NULL; return NULL;
preg_match_all('/^cpu[0-9]?(.*)$/im', $file[0], $prevCPUStrings); preg_match_all('/^cpu[0-9]?(.*)$/im', $file[0], $prevCPUStrings);
preg_match_all('/^cpu[0-9]?(.*)$/im', $file[1], $curCPUStrings); preg_match_all('/^cpu[0-9]?(.*)$/im', $file[1], $curCPUStrings);
for ($i = 0; $i < count($prevCPUStrings[0]); $i++) for ($i = 0; $i < count($prevCPUStrings[0]); $i++)
{ {
$prevCPU = preg_split('/\s+/', $prevCPUStrings[0][$i]); $prevCPU = preg_split('/\s+/', $prevCPUStrings[0][$i]);
$curCPU = preg_split('/\s+/', $curCPUStrings[0][$i]); $curCPU = preg_split('/\s+/', $curCPUStrings[0][$i]);
if ($prevCPU[0] != 'cpu' && $mulitcore == false) if ($prevCPU[0] != 'cpu' && $mulitcore == false)
break; break;
if (!isset($prevCPU[0], $curCPU[1]) || count($prevCPU) != 11 || count($curCPU) != 11) if (!isset($prevCPU[0], $curCPU[1]) || count($prevCPU) != 11 || count($curCPU) != 11)
return NULL; return NULL;
$prevIdle = $prevCPU[4] + $prevCPU[5]; $prevIdle = $prevCPU[4] + $prevCPU[5];
$curIdle = $curCPU[4] + $curCPU[5]; $curIdle = $curCPU[4] + $curCPU[5];
$prevNonIdle = $prevCPU[1] + $prevCPU[2] + $prevCPU[3] + $prevCPU[6] + $prevCPU[7] + $prevCPU[8]; $prevNonIdle = $prevCPU[1] + $prevCPU[2] + $prevCPU[3] + $prevCPU[6] + $prevCPU[7] + $prevCPU[8];
$curNonIdle = $curCPU[1] + $curCPU[2] + $curCPU[3] + $curCPU[6] + $curCPU[7] + $curCPU[8]; $curNonIdle = $curCPU[1] + $curCPU[2] + $curCPU[3] + $curCPU[6] + $curCPU[7] + $curCPU[8];
$prevTotal = $prevIdle + $prevNonIdle; $prevTotal = $prevIdle + $prevNonIdle;
$curTotal = $curIdle + $curNonIdle; $curTotal = $curIdle + $curNonIdle;
$total = $curTotal - $prevTotal; $total = $curTotal - $prevTotal;
$idle = $curIdle - $prevIdle; $idle = $curIdle - $prevIdle;
if ($mulitcore == true) if ($mulitcore == true)
$return[$prevCPU[0]] = (int) round(($total - $idle) / $total * 100); $return[$prevCPU[0]] = (int) round(($total - $idle) / $total * 100);
else else
$return = (int) round(($total - $idle) / $total * 100); $return = (int) round(($total - $idle) / $total * 100);
} }
return $return; return $return;
} }
function rpi_getDistribution() function rpi_getDistribution()
{ {
$distribution = trim(@shell_exec('cat /etc/issue | cut -d " " -f 1-3')); $distribution = trim(@shell_exec('cat /etc/issue | cut -d " " -f 1-3'));
if ($distribution == '') if ($distribution == '')
{ {
$distributionString = @shell_exec('cat /etc/*-release | grep PRETTY_NAME'); $distributionString = @shell_exec('cat /etc/*-release | grep PRETTY_NAME');
preg_match('/.*="([\w\s\d\/]*).*"/i', $distributionString, $match); preg_match('/.*="([\w\s\d\/]*).*"/i', $distributionString, $match);
if (count($match) == 2) if (count($match) == 2)
$distribution = trim($match[1]); $distribution = trim($match[1]);
else else
$distribution = _t('Unbekannt'); $distribution = _t('Unbekannt');
} }
return $distribution; return $distribution;
} }
@@ -174,7 +174,7 @@ function rpi_getCountInstalledPackages()
function rpi_getInstalledPackages() function rpi_getInstalledPackages()
{ {
@exec('dpkg -l | grep ^ii', $packages); @exec('dpkg -l | grep ^ii', $packages);
$packages = array_map(function($package) { return preg_split('/[\s]+/', $package, 5); }, $packages); $packages = array_map(function($package) { return preg_split('/[\s]+/', $package, 5); }, $packages);
return $packages; return $packages;
} }
@@ -199,14 +199,14 @@ function rpi_getRpiRevision()
$revision[19] = array('revision' => '0013', 'model' => 'B+', 'pcb' => '1.2', 'memory' => 512, 'manufacturer' => 'Embest'); $revision[19] = array('revision' => '0013', 'model' => 'B+', 'pcb' => '1.2', 'memory' => 512, 'manufacturer' => 'Embest');
$revision[20] = array('revision' => '0014', 'model' => 'Compute Module', 'pcb' => '1.0', 'memory' => 512, 'manufacturer' => 'Embest'); $revision[20] = array('revision' => '0014', 'model' => 'Compute Module', 'pcb' => '1.0', 'memory' => 512, 'manufacturer' => 'Embest');
$revision[21] = array('revision' => '0015', 'model' => 'A+', 'pcb' => '1.1', 'memory' => 256, 'manufacturer' => 'Embest'); $revision[21] = array('revision' => '0015', 'model' => 'A+', 'pcb' => '1.1', 'memory' => 256, 'manufacturer' => 'Embest');
$revision_model = array(0 => 'A', 1 => 'B', 2 => 'A+', 3 => 'B+', 4 => 'Pi 2 B', 5 => 'Alpha', 6 => 'Compute Module', 7 => 'Zero', 8 => 'Pi 3 B', 9 => 'Zero', 10 => 'Compute Module 3', 12 => 'Zero W'); $revision_model = array(0 => 'A', 1 => 'B', 2 => 'A+', 3 => 'B+', 4 => 'Pi 2 B', 5 => 'Alpha', 6 => 'Compute Module', 7 => 'Zero', 8 => 'Pi 3 B', 9 => 'Zero', 10 => 'Compute Module 3', 12 => 'Zero W');
$revision_memory = array(0 => 256, 1 => 512, 2 => 1024); $revision_memory = array(0 => 256, 1 => 512, 2 => 1024);
$revision_manufacturer = array(0 => 'Sony', 1 => 'Egoman', 2 => 'Embest', 3 => 'Sony Japan', 4 => 'Embest'); $revision_manufacturer = array(0 => 'Sony', 1 => 'Egoman', 2 => 'Embest', 3 => 'Sony Japan', 4 => 'Embest');
$file = shell_exec('cat /proc/cpuinfo'); $file = shell_exec('cat /proc/cpuinfo');
preg_match('#\nRevision\s*:\s*([\da-f]+)#i', $file, $match); preg_match('#\nRevision\s*:\s*([\da-f]+)#i', $file, $match);
/* /*
* ###### * ######
* |||||+- PCB * |||||+- PCB
@@ -216,12 +216,12 @@ function rpi_getRpiRevision()
* |+- Manufacturer * |+- Manufacturer
* +- Memory * +- Memory
*/ */
if (isset($match[1])) if (isset($match[1]))
{ {
if ($match[1][0] == '1' || $match[1][0] == '2') if ($match[1][0] == '1' || $match[1][0] == '2')
$match[1] = substr($match[1], 1); $match[1] = substr($match[1], 1);
if (strlen($match[1]) == 4) if (strlen($match[1]) == 4)
return $revision[hexdec($match[1])]; return $revision[hexdec($match[1])];
elseif (strlen($match[1]) == 6 && $match[1][0] != 'a' && $match[1][0] != '9') elseif (strlen($match[1]) == 6 && $match[1][0] != 'a' && $match[1][0] != '9')
@@ -235,7 +235,7 @@ function rpi_getRpiRevision()
'manufacturer' => $revision_manufacturer[hexdec(substr($match[1], 1, 1))]); 'manufacturer' => $revision_manufacturer[hexdec(substr($match[1], 1, 1))]);
} }
} }
return NULL; return NULL;
} }
@@ -243,7 +243,7 @@ function rpi_getRpiSerial()
{ {
$file = shell_exec('cat /proc/cpuinfo'); $file = shell_exec('cat /proc/cpuinfo');
preg_match('#\nSerial\s*:\s*([\da-f]+)#i', $file, $match); preg_match('#\nSerial\s*:\s*([\da-f]+)#i', $file, $match);
return $match[1]; return $match[1];
} }
@@ -256,7 +256,7 @@ function rpi_getMemorySplit()
$config = @shell_exec('cat /boot/config.txt'); $config = @shell_exec('cat /boot/config.txt');
preg_match('#gpu_mem=([0-9]+)#i', $config, $match); preg_match('#gpu_mem=([0-9]+)#i', $config, $match);
$total = intval($match[1]); $total = intval($match[1]);
if ($total == 16) if ($total == 16)
return array('system' => '496 MiB', 'video' => '16 MiB'); return array('system' => '496 MiB', 'video' => '16 MiB');
elseif ($total == 32) elseif ($total == 32)
@@ -265,38 +265,38 @@ function rpi_getMemorySplit()
return array('system' => '448 MiB', 'video' => '64 MiB'); return array('system' => '448 MiB', 'video' => '64 MiB');
elseif ($total == 128) elseif ($total == 128)
return array('system' => '384 MiB', 'video' => '128 MiB'); return array('system' => '384 MiB', 'video' => '128 MiB');
return array('system' => '256 MiB', 'video' => '256 MiB'); return array('system' => '256 MiB', 'video' => '256 MiB');
} }
// 256 MB // 256 MB
$mem = $this->getMemoryUsage(); $mem = $this->getMemoryUsage();
$total = round($mem['total'] / 1024 / 1024, 0); $total = round($mem['total'] / 1024 / 1024, 0);
if ($total <= 128) if ($total <= 128)
return array('system' => '128 MiB', 'video' => '128 MiB'); return array('system' => '128 MiB', 'video' => '128 MiB');
elseif ($total > 128 && $total <= 192) elseif ($total > 128 && $total <= 192)
return array('system' => '192 MiB', 'video' => '64 MiB'); return array('system' => '192 MiB', 'video' => '64 MiB');
elseif ($total > 192 && $total <= 224) elseif ($total > 192 && $total <= 224)
return array('system' => '224 MiB', 'video' => '32 MiB'); return array('system' => '224 MiB', 'video' => '32 MiB');
return array('system' => '240 MiB', 'video' => '16 MiB'); return array('system' => '240 MiB', 'video' => '16 MiB');
} }
function rpi_getMemoryUsage() function rpi_getMemoryUsage()
{ {
exec('free -bo 2>/dev/null || free -b', $data); exec('free -bo 2>/dev/null || free -b', $data);
if (strpos($data[0], 'available') !== false) { if (strpos($data[0], 'available') !== false) {
list($type, $total, $used, $free, $shared, $buffers, $available) = preg_split('#\s+#', $data[1]); list($type, $total, $used, $free, $shared, $buffers, $available) = preg_split('#\s+#', $data[1]);
$usage = (int) round(($total - $available) / $total * 100); $usage = (int) round(($total - $available) / $total * 100);
return array('percent' => $usage, 'total' => $total, 'free' => $available, 'used' => ($total - $available)); return array('percent' => $usage, 'total' => $total, 'free' => $available, 'used' => ($total - $available));
} }
list($type, $total, $used, $free, $shared, $buffers, $cached) = preg_split('#\s+#', $data[1]); list($type, $total, $used, $free, $shared, $buffers, $cached) = preg_split('#\s+#', $data[1]);
$usage = (int) round(($used - $buffers - $cached) / $total * 100); $usage = (int) round(($used - $buffers - $cached) / $total * 100);
return array('percent' => $usage, 'total' => $total, 'free' => ($free + $buffers + $cached), 'used' => ($used - $buffers - $cached)); return array('percent' => $usage, 'total' => $total, 'free' => ($free + $buffers + $cached), 'used' => ($used - $buffers - $cached));
} }
@@ -305,7 +305,7 @@ function rpi_getSwapUsage()
exec('free -bo 2>/dev/null || free -b', $data); exec('free -bo 2>/dev/null || free -b', $data);
list($type, $total, $used, $free) = preg_split('#\s+#', $data[2]); list($type, $total, $used, $free) = preg_split('#\s+#', $data[2]);
$usage = (int) round($used / $total * 100); $usage = (int) round($used / $total * 100);
return array('percent' => $usage, 'total' => $total, 'free' => $free, 'used' => $used); return array('percent' => $usage, 'total' => $total, 'free' => $free, 'used' => $used);
} }
@@ -314,28 +314,28 @@ function multiArraySearch($array, $key, $value)
foreach ($array as $item) foreach ($array as $item)
if (isset($item[$key]) && $item[$key] == $value) if (isset($item[$key]) && $item[$key] == $value)
return true; return true;
return false; return false;
} }
function rpi_getMemoryInfo() function rpi_getMemoryInfo()
{ {
exec('df -lT | grep -vE "tmpfs|rootfs|Filesystem|Dateisystem"', $data); exec('df -lT | grep -vE "tmpfs|rootfs|Filesystem|Dateisystem"', $data);
$devices = array(); $devices = array();
$totalSize = 0; $totalSize = 0;
$usedSize = 0; $usedSize = 0;
foreach ($data as $row) foreach ($data as $row)
{ {
list($device, $type, $blocks, $use, $available, $used, $mountpoint) = preg_split('#[\s%]+#i', $row); list($device, $type, $blocks, $use, $available, $used, $mountpoint) = preg_split('#[\s%]+#i', $row);
if (multiArraySearch($devices, 'device', $device) === false) if (multiArraySearch($devices, 'device', $device) === false)
{ {
$totalSize += $blocks * 1024; $totalSize += $blocks * 1024;
$usedSize += $use * 1024; $usedSize += $use * 1024;
} }
$devices[] = array( $devices[] = array(
'device' => $device, 'device' => $device,
'type' => $type, 'type' => $type,
@@ -346,14 +346,14 @@ function rpi_getMemoryInfo()
'mountpoint' => $mountpoint 'mountpoint' => $mountpoint
); );
} }
usort($devices, function($a, $b) usort($devices, function($a, $b)
{ {
return strcasecmp($a['device'], $b['device']); return strcasecmp($a['device'], $b['device']);
}); });
$devices[] = array('total' => $totalSize, 'used' => $usedSize, 'free' => $totalSize - $usedSize, 'percent' => (int) round(($usedSize * 100 / $totalSize))); $devices[] = array('total' => $totalSize, 'used' => $usedSize, 'free' => $totalSize - $usedSize, 'percent' => (int) round(($usedSize * 100 / $totalSize)));
return $devices; return $devices;
} }
@@ -361,17 +361,17 @@ function rpi_getUsbDevices()
{ {
exec('lsusb', $data); exec('lsusb', $data);
$devices = array(); $devices = array();
foreach ($data as $row) foreach ($data as $row)
{ {
preg_match('#[0-9a-f]{4}:[0-9a-f]{4}\s+(.+)#i', $row, $match); preg_match('#[0-9a-f]{4}:[0-9a-f]{4}\s+(.+)#i', $row, $match);
if (count($match) == 2) if (count($match) == 2)
$devices[] = trim($match[1]); $devices[] = trim($match[1]);
else else
$devices[] = '<'._t('Unbekannt').'>'; $devices[] = '<'._t('Unbekannt').'>';
} }
return $devices; return $devices;
} }
@@ -393,33 +393,33 @@ function rpi_getAllUsers()
call_user_func_array('array_multisort', $args); call_user_func_array('array_multisort', $args);
return array_pop($args); return array_pop($args);
} }
exec('/usr/bin/who --ips', $dataLoggedIn); exec('/usr/bin/who --ips', $dataLoggedIn);
exec('/usr/bin/lastlog | grep -vE "Benutzername|Username" | cut -f 1 -d " "', $dataAllUsers); exec('/usr/bin/lastlog | grep -vE "Benutzername|Username" | cut -f 1 -d " "', $dataAllUsers);
$usersLoggedIn = array(); $usersLoggedIn = array();
$usersAll = array(); $usersAll = array();
foreach ($dataLoggedIn as $row) foreach ($dataLoggedIn as $row)
{ {
$split = preg_split('/\s+/i', $row); $split = preg_split('/\s+/i', $row);
if (count($split) == 6) if (count($split) == 6)
$usersLoggedIn[$split[0]][] = array('port' => $split[1], 'lastLogin' => strtotime($split[2].' '.$split[3].' '.$split[4]), 'lastLoginAddress' => $split[5]); $usersLoggedIn[$split[0]][] = array('port' => $split[1], 'lastLogin' => strtotime($split[2].' '.$split[3].' '.$split[4]), 'lastLoginAddress' => $split[5]);
} }
foreach ($dataAllUsers as $row) foreach ($dataAllUsers as $row)
{ {
$userLastLoginInformation = ''; $userLastLoginInformation = '';
$userLastLoginInformation = shell_exec('/usr/bin/last -i -f /var/log/wtmp | grep -m 1 "^'.$row.' "'); $userLastLoginInformation = shell_exec('/usr/bin/last -i -f /var/log/wtmp | grep -m 1 "^'.$row.' "');
if ($userLastLoginInformation == '') if ($userLastLoginInformation == '')
$userLastLoginInformation = shell_exec('/usr/bin/last -i -f /var/log/wtmp.1 | grep -m 1 "^'.$row.' "'); $userLastLoginInformation = shell_exec('/usr/bin/last -i -f /var/log/wtmp.1 | grep -m 1 "^'.$row.' "');
if ($userLastLoginInformation != '') if ($userLastLoginInformation != '')
{ {
$split = preg_split('/\s+/i', $userLastLoginInformation); $split = preg_split('/\s+/i', $userLastLoginInformation);
$usersAll[] = array('username' => $row, $usersAll[] = array('username' => $row,
'userId' => exec('id -u '.escapeshellarg($row)), 'userId' => exec('id -u '.escapeshellarg($row)),
'groupId' => exec('id -g '.escapeshellarg($row)), 'groupId' => exec('id -g '.escapeshellarg($row)),
@@ -440,9 +440,9 @@ function rpi_getAllUsers()
'isLoggedIn' => isset($usersLoggedIn[$row]) ? true : false); 'isLoggedIn' => isset($usersLoggedIn[$row]) ? true : false);
} }
} }
$usersAll = array_orderby($usersAll, 'isLoggedIn', SORT_DESC, 'username', SORT_ASC); $usersAll = array_orderby($usersAll, 'isLoggedIn', SORT_DESC, 'username', SORT_ASC);
return $usersAll; return $usersAll;
} }
?> ?>

File diff suppressed because it is too large Load Diff

View File

@@ -4,133 +4,129 @@ if (!defined('PICONTROL')) exit();
class LogStatistic class LogStatistic
{ {
private $file, $stream, $limit = -1, $length = 100; private $file, $stream, $limit = -1, $length = 100;
function __destruct() function __destruct()
{ {
if (is_resource($this->stream)) if (is_resource($this->stream))
fclose($this->stream); fclose($this->stream);
} }
public function setFile($pFile = '') public function setFile($pFile = '')
{ {
$this->file = $pFile; $this->file = $pFile;
} }
public function setLimit($pLimit = -1) public function setLimit($pLimit = -1)
{ {
$this->limit = $pLimit; $this->limit = $pLimit;
} }
public function setLength($pLength = 100) public function setLength($pLength = 100)
{ {
$this->length = $pLength; $this->length = $pLength;
} }
public function add($entry, $moreThanOne = false) public function add($entry, $moreThanOne = false)
{ {
if (!is_array($entry) || empty($entry)) if (!is_array($entry) || empty($entry))
return false; return false;
if (!is_resource($this->stream)) if (!is_resource($this->stream))
$this->open(); $this->open();
if ($this->limit > -1) if ($this->limit > -1)
$this->shortLog(); $this->shortLog();
fseek($this->stream, 0, SEEK_END); fseek($this->stream, 0, SEEK_END);
if ($moreThanOne === false) if ($moreThanOne === false)
fputcsv($this->stream, $entry); fputcsv($this->stream, $entry);
else else {
{
foreach ($entry as $item) foreach ($entry as $item)
fputcsv($this->stream, $item); fputcsv($this->stream, $item);
} }
return true; return true;
} }
public function getAll() public function getAll()
{ {
if (!is_resource($this->stream)) if (!is_resource($this->stream))
$this->open(); $this->open();
$entries = array(); $entries = array();
fseek($this->stream, 0); fseek($this->stream, 0);
while (($entry = fgetcsv($this->stream, $this->length)) !== false) while (($entry = fgetcsv($this->stream, $this->length)) !== false)
$entries[] = $entry; $entries[] = $entry;
return $entries; return $entries;
} }
public function getLast() public function getLast()
{ {
if (!is_resource($this->stream)) if (!is_resource($this->stream))
$this->open(); $this->open();
$entries = $this->getAll(); $entries = $this->getAll();
if (is_array($entries)) if (is_array($entries))
return end($entries); return end($entries);
} }
private function shortLog() private function shortLog()
{ {
if ($this->limit == -1) if ($this->limit == -1)
return false; return false;
if (!is_array(($entries = $this->getAll()))) if (!is_array(($entries = $this->getAll())))
return false; return false;
if (count($entries) >= $this->limit) if (count($entries) >= $this->limit) {
{
$unsetLineCount = count($entries) - $this->limit; $unsetLineCount = count($entries) - $this->limit;
for ($i = 0; $i <= $unsetLineCount; $i++) for ($i = 0; $i <= $unsetLineCount; $i++)
unset($entries[$i]); unset($entries[$i]);
fseek($this->stream, 0); fseek($this->stream, 0);
ftruncate($this->stream, 0); ftruncate($this->stream, 0);
foreach ($entries as $entry) foreach ($entries as $entry)
fputcsv($this->stream, $entry); fputcsv($this->stream, $entry);
} }
return true; return true;
} }
public function deleteLog() public function deleteLog()
{ {
if (is_file($this->file)) if (is_file($this->file)) {
{
if (unlink($this->file) or exit(_t('Konnte Log-Datei nicht l&ouml;schen: %s', $this->file))) if (unlink($this->file) or exit(_t('Konnte Log-Datei nicht l&ouml;schen: %s', $this->file)))
return true; return true;
} } else
else
return false; return false;
} }
public function clearLog() public function clearLog()
{ {
if (!is_resource($this->stream)) if (!is_resource($this->stream))
$this->open(); $this->open();
fseek($this->stream, 0); fseek($this->stream, 0);
ftruncate($this->stream, 0); ftruncate($this->stream, 0);
} }
public function close() public function close()
{ {
fclose($this->stream); fclose($this->stream);
} }
private function open() private function open()
{ {
if (!file_exists($this->file) || !is_file($this->file)) if (!file_exists($this->file) || !is_file($this->file))
touch($this->file); touch($this->file);
$this->stream = fopen($this->file, 'r+') or exit(_t('Konnte Log-Datei nicht &ouml;ffnen: %s', $this->file)); $this->stream = fopen($this->file, 'r+') or exit(_t('Konnte Log-Datei nicht &ouml;ffnen: %s', $this->file));
} }
} }
@@ -138,107 +134,104 @@ class LogStatistic
class StatisticController class StatisticController
{ {
private $statistics = array(); private $statistics = array();
public function __construct($tpl = NULL) public function __construct($tpl = NULL)
{ {
if (!isset($tpl)) if (!isset($tpl))
return; return;
$jsTranslations = array(); $jsTranslations = array();
$jsTranslations[] = 'Es sind noch keine Werte verf&uuml;gbar. Werte werden alle %%s Minuten eingetragen.'; $jsTranslations[] = 'Es sind noch keine Werte verf&uuml;gbar. Werte werden alle %%s Minuten eingetragen.';
$jsTranslations[] = 'Es ist ein Fehler aufgetreten! Fehler: %%s'; $jsTranslations[] = 'Es ist ein Fehler aufgetreten! Fehler: %%s';
$jsTranslations[] = 'Zeit'; $jsTranslations[] = 'Zeit';
$jsTranslations[] = 'Es ist ein Fehler aufgetreten! Fehlercode: %%s'; $jsTranslations[] = 'Es ist ein Fehler aufgetreten! Fehlercode: %%s';
$tpl->assign('jsTranslations', $jsTranslations, true); $tpl->assign('jsTranslations', $jsTranslations, true);
} }
public function loadStatistics($folder = NULL) public function loadStatistics($folder = NULL)
{ {
$files = array();
if ($folder == NULL) if ($folder == NULL)
$possibleFolders = array(LOG_PATH); $possibleFolders = array(LOG_PATH);
else else
$possibleFolders = array(LOG_PATH.$folder); $possibleFolders = array(LOG_PATH . $folder);
while (list($key, $folder) = each($possibleFolders)) foreach ($possibleFolders as $folder) {
{ $this->statistics = array_merge($this->statistics, $this->loadStatisticsIterator($folder));
foreach (@scandir($folder) as $file)
{
if ($file[0] != '.')
{
if (is_file($folder.'/'.$file) && substr($file, -4) == '.csv')
{
$fileName = str_replace(LOG_PATH, '', $folder).substr($file, 0, -4);
$this->statistics[substr(md5($fileName), 0, 8)] = $fileName;
}
elseif (is_dir($folder.$file))
$possibleFolders[] = $folder.$file.'/';
}
}
} }
} }
private function loadStatisticsIterator($folder)
{
$fileNames = array();
$files = array_diff(@scandir($folder), array('..', '.'));
foreach ($files as $file) {
$absolutePath = $folder . '/' . $file;
if (is_file($absolutePath) && substr($file, -4) == '.csv') {
$fileName = str_replace(LOG_PATH, '', $folder) . substr($file, 0, -4);
$fileNames[substr(md5($fileName), 0, 8)] = $fileName;
} elseif (is_dir($absolutePath))
$fileNames = array_merge($fileNames, $this->loadStatisticsIterator($folder . $file . '/'));
}
return $fileNames;
}
public function getStatisticID($name) public function getStatisticID($name)
{ {
if (empty($this->statistics)) if (empty($this->statistics))
$this->loadStatistics(); $this->loadStatistics();
if (!is_string($name)) if (!is_string($name))
return false; return false;
if (($id = array_search($name, $this->statistics)) !== false) if (($id = array_search($name, $this->statistics)) !== false)
return $id; return $id;
return false; return false;
} }
public function getStatisticName($id) public function getStatisticName($id)
{ {
if (empty($this->statistics)) if (empty($this->statistics))
$this->loadStatistics(); $this->loadStatistics();
if (!is_string($id)) if (!is_string($id))
return false; return false;
if (isset($this->statistics[$id])) if (isset($this->statistics[$id]))
return $this->statistics[$id]; return $this->statistics[$id];
return false; return false;
} }
public function checkStatistic($value, $isID = false) public function checkStatistic($value, $isID = false)
{ {
if (!is_string($value)) if (!is_string($value))
return false; return false;
if (!is_bool($isID)) if (!is_bool($isID))
return false; return false;
if ($isID === true) if ($isID === true) {
{
if ($this->getStatisticName($value) !== false) if ($this->getStatisticName($value) !== false)
return true; return true;
else else
return false; return false;
} } elseif ($isID === false) {
elseif ($isID === false)
{
if ($this->getStatisticID($value) !== false) if ($this->getStatisticID($value) !== false)
return true; return true;
else else
return false; return false;
} }
return false; return false;
} }
public function getStatistics() public function getStatistics()
{ {
if (empty($this->statistics)) if (empty($this->statistics))
$this->loadStatistics(); $this->loadStatistics();
return $this->statistics; return $this->statistics;
} }
} }
@@ -246,46 +239,43 @@ class StatisticController
class StatisticBuilder class StatisticBuilder
{ {
private $name, $columns, $title, $prefix, $suffix, $raw, $label, $unit, $cycle, $limits; private $name, $columns, $title, $prefix, $suffix, $raw, $label, $unit, $cycle, $limits;
public function loadFromFile($name, $plugin = NULL) public function loadFromFile($name, $plugin = NULL)
{ {
$source = LIBRARY_PATH.'statistic/statistic.config.php'; $source = LIBRARY_PATH . 'statistic/statistic.config.php';
if ($plugin != NULL && is_string($plugin)) if ($plugin != NULL && is_string($plugin))
$source = PLUGINS_PATH.$plugin.'/plugin.statistic.config.php'; $source = PLUGINS_PATH . $plugin . '/plugin.statistic.config.php';
if (!file_exists($source) || !is_file($source)) if (!file_exists($source) || !is_file($source))
return false; return false;
include $source; include $source;
if (!isset($statisticConfig) || !is_array($statisticConfig)) if (!isset($statisticConfig) || !is_array($statisticConfig))
return false; return false;
$this->raw = $name; $this->raw = $name;
if (strpos($name, '/') !== false) if (strpos($name, '/') !== false) {
{
$explodes = explode('/', strrev($name), 2); $explodes = explode('/', strrev($name), 2);
$name = strrev($explodes[0]); $name = strrev($explodes[0]);
$prefix = strrev($explodes[1]).'/'; $prefix = strrev($explodes[1]) . '/';
} }
if (!isset($statisticConfig[$name]) && isset($statisticConfig[substr($name, 0, strpos($name, '_'))])) if (!isset($statisticConfig[$name]) && isset($statisticConfig[substr($name, 0, strpos($name, '_'))])) {
{ if (strpos($name, '_') !== false) {
if (strpos($name, '_') !== false)
{
$explodes = explode('_', strrev($name), 2); $explodes = explode('_', strrev($name), 2);
$suffix = strrev($explodes[0]); $suffix = strrev($explodes[0]);
$name = strrev($explodes[1]); $name = strrev($explodes[1]);
} }
} }
if (!isset($statisticConfig[$name])) if (!isset($statisticConfig[$name]))
return false; return false;
$statistic = $statisticConfig[$name]; $statistic = $statisticConfig[$name];
$this->name = $name; $this->name = $name;
$this->title = _t($statistic['title']); $this->title = _t($statistic['title']);
$this->prefix = isset($prefix) ? $prefix : ''; $this->prefix = isset($prefix) ? $prefix : '';
@@ -294,70 +284,68 @@ class StatisticBuilder
$this->unit = $statistic['unit']; $this->unit = $statistic['unit'];
$this->cycle = $statistic['cycle']; $this->cycle = $statistic['cycle'];
$this->limits = $statistic['limits']; $this->limits = $statistic['limits'];
foreach ($statistic['columns'] as $column) foreach ($statistic['columns'] as $column) {
{ foreach ($column as &$values) {
foreach ($column as &$values)
{
if (is_string($values)) if (is_string($values))
$values = _t($values); $values = _t($values);
} }
$this->columns[] = $column; $this->columns[] = $column;
} }
if (substr_count($this->title, '%s') == 1) { if (substr_count($this->title, '%s') == 1) {
$this->title = sprintf($this->title, $this->suffix); $this->title = sprintf($this->title, $this->suffix);
} }
if ($this->title == '') if ($this->title == '')
$this->title = $this->suffix; $this->title = $this->suffix;
return true; return true;
} }
public function setTitle($title) public function setTitle($title)
{ {
if (!is_string($title)) if (!is_string($title))
return false; return false;
$this->title = $title; $this->title = $title;
} }
public function getId() public function getId()
{ {
return substr(md5($this->raw), 0, 8); return substr(md5($this->raw), 0, 8);
} }
public function getArray() public function getArray()
{ {
return array( return array(
'id' => $this->getId(), 'id' => $this->getId(),
'name' => $this->name, 'name' => $this->name,
'title' => $this->title, 'title' => $this->title,
'prefix' => $this->prefix, 'prefix' => $this->prefix,
'suffix' => $this->suffix, 'suffix' => $this->suffix,
'raw' => $this->raw, 'raw' => $this->raw,
'label' => $this->label, 'label' => $this->label,
'unit' => $this->unit, 'unit' => $this->unit,
'cycle' => $this->cycle, 'cycle' => $this->cycle,
'columns' => $this->columns, 'columns' => $this->columns,
'limits' => $this->limits 'limits' => $this->limits
); );
} }
public function getJSON() public function getJSON()
{ {
$json = json_encode(array( $json = json_encode(
'id' => $this->getId(), array(
'label' => $this->label, 'id' => $this->getId(),
'unit' => $this->unit, 'label' => $this->label,
'cycle' => $this->cycle, 'unit' => $this->unit,
'columns' => $this->columns 'cycle' => $this->cycle,
) 'columns' => $this->columns
); )
);
return $json; return $json;
} }
} }
?>

View File

@@ -1,5 +1,5 @@
<?php <?php
define('PICONTROL', true); const PICONTROL = true;
(include_once realpath(dirname(__FILE__)).'/../init.php') or die('Error: 0x0000'); (include_once realpath(dirname(__FILE__)).'/../init.php') or die('Error: 0x0000');
(include_once LIBRARY_PATH.'main/tpl.class.php') or die('Error: 0x0001'); (include_once LIBRARY_PATH.'main/tpl.class.php') or die('Error: 0x0001');
@@ -18,10 +18,10 @@ $updateStatus = $updateController->fetchData();
if ($updateStatus === true) { if ($updateStatus === true) {
$nextUpdate = $updateController->getNextUpdate(); $nextUpdate = $updateController->getNextUpdate();
if ($nextUpdate instanceof Update) { if ($nextUpdate instanceof Update) {
$downloadStatus = $updateController->download($nextUpdate); $downloadStatus = $updateController->download($nextUpdate);
if ($downloadStatus === true) { if ($downloadStatus === true) {
$tpl->redirect('?s=settings&do=update&complete'); $tpl->redirect('?s=settings&do=update&complete');
} elseif ($downloadStatus === 10) { } elseif ($downloadStatus === 10) {
@@ -41,4 +41,4 @@ if ($updateStatus === true) {
if (isset($errorMsg)) { if (isset($errorMsg)) {
$tpl->assign('content', '<div class="inner-header"><span>'._t('Aktualisierung').'</span></div><div class="inner red">'.$errorMsg.'</div><div class="inner-end"><a href="?s=settings&amp;do=update" class="button">'._t('Zur&uuml;ck zur Aktualisierung').'</a></div>'); $tpl->assign('content', '<div class="inner-header"><span>'._t('Aktualisierung').'</span></div><div class="inner red">'.$errorMsg.'</div><div class="inner-end"><a href="?s=settings&amp;do=update" class="button">'._t('Zur&uuml;ck zur Aktualisierung').'</a></div>');
$tpl->draw('single_box'); $tpl->draw('single_box');
} }